From 6f08c06c4f89456ba2817594b5a1eb47e940ed5c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Jan 2015 13:27:27 +0800 Subject: [PATCH 0001/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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/4971] 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 | From 9eb7e7ce4042a398e53553d75dc9c99c636e7cc3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Mar 2016 15:05:58 +0800 Subject: [PATCH 1940/4971] Update and rename mergeKLists.cpp to merge-k-sorted-lists.cpp --- C++/merge-k-sorted-lists.cpp | 98 ++++++++++++++++++++++++++++++++++++ C++/mergeKLists.cpp | 48 ------------------ 2 files changed, 98 insertions(+), 48 deletions(-) create mode 100644 C++/merge-k-sorted-lists.cpp delete mode 100644 C++/mergeKLists.cpp diff --git a/C++/merge-k-sorted-lists.cpp b/C++/merge-k-sorted-lists.cpp new file mode 100644 index 000000000..f73990a52 --- /dev/null +++ b/C++/merge-k-sorted-lists.cpp @@ -0,0 +1,98 @@ +// Time: O(n * logk) +// Space: O(k) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + ListNode dummy(0); + auto *cur = &dummy; + + struct Compare { + bool operator() (const ListNode *a, const ListNode *b) { + return a->val > b->val; + } + }; + + // Use min heap to keep the smallest node of each list + priority_queue, Compare> min_heap; + for (const auto& n : lists) { + if (n) { + min_heap.emplace(n); + } + } + + while (!min_heap.empty()) { + // Get min of k lists. + auto *node = min_heap.top(); + min_heap.pop(); + cur->next = node; + cur = cur->next; + if (node->next) { + min_heap.emplace(node->next); + } + } + + return dummy.next; + } +}; + +// Time: O(n * logk) +// Space: O(k) +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution2 { +public: + ListNode *mergeKLists(vector &lists) { + return mergeKLists(lists, 0, lists.size() - 1); + } + +private: + ListNode *mergeKLists(const vector &lists, int begin, int end) { + if (begin > end) { + return nullptr; + } + if (begin == end) { + return lists[begin]; + } + return mergeTwoLists(mergeKLists(lists, begin, (begin + end) / 2), + mergeKLists(lists, (begin + end) / 2 + 1, end)); + } + + ListNode *mergeTwoLists(ListNode *left, ListNode *right) { + ListNode dummy(0); + auto *p = &dummy; + for(; left && right; p = p->next) { + if(left->val < right->val) { + p->next = left; + left = left->next; + } + else { + p->next = right; + right = right->next; + } + } + if(left) { + p->next = left; + } + else { + p->next = right; + } + + return dummy.next; + } +}; + diff --git a/C++/mergeKLists.cpp b/C++/mergeKLists.cpp deleted file mode 100644 index f75d4d8ce..000000000 --- a/C++/mergeKLists.cpp +++ /dev/null @@ -1,48 +0,0 @@ -// Time Complexity: O(n * logk) -// Space Complexity: O(k) - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution { - public: - ListNode *mergeKLists(vector &lists) { - return mergeKLists(lists, 0, lists.size() - 1); - } - private: - ListNode *mergeKLists(vector &lists, int begin, int end) { - if(begin > end) - return NULL; - if(begin == end) - return lists[begin]; - return mergeTwoLists(mergeKLists(lists, begin, (begin + end) / 2), mergeKLists(lists, (begin + end) / 2 + 1, end)); - } - - ListNode *mergeTwoLists(ListNode *left, ListNode *right) { - ListNode dummy(INT_MIN); - ListNode *p = &dummy; - for(; left && right; p = p->next) { - if(left->val < right->val) { - p->next = left; - left = left->next; - } - else { - p->next = right; - right = right->next; - } - } - if(left) { - p->next = left; - } - else { - p->next = right; - } - - return dummy.next; - } -}; From f7fcb48daeb80275ca5dc8bd40a2da4bca570a62 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Mar 2016 15:06:52 +0800 Subject: [PATCH 1941/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5c1e3341c..9b8ebd7ac 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Heap # | 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 || +23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [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 | From 104b38b31ec4d3f022ecaa5b0114d3e4a37e5c82 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Mar 2016 15:07:42 +0800 Subject: [PATCH 1942/4971] Update merge-k-sorted-lists.cpp --- C++/merge-k-sorted-lists.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/C++/merge-k-sorted-lists.cpp b/C++/merge-k-sorted-lists.cpp index f73990a52..b7b6fa031 100644 --- a/C++/merge-k-sorted-lists.cpp +++ b/C++/merge-k-sorted-lists.cpp @@ -44,6 +44,7 @@ class Solution { } }; + // Time: O(n * logk) // Space: O(k) /** @@ -75,23 +76,20 @@ class Solution2 { ListNode *mergeTwoLists(ListNode *left, ListNode *right) { ListNode dummy(0); auto *p = &dummy; - for(; left && right; p = p->next) { + for (; left && right; p = p->next) { if(left->val < right->val) { p->next = left; left = left->next; - } - else { + } else { p->next = right; right = right->next; } } - if(left) { + if (left) { p->next = left; - } - else { + } else { p->next = right; } - return dummy.next; } }; From 52e54d12e23cd4024852b6a2137d292ad69bf387 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Mar 2016 16:02:58 +0800 Subject: [PATCH 1943/4971] Update and rename isValid.cpp to valid-parentheses.cpp --- C++/isValid.cpp | 25 ------------------------- C++/valid-parentheses.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 25 deletions(-) delete mode 100644 C++/isValid.cpp create mode 100644 C++/valid-parentheses.cpp diff --git a/C++/isValid.cpp b/C++/isValid.cpp deleted file mode 100644 index 2f132d8bc..000000000 --- a/C++/isValid.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - bool isValid(string s) { - const string left = "([{"; - const string right = ")]}"; - stack stack; - for(auto c : s) { - if(left.find(c) != string::npos) { - stack.push(c); - } - else if (right.find(c) != string::npos){ - if(!stack.empty() && stack.top() == left[right.find(c)]) { - stack.pop(); - } - else - return false; - } - } - - return stack.empty(); - } -}; diff --git a/C++/valid-parentheses.cpp b/C++/valid-parentheses.cpp new file mode 100644 index 000000000..aeb15cac0 --- /dev/null +++ b/C++/valid-parentheses.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + bool isValid(string s) { + const unordered_map symbol_pair = {{')', '('}, + {']', '['}, + {'}', '{'}}; + stack parentheses; + for (const auto& c: s) { + const auto& it = symbol_pair.find(c); + if (it != symbol_pair.cend()) { + if (parentheses.empty() || + parentheses.top() != it->second) { + return false; + } + parentheses.pop(); + } else { + parentheses.emplace(c); + } + } + return parentheses.empty(); + } +}; From bfe913a83e1dd009af9c5391271a6acd6fb9f49e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Mar 2016 16:03:46 +0800 Subject: [PATCH 1944/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b8ebd7ac..c1c8ee369 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Stack # | 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 || +20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [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 || From f9bb46db205a51ff4305747affd2020ff2c5fde0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Mar 2016 19:40:28 +0800 Subject: [PATCH 1945/4971] Update and rename longestValidParentheses.cpp to longest-valid-parentheses.cpp --- C++/longest-valid-parentheses.cpp | 32 ++++++++++++++++++++ C++/longestValidParentheses.cpp | 49 ------------------------------- 2 files changed, 32 insertions(+), 49 deletions(-) create mode 100644 C++/longest-valid-parentheses.cpp delete mode 100644 C++/longestValidParentheses.cpp diff --git a/C++/longest-valid-parentheses.cpp b/C++/longest-valid-parentheses.cpp new file mode 100644 index 000000000..1b5664db9 --- /dev/null +++ b/C++/longest-valid-parentheses.cpp @@ -0,0 +1,32 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int longestValidParentheses(string s) { + return max(length(s.begin(), s.end(), '('), length(s.rbegin(), s.rend(), ')')); + } + +private: + template + int length(T begin, T end, char c) { + int len = 0, depth = 0; + T start = prev(begin); + for (T it = begin; it != end; ++it) { + if (*it == c) { + ++depth; + } else { + --depth; + if (depth < 0) { + start = it; + depth = 0; + } else { + if (depth == 0) { + len = max(len, static_cast(distance(start, it))); + } + } + } + } + return len; + } +}; diff --git a/C++/longestValidParentheses.cpp b/C++/longestValidParentheses.cpp deleted file mode 100644 index 9f18d84fb..000000000 --- a/C++/longestValidParentheses.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - int longestValidParentheses(string s) { - int ans = 0; - - int depth = 0; - int last = -1; - for(int i = 0; i < s.length(); ++i) { - if(s[i] == '(') { - ++depth; - } - else { - --depth; - if(depth < 0) { - last = i; - depth = 0; - } - else { - if(depth == 0) - ans = max(ans, i - last); - } - } - } - - depth = 0; - last = s.size(); - for(int i = s.length() - 1; i >= 0; --i) { - if(s[i] == ')') { - ++depth; - } - else { - --depth; - if(depth < 0) { - last = i; - depth = 0; - } - else { - if(depth == 0) - ans = max(ans, last - i); - } - } - } - - return ans; - } -}; From 7777635b68c98130231442246a6ea576151bc62d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Mar 2016 19:42:59 +0800 Subject: [PATCH 1946/4971] Update longest-valid-parentheses.cpp --- C++/longest-valid-parentheses.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/longest-valid-parentheses.cpp b/C++/longest-valid-parentheses.cpp index 1b5664db9..d8c4d84b2 100644 --- a/C++/longest-valid-parentheses.cpp +++ b/C++/longest-valid-parentheses.cpp @@ -11,18 +11,18 @@ class Solution { template int length(T begin, T end, char c) { int len = 0, depth = 0; - T start = prev(begin); + T start = begin; for (T it = begin; it != end; ++it) { if (*it == c) { ++depth; } else { --depth; if (depth < 0) { - start = it; + start = next(it); depth = 0; } else { if (depth == 0) { - len = max(len, static_cast(distance(start, it))); + len = max(len, static_cast(distance(start, it)) + 1); } } } From ab4e286337bd412145385c961374a178e6dd2815 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Mar 2016 19:44:36 +0800 Subject: [PATCH 1947/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c1c8ee369..a1f4b66f4 100644 --- a/README.md +++ b/README.md @@ -141,7 +141,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [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 || +32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./C++/longest-valid-parentheses.cpp) [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 || From 1b34ba12c9ac951f1a2993feb1bcf167c8c9bb21 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Mar 2016 21:18:02 +0800 Subject: [PATCH 1948/4971] Create lru-cache.cpp --- C++/lru-cache.cpp | 53 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 C++/lru-cache.cpp diff --git a/C++/lru-cache.cpp b/C++/lru-cache.cpp new file mode 100644 index 000000000..ddbb58b51 --- /dev/null +++ b/C++/lru-cache.cpp @@ -0,0 +1,53 @@ +// Time: O(1), per operation. +// Space: O(c), k is the capacity of cache. + +#include + +class LRUCache { +public: + LRUCache(int capacity) : capa_(capacity) { + } + + int get(int key) { + auto it = map_.find(key); + if (it != map_.end()) { + // It key exists, update it. + auto l_it = it->second; + int value = l_it->second; + update(it, value); + return value; + } else { + return -1; + } + } + + void set(int key, int value) { + auto it = map_.find(key); + // It key exists, update it. + if (it != map_.end()) { + update(it, value); + } else { + // If cache is full, remove the last one. + if (list_.size() == capa_) { + auto del = list_.back(); list_.pop_back(); + map_.erase(del.first); + } + list_.emplace_front(key, value); + map_[key]=list_.begin(); + } + } + +private: + list> list_; // key, value + unordered_map>::iterator> map_; // key, list iterator + int capa_; + + // Update (key, iterator of (key, value)) pair + void update(unordered_map>::iterator>::iterator it, int value) { + auto l_it = it->second; + int key = l_it->first; + list_.erase(l_it); + list_.emplace_front(key, value); + it->second = list_.begin(); + } +}; From 204afe214714c45761a8811fc4b8f1da4bfbcaa1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Mar 2016 21:19:26 +0800 Subject: [PATCH 1949/4971] Update lru-cache.py --- Python/lru-cache.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Python/lru-cache.py b/Python/lru-cache.py index b0aa97aa1..b327f8cdd 100644 --- a/Python/lru-cache.py +++ b/Python/lru-cache.py @@ -1,6 +1,6 @@ -# Time: O(1) -# Space: O(n) -# +# Time: O(1), per operation. +# Space: O(k), k is the capacity of cache. + # Design and implement a data structure for Least Recently Used (LRU) cache. # It should support the following operations: get and set. # @@ -8,7 +8,6 @@ # # set(key, value) - Set or insert the value if the key is not already present. # When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. -# class ListNode: def __init__(self, key, val): @@ -106,4 +105,4 @@ def set(self, key, value): print cache.get(1) cache.set(4, 4) print cache.get(2) - \ No newline at end of file + From 3042ad27bd4f9fb4459b5e49966eb5e5cf918147 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Mar 2016 21:20:06 +0800 Subject: [PATCH 1950/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a1f4b66f4..b2a6f305b 100644 --- a/README.md +++ b/README.md @@ -218,7 +218,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Data Structure # | 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 || +146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [C++](./C++/lru-cache.cpp) [Python](./Python/lru-cache.py) | _O(1)_ | _O(k)_ | 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 From dbb40683c064a0c56368a070ad59b45e831cf718 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Mar 2016 21:20:18 +0800 Subject: [PATCH 1951/4971] Update lru-cache.cpp --- C++/lru-cache.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/lru-cache.cpp b/C++/lru-cache.cpp index ddbb58b51..6e8356873 100644 --- a/C++/lru-cache.cpp +++ b/C++/lru-cache.cpp @@ -1,5 +1,5 @@ // Time: O(1), per operation. -// Space: O(c), k is the capacity of cache. +// Space: O(k), k is the capacity of cache. #include From dfacbb20259e78f37d9d13a6b0b0a9ef80c9cdc3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Mar 2016 22:21:43 +0800 Subject: [PATCH 1952/4971] Update lru-cache.cpp --- C++/lru-cache.cpp | 38 +++++++++++++++----------------------- 1 file changed, 15 insertions(+), 23 deletions(-) diff --git a/C++/lru-cache.cpp b/C++/lru-cache.cpp index 6e8356873..3f7b99884 100644 --- a/C++/lru-cache.cpp +++ b/C++/lru-cache.cpp @@ -1,5 +1,5 @@ // Time: O(1), per operation. -// Space: O(k), k is the capacity of cache. +// Space: O(k), k is capacity of cache. #include @@ -9,12 +9,10 @@ class LRUCache { } int get(int key) { - auto it = map_.find(key); - if (it != map_.end()) { + if (map_.find(key) != map_.end()) { // It key exists, update it. - auto l_it = it->second; - int value = l_it->second; - update(it, value); + const auto value = map_[key]->second; + update(key, value); return value; } else { return -1; @@ -22,19 +20,12 @@ class LRUCache { } void set(int key, int value) { - auto it = map_.find(key); - // It key exists, update it. - if (it != map_.end()) { - update(it, value); - } else { - // If cache is full, remove the last one. - if (list_.size() == capa_) { - auto del = list_.back(); list_.pop_back(); - map_.erase(del.first); - } - list_.emplace_front(key, value); - map_[key]=list_.begin(); + // If cache is full while inserting, remove the last one. + if (map_.find(key) == map_.end() && list_.size() == capa_) { + auto del = list_.back(); list_.pop_back(); + map_.erase(del.first); } + update(key, value); } private: @@ -43,11 +34,12 @@ class LRUCache { int capa_; // Update (key, iterator of (key, value)) pair - void update(unordered_map>::iterator>::iterator it, int value) { - auto l_it = it->second; - int key = l_it->first; - list_.erase(l_it); + void update(int key, int value) { + auto it = map_.find(key); + if (it != map_.end()) { + list_.erase(it->second); + } list_.emplace_front(key, value); - it->second = list_.begin(); + map_[key] = list_.begin(); } }; From e0ba62ba0ee480046eac5a5857ca47b1116fea8f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Mar 2016 22:22:12 +0800 Subject: [PATCH 1953/4971] Update lru-cache.cpp --- C++/lru-cache.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/lru-cache.cpp b/C++/lru-cache.cpp index 3f7b99884..e9fb97680 100644 --- a/C++/lru-cache.cpp +++ b/C++/lru-cache.cpp @@ -1,5 +1,5 @@ // Time: O(1), per operation. -// Space: O(k), k is capacity of cache. +// Space: O(k), k is the capacity of cache. #include From 03fdbf02b73f755f3d93aaf8d35d038b716fb8c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Mar 2016 16:29:26 +0800 Subject: [PATCH 1954/4971] Update and rename simplifyPath.cpp to simplify-path.cpp --- C++/simplify-path.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ C++/simplifyPath.cpp | 34 ---------------------------------- 2 files changed, 42 insertions(+), 34 deletions(-) create mode 100644 C++/simplify-path.cpp delete mode 100644 C++/simplifyPath.cpp diff --git a/C++/simplify-path.cpp b/C++/simplify-path.cpp new file mode 100644 index 000000000..3528b86f0 --- /dev/null +++ b/C++/simplify-path.cpp @@ -0,0 +1,42 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + string simplifyPath(string path) { + vector names; + vector tokens(move(split(path, '/'))); + for (const auto& token : tokens) { + if (token == ".." && !names.empty()) { + names.pop_back(); + } else if (token != ".." && token != "." && !token.empty()) { + names.emplace_back(token); + } + } + return string("/").append(join(names, '/')); + } + +private: + // Split string by delimitor. + vector split(const string& s, const char delim) { + vector tokens; + stringstream ss(s); + string token; + while (getline(ss, token, delim)) { + tokens.emplace_back(token); + } + return tokens; + } + + // Join strings with delimitor. + string join(const vector& names, const char delim) { + ostringstream ss; + if (!names.empty()) { + const string delim_str(1, delim); + copy(names.cbegin(), prev(names.cend()), + ostream_iterator(ss, delim_str.c_str())); + ss << names.back(); + } + return ss.str(); + } +}; diff --git a/C++/simplifyPath.cpp b/C++/simplifyPath.cpp deleted file mode 100644 index 992aafdac..000000000 --- a/C++/simplifyPath.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(n) - -class Solution { - public: - string simplifyPath(string path) { - vector dirs; - - for(auto i = path.cbegin(); i != path.cend();) { - ++i; // write here is to make sure i is not end - - auto j = find(i, path.cend(), '/'); - string dir = string(i, j); - - if(!dir.empty() && dir != ".") { - if(dir == "..") { - if(!dirs.empty()) dirs.pop_back(); - } - else - dirs.push_back(dir); - } - i = j; // i may be end - } - - if(dirs.empty()) return "/"; - - string ans; - for(auto dir : dirs) { - ans.append("/" + dir); - } - - return ans; - } -}; From f0bb3f4270f645d9ad07a1d3cfe85f3caae6788b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Mar 2016 16:30:21 +0800 Subject: [PATCH 1955/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b2a6f305b..6caf992c2 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || 32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./C++/longest-valid-parentheses.cpp) [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 || +71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./C++/simplify-path.cpp) [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 || From d0f0f42f5a5ea92bb7ea919a6b7832b60fb828e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Mar 2016 21:05:26 +0800 Subject: [PATCH 1956/4971] Create symmetric-tree.cpp --- C++/symmetric-tree.cpp | 70 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 C++/symmetric-tree.cpp diff --git a/C++/symmetric-tree.cpp b/C++/symmetric-tree.cpp new file mode 100644 index 000000000..8552214a2 --- /dev/null +++ b/C++/symmetric-tree.cpp @@ -0,0 +1,70 @@ +// Time: O(n) +// Space: O(h), h is the height of the binary tree. + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +# Iterative solution. +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if (!root) { + return true; + } + // isSymmetricHelper(root->left, root->right) + stack nodes; + nodes.emplace(root->left); + nodes.emplace(root->right); + + while (!nodes.empty()) { + auto right = nodes.top(); + nodes.pop(); + auto left = nodes.top(); + nodes.pop(); + if (!left && !right) { + continue; + } + if (!left || !right || left->val != right->val) { + return false; + } + // isSymmetricHelper(left->right, right->left) + nodes.emplace(left->right); + nodes.emplace(right->left); + + // isSymmetricHelper(left->left, right->right) + nodes.emplace(left->left); + nodes.emplace(right->right); + } + return true; + } +}; + + +# Recursive solution. +class Solution2 { +public: + bool isSymmetric(TreeNode* root) { + if (!root) { + return true; + } + return isSymmetricHelper(root->left, root->right); + } + + bool isSymmetricHelper(TreeNode *left, TreeNode *right) { + if (!left && !right) { + return true; + } + if (!left || !right || left->val != right->val) { + return false; + } + return isSymmetricHelper(left->left, right->right) && + isSymmetricHelper(left->right, right->left); + } +}; From b1af8c1624b01f16e475f75e052dd03b9a11f91c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Mar 2016 21:06:04 +0800 Subject: [PATCH 1957/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6caf992c2..c087dadff 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || 32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./C++/longest-valid-parentheses.cpp) [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || 71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./C++/simplify-path.cpp) [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 || +101| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./C++/symmetric-tree.cpp) [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 || From 4b22abaf213415ee6f1da320a4b6cdf1b3c3b306 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Mar 2016 21:06:33 +0800 Subject: [PATCH 1958/4971] Update symmetric-tree.cpp --- C++/symmetric-tree.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/symmetric-tree.cpp b/C++/symmetric-tree.cpp index 8552214a2..22c4a3feb 100644 --- a/C++/symmetric-tree.cpp +++ b/C++/symmetric-tree.cpp @@ -11,7 +11,7 @@ * }; */ -# Iterative solution. +// Iterative solution. class Solution { public: bool isSymmetric(TreeNode* root) { @@ -47,7 +47,7 @@ class Solution { }; -# Recursive solution. +// Recursive solution. class Solution2 { public: bool isSymmetric(TreeNode* root) { From e2cfc6b469091ccaaec7fafaf2dc22eea27db804 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Mar 2016 21:27:51 +0800 Subject: [PATCH 1959/4971] Update and rename evalRPN.cpp to evaluate-reverse-polish-notation.cpp --- C++/evalRPN.cpp | 30 ------------------- C++/evaluate-reverse-polish-notation.cpp | 38 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 30 deletions(-) delete mode 100644 C++/evalRPN.cpp create mode 100644 C++/evaluate-reverse-polish-notation.cpp diff --git a/C++/evalRPN.cpp b/C++/evalRPN.cpp deleted file mode 100644 index 6f04b0e26..000000000 --- a/C++/evalRPN.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// Time Space: O(n) -// Space Space: O(logn) - -class Solution { - public: - int evalRPN(vector &tokens) { - stack s; - for(auto tok : tokens) { - if(!is_operator(tok)) { - s.push(tok); - } - else { - int y = stoi(s.top()); - s.pop(); - int x = stoi(s.top()); - s.pop(); - if(tok[0] == '+') x += y; - else if (tok[0] == '-') x -= y; - else if (tok[0] == '*') x *= y; - else x /= y; - s.push(to_string(x)); - } - } - return stoi(s.top()); - } - private: - bool is_operator(const string &op) { - return op.length() == 1 && string("+-*/").find(op) != string::npos; - } -}; diff --git a/C++/evaluate-reverse-polish-notation.cpp b/C++/evaluate-reverse-polish-notation.cpp new file mode 100644 index 000000000..d3944c664 --- /dev/null +++ b/C++/evaluate-reverse-polish-notation.cpp @@ -0,0 +1,38 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int evalRPN(vector& tokens) { + if (tokens.empty()) { + return 0; + } + stack s; + for (const auto& tok : tokens) { + if (!is_operator(tok)) { + s.emplace(tok); + } else { + auto y = stoi(s.top()); + s.pop(); + auto x = stoi(s.top()); + s.pop(); + if (tok[0] == '+') { + x += y; + } else if (tok[0] == '-') { + x -= y; + } else if (tok[0] == '*') { + x *= y; + } else { + x /= y; + } + s.emplace(to_string(x)); + } + } + return stoi(s.top()); + } + +private: + bool is_operator(const string &op) { + return op.length() == 1 && string("+-*/").find(op) != string::npos; + } +}; From b4e15ab82e10191af96f0d321881296ff6694fa6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Mar 2016 21:28:32 +0800 Subject: [PATCH 1960/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c087dadff..7803a14a6 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./C++/longest-valid-parentheses.cpp) [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || 71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./C++/simplify-path.cpp) [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || 101| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./C++/symmetric-tree.cpp) [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 || +150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [C++](./C++/evaluate-reverse-polish-notation.cpp) [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 || From 360efba0c210e91efbebcf85f36927b5cb850280 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Mar 2016 21:29:06 +0800 Subject: [PATCH 1961/4971] Update evaluate-reverse-polish-notation.cpp --- C++/evaluate-reverse-polish-notation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/evaluate-reverse-polish-notation.cpp b/C++/evaluate-reverse-polish-notation.cpp index d3944c664..c24c82169 100644 --- a/C++/evaluate-reverse-polish-notation.cpp +++ b/C++/evaluate-reverse-polish-notation.cpp @@ -32,7 +32,7 @@ class Solution { } private: - bool is_operator(const string &op) { + bool is_operator(const string& op) { return op.length() == 1 && string("+-*/").find(op) != string::npos; } }; From d9bd5dcde5b0b753dfcca79bee085ecec16580ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Mar 2016 21:20:10 +0800 Subject: [PATCH 1962/4971] Create nested-list-weight-sum.cpp --- C++/nested-list-weight-sum.cpp | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/nested-list-weight-sum.cpp diff --git a/C++/nested-list-weight-sum.cpp b/C++/nested-list-weight-sum.cpp new file mode 100644 index 000000000..0a58943f3 --- /dev/null +++ b/C++/nested-list-weight-sum.cpp @@ -0,0 +1,39 @@ +// Time: O(n) +// Space: O(h) + +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ +class Solution { +public: + int depthSum(vector& nestedList) { + return depthSumHelper(nestedList, 1); + } + +private: + int depthSumHelper(const vector& nestedList, int depth) { + int sum = 0; + for (const auto& list : nestedList) { + if (list.isInteger()) { + sum += list.getInteger() * depth; + } else { + sum += depthSumHelper(list.getList(), depth + 1); + } + } + return sum; + } +}; From 6db8e963f5c6bf4f7abb21876a3fdcef3a594b2d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Mar 2016 21:26:10 +0800 Subject: [PATCH 1963/4971] Create nested-list-weight-sum.cpp --- Python/nested-list-weight-sum.cpp | 43 +++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/nested-list-weight-sum.cpp diff --git a/Python/nested-list-weight-sum.cpp b/Python/nested-list-weight-sum.cpp new file mode 100644 index 000000000..f014799e1 --- /dev/null +++ b/Python/nested-list-weight-sum.cpp @@ -0,0 +1,43 @@ +# Time: O(n) +# Space: O(h) + +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger(object): +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ + +class Solution(object): + def depthSum(self, nestedList): + """ + :type nestedList: List[NestedInteger] + :rtype: int + """ + def depthSumHelper(nestedList, depth): + res = 0 + for l in nestedList: + if l.isInteger(): + res += l.getInteger() * depth + else: + res += depthSumHelper(l.getList(), depth + 1) + return res + return depthSumHelper(nestedList, 1) From c9b8657dce797d3d5b78bc83818e5b4c4223ad9a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Mar 2016 21:26:27 +0800 Subject: [PATCH 1964/4971] Rename nested-list-weight-sum.cpp to nested-list-weight-sum.py --- Python/{nested-list-weight-sum.cpp => nested-list-weight-sum.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{nested-list-weight-sum.cpp => nested-list-weight-sum.py} (100%) diff --git a/Python/nested-list-weight-sum.cpp b/Python/nested-list-weight-sum.py similarity index 100% rename from Python/nested-list-weight-sum.cpp rename to Python/nested-list-weight-sum.py From 9b5997b5aa8e924fe916ee9e2d47fd8b23c10d72 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Mar 2016 21:33:40 +0800 Subject: [PATCH 1965/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7803a14a6..0d60f6d62 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-338%20%2F%20338-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-339%20%2F%20339-ff69b4.svg) -Up to date (2016-03-17), there are `321` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-03-30), there are `322` 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 `338` questions. +Here is the classification of all `339` 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. ) @@ -365,6 +365,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 ||| +339| [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) | [C++](./C++/nested-list-weight-sum.cpp) [Python](./Python/nested-list-weight-sum.py) | _O(n)_ | _O(h)_ | Easy |📖|| ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note From 685bbd32c0cf913f553ac843cfb0f5063d7236bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Mar 2016 21:50:19 +0800 Subject: [PATCH 1966/4971] 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 b93946378..9e66eca21 100644 --- a/C++/walls-and-gates.cpp +++ b/C++/walls-and-gates.cpp @@ -9,7 +9,7 @@ class Solution { for (int i = 0; i < rooms.size(); ++i) { for (int j = 0; j < rooms[0].size(); ++j) { if (rooms[i][j] == 0) { - q.emplace(make_pair(i, j)); + q.emplace(i, j); } } } @@ -26,7 +26,7 @@ class Solution { J >= 0 && J < rooms[0].size() && rooms[I][J] == INF) { rooms[I][J] = rooms[i][j] + 1; - q.emplace(make_pair(I, J)); + q.emplace(I, J); } } } From 99495572b971324d4798e109a8132dfc14fc8cfe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 31 Mar 2016 21:51:34 +0800 Subject: [PATCH 1967/4971] Create min-stack.cpp --- C++/min-stack.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 C++/min-stack.cpp diff --git a/C++/min-stack.cpp b/C++/min-stack.cpp new file mode 100644 index 000000000..3b5c5c034 --- /dev/null +++ b/C++/min-stack.cpp @@ -0,0 +1,41 @@ +// Time: O(n) +// Space: O(n) + +class MinStack { +public: + void push(int number) { + if (cached_min_with_count_.empty() || cached_min_with_count_.top().first > number) { + cached_min_with_count_.emplace(number, 1); + } else if (cached_min_with_count_.top().first == number) { + ++cached_min_with_count_.top().second; + } + elements_.emplace(number); + } + + void pop() { + if (!elements_.empty()) { + if (!cached_min_with_count_.empty() && + cached_min_with_count_.top().first == elements_.top()) { + if (--cached_min_with_count_.top().second == 0) { + cached_min_with_count_.pop(); + } + } + auto number = elements_.top(); + elements_.pop(); + } + } + + int top() { + return elements_.top(); + } + + int getMin() { + if (!cached_min_with_count_.empty()) { + return cached_min_with_count_.top().first; + } + } + +private: + stack elements_; + stack> cached_min_with_count_; +}; From 4bad0571aeba4937672b3435ea0a205b8344a76e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 31 Mar 2016 23:45:53 +0800 Subject: [PATCH 1968/4971] Update min-stack.cpp --- C++/min-stack.cpp | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/C++/min-stack.cpp b/C++/min-stack.cpp index 3b5c5c034..ede5da4a5 100644 --- a/C++/min-stack.cpp +++ b/C++/min-stack.cpp @@ -1,7 +1,49 @@ // Time: O(n) -// Space: O(n) +// Space: O(1) class MinStack { +public: + void push(int number) { + if (elements_.empty()) { + elements_.emplace(0); + stack_min_ = number; + } else { + elements_.emplace(static_cast(number) - stack_min_); + if (number < stack_min_) { + stack_min_ = number; // Update min. + } + } + } + + void pop() { + auto diff = elements_.top(); + elements_.pop(); + if (diff < 0) { + stack_min_ -= diff; // Restore previous min. + } + } + + int top() { + if (elements_.top() > 0) { + return stack_min_ + elements_.top(); + } else { + return stack_min_; + } + } + + int getMin() { + return stack_min_; + } + +private: + stack elements_; + int stack_min_; +}; + + +// Time: O(n) +// Space: O(n) +class MinStack2 { public: void push(int number) { if (cached_min_with_count_.empty() || cached_min_with_count_.top().first > number) { From 0b75c89c1df7203de26a6af591986bb56f0f6dd7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 31 Mar 2016 23:49:59 +0800 Subject: [PATCH 1969/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0d60f6d62..a69ebfa3c 100644 --- a/README.md +++ b/README.md @@ -145,7 +145,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./C++/simplify-path.cpp) [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || 101| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./C++/symmetric-tree.cpp) [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || 150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [C++](./C++/evaluate-reverse-polish-notation.cpp) [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 || +155| [Min Stack](https://leetcode.com/problems/min-stack/) | [C++](./C++/min-stack.cpp) [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 || 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 27bbec5c77018f9d7f191ce025b2f738a9f6462f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Apr 2016 11:30:58 -0500 Subject: [PATCH 1970/4971] Create binary-tree-inorder-traversal.cpp --- C++/binary-tree-inorder-traversal.cpp | 41 +++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 C++/binary-tree-inorder-traversal.cpp diff --git a/C++/binary-tree-inorder-traversal.cpp b/C++/binary-tree-inorder-traversal.cpp new file mode 100644 index 000000000..2555c18fd --- /dev/null +++ b/C++/binary-tree-inorder-traversal.cpp @@ -0,0 +1,41 @@ +// 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: + vector inorderTraversal(TreeNode* root) { + vector res; + TreeNode *prev = nullptr; + TreeNode *curr = root; + while (curr) { + if (!curr->left) { + res.emplace_back(curr->val); + prev = curr; + curr = curr->right; + } else { + TreeNode *node = curr->left; + while (node->right && node->right != curr) { + node = node->right; + } + if (!node->right) { + node->right = curr; + curr = curr->left; + } else { + res.emplace_back(curr->val); + prev = curr; + node->right = nullptr; + curr = curr->right; + } + } + } + return res; + } +}; From 44b1ff29eadcce176968966b3a234bd44f078ccd Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Apr 2016 11:31:37 -0500 Subject: [PATCH 1971/4971] Update binary-tree-inorder-traversal.cpp --- C++/binary-tree-inorder-traversal.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/binary-tree-inorder-traversal.cpp b/C++/binary-tree-inorder-traversal.cpp index 2555c18fd..53cb9393e 100644 --- a/C++/binary-tree-inorder-traversal.cpp +++ b/C++/binary-tree-inorder-traversal.cpp @@ -1,5 +1,6 @@ // Time: O(n) // Space: O(1) + /** * Definition for a binary tree node. * struct TreeNode { From c1f47fe5f2f91bb380d8e861c702eadb9ada695b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 Apr 2016 20:32:43 +0900 Subject: [PATCH 1972/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a69ebfa3c..b82fe6b44 100644 --- a/README.md +++ b/README.md @@ -171,7 +171,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Tree # | 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` | +94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C++](./C++/binary-tree-inorder-traversal.cpp) [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` From 9753724e42f2c4a2b366d249247ab26f4b2f3750 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Apr 2016 13:04:42 +0900 Subject: [PATCH 1973/4971] Create longest-substring-with-at-most-k-distinct-characters.py --- ...ring-with-at-most-k-distinct-characters.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/longest-substring-with-at-most-k-distinct-characters.py diff --git a/Python/longest-substring-with-at-most-k-distinct-characters.py b/Python/longest-substring-with-at-most-k-distinct-characters.py new file mode 100644 index 000000000..a5f6d0c45 --- /dev/null +++ b/Python/longest-substring-with-at-most-k-distinct-characters.py @@ -0,0 +1,24 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def lengthOfLongestSubstringKDistinct(self, s, k): + """ + :type s: str + :type k: int + :rtype: int + """ + longest, start, distinct_count, visited = 0, 0, 0, [0 for _ in xrange(256)] + for i, char in enumerate(s): + if visited[ord(char)] == 0: + distinct_count += 1 + visited[ord(char)] += 1 + + while distinct_count > k: + visited[ord(s[start])] -= 1 + if visited[ord(s[start])] == 0: + distinct_count -= 1 + start += 1 + + longest = max(longest, i - start + 1) + return longest From e253505ca05b4de3b8f5cdad35f86d74650993b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Apr 2016 15:18:12 +0900 Subject: [PATCH 1974/4971] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b82fe6b44..f4fa89165 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-339%20%2F%20339-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-340%20%2F%20340-ff69b4.svg) -Up to date (2016-03-30), there are `322` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-04-03), there are `323` 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 `339` questions. +Here is the classification of all `340` 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 2c2bb2b52f5aef35154852533236776f6db14506 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Apr 2016 23:34:41 +0800 Subject: [PATCH 1975/4971] Create longest-substring-with-at-most-k-distinct-characters.cpp --- ...ing-with-at-most-k-distinct-characters.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/longest-substring-with-at-most-k-distinct-characters.cpp diff --git a/C++/longest-substring-with-at-most-k-distinct-characters.cpp b/C++/longest-substring-with-at-most-k-distinct-characters.cpp new file mode 100644 index 000000000..c9ce78198 --- /dev/null +++ b/C++/longest-substring-with-at-most-k-distinct-characters.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int lengthOfLongestSubstringKDistinct(string s, int k) { + int longest = 0, start = 0, distinct_count = 0; + array visited = {0}; + for (int i = 0; i < s.length(); ++i) { + if (visited[s[i]] == 0) { + ++distinct_count; + } + ++visited[s[i]]; + while (distinct_count > k) { + --visited[s[start]]; + if (visited[s[start]] == 0) { + --distinct_count; + } + ++start; + } + longest = max(longest, i - start + 1); + } + return longest; + } +}; From 8557c22340b49c1577147eed64bfcc30448cd3c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Apr 2016 23:38:07 +0800 Subject: [PATCH 1976/4971] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f4fa89165..4a3b7e3f5 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 |📖| +159| [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [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/) | [C++](./C++/happy-number.cpp) [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || @@ -214,6 +214,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | | | +340| [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-k-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note From 5c8b4675e6fda6eab4adb47eda8b68730c8e7f51 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Apr 2016 23:39:11 +0800 Subject: [PATCH 1977/4971] Update longest-substring-with-at-most-k-distinct-characters.py --- Python/longest-substring-with-at-most-k-distinct-characters.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/longest-substring-with-at-most-k-distinct-characters.py b/Python/longest-substring-with-at-most-k-distinct-characters.py index a5f6d0c45..ac38072cb 100644 --- a/Python/longest-substring-with-at-most-k-distinct-characters.py +++ b/Python/longest-substring-with-at-most-k-distinct-characters.py @@ -1,4 +1,4 @@ -# Time: O(n) +# Time: O(n^2) # Space: O(1) class Solution(object): From 9ef425adc683b173b34880e692177e6a35c89b70 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Apr 2016 23:40:35 +0800 Subject: [PATCH 1978/4971] Update longest-substring-with-at-most-k-distinct-characters.py --- Python/longest-substring-with-at-most-k-distinct-characters.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/longest-substring-with-at-most-k-distinct-characters.py b/Python/longest-substring-with-at-most-k-distinct-characters.py index ac38072cb..a5f6d0c45 100644 --- a/Python/longest-substring-with-at-most-k-distinct-characters.py +++ b/Python/longest-substring-with-at-most-k-distinct-characters.py @@ -1,4 +1,4 @@ -# Time: O(n^2) +# Time: O(n) # Space: O(1) class Solution(object): From bb87056abc6c2cb304dff585d058d10001fa6908 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Apr 2016 23:41:15 +0800 Subject: [PATCH 1979/4971] Update longest-substring-with-at-most-two-distinct-characters.py --- .../longest-substring-with-at-most-two-distinct-characters.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/longest-substring-with-at-most-two-distinct-characters.py b/Python/longest-substring-with-at-most-two-distinct-characters.py index 6ffc113c2..3a58b3024 100644 --- a/Python/longest-substring-with-at-most-two-distinct-characters.py +++ b/Python/longest-substring-with-at-most-two-distinct-characters.py @@ -1,4 +1,4 @@ -# Time: O(n^2) +# Time: O(n) # Space: O(1) # # Given a string, find the length of the longest substring T @@ -29,4 +29,4 @@ def lengthOfLongestSubstringTwoDistinct(self, s): return longest if __name__ == "__main__": - print Solution().lengthOfLongestSubstringTwoDistinct("eceba") \ No newline at end of file + print Solution().lengthOfLongestSubstringTwoDistinct("eceba") From 891bdfc7473545c0a84f12252205463736e9e089 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Apr 2016 23:41:51 +0800 Subject: [PATCH 1980/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4a3b7e3f5..360384bfe 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| +159| [Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _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/) | [C++](./C++/happy-number.cpp) [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || @@ -214,7 +214,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | | | -340| [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-k-distinct-characters.py) | _O(n^2)_ | _O(1)_ | Hard |📖| +340| [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-k-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note From 5aed9e6c3a7ea321aa4287c394d581a24f4955ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Apr 2016 23:44:27 +0800 Subject: [PATCH 1981/4971] Create longest-substring-with-at-most-two-distinct-characters.cpp --- ...g-with-at-most-two-distinct-characters.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/longest-substring-with-at-most-two-distinct-characters.cpp diff --git a/C++/longest-substring-with-at-most-two-distinct-characters.cpp b/C++/longest-substring-with-at-most-two-distinct-characters.cpp new file mode 100644 index 000000000..d4eb2484c --- /dev/null +++ b/C++/longest-substring-with-at-most-two-distinct-characters.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int lengthOfLongestSubstringTwoDistinct(string s) { + const int k = 2; + int longest = 0, start = 0, distinct_count = 0; + array visited = {0}; + for (int i = 0; i < s.length(); ++i) { + if (visited[s[i]] == 0) { + ++distinct_count; + } + ++visited[s[i]]; + while (distinct_count > k) { + --visited[s[start]]; + if (visited[s[start]] == 0) { + --distinct_count; + } + ++start; + } + longest = max(longest, i - start + 1); + } + return longest; + } +}; From a01376934882869c335d4987daae34c11b397fd2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 13:38:04 +0900 Subject: [PATCH 1982/4971] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 360384bfe..73393f135 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-340%20%2F%20340-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-340%20%2F%20341-ff69b4.svg) -Up to date (2016-04-03), there are `323` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-04-05), there are `324` 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 `340` questions. +Here is the classification of all `341` 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 5a4c54f6cbbca168ef12c324c507c0247a648b9b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 20:18:57 +0800 Subject: [PATCH 1983/4971] Create flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 59 ++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 C++/flatten-nested-list-iterator.cpp diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp new file mode 100644 index 000000000..63424fba0 --- /dev/null +++ b/C++/flatten-nested-list-iterator.cpp @@ -0,0 +1,59 @@ +// Time: O(n) +// Space: O(n) + +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ +class NestedIterator { +public: + NestedIterator(vector &nestedList) { + for (int i = static_cast(nestedList.size()) - 1; i >= 0; --i) { + nodes_.push(&nestedList[i]); + } + } + + int next() { + int result = nodes_.top()->getInteger(); + nodes_.pop(); + return result; + } + + bool hasNext() { + while(!nodes_.empty()) { + auto *cur = nodes_.top(); + if (cur->isInteger()) { + return true; + } + nodes_.pop(); + auto& children = cur->getList(); + for (int i = static_cast(children.size()) - 1; i >= 0; --i) { + nodes_.push(&children[i]); + } + } + return false; + } +private: + stack nodes_; +}; + + +/** + * Your NestedIterator object will be instantiated and called as such: + * NestedIterator i(nestedList); + * while (i.hasNext()) cout << i.next(); + */ + From 7a93c8536c49b34db60cb55a0cabd6f2d58dd4c8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 20:23:20 +0800 Subject: [PATCH 1984/4971] Update flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp index 63424fba0..f6bc264a4 100644 --- a/C++/flatten-nested-list-iterator.cpp +++ b/C++/flatten-nested-list-iterator.cpp @@ -22,18 +22,18 @@ class NestedIterator { public: NestedIterator(vector &nestedList) { for (int i = static_cast(nestedList.size()) - 1; i >= 0; --i) { - nodes_.push(&nestedList[i]); + nodes_.emplace(&nestedList[i]); } } int next() { - int result = nodes_.top()->getInteger(); + auto result = nodes_.top()->getInteger(); nodes_.pop(); return result; } bool hasNext() { - while(!nodes_.empty()) { + while (!nodes_.empty()) { auto *cur = nodes_.top(); if (cur->isInteger()) { return true; @@ -41,11 +41,12 @@ class NestedIterator { nodes_.pop(); auto& children = cur->getList(); for (int i = static_cast(children.size()) - 1; i >= 0; --i) { - nodes_.push(&children[i]); + nodes_.emplace(&children[i]); } } return false; } + private: stack nodes_; }; From acf19fcd927d828f98a423695b5ff56a39c76bb5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 20:37:02 +0800 Subject: [PATCH 1985/4971] Update flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 36 +++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp index f6bc264a4..0ab79e210 100644 --- a/C++/flatten-nested-list-iterator.cpp +++ b/C++/flatten-nested-list-iterator.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(n) +// Space: O(1) /** * // This is the interface that allows for creating nested lists. @@ -19,6 +19,40 @@ * }; */ class NestedIterator { +public: + using IT = vector::iterator; + NestedIterator(vector &nestedList) { + nodes_.emplace(nestedList.begin(), nestedList.end()); + } + + int next() { + const auto result = nodes_.top().first->getInteger(); + ++nodes_.top().first; + return result; + } + + bool hasNext() { + while (!nodes_.empty()) { + auto& cur = nodes_.top(); + if (cur.first == cur.second) { + nodes_.pop(); + } else if (cur.first->isInteger()) { + return true; + } else { + auto& nestedList = cur.first->getList(); + ++cur.first; + nodes_.emplace(nestedList.begin(), nestedList.end()); + } + } + return false; + } +private: + stack> nodes_; +}; + +// Time: O(n) +// Space: O(n) +class NestedIterator2 { public: NestedIterator(vector &nestedList) { for (int i = static_cast(nestedList.size()) - 1; i >= 0; --i) { From 73af582885a88b29e0a0f436cbdb17ba4dbb955b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 20:38:26 +0800 Subject: [PATCH 1986/4971] Update flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp index 0ab79e210..8e5989b0a 100644 --- a/C++/flatten-nested-list-iterator.cpp +++ b/C++/flatten-nested-list-iterator.cpp @@ -18,6 +18,8 @@ * const vector &getList() const; * }; */ + + // Using stack and iterator. class NestedIterator { public: using IT = vector::iterator; @@ -52,6 +54,7 @@ class NestedIterator { // Time: O(n) // Space: O(n) +// Using stack. class NestedIterator2 { public: NestedIterator(vector &nestedList) { From 383102f20632b51890ff96a7460e5fb1d9d0b476 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 20:39:08 +0800 Subject: [PATCH 1987/4971] Update flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp index 8e5989b0a..5a209566e 100644 --- a/C++/flatten-nested-list-iterator.cpp +++ b/C++/flatten-nested-list-iterator.cpp @@ -1,5 +1,5 @@ -// Time: O(n) -// Space: O(1) +// Time: O(n), n is the number of the integers. +// Space: O(l), l is the number of the nested lists. /** * // This is the interface that allows for creating nested lists. From 4fcd04eb58dd4c7d6476b1f301dd5700a7947216 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 20:39:43 +0800 Subject: [PATCH 1988/4971] Update flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp index 5a209566e..3d5352f32 100644 --- a/C++/flatten-nested-list-iterator.cpp +++ b/C++/flatten-nested-list-iterator.cpp @@ -48,6 +48,7 @@ class NestedIterator { } return false; } + private: stack> nodes_; }; From 52d90243316325a3452c740d1f548c85983db120 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 21:25:18 +0800 Subject: [PATCH 1989/4971] Create flatten-nested-list-iterator.py --- Python/flatten-nested-list-iterator.py | 63 ++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Python/flatten-nested-list-iterator.py diff --git a/Python/flatten-nested-list-iterator.py b/Python/flatten-nested-list-iterator.py new file mode 100644 index 000000000..3d0749a91 --- /dev/null +++ b/Python/flatten-nested-list-iterator.py @@ -0,0 +1,63 @@ +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger(object): +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ + +class NestedIterator(object): + + def __init__(self, nestedList): + """ + Initialize your data structure here. + :type nestedList: List[NestedInteger] + """ + self.__nodes = [[nestedList, 0]] + + + def next(self): + """ + :rtype: int + """ + nestedList, i = self.__nodes[-1] + self.__nodes[-1][1] += 1 + return nestedList[i].getInteger() + + + def hasNext(self): + """ + :rtype: bool + """ + while self.__nodes: + nestedList, i = self.__nodes[-1] + if i == len(nestedList): + self.__nodes.pop() + elif nestedList[i].isInteger(): + return True + else: + self.__nodes[-1][1] += 1 + self.__nodes.append([nestedList[i].getList(), 0]) + return False + + +# Your NestedIterator object will be instantiated and called as such: +# i, v = NestedIterator(nestedList), [] +# while i.hasNext(): v.append(i.next()) From 84d94ebb1335390afc42b848b3e951be7daed746 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 21:26:57 +0800 Subject: [PATCH 1990/4971] Update flatten-nested-list-iterator.py --- Python/flatten-nested-list-iterator.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/flatten-nested-list-iterator.py b/Python/flatten-nested-list-iterator.py index 3d0749a91..09fa01c7d 100644 --- a/Python/flatten-nested-list-iterator.py +++ b/Python/flatten-nested-list-iterator.py @@ -1,3 +1,6 @@ +# Time: O(n), n is the number of the integers. +# Space: O(l), l is the number of the nested lists. + # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation From 8ff3d02478e45ee7846e57e25637b8f37de2a23d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 21:28:53 +0800 Subject: [PATCH 1991/4971] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 73393f135..2e6387695 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-340%20%2F%20341-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-341%20%2F%20341-ff69b4.svg) Up to date (2016-04-05), there are `324` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. @@ -153,6 +153,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 ||| +341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(l)_ | Medium |📖|| ## Queue # | Title | Solution | Time | Space | Difficulty | Tag | Note From 099ea59bd564ce16330f62a940c68f6cac97b7bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 21:39:14 +0800 Subject: [PATCH 1992/4971] Update flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp index 3d5352f32..97e1f78fc 100644 --- a/C++/flatten-nested-list-iterator.cpp +++ b/C++/flatten-nested-list-iterator.cpp @@ -28,9 +28,7 @@ class NestedIterator { } int next() { - const auto result = nodes_.top().first->getInteger(); - ++nodes_.top().first; - return result; + return (nodes_.top().first++)->getInteger(); } bool hasNext() { @@ -58,7 +56,7 @@ class NestedIterator { // Using stack. class NestedIterator2 { public: - NestedIterator(vector &nestedList) { + NestedIterator2(vector &nestedList) { for (int i = static_cast(nestedList.size()) - 1; i >= 0; --i) { nodes_.emplace(&nestedList[i]); } From 85d5d5751ad38631a217679f40bfd359b326a947 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 21:40:51 +0800 Subject: [PATCH 1993/4971] Update flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp index 97e1f78fc..ac4d57acc 100644 --- a/C++/flatten-nested-list-iterator.cpp +++ b/C++/flatten-nested-list-iterator.cpp @@ -19,12 +19,12 @@ * }; */ - // Using stack and iterator. +// Using stack and iterator. class NestedIterator { public: - using IT = vector::iterator; + using IT = vector::const_iterator; NestedIterator(vector &nestedList) { - nodes_.emplace(nestedList.begin(), nestedList.end()); + nodes_.emplace(nestedList.cbegin(), nestedList.cend()); } int next() { @@ -41,7 +41,7 @@ class NestedIterator { } else { auto& nestedList = cur.first->getList(); ++cur.first; - nodes_.emplace(nestedList.begin(), nestedList.end()); + nodes_.emplace(nestedList.cbegin(), nestedList.cend()); } } return false; From fd4b3d45f69e61519064dd8d9e2d365e919aa8a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 23:21:00 +0900 Subject: [PATCH 1994/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e6387695..d30bfa732 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 ||| -341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(l)_ | Medium |📖|| +341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(h)_ | Medium |📖|| ## Queue # | Title | Solution | Time | Space | Difficulty | Tag | Note From 19b91e417a33c1ae0a381ceef7b0d459da4ca2a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 23:22:10 +0900 Subject: [PATCH 1995/4971] Update flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp index ac4d57acc..782220913 100644 --- a/C++/flatten-nested-list-iterator.cpp +++ b/C++/flatten-nested-list-iterator.cpp @@ -1,5 +1,5 @@ // Time: O(n), n is the number of the integers. -// Space: O(l), l is the number of the nested lists. +// Space: O(h), h is the depth of the nested lists. /** * // This is the interface that allows for creating nested lists. From f565f7702c562b0db7e45e67163110b3bbee8cf9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 23:23:16 +0900 Subject: [PATCH 1996/4971] Update flatten-nested-list-iterator.py --- Python/flatten-nested-list-iterator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/flatten-nested-list-iterator.py b/Python/flatten-nested-list-iterator.py index 09fa01c7d..843c3ca8f 100644 --- a/Python/flatten-nested-list-iterator.py +++ b/Python/flatten-nested-list-iterator.py @@ -1,5 +1,5 @@ # Time: O(n), n is the number of the integers. -# Space: O(l), l is the number of the nested lists. +# Space: O(h), h is the depth of the nested lists. # """ # This is the interface that allows for creating nested lists. From cee2fe2b71bc2e9d4826e5c0afde3b62f24fedc8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 22:25:28 +0800 Subject: [PATCH 1997/4971] Update flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp index 782220913..3ac4b7bc1 100644 --- a/C++/flatten-nested-list-iterator.cpp +++ b/C++/flatten-nested-list-iterator.cpp @@ -24,31 +24,31 @@ class NestedIterator { public: using IT = vector::const_iterator; NestedIterator(vector &nestedList) { - nodes_.emplace(nestedList.cbegin(), nestedList.cend()); + depth_.emplace(nestedList.cbegin(), nestedList.cend()); } int next() { - return (nodes_.top().first++)->getInteger(); + return (depth_.top().first++)->getInteger(); } bool hasNext() { - while (!nodes_.empty()) { - auto& cur = nodes_.top(); + while (!depth_.empty()) { + auto& cur = depth_.top(); if (cur.first == cur.second) { - nodes_.pop(); + depth_.pop(); } else if (cur.first->isInteger()) { return true; } else { auto& nestedList = cur.first->getList(); ++cur.first; - nodes_.emplace(nestedList.cbegin(), nestedList.cend()); + depth_.emplace(nestedList.cbegin(), nestedList.cend()); } } return false; } private: - stack> nodes_; + stack> depth_; }; // Time: O(n) From 92ebc08b87a4c263b9a461045b75acfe0f31e7d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Apr 2016 22:26:38 +0800 Subject: [PATCH 1998/4971] Update flatten-nested-list-iterator.py --- Python/flatten-nested-list-iterator.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Python/flatten-nested-list-iterator.py b/Python/flatten-nested-list-iterator.py index 843c3ca8f..e9646fb69 100644 --- a/Python/flatten-nested-list-iterator.py +++ b/Python/flatten-nested-list-iterator.py @@ -33,15 +33,15 @@ def __init__(self, nestedList): Initialize your data structure here. :type nestedList: List[NestedInteger] """ - self.__nodes = [[nestedList, 0]] + self.__depth = [[nestedList, 0]] def next(self): """ :rtype: int """ - nestedList, i = self.__nodes[-1] - self.__nodes[-1][1] += 1 + nestedList, i = self.__depth[-1] + self.__depth[-1][1] += 1 return nestedList[i].getInteger() @@ -49,15 +49,15 @@ def hasNext(self): """ :rtype: bool """ - while self.__nodes: - nestedList, i = self.__nodes[-1] + while self.__depth: + nestedList, i = self.__depth[-1] if i == len(nestedList): - self.__nodes.pop() + self.__depth.pop() elif nestedList[i].isInteger(): return True else: - self.__nodes[-1][1] += 1 - self.__nodes.append([nestedList[i].getList(), 0]) + self.__depth[-1][1] += 1 + self.__depth.append([nestedList[i].getList(), 0]) return False From cf7317ce2ea520f0a9e5884c880f042af88f116c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Apr 2016 17:04:17 +0900 Subject: [PATCH 1999/4971] Update flatten-nested-list-iterator.cpp --- C++/flatten-nested-list-iterator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flatten-nested-list-iterator.cpp b/C++/flatten-nested-list-iterator.cpp index 3ac4b7bc1..951d80c3a 100644 --- a/C++/flatten-nested-list-iterator.cpp +++ b/C++/flatten-nested-list-iterator.cpp @@ -63,7 +63,7 @@ class NestedIterator2 { } int next() { - auto result = nodes_.top()->getInteger(); + const auto result = nodes_.top()->getInteger(); nodes_.pop(); return result; } From 4bd50accf73180ca52b4eb1081f10469e66ca346 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Apr 2016 17:59:43 +0900 Subject: [PATCH 2000/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d30bfa732..6f2643225 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 ||| -341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(h)_ | Medium |📖|| +341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(h)_ | Medium |📖| Iterator | ## Queue # | Title | Solution | Time | Space | Difficulty | Tag | Note From 3262f938863a56877d5fd52584cfd7dc479a1a17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Apr 2016 21:17:57 +0800 Subject: [PATCH 2001/4971] Update and rename recoverTree.cpp to recover-binary-search-tree.cpp --- C++/recover-binary-search-tree.cpp | 59 +++++++++++++++++++++++ C++/recoverTree.cpp | 76 ------------------------------ 2 files changed, 59 insertions(+), 76 deletions(-) create mode 100644 C++/recover-binary-search-tree.cpp delete mode 100644 C++/recoverTree.cpp diff --git a/C++/recover-binary-search-tree.cpp b/C++/recover-binary-search-tree.cpp new file mode 100644 index 000000000..b0b9105f4 --- /dev/null +++ b/C++/recover-binary-search-tree.cpp @@ -0,0 +1,59 @@ +// Time: O(n) +// Space: O(1) + +/** + * Definition for binary tree + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + void recoverTree(TreeNode *root) { + MorrisTraversal(root); + } + +private: + void MorrisTraversal(TreeNode *root) { + if (!root) { + return; + } + pair broken; + TreeNode *prev = nullptr; + TreeNode *cur = root; + while (cur) { + if (!cur->left) { + detect(prev, cur, &broken); + prev = cur; + cur = cur->right; + } else { + TreeNode *node = cur->left; + while (node->right && node->right != cur) { + node = node->right; + } + if (!node->right) { + node->right = cur; + cur = cur->left; + } else { + detect(prev, cur, &broken); + prev = cur; + node->right = nullptr; + cur = cur->right; + } + } + } + swap(broken.first->val, broken.second->val); + } + + void detect(TreeNode *prev, TreeNode *cur, pair *broken) { + if (prev && prev->val > cur->val) { + if (!broken->first) { // Find the first broken node. + broken->first = prev; + } + broken->second = cur; // Find the last broken node. + } + } +}; diff --git a/C++/recoverTree.cpp b/C++/recoverTree.cpp deleted file mode 100644 index a260f5329..000000000 --- a/C++/recoverTree.cpp +++ /dev/null @@ -1,76 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -/** - * Definition for binary tree - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - public: - void recoverTree(TreeNode *root) { - MorrisTraversal(root); - } - - private: - /* Function to traverse binary tree without recursion and - without stack */ - void MorrisTraversal(TreeNode *root) - { - if(root == NULL) - return; - - pair broken; - TreeNode *cur = root; - TreeNode *pre = NULL; - - while(cur != NULL) - { - if(cur->left == NULL) - { - detect(broken, pre, cur); - pre = cur; - cur = cur->right; - } - else - { - /* Find the inorder predecessor of current */ - auto node = cur->left; - while(node->right != NULL && node->right != cur) - node = node->right; - - /* Make current as right child of its inorder predecessor */ - if(node->right == NULL) - { - node->right = cur; - cur = cur->left; - } - - /* Revert the changes made in if part to restore the original - tree i.e., fix the right child of predecssor */ - else - { - detect(broken, pre, cur); - node->right = NULL; - pre = cur; - cur = cur->right; - } - } - } - - swap(broken.first->val, broken.second->val); // swap the fist and the last broken node - } - - void detect(pair &broken, TreeNode *pre, TreeNode *cur) { - if(pre && pre->val > cur->val) { - if(!broken.first) { // find the first broken node - broken.first = pre; - } - broken.second = cur; // find the last broken node - } - } -}; From a15f2c7180d3b95b0a8a03d60850863bf77ee9d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Apr 2016 21:19:01 +0800 Subject: [PATCH 2002/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6f2643225..6734743b2 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C++](./C++/binary-tree-inorder-traversal.cpp) [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` +99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | [C++](./C++/recover-binary-search-tree.cpp) [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 From b2eec053ac1882bd582076eefbcebde43f7e3e54 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Apr 2016 11:19:51 +0800 Subject: [PATCH 2003/4971] Update binary-tree-inorder-traversal.cpp --- C++/binary-tree-inorder-traversal.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/C++/binary-tree-inorder-traversal.cpp b/C++/binary-tree-inorder-traversal.cpp index 53cb9393e..48334250d 100644 --- a/C++/binary-tree-inorder-traversal.cpp +++ b/C++/binary-tree-inorder-traversal.cpp @@ -15,25 +15,25 @@ class Solution { vector inorderTraversal(TreeNode* root) { vector res; TreeNode *prev = nullptr; - TreeNode *curr = root; - while (curr) { - if (!curr->left) { - res.emplace_back(curr->val); - prev = curr; - curr = curr->right; + TreeNode *cur = root; + while (cur) { + if (!cur->left) { + res.emplace_back(cur->val); + prev = cur; + cur = cur->right; } else { - TreeNode *node = curr->left; - while (node->right && node->right != curr) { + TreeNode *node = cur->left; + while (node->right && node->right != cur) { node = node->right; } if (!node->right) { - node->right = curr; - curr = curr->left; + node->right = cur; + cur = cur->left; } else { - res.emplace_back(curr->val); - prev = curr; + res.emplace_back(cur->val); + prev = cur; node->right = nullptr; - curr = curr->right; + cur = cur->right; } } } From 704624cfcbcf858b9314a282920607134c472a1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Apr 2016 01:45:46 +0800 Subject: [PATCH 2004/4971] Create binary-tree-preorder-traversal.cpp --- C++/binary-tree-preorder-traversal.cpp | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/binary-tree-preorder-traversal.cpp diff --git a/C++/binary-tree-preorder-traversal.cpp b/C++/binary-tree-preorder-traversal.cpp new file mode 100644 index 000000000..27425c540 --- /dev/null +++ b/C++/binary-tree-preorder-traversal.cpp @@ -0,0 +1,42 @@ +// 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: + vector preorderTraversal(TreeNode* root) { + vector res; + TreeNode *prev = nullptr; + auto *cur = root; + while (cur) { + if (!cur->left) { + res.emplace_back(cur->val); + prev = cur; + cur = cur->right; + } else { + auto *node = cur->left; + while (node->right && node->right != cur) { + node = node->right; + } + if (!node->right) { + res.emplace_back(cur->val); + prev = cur; + node->right = cur; + cur = cur->left; + } else { + node->right = nullptr; + cur = cur->right; + } + } + } + return res; + } +}; From 5e7b8affdb4424c6d9779db6db5edf7923844162 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Apr 2016 01:46:46 +0800 Subject: [PATCH 2005/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6734743b2..d38075d3c 100644 --- a/README.md +++ b/README.md @@ -174,7 +174,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C++](./C++/binary-tree-inorder-traversal.cpp) [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/) | [C++](./C++/recover-binary-search-tree.cpp) [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` +144 | [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | [C++](./C++/binary-tree-preorder-traversal.cpp) [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 From cf9fb4ab0a07ea8b2284cbc787b47a443db07955 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Apr 2016 21:09:36 +0800 Subject: [PATCH 2006/4971] Create binary-tree-postorder-traversal.cpp --- C++/binary-tree-postorder-traversal.cpp | 51 +++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 C++/binary-tree-postorder-traversal.cpp diff --git a/C++/binary-tree-postorder-traversal.cpp b/C++/binary-tree-postorder-traversal.cpp new file mode 100644 index 000000000..550617cd1 --- /dev/null +++ b/C++/binary-tree-postorder-traversal.cpp @@ -0,0 +1,51 @@ +/** + * 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 postorderTraversal(TreeNode* root) { + vector res; + TreeNode dummy(INT_MIN); + dummy.left = root; + auto *cur = &dummy; + while (cur) { + if (!cur->left) { + cur = cur->right; + } else { + auto *node = cur->left; + while (node->right && node->right != cur) { + node = node->right; + } + if (!node->right) { + node->right = cur; + cur = cur->left; + } else { + const auto& v = trace_back(cur->left, node); + res.insert(res.end(), v.cbegin(), v.cend()); + node->right = nullptr; + cur = cur->right; + } + } + } + return res; + } + +private: + vector trace_back(const TreeNode *from, const TreeNode *to) { + vector res; + auto *cur = from; + while (cur != to) { + res.emplace_back(cur->val); + cur = cur->right; + } + res.emplace_back(to->val); + reverse(res.begin(), res.end()); + return res; + } +}; From 0ab016146941410ba25316334dc3daaf7c010e6c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Apr 2016 21:10:23 +0800 Subject: [PATCH 2007/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d38075d3c..91c9dfd8d 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 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C++](./C++/binary-tree-inorder-traversal.cpp) [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/) | [C++](./C++/recover-binary-search-tree.cpp) [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/) | [C++](./C++/binary-tree-preorder-traversal.cpp) [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` +145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | [C++](./Python/binary-tree-postorder-traversal.cpp) [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 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 6768f609652e7fceee3e61fe5c1b5fb8568a2c62 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Apr 2016 21:11:19 +0800 Subject: [PATCH 2008/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 91c9dfd8d..df98f884e 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 94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C++](./C++/binary-tree-inorder-traversal.cpp) [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/) | [C++](./C++/recover-binary-search-tree.cpp) [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/) | [C++](./C++/binary-tree-preorder-traversal.cpp) [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/) | [C++](./Python/binary-tree-postorder-traversal.cpp) [Python](./Python/binary-tree-postorder-traversal.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` +145 | [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | [C++](./C++/binary-tree-postorder-traversal.cpp) [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 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 0be32b302ea64684ed91449d55716d846ab84ae2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Apr 2016 21:11:39 +0800 Subject: [PATCH 2009/4971] Update binary-tree-postorder-traversal.cpp --- C++/binary-tree-postorder-traversal.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/binary-tree-postorder-traversal.cpp b/C++/binary-tree-postorder-traversal.cpp index 550617cd1..15f071465 100644 --- a/C++/binary-tree-postorder-traversal.cpp +++ b/C++/binary-tree-postorder-traversal.cpp @@ -1,3 +1,6 @@ +// Time: O(n) +// Space: O(1) + /** * Definition for a binary tree node. * struct TreeNode { From 705d6a68d28a86b6ada6e41ae2f256c4bc01acb5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Apr 2016 21:19:53 +0800 Subject: [PATCH 2010/4971] Create binary-search-tree-iterator.cpp --- C++/binary-search-tree-iterator.cpp | 49 +++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 C++/binary-search-tree-iterator.cpp diff --git a/C++/binary-search-tree-iterator.cpp b/C++/binary-search-tree-iterator.cpp new file mode 100644 index 000000000..ec0569d76 --- /dev/null +++ b/C++/binary-search-tree-iterator.cpp @@ -0,0 +1,49 @@ +// Time: O(1), amortized +// Space: O(h) + +/** + * Definition for binary tree + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class BSTIterator { +public: + BSTIterator(TreeNode *root) : cur_(root) { + } + + /** @return whether we have a next smallest number */ + bool hasNext() { + return !s_.empty() || cur_ != nullptr; + } + + /** @return the next smallest number */ + int next() { + // Go to the left most descendant. + while (cur_ != nullptr) { + s_.emplace(cur_); + cur_ = cur_->left; + } + cur_ = s_.top(); // Left most node. + s_.pop(); + + const auto *node = cur_; + cur_ = cur_->right; // Visit right child. + + return node->val; + } + +private: + stack s_; + TreeNode *cur_; +}; + +/** + * Your BSTIterator will be called like this: + * BSTIterator i = BSTIterator(root); + * while (i.hasNext()) cout << i.next(); + */ + From 77923c752bd257dfc8b425c89a09a0c691f937ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Apr 2016 21:20:47 +0800 Subject: [PATCH 2011/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index df98f884e..5417f43c3 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 101| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./C++/symmetric-tree.cpp) [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || 150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [C++](./C++/evaluate-reverse-polish-notation.cpp) [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || 155| [Min Stack](https://leetcode.com/problems/min-stack/) | [C++](./C++/min-stack.cpp) [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 || +173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [C++](./C++/binary-search-tree-iterator.cpp) [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)_| Easy | EPI, LintCode | From 01543a5a9e0696acc83ce20251a27ceec302d8c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Apr 2016 21:21:46 +0800 Subject: [PATCH 2012/4971] Update binary-search-tree-iterator.cpp --- C++/binary-search-tree-iterator.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/binary-search-tree-iterator.cpp b/C++/binary-search-tree-iterator.cpp index ec0569d76..0bcf46624 100644 --- a/C++/binary-search-tree-iterator.cpp +++ b/C++/binary-search-tree-iterator.cpp @@ -27,11 +27,11 @@ class BSTIterator { s_.emplace(cur_); cur_ = cur_->left; } - cur_ = s_.top(); // Left most node. + cur_ = s_.top(); // Left most node. s_.pop(); const auto *node = cur_; - cur_ = cur_->right; // Visit right child. + cur_ = cur_->right; // Visit right child. return node->val; } From 5a0b9a4a610fe22e8aa10bc5f24e6bdb1764bdde Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Apr 2016 22:38:06 +0800 Subject: [PATCH 2013/4971] Create implement-trie-prefix-tree.cpp --- C++/implement-trie-prefix-tree.cpp | 66 ++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 C++/implement-trie-prefix-tree.cpp diff --git a/C++/implement-trie-prefix-tree.cpp b/C++/implement-trie-prefix-tree.cpp new file mode 100644 index 000000000..5576063fd --- /dev/null +++ b/C++/implement-trie-prefix-tree.cpp @@ -0,0 +1,66 @@ +// Time: O(n), per operation +// Space: O(1) + +class TrieNode { +public: + // Initialize your data structure here. + TrieNode() : is_string(false) { + + } + bool is_string; + unordered_map leaves; +}; + +class Trie { +public: + Trie() { + root_ = new TrieNode(); + } + + // Inserts a word into the trie. + void insert(string word) { + auto *cur = root_; + for (const auto& c : word) { + if (!cur->leaves.count(c)) { + cur->leaves[c] = new TrieNode(); + } + cur = cur->leaves[c]; + } + cur->is_string = true; + } + + // Returns if the word is in the trie. + bool search(string word) { + auto *node = childSearch(word); + if (node) { + return node->is_string; + } + return false; + } + + // Returns if there is any word in the trie + // that starts with the given prefix. + bool startsWith(string prefix) { + return childSearch(prefix); + } + + TrieNode * childSearch(const string& word) { + auto *cur = root_; + for (const auto& c : word) { + if (cur->leaves.count(c)) { + cur = cur->leaves[c]; + } else { + return nullptr; + } + } + return cur; + } + +private: + TrieNode* root_; +}; + +// Your Trie object will be instantiated and called as such: +// Trie trie; +// trie.insert("somestring"); +// trie.search("key"); From b1e5ecdc203097ad3b2d609f0b7c90598d76dc48 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Apr 2016 22:47:22 +0800 Subject: [PATCH 2014/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5417f43c3..8ecf91055 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | [C++](./C++/recover-binary-search-tree.cpp) [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/) | [C++](./C++/binary-tree-preorder-traversal.cpp) [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/) | [C++](./C++/binary-tree-postorder-traversal.cpp) [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 +208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [C++](./C++/implement-trie-prefix-tree.cpp) [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 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 From 9ed02901265ad0fca01a74fd34f32c6406cfb409 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Apr 2016 22:48:57 +0800 Subject: [PATCH 2015/4971] Update implement-trie-prefix-tree.cpp --- C++/implement-trie-prefix-tree.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/implement-trie-prefix-tree.cpp b/C++/implement-trie-prefix-tree.cpp index 5576063fd..8a94245dd 100644 --- a/C++/implement-trie-prefix-tree.cpp +++ b/C++/implement-trie-prefix-tree.cpp @@ -44,7 +44,7 @@ class Trie { return childSearch(prefix); } - TrieNode * childSearch(const string& word) { + TrieNode *childSearch(const string& word) { auto *cur = root_; for (const auto& c : word) { if (cur->leaves.count(c)) { @@ -57,7 +57,7 @@ class Trie { } private: - TrieNode* root_; + TrieNode *root_; }; // Your Trie object will be instantiated and called as such: From d26e24df0d9a1f4d124c9504b216fb5e6b82455e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Apr 2016 14:18:29 +0800 Subject: [PATCH 2016/4971] Create two-sum.cpp --- C++/two-sum.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/two-sum.cpp diff --git a/C++/two-sum.cpp b/C++/two-sum.cpp new file mode 100644 index 000000000..7720f6d83 --- /dev/null +++ b/C++/two-sum.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector twoSum(vector& nums, int target) { + vector res; + unordered_map lookup; + for (int i = 0; i < nums.size(); ++i) { + if (lookup.count(target - nums[i])) { + res = {lookup[target - nums[i]], i}; + break; + } + lookup[nums[i]] = i; + } + return res; + } +}; From fc92d7fc99baeb7a431fba6add41e970f056d588 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Apr 2016 14:19:40 +0800 Subject: [PATCH 2017/4971] Update two-sum.cpp --- C++/two-sum.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/two-sum.cpp b/C++/two-sum.cpp index 7720f6d83..841d2e1a5 100644 --- a/C++/two-sum.cpp +++ b/C++/two-sum.cpp @@ -4,15 +4,13 @@ class Solution { public: vector twoSum(vector& nums, int target) { - vector res; unordered_map lookup; for (int i = 0; i < nums.size(); ++i) { if (lookup.count(target - nums[i])) { - res = {lookup[target - nums[i]], i}; - break; + return {lookup[target - nums[i]], i}; } lookup[nums[i]] = i; } - return res; + return {}; } }; From f378cb7261fd3fb51acc1115008b893e87fafe6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Apr 2016 14:20:45 +0800 Subject: [PATCH 2018/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8ecf91055..9596c4c75 100644 --- a/README.md +++ b/README.md @@ -187,7 +187,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Hash Table # | 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 || +1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [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 || From 27bbf6f807c2f86242914076402a9924d22f68f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Apr 2016 14:23:17 +0800 Subject: [PATCH 2019/4971] Update two-sum.py --- Python/two-sum.py | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/Python/two-sum.py b/Python/two-sum.py index e89be65fe..d34165ab9 100644 --- a/Python/two-sum.py +++ b/Python/two-sum.py @@ -1,25 +1,32 @@ # Time: O(n) # Space: O(n) + +# Given an array of integers, return indices of the two numbers +# such that they add up to a specific target. # -# Given an array of integers, find two numbers such that -# they add up to a specific target number. -# The function twoSum should return indices of the two numbers such that -# they add up to the target, -# where index1 must be less than index2. Please note that -# your returned answers (both index1 and index2) are not zero-based. # You may assume that each input would have exactly one solution. # -# Input: numbers={2, 7, 11, 15}, target=9 -# Output: index1=1, index2=2 +# Example: +# Given nums = [2, 7, 11, 15], target = 9, # +# Because nums[0] + nums[1] = 2 + 7 = 9, +# return [0, 1]. + -class Solution: +class Solution(object): def twoSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ lookup = {} for i, num in enumerate(nums): if target - num in lookup: - return (lookup[target - num] + 1, i + 1) + return [lookup[target - num], i] lookup[num] = i + return [] + if __name__ == '__main__': - print "index1=%d, index2=%d" % Solution().twoSum((2, 7, 11, 15), 9) \ No newline at end of file + print "index1=%d, index2=%d" % Solution().twoSum((2, 7, 11, 15), 9) From 4a92b086206367b698f760a7db9b2baa9f274de8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Apr 2016 14:23:29 +0800 Subject: [PATCH 2020/4971] Update two-sum.py --- Python/two-sum.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/two-sum.py b/Python/two-sum.py index d34165ab9..7b7aeaf48 100644 --- a/Python/two-sum.py +++ b/Python/two-sum.py @@ -12,7 +12,6 @@ # Because nums[0] + nums[1] = 2 + 7 = 9, # return [0, 1]. - class Solution(object): def twoSum(self, nums, target): """ From 63ea24aa7b6c29e28e786fa72cee9930ac20d4fd Mon Sep 17 00:00:00 2001 From: Yuncong Zhang Date: Fri, 15 Apr 2016 12:19:05 -0400 Subject: [PATCH 2021/4971] add the missing } --- C++/linked-list-cycle-ii.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/linked-list-cycle-ii.cpp b/C++/linked-list-cycle-ii.cpp index c4cf61ba2..3acc2385a 100644 --- a/C++/linked-list-cycle-ii.cpp +++ b/C++/linked-list-cycle-ii.cpp @@ -23,6 +23,7 @@ class Solution { slow = slow->next, fast = fast->next; } return slow; // slow is the begin of cycle. + } } return nullptr; // No cycle. } From 6fd00c82b1563a261b8a9a6eb6c39c9be75431be Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Apr 2016 14:52:00 +0800 Subject: [PATCH 2022/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9596c4c75..74ab42064 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-341%20%2F%20341-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-341%20%2F%20341-ff69b4.svg) Up to date (2016-04-05), there are `324` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. From 4bdf6508e5ff6d93f05d1e5d020b29fed0ea7166 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Apr 2016 10:52:05 +0800 Subject: [PATCH 2023/4971] Create power-of-four.cpp --- C++/power-of-four.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 C++/power-of-four.cpp diff --git a/C++/power-of-four.cpp b/C++/power-of-four.cpp new file mode 100644 index 000000000..b35860dce --- /dev/null +++ b/C++/power-of-four.cpp @@ -0,0 +1,12 @@ +// Time: O(logn) +// Space: O(logn) + +class Solution { +public: + bool isPowerOfFour(int num) { + while (num && !(num & 0b11)) { + num >>= 2; + } + return (num == 1); + } +}; From 711ef335f69824274a0c6f50885b9df369039437 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Apr 2016 10:53:58 +0800 Subject: [PATCH 2024/4971] Create power-of-four.py --- Python/power-of-four.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Python/power-of-four.py diff --git a/Python/power-of-four.py b/Python/power-of-four.py new file mode 100644 index 000000000..687e8def8 --- /dev/null +++ b/Python/power-of-four.py @@ -0,0 +1,19 @@ +# Time: O(logn) +# Space: O(logn) + +# Given an integer (signed 32 bits), write a function to check whether it is a power of 4. +# +# Example: +# Given num = 16, return true. Given num = 5, return false. +# +# Follow up: Could you solve it without loops/recursion? + +class Solution(object): + def isPowerOfFour(self, num): + """ + :type num: int + :rtype: bool + """ + while num and not (num & 3): + num >>= 2 + return (num == 1) From 2d6945515293d41f5addfd610a727cfcfa0a3872 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Apr 2016 10:57:24 +0800 Subject: [PATCH 2025/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 74ab42064..236a1b589 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-341%20%2F%20341-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-342%20%2F%20342-ff69b4.svg) -Up to date (2016-04-05), there are `324` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-04-18), there are `325` 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 `341` questions. +Here is the classification of all `342` 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 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(n^2)_ | _O(n)_ | Medium || Bit Manipulation, Counting Sort, Pruning| +342 | [Power of four](https://leetcode.com/problems/power-of-four/) | [C++](./C++/power-of-four.cpp) [Python](./Python/power-of-four.py) | _O(1)_ | _O(1)_ | Easy | | ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note From 3a241bfdd4c5815e003b15acfe47a3150d2d6937 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Apr 2016 10:57:36 +0800 Subject: [PATCH 2026/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 236a1b589..e15fe592c 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 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(n^2)_ | _O(n)_ | Medium || Bit Manipulation, Counting Sort, Pruning| -342 | [Power of four](https://leetcode.com/problems/power-of-four/) | [C++](./C++/power-of-four.cpp) [Python](./Python/power-of-four.py) | _O(1)_ | _O(1)_ | Easy | | +342 | [Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./C++/power-of-four.cpp) [Python](./Python/power-of-four.py) | _O(1)_ | _O(1)_ | Easy | | ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note From ed94c067c1a46f73fcca5ae1c0ad60279edadc4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Apr 2016 11:04:56 +0800 Subject: [PATCH 2027/4971] Update power-of-four.py --- Python/power-of-four.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/Python/power-of-four.py b/Python/power-of-four.py index 687e8def8..8c9e815a2 100644 --- a/Python/power-of-four.py +++ b/Python/power-of-four.py @@ -1,5 +1,5 @@ -# Time: O(logn) -# Space: O(logn) +# Time: O(1) +# Space: O(1) # Given an integer (signed 32 bits), write a function to check whether it is a power of 4. # @@ -9,6 +9,16 @@ # Follow up: Could you solve it without loops/recursion? class Solution(object): + def isPowerOfFour(self, num): + """ + :type num: int + :rtype: bool + """ + return num > 0 and (num & (num - 1)) == 0 and ((num & 0b101010101010101010101010101010101) == num) + +# Time: O(1) +# Space: O(1) +class Solution2(object): def isPowerOfFour(self, num): """ :type num: int From 9b80be86d5c4cdb5bf82aaeea603c2e4253231a9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Apr 2016 11:06:40 +0800 Subject: [PATCH 2028/4971] Update power-of-four.cpp --- C++/power-of-four.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/C++/power-of-four.cpp b/C++/power-of-four.cpp index b35860dce..3ed7e8106 100644 --- a/C++/power-of-four.cpp +++ b/C++/power-of-four.cpp @@ -2,6 +2,16 @@ // Space: O(logn) class Solution { +public: + bool isPowerOfFour(int num) { + return num > 0 && (num & (num - 1)) == 0 && + ((num & 0b101010101010101010101010101010101) == num); + } +}; + +// Time: O(1) +// Space: O(1) +class Solution2 { public: bool isPowerOfFour(int num) { while (num && !(num & 0b11)) { From 8a45e41c42deb344030f60ade7e20f9088ea27d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Apr 2016 11:07:07 +0800 Subject: [PATCH 2029/4971] Update power-of-four.py --- Python/power-of-four.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Python/power-of-four.py b/Python/power-of-four.py index 8c9e815a2..f96def608 100644 --- a/Python/power-of-four.py +++ b/Python/power-of-four.py @@ -14,7 +14,9 @@ def isPowerOfFour(self, num): :type num: int :rtype: bool """ - return num > 0 and (num & (num - 1)) == 0 and ((num & 0b101010101010101010101010101010101) == num) + return num > 0 and (num & (num - 1)) == 0 and \ + ((num & 0b101010101010101010101010101010101) == num) + # Time: O(1) # Space: O(1) From a04a8c3574965d510645b1ea2357704e28d7b1d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Apr 2016 11:09:36 +0800 Subject: [PATCH 2030/4971] Update power-of-four.cpp --- C++/power-of-four.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/power-of-four.cpp b/C++/power-of-four.cpp index 3ed7e8106..0bcca2d46 100644 --- a/C++/power-of-four.cpp +++ b/C++/power-of-four.cpp @@ -1,11 +1,11 @@ -// Time: O(logn) -// Space: O(logn) +// Time: O(1) +// Space: O(1) class Solution { public: bool isPowerOfFour(int num) { return num > 0 && (num & (num - 1)) == 0 && - ((num & 0b101010101010101010101010101010101) == num); + ((num & 0b01010101010101010101010101010101) == num); } }; From 17f1c5d3f9250c07ad74d71053bb8d91864c1a6b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Apr 2016 11:10:07 +0800 Subject: [PATCH 2031/4971] Update power-of-four.py --- Python/power-of-four.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/power-of-four.py b/Python/power-of-four.py index f96def608..cd8c1bbe9 100644 --- a/Python/power-of-four.py +++ b/Python/power-of-four.py @@ -15,7 +15,7 @@ def isPowerOfFour(self, num): :rtype: bool """ return num > 0 and (num & (num - 1)) == 0 and \ - ((num & 0b101010101010101010101010101010101) == num) + ((num & 0b1010101010101010101010101010101) == num) # Time: O(1) From e322a89830b79f482b8823abb9a797f08bd35578 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Apr 2016 11:48:56 +0800 Subject: [PATCH 2032/4971] Update power-of-four.py --- Python/power-of-four.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/power-of-four.py b/Python/power-of-four.py index cd8c1bbe9..a1518b74f 100644 --- a/Python/power-of-four.py +++ b/Python/power-of-four.py @@ -26,6 +26,6 @@ def isPowerOfFour(self, num): :type num: int :rtype: bool """ - while num and not (num & 3): + while num and not (num & 0b11): num >>= 2 return (num == 1) From 62954690dc974674483b446a06e5d254585dd7e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Apr 2016 23:16:35 -0500 Subject: [PATCH 2033/4971] Update power-of-four.py --- Python/power-of-four.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/power-of-four.py b/Python/power-of-four.py index a1518b74f..b8da27b99 100644 --- a/Python/power-of-four.py +++ b/Python/power-of-four.py @@ -15,7 +15,7 @@ def isPowerOfFour(self, num): :rtype: bool """ return num > 0 and (num & (num - 1)) == 0 and \ - ((num & 0b1010101010101010101010101010101) == num) + ((num & 0b01010101010101010101010101010101) == num) # Time: O(1) From a3398468f2795301990e388cbe302709669c0caf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:34:42 +0800 Subject: [PATCH 2034/4971] Create integer-break.cpp --- C++/integer-break.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/integer-break.cpp diff --git a/C++/integer-break.cpp b/C++/integer-break.cpp new file mode 100644 index 000000000..98e5598d0 --- /dev/null +++ b/C++/integer-break.cpp @@ -0,0 +1,42 @@ +// Time: O(logn), pow is O(logn) +// Space: O(logn) + +class Solution { +public: + int integerBreak(int n) { + if (n < 4) { + return n - 1; + } + // Proof. + // 1. Let n = a1 + a2 + ... + ak, product = a1 * a2 * ... * ak + // - For each aj >= 4, we can always maximize the product by: + // ai <= 2 * (ai - 2) + // - For each aj >= 5, we can always maximize the product by: + // aj <= 3 * (aj - 3) + // + // Conclusion 1: + // - For n >= 4, the max of the product must be in the form of + // 3^a * 2^b, s.t. 3a + 2b = n + // + // 2. To maximize the product = 3^a * 2^b s.t. 3a + 2b = n + // - For each b >= 3, we can always maximize the product by: + // 3^a * 2^b <= 3^(a+2) * 2^(b-3) s.t. 3(a+2) + 2(b-3) = n + // + // Conclusion 2: + // - For n >= 4, the max of the product must be in the form of + // 3^Q * 2^R, 0 <= R < 2 s.t. 3Q + 2R = n + // i.e. + // if n = 3Q + 0, the max of the product = 3^Q * 2^0 + // if n = 3Q + 2, the max of the product = 3^Q * 2^1 + // if n = 3Q + 2*2, the max of the product = 3^Q * 2^2 + + if (n % 3 == 0) { // n = 3Q + 0, the max is 3^Q * 2^0 + return pow(3, n / 3); + } else if (n % 3 == 2) { // n = 3Q + 2, the max is 3^Q * 2^1 + return pow(3, n / 3) * 2; + } else { // n = 3Q + 4, , the max is 3^Q * 2^2 + return pow(3, n / 3 - 1) * 4; + } + return 0; + } +}; From 0ee5f8cfcd4a1373c00fe729600fbf3caf85e9e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:39:05 +0800 Subject: [PATCH 2035/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e15fe592c..b85c1637d 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-342%20%2F%20342-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-343%20%2F%20343-ff69b4.svg) -Up to date (2016-04-18), there are `325` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-04-19), there are `326` 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 `342` questions. +Here is the classification of all `343` 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. ) @@ -249,6 +249,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 ||| 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 ||| +343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(logn)_ | Medium || Tricky | ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From 086077b660df160338cca4aaa78f217a4f7bf172 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:40:59 +0800 Subject: [PATCH 2036/4971] Update integer-break.cpp --- C++/integer-break.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/integer-break.cpp b/C++/integer-break.cpp index 98e5598d0..05abf2686 100644 --- a/C++/integer-break.cpp +++ b/C++/integer-break.cpp @@ -1,4 +1,4 @@ -// Time: O(logn), pow is O(logn) +// Time: O(logn), pow is O(logn). // Space: O(logn) class Solution { @@ -7,6 +7,7 @@ class Solution { if (n < 4) { return n - 1; } + // Proof. // 1. Let n = a1 + a2 + ... + ak, product = a1 * a2 * ... * ak // - For each aj >= 4, we can always maximize the product by: From 03ac7fe9f72ae4a0730d9ca9eac4ec9cf17f2843 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:44:16 +0800 Subject: [PATCH 2037/4971] Update integer-break.cpp --- C++/integer-break.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/C++/integer-break.cpp b/C++/integer-break.cpp index 05abf2686..a1c866aa9 100644 --- a/C++/integer-break.cpp +++ b/C++/integer-break.cpp @@ -31,13 +31,14 @@ class Solution { // if n = 3Q + 2, the max of the product = 3^Q * 2^1 // if n = 3Q + 2*2, the max of the product = 3^Q * 2^2 + int res = 0; if (n % 3 == 0) { // n = 3Q + 0, the max is 3^Q * 2^0 - return pow(3, n / 3); + res = pow(3, n / 3); } else if (n % 3 == 2) { // n = 3Q + 2, the max is 3^Q * 2^1 - return pow(3, n / 3) * 2; + res = pow(3, n / 3) * 2; } else { // n = 3Q + 4, , the max is 3^Q * 2^2 - return pow(3, n / 3 - 1) * 4; + res = pow(3, n / 3 - 1) * 4; } - return 0; + return res; } }; From bc06ca47513c6a6b0a833b44fcb4695543e37338 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:49:37 +0800 Subject: [PATCH 2038/4971] Create integer-break.py --- Python/integer-break.py | 58 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Python/integer-break.py diff --git a/Python/integer-break.py b/Python/integer-break.py new file mode 100644 index 000000000..31befea0f --- /dev/null +++ b/Python/integer-break.py @@ -0,0 +1,58 @@ +# Time: O(logn), pow is O(logn). +# Space: O(logn) + +# Given a positive integer n, break it into the sum of +# at least two positive integers and maximize the product +# of those integers. Return the maximum product you can get. +# +# For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, +# return 36 (10 = 3 + 3 + 4). +# +# Note: you may assume that n is not less than 2. +# +# Hint: +# +# There is a simple O(n) solution to this problem. +# You may check the breaking results of n ranging from 7 to 10 +# to discover the regularities. + +class Solution(object): + def integerBreak(self, n): + """ + :type n: int + :rtype: int + """ + if n < 4: + return n - 1 + + # Proof. + # 1. Let n = a1 + a2 + ... + ak, product = a1 * a2 * ... * ak + # - For each aj >= 4, we can always maximize the product by: + # ai <= 2 * (ai - 2) + # - For each aj >= 5, we can always maximize the product by: + # aj <= 3 * (aj - 3) + # + # Conclusion 1: + # - For n >= 4, the max of the product must be in the form of + # 3^a * 2^b, s.t. 3a + 2b = n + # + # 2. To maximize the product = 3^a * 2^b s.t. 3a + 2b = n + # - For each b >= 3, we can always maximize the product by: + # 3^a * 2^b <= 3^(a+2) * 2^(b-3) s.t. 3(a+2) + 2(b-3) = n + # + # Conclusion 2: + # - For n >= 4, the max of the product must be in the form of + # 3^Q * 2^R, 0 <= R < 2 s.t. 3Q + 2R = n + # i.e. + # if n = 3Q + 0, the max of the product = 3^Q * 2^0 + # if n = 3Q + 2, the max of the product = 3^Q * 2^1 + # if n = 3Q + 2*2, the max of the product = 3^Q * 2^2 + + res = 0 + if n % 3 == 0: # n = 3Q + 0, the max is 3^Q * 2^0 + res = 3 ** (n // 3) + elif n % 3 == 2: # n = 3Q + 2, the max is 3^Q * 2^1 + res = 3 ** (n // 3) * 2 + else: # n = 3Q + 4, , the max is 3^Q * 2^2 + res = 3 ** (n // 3 - 1) * 4 + return res From 1ae919525e881602e5477c7544217873f2c9c395 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:51:14 +0800 Subject: [PATCH 2039/4971] Update integer-break.py --- Python/integer-break.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/integer-break.py b/Python/integer-break.py index 31befea0f..5fe6403dd 100644 --- a/Python/integer-break.py +++ b/Python/integer-break.py @@ -53,6 +53,6 @@ def integerBreak(self, n): res = 3 ** (n // 3) elif n % 3 == 2: # n = 3Q + 2, the max is 3^Q * 2^1 res = 3 ** (n // 3) * 2 - else: # n = 3Q + 4, , the max is 3^Q * 2^2 + else: # n = 3Q + 4, the max is 3^Q * 2^2 res = 3 ** (n // 3 - 1) * 4 return res From 86dfb425ecf0f50537b1d105e0b56af99ec51b57 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:51:29 +0800 Subject: [PATCH 2040/4971] Update integer-break.cpp --- C++/integer-break.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/integer-break.cpp b/C++/integer-break.cpp index a1c866aa9..d9339cc51 100644 --- a/C++/integer-break.cpp +++ b/C++/integer-break.cpp @@ -36,7 +36,7 @@ class Solution { res = pow(3, n / 3); } else if (n % 3 == 2) { // n = 3Q + 2, the max is 3^Q * 2^1 res = pow(3, n / 3) * 2; - } else { // n = 3Q + 4, , the max is 3^Q * 2^2 + } else { // n = 3Q + 4, the max is 3^Q * 2^2 res = pow(3, n / 3 - 1) * 4; } return res; From 6ce357c6adc871519ed8f05947183e87fb1554e4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:53:40 +0800 Subject: [PATCH 2041/4971] Update integer-break.cpp --- C++/integer-break.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/integer-break.cpp b/C++/integer-break.cpp index d9339cc51..1b4b65709 100644 --- a/C++/integer-break.cpp +++ b/C++/integer-break.cpp @@ -25,7 +25,7 @@ class Solution { // // Conclusion 2: // - For n >= 4, the max of the product must be in the form of - // 3^Q * 2^R, 0 <= R < 2 s.t. 3Q + 2R = n + // 3^Q * 2^R, 0 <= R < 3 s.t. 3Q + 2R = n // i.e. // if n = 3Q + 0, the max of the product = 3^Q * 2^0 // if n = 3Q + 2, the max of the product = 3^Q * 2^1 From 100b7e9f84a595ce124389bc774761225be52ab7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:53:59 +0800 Subject: [PATCH 2042/4971] Update integer-break.py --- Python/integer-break.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/integer-break.py b/Python/integer-break.py index 5fe6403dd..46828fa6d 100644 --- a/Python/integer-break.py +++ b/Python/integer-break.py @@ -42,7 +42,7 @@ def integerBreak(self, n): # # Conclusion 2: # - For n >= 4, the max of the product must be in the form of - # 3^Q * 2^R, 0 <= R < 2 s.t. 3Q + 2R = n + # 3^Q * 2^R, 0 <= R < 3 s.t. 3Q + 2R = n # i.e. # if n = 3Q + 0, the max of the product = 3^Q * 2^0 # if n = 3Q + 2, the max of the product = 3^Q * 2^1 From 8c55477d5510bd375921cd8afde6d041dfdf05c8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:55:03 +0800 Subject: [PATCH 2043/4971] Update integer-break.py --- Python/integer-break.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/integer-break.py b/Python/integer-break.py index 46828fa6d..67e713964 100644 --- a/Python/integer-break.py +++ b/Python/integer-break.py @@ -27,7 +27,7 @@ def integerBreak(self, n): # Proof. # 1. Let n = a1 + a2 + ... + ak, product = a1 * a2 * ... * ak - # - For each aj >= 4, we can always maximize the product by: + # - For each ai >= 4, we can always maximize the product by: # ai <= 2 * (ai - 2) # - For each aj >= 5, we can always maximize the product by: # aj <= 3 * (aj - 3) From ee28bff5a643d0a7864da3bbf57ccd360b05cfad Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:55:18 +0800 Subject: [PATCH 2044/4971] Update integer-break.cpp --- C++/integer-break.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/integer-break.cpp b/C++/integer-break.cpp index 1b4b65709..ec8077ffb 100644 --- a/C++/integer-break.cpp +++ b/C++/integer-break.cpp @@ -10,7 +10,7 @@ class Solution { // Proof. // 1. Let n = a1 + a2 + ... + ak, product = a1 * a2 * ... * ak - // - For each aj >= 4, we can always maximize the product by: + // - For each ai >= 4, we can always maximize the product by: // ai <= 2 * (ai - 2) // - For each aj >= 5, we can always maximize the product by: // aj <= 3 * (aj - 3) From 6548c23740e9dece2e96048126548efe8a187bbe Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:56:45 +0800 Subject: [PATCH 2045/4971] Update integer-break.cpp --- C++/integer-break.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/integer-break.cpp b/C++/integer-break.cpp index ec8077ffb..f1d7534b2 100644 --- a/C++/integer-break.cpp +++ b/C++/integer-break.cpp @@ -35,7 +35,7 @@ class Solution { if (n % 3 == 0) { // n = 3Q + 0, the max is 3^Q * 2^0 res = pow(3, n / 3); } else if (n % 3 == 2) { // n = 3Q + 2, the max is 3^Q * 2^1 - res = pow(3, n / 3) * 2; + res = pow(3, n / 3) * 2; } else { // n = 3Q + 4, the max is 3^Q * 2^2 res = pow(3, n / 3 - 1) * 4; } From e6d63f01d71cc0945bc5e54516d7360fae3085ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 22:57:07 +0800 Subject: [PATCH 2046/4971] Update integer-break.py --- Python/integer-break.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/integer-break.py b/Python/integer-break.py index 67e713964..533be9fa0 100644 --- a/Python/integer-break.py +++ b/Python/integer-break.py @@ -52,7 +52,7 @@ def integerBreak(self, n): if n % 3 == 0: # n = 3Q + 0, the max is 3^Q * 2^0 res = 3 ** (n // 3) elif n % 3 == 2: # n = 3Q + 2, the max is 3^Q * 2^1 - res = 3 ** (n // 3) * 2 + res = 3 ** (n // 3) * 2 else: # n = 3Q + 4, the max is 3^Q * 2^2 res = 3 ** (n // 3 - 1) * 4 return res From 09ff8bd6772fe4487e6f99dcbdd933477e822dd8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 23:03:24 +0800 Subject: [PATCH 2047/4971] Update integer-break.py --- Python/integer-break.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/integer-break.py b/Python/integer-break.py index 533be9fa0..4a2f69ce5 100644 --- a/Python/integer-break.py +++ b/Python/integer-break.py @@ -37,7 +37,7 @@ def integerBreak(self, n): # 3^a * 2^b, s.t. 3a + 2b = n # # 2. To maximize the product = 3^a * 2^b s.t. 3a + 2b = n - # - For each b >= 3, we can always maximize the product by: + # - For each b >= 3, we can always maximize the product by: # 3^a * 2^b <= 3^(a+2) * 2^(b-3) s.t. 3(a+2) + 2(b-3) = n # # Conclusion 2: From 9a8e03c4944ad856a9c2c15c5ec4d7553732403d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Apr 2016 23:04:02 +0800 Subject: [PATCH 2048/4971] Update integer-break.cpp --- C++/integer-break.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/integer-break.cpp b/C++/integer-break.cpp index f1d7534b2..8288c91f2 100644 --- a/C++/integer-break.cpp +++ b/C++/integer-break.cpp @@ -20,7 +20,7 @@ class Solution { // 3^a * 2^b, s.t. 3a + 2b = n // // 2. To maximize the product = 3^a * 2^b s.t. 3a + 2b = n - // - For each b >= 3, we can always maximize the product by: + // - For each b >= 3, we can always maximize the product by: // 3^a * 2^b <= 3^(a+2) * 2^(b-3) s.t. 3(a+2) + 2(b-3) = n // // Conclusion 2: From 70d9981ee459b23bf6c2bb53429aeacddbc8cdaf Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Apr 2016 00:34:58 +0800 Subject: [PATCH 2049/4971] Update integer-break.py --- Python/integer-break.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Python/integer-break.py b/Python/integer-break.py index 4a2f69ce5..5e0b62486 100644 --- a/Python/integer-break.py +++ b/Python/integer-break.py @@ -56,3 +56,22 @@ def integerBreak(self, n): else: # n = 3Q + 4, the max is 3^Q * 2^2 res = 3 ** (n // 3 - 1) * 4 return res + +# Time: O(n) +# Space: O(logn) +# DP solution. +class Solution2(object): + def integerBreak(self, n): + """ + :type n: int + :rtype: int + """ + if n < 4: + return n - 1 + + # integerBreak(n) = max(integerBreak(n - 2) * 2, integerBreak(n - 3) * 3) + res = [0] * 4 + res[1 % 4], res[2 % 4], res[3 % 4] = 1, 2, 3 + for i in xrange(4, n + 1): + res[i % 4] = max(res[(i - 2) % 4] * 2, res[(i - 3) % 4] * 3) + return res[n % 4] From 923d7382815398dd346559ccbf0bc8ac3b5e2d8c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Apr 2016 00:37:13 +0800 Subject: [PATCH 2050/4971] Update integer-break.cpp --- C++/integer-break.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/C++/integer-break.cpp b/C++/integer-break.cpp index 8288c91f2..82a06b323 100644 --- a/C++/integer-break.cpp +++ b/C++/integer-break.cpp @@ -42,3 +42,22 @@ class Solution { return res; } }; + +// Time: O(n) +// Space: O(logn) +// DP solution. +class Solution2 { +public: + int integerBreak(int n) { + if (n < 4) { + return n - 1; + } + + // integerBreak(n) = max(integerBreak(n - 2) * 2, integerBreak(n - 3) * 3) + vector res{0, 1, 2, 3}; + for (int i = 4; i <= n; ++i) { + res[i % 4] = max(res[(i - 2) % 4] * 2, res[(i - 3) % 4] * 3); + } + return res[n % 4]; + } +}; From 7d5c40d9917537c33b4d5a30d3a274c03797ae6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Apr 2016 00:37:45 +0800 Subject: [PATCH 2051/4971] Update integer-break.py --- Python/integer-break.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/integer-break.py b/Python/integer-break.py index 5e0b62486..daf509418 100644 --- a/Python/integer-break.py +++ b/Python/integer-break.py @@ -70,8 +70,7 @@ def integerBreak(self, n): return n - 1 # integerBreak(n) = max(integerBreak(n - 2) * 2, integerBreak(n - 3) * 3) - res = [0] * 4 - res[1 % 4], res[2 % 4], res[3 % 4] = 1, 2, 3 + res = [0, 1, 2, 3] for i in xrange(4, n + 1): res[i % 4] = max(res[(i - 2) % 4] * 2, res[(i - 3) % 4] * 3) return res[n % 4] From 1813c5a4e45e017985d10423785d00ff60b92378 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Apr 2016 00:38:21 +0800 Subject: [PATCH 2052/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b85c1637d..90c69a55e 100644 --- a/README.md +++ b/README.md @@ -249,7 +249,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 ||| 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 ||| -343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(logn)_ | Medium || Tricky | +343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(logn)_ | Medium || Tricky, DP | ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From 9787692dcd067844a6f774d8de4159fa7a511f72 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Apr 2016 00:38:47 +0800 Subject: [PATCH 2053/4971] Update integer-break.py --- Python/integer-break.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/integer-break.py b/Python/integer-break.py index daf509418..e074792d0 100644 --- a/Python/integer-break.py +++ b/Python/integer-break.py @@ -57,6 +57,7 @@ def integerBreak(self, n): res = 3 ** (n // 3 - 1) * 4 return res + # Time: O(n) # Space: O(logn) # DP solution. From f72638fadb900269a78ce60900679b80f4a52ce7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Apr 2016 06:40:01 -0500 Subject: [PATCH 2054/4971] Update evaluate-reverse-polish-notation.cpp --- C++/evaluate-reverse-polish-notation.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/evaluate-reverse-polish-notation.cpp b/C++/evaluate-reverse-polish-notation.cpp index c24c82169..6d1b33020 100644 --- a/C++/evaluate-reverse-polish-notation.cpp +++ b/C++/evaluate-reverse-polish-notation.cpp @@ -12,9 +12,9 @@ class Solution { if (!is_operator(tok)) { s.emplace(tok); } else { - auto y = stoi(s.top()); + auto&& y = stoi(s.top()); s.pop(); - auto x = stoi(s.top()); + auto&& x = stoi(s.top()); s.pop(); if (tok[0] == '+') { x += y; From a4184718ba1146f770ac908428b8c41f74e88d14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Apr 2016 13:31:56 +0800 Subject: [PATCH 2055/4971] Create reverse-string.py --- Python/reverse-string.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Python/reverse-string.py diff --git a/Python/reverse-string.py b/Python/reverse-string.py new file mode 100644 index 000000000..be5e9ce83 --- /dev/null +++ b/Python/reverse-string.py @@ -0,0 +1,33 @@ +# Time: O(n) +# Space: O(n) + +# Write a function that takes a string as input and +# returns the string reversed. +# +# Example: +# Given s = "hello", return "olleh". + +class Solution(object): + def reverseString(self, s): + """ + :type s: str + :rtype: str + """ + string = list(s) + i, j = 0, len(string) - 1 + while i < j: + string[i], string[j] = string[j], string[i] + i += 1 + j -= 1 + return "".join(string) + + +# Time: O(n) +# Space: O(n) +class Solution2(object): + def reverseString(self, s): + """ + :type s: str + :rtype: str + """ + return s[::-1] From 99a011fd6fc612260654dff31031c2abbf989fa3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Apr 2016 13:33:55 +0800 Subject: [PATCH 2056/4971] Create reverse-string.cpp --- C++/reverse-string.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/reverse-string.cpp diff --git a/C++/reverse-string.cpp b/C++/reverse-string.cpp new file mode 100644 index 000000000..c9fc329bc --- /dev/null +++ b/C++/reverse-string.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string reverseString(string s) { + for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { + swap(s[i], s[j]); + } + return s; + } +}; + +// Time: O(n) +// Space: O(1) +class Solution2 { +public: + string reverseString(string s) { + reverse(s.begin(), s.end()); + return s; + } +}; From bb1f651a13e26a292fd391459f4f8877be71e033 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Apr 2016 13:36:09 +0800 Subject: [PATCH 2057/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 90c69a55e..0307cc96f 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-343%20%2F%20343-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-344%20%2F%20344-ff69b4.svg) -Up to date (2016-04-19), there are `326` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-04-21), there are `327` 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 `343` questions. +Here is the classification of all `344` 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. ) @@ -118,6 +118,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | | +344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note From 3463b6f35765a586f9d29f2a668a0528c515e937 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Apr 2016 20:58:03 -0500 Subject: [PATCH 2058/4971] Update rotate-image.cpp --- C++/rotate-image.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/rotate-image.cpp b/C++/rotate-image.cpp index 70ff90fcd..d3ca7cc1a 100644 --- a/C++/rotate-image.cpp +++ b/C++/rotate-image.cpp @@ -7,7 +7,7 @@ class Solution { 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]; + const auto 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]; From 1b04bd4cfc8520d7681c7e3a0d80e153818519d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Apr 2016 23:33:53 +0800 Subject: [PATCH 2059/4971] Create reverse-vowels-of-a-string.cpp --- C++/reverse-vowels-of-a-string.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/reverse-vowels-of-a-string.cpp diff --git a/C++/reverse-vowels-of-a-string.cpp b/C++/reverse-vowels-of-a-string.cpp new file mode 100644 index 000000000..3bc11058a --- /dev/null +++ b/C++/reverse-vowels-of-a-string.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string reverseVowels(string s) { + for (int i = 0, j = s.length() - 1; i < j;) { + if (is_vowel(tolower(s[i])) && + is_vowel(tolower(s[j]))) { + swap(s[i++], s[j--]); + } else if (!is_vowel(tolower(s[i]))) { + ++i; + } else { + --j; + } + } + return s; + } + +private: + const string vowels_ = "aeiou"; + bool is_vowel(char a){ + return vowels_.find(a) != string::npos; + } +}; From dab37d1b094337575eadc9bed15c7beb9040cf99 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Apr 2016 23:40:32 +0800 Subject: [PATCH 2060/4971] Create reverse-vowels-of-a-string.py --- Python/reverse-vowels-of-a-string.py | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/reverse-vowels-of-a-string.py diff --git a/Python/reverse-vowels-of-a-string.py b/Python/reverse-vowels-of-a-string.py new file mode 100644 index 000000000..c6c4c8916 --- /dev/null +++ b/Python/reverse-vowels-of-a-string.py @@ -0,0 +1,32 @@ +# Time: O(n) +# Space: O(1) + +# Write a function that takes a string as input +# and reverse only the vowels of a string. +# +# Example 1: +# Given s = "hello", return "holle". +# +# Example 2: +# Given s = "leetcode", return "leotcede". + +class Solution(object): + def reverseVowels(self, s): + """ + :type s: str + :rtype: str + """ + vowels = "aeiou" + string = list(s) + i, j = 0, len(s) - 1 + while i < j: + if string[i].lower() in vowels and \ + string[j].lower() in vowels: + string[i], string[j] = string[j], string[i] + i += 1 + j -= 1 + elif string[i].lower() not in vowels: + i += 1 + else: + j -= 1 + return "".join(string) From 8fa4c168ca19f8d74a77919841a02c1e7540b158 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Apr 2016 23:42:29 +0800 Subject: [PATCH 2061/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0307cc96f..dc23a43fe 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-344%20%2F%20344-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-345%20%2F%20345-ff69b4.svg) -Up to date (2016-04-21), there are `327` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-04-23), there are `328` 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 `344` questions. +Here is the classification of all `345` 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. ) @@ -119,6 +119,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | | 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | +345| [Reverse String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note From 6046469654ee292cf90881c9904a4c81cd36fd04 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Apr 2016 23:44:17 +0800 Subject: [PATCH 2062/4971] Update reverse-vowels-of-a-string.cpp --- C++/reverse-vowels-of-a-string.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/C++/reverse-vowels-of-a-string.cpp b/C++/reverse-vowels-of-a-string.cpp index 3bc11058a..f919e4fdd 100644 --- a/C++/reverse-vowels-of-a-string.cpp +++ b/C++/reverse-vowels-of-a-string.cpp @@ -5,13 +5,12 @@ class Solution { public: string reverseVowels(string s) { for (int i = 0, j = s.length() - 1; i < j;) { - if (is_vowel(tolower(s[i])) && - is_vowel(tolower(s[j]))) { - swap(s[i++], s[j--]); - } else if (!is_vowel(tolower(s[i]))) { + if (!is_vowel(tolower(s[i]))) { ++i; - } else { + } else if (!is_vowel(tolower(s[j]))) { --j; + } else { + swap(s[i++], s[j--]); } } return s; From 3d3f5b809d73e4c6a754918ccc12f4abe49a1f73 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Apr 2016 23:45:30 +0800 Subject: [PATCH 2063/4971] Update reverse-vowels-of-a-string.py --- Python/reverse-vowels-of-a-string.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Python/reverse-vowels-of-a-string.py b/Python/reverse-vowels-of-a-string.py index c6c4c8916..f7eb88ae2 100644 --- a/Python/reverse-vowels-of-a-string.py +++ b/Python/reverse-vowels-of-a-string.py @@ -20,13 +20,12 @@ def reverseVowels(self, s): string = list(s) i, j = 0, len(s) - 1 while i < j: - if string[i].lower() in vowels and \ - string[j].lower() in vowels: - string[i], string[j] = string[j], string[i] + if string[i].lower() not in vowels: i += 1 + elif string[j].lower() not in vowels: j -= 1 - elif string[i].lower() not in vowels: - i += 1 else: + string[i], string[j] = string[j], string[i] + i += 1 j -= 1 return "".join(string) From 4497e870c387841e27d78ebf0b4c21d8087f1f45 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Apr 2016 23:47:58 +0800 Subject: [PATCH 2064/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index dc23a43fe..d17492fd1 100644 --- a/README.md +++ b/README.md @@ -118,8 +118,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | | -344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | -345| [Reverse String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -284,6 +282,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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)_ | Hard | | Binary Search, Two Pointers | +344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | +345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | ## Divide and Conquer # | Title | Solution | Time | Space | Difficulty | Tag | Note From 46dbe0cc0241e25abe4a472fd3e2f12bbcb5ba4e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Apr 2016 21:07:02 +0800 Subject: [PATCH 2065/4971] Update and rename lengthOfLongestSubstring.cpp to longest-substring-without-repeating-characters.cpp --- C++/lengthOfLongestSubstring.cpp | 21 ---------------- ...substring-without-repeating-characters.cpp | 25 +++++++++++++++++++ 2 files changed, 25 insertions(+), 21 deletions(-) delete mode 100644 C++/lengthOfLongestSubstring.cpp create mode 100644 C++/longest-substring-without-repeating-characters.cpp diff --git a/C++/lengthOfLongestSubstring.cpp b/C++/lengthOfLongestSubstring.cpp deleted file mode 100644 index 4d7486d17..000000000 --- a/C++/lengthOfLongestSubstring.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - int lengthOfLongestSubstring(string s) { - vector last(26, -1); - int start = 0; - int ans = 0; - - for(int i = 0; i < s.size(); ++i) { - if(last[s[i] - 'a'] >= start) { // meet a repeated character - ans = max(i - start, ans); // recount max length of substring - start = last[s[i] - 'a'] + 1; // update start index next to the repeated one - } - last[s[i] - 'a'] = i; // update last index - } - - return max(static_cast(s.size()) - start, ans); // recount max length of substring due to end - } -}; diff --git a/C++/longest-substring-without-repeating-characters.cpp b/C++/longest-substring-without-repeating-characters.cpp new file mode 100644 index 000000000..95aa6b37b --- /dev/null +++ b/C++/longest-substring-without-repeating-characters.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int lengthOfLongestSubstring(string s) { + // Record the last occurrence of each char. + unordered_map last_occurrence; + size_t starting_idx = 0, ans = 0; + for (size_t i = 0; i < s.size(); ++i) { + auto it(last_occurrence.find(s[i])); + if (it == last_occurrence.cend()) { + last_occurrence.emplace_hint(it, s[i], i); + } else { // s[i] appeared before. Check its validity. + if (it->second >= starting_idx) { + ans = max(ans, i - starting_idx); + starting_idx = it->second + 1; + } + it->second = i; + } + } + ans = max(ans, s.size() - starting_idx); + return ans; + } +}; From 9ff4d97647b74a8074e548e2deefdb579a8fb8e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Apr 2016 21:07:37 +0800 Subject: [PATCH 2066/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d17492fd1..c2947ea7e 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [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 || +3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [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 || From 3b19b1ac1cfb935b895570247206ee5a131f2621 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 17:45:29 +0800 Subject: [PATCH 2067/4971] Update and rename fourSum.cpp to 4sum.cpp --- C++/4sum.cpp | 36 ++++++++++++++++++++++++++++++++++++ C++/fourSum.cpp | 34 ---------------------------------- 2 files changed, 36 insertions(+), 34 deletions(-) create mode 100644 C++/4sum.cpp delete mode 100644 C++/fourSum.cpp diff --git a/C++/4sum.cpp b/C++/4sum.cpp new file mode 100644 index 000000000..a87b8e471 --- /dev/null +++ b/C++/4sum.cpp @@ -0,0 +1,36 @@ +// Time: O(n^2) +// Space: O(n^2) + +class Solution { +public: + vector > fourSum(vector &num, int target) { + vector> ans; + if (num.size() < 4) + return ans; + sort(num.begin(), num.end()); + unordered_multimap> cache; + + for (int i = 0; i + 1 < num.size(); ++i) { + for (int j = i + 1; j < num.size(); ++j) { + cache.insert(make_pair(num[i] + num[j], make_pair(i, j))); + } + } + + for (auto i = cache.begin(); i != cache.end(); ++i) { + int x = target - i->first; + auto range = cache.equal_range(x); + for (auto j = range.first; j != range.second; ++j) { + auto a = i->second.first; + auto b = i->second.second; + auto c = j->second.first; + auto d = j->second.second; + if (b < c) { + ans.push_back({num[a], num[b], num[c], num[d]}); + } + } + } + sort(ans.begin(), ans.end()); + ans.erase(unique(ans.begin(), ans.end()), ans.end()); + return ans; + } +}; diff --git a/C++/fourSum.cpp b/C++/fourSum.cpp deleted file mode 100644 index 0b62b1364..000000000 --- a/C++/fourSum.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// Time Complexity: O(n^2) -// Space Complexity: O(n^2) - -class Solution { - public: - vector > fourSum(vector &num, int target) { - vector> ans; - if (num.size() < 4) - return ans; - sort(num.begin(), num.end()); - unordered_multimap> cache; - - for (int i = 0; i + 1 < num.size(); ++i) - for (int j = i + 1; j < num.size(); ++j) - cache.insert(make_pair(num[i] + num[j], make_pair(i, j))); - - for (auto i = cache.begin(); i != cache.end(); ++i) { - int x = target - i->first; - auto range = cache.equal_range(x); - for (auto j = range.first; j != range.second; ++j) { - auto a = i->second.first; - auto b = i->second.second; - auto c = j->second.first; - auto d = j->second.second; - if (b < c) { - ans.push_back({ num[a], num[b], num[c], num[d] }); - } - } - } - sort(ans.begin(), ans.end()); - ans.erase(unique(ans.begin(), ans.end()), ans.end()); - return ans; - } -}; From 13e3a374813b215ce3b7440e24dd5a8ceab52749 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 17:48:58 +0800 Subject: [PATCH 2068/4971] Update 4sum.cpp --- C++/4sum.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/C++/4sum.cpp b/C++/4sum.cpp index a87b8e471..eed997c8a 100644 --- a/C++/4sum.cpp +++ b/C++/4sum.cpp @@ -5,14 +5,15 @@ class Solution { public: vector > fourSum(vector &num, int target) { vector> ans; - if (num.size() < 4) + if (num.size() < 4) { return ans; + } sort(num.begin(), num.end()); unordered_multimap> cache; for (int i = 0; i + 1 < num.size(); ++i) { for (int j = i + 1; j < num.size(); ++j) { - cache.insert(make_pair(num[i] + num[j], make_pair(i, j))); + cache.emplace(num[i] + num[j], make_pair(i, j)); } } From 0f2459566848141acc42824f6f1f81131ea8eff2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 17:49:43 +0800 Subject: [PATCH 2069/4971] Update 4sum.cpp --- C++/4sum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/4sum.cpp b/C++/4sum.cpp index eed997c8a..73f469223 100644 --- a/C++/4sum.cpp +++ b/C++/4sum.cpp @@ -1,4 +1,4 @@ -// Time: O(n^2) +// Time: O(n^4) // Space: O(n^2) class Solution { From 9d3d66f36d7b2e01441fc69c310fe88a1274005d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 18:00:05 +0800 Subject: [PATCH 2070/4971] Update 4sum.cpp --- C++/4sum.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/C++/4sum.cpp b/C++/4sum.cpp index 73f469223..b5229259a 100644 --- a/C++/4sum.cpp +++ b/C++/4sum.cpp @@ -1,7 +1,56 @@ -// Time: O(n^4) +// Time: O(n^3) // Space: O(n^2) class Solution { +public: + vector > fourSum(vector &nums, int target) { + int len = nums.size(); + int left, right, sum; + sort(nums.begin(), nums.end()); + vector> res; + vector tmp; + for (int i = 0; i < len - 3; ++i) { + if (i && nums[i] == nums[i - 1]) { + continue; + } + for (int j = i + 1; j < len - 2; ++j) { + if (j != i + 1 && nums[j] == nums[j - 1]) { + continue; + } + sum = target - nums[i] - nums[j]; + left = j + 1, right = len - 1; + while (left < right) { + if (nums[left] + nums[right] == sum) { + tmp.clear(); + tmp.emplace_back(nums[i]); + tmp.emplace_back(nums[j]); + tmp.emplace_back(nums[left]); + tmp.emplace_back(nums[right]); + res.emplace_back(tmp); + left++, right--; + while (left < right && nums[left] == nums[left - 1]) { + ++left; + } + while (left < right && nums[right] == nums[right + 1]) { + --right; + } + } else { + if (nums[left] + nums[right] > sum) { + --right; + } else { + ++left; + } + } + } + } + } + return res; + } +}; + +// Time: O(n^4) +// Space: O(n^2) +class Solution2 { public: vector > fourSum(vector &num, int target) { vector> ans; From fa7d6826e42b37a73fba53e3c53e2df5c622406e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 22:19:34 +0800 Subject: [PATCH 2071/4971] Update 4sum.cpp --- C++/4sum.cpp | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/C++/4sum.cpp b/C++/4sum.cpp index b5229259a..5a8b756d3 100644 --- a/C++/4sum.cpp +++ b/C++/4sum.cpp @@ -3,39 +3,33 @@ class Solution { public: - vector > fourSum(vector &nums, int target) { - int len = nums.size(); + vector > fourSum(vector &num, int target) { + int len = num.size(); int left, right, sum; - sort(nums.begin(), nums.end()); + sort(num.begin(), num.end()); vector> res; - vector tmp; for (int i = 0; i < len - 3; ++i) { - if (i && nums[i] == nums[i - 1]) { + if (i && num[i] == num[i - 1]) { continue; } for (int j = i + 1; j < len - 2; ++j) { - if (j != i + 1 && nums[j] == nums[j - 1]) { + if (j != i + 1 && num[j] == num[j - 1]) { continue; } - sum = target - nums[i] - nums[j]; + sum = target - num[i] - num[j]; left = j + 1, right = len - 1; while (left < right) { - if (nums[left] + nums[right] == sum) { - tmp.clear(); - tmp.emplace_back(nums[i]); - tmp.emplace_back(nums[j]); - tmp.emplace_back(nums[left]); - tmp.emplace_back(nums[right]); - res.emplace_back(tmp); - left++, right--; - while (left < right && nums[left] == nums[left - 1]) { + if (num[left] + num[right] == sum) { + res.emplace_back(move(vector{num[i], num[j], num[left], num[right]})); + ++left, --right; + while (left < right && num[left] == num[left - 1]) { ++left; } - while (left < right && nums[right] == nums[right + 1]) { + while (left < right && num[right] == num[right + 1]) { --right; } } else { - if (nums[left] + nums[right] > sum) { + if (num[left] + num[right] > sum) { --right; } else { ++left; From dc5f08adaf5bee03a043cd8f8818d81f1243482c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 22:20:27 +0800 Subject: [PATCH 2072/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c2947ea7e..af3c379da 100644 --- a/README.md +++ b/README.md @@ -190,7 +190,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [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/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [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 || +18| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(n^2)_ | 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| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(nlogg)_ | _O(n)_ | Medium || From c80b17ad2fd8af101f900d5646ccdb7642cab65c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 22:22:39 +0800 Subject: [PATCH 2073/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index af3c379da..02640d683 100644 --- a/README.md +++ b/README.md @@ -190,7 +190,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [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/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || -18| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(n^2)_ | Medium || +18| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(1)_ | 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| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(nlogg)_ | _O(n)_ | Medium || From c874c14c9a201aa6ca096575046516546891e24a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 22:22:57 +0800 Subject: [PATCH 2074/4971] Update 4sum.cpp --- C++/4sum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/4sum.cpp b/C++/4sum.cpp index 5a8b756d3..72e8cc5e7 100644 --- a/C++/4sum.cpp +++ b/C++/4sum.cpp @@ -1,5 +1,5 @@ // Time: O(n^3) -// Space: O(n^2) +// Space: O(1) class Solution { public: From 904ec537a4098e966aefee337b31ed41c34f7c3b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 22:32:31 +0800 Subject: [PATCH 2075/4971] Update 4sum.py --- Python/4sum.py | 61 ++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/Python/4sum.py b/Python/4sum.py index 0ad8b8075..d65759bdc 100644 --- a/Python/4sum.py +++ b/Python/4sum.py @@ -1,6 +1,6 @@ -# Time: O(n^2 * p) -# Space: O(n^2 * p) -# +# Time: O(n^3) +# Space: O(1) + # Given an array S of n integers, # are there elements a, b, c, and d in S such that a + b + c + d = target? # Find all unique quadruplets in the array which gives the sum of target. @@ -16,9 +16,50 @@ # (-2, 0, 0, 2) # -class Solution: - # @return a list of lists of length 4, [[val1,val2,val3,val4]] +# Two pointer solution. (1356ms) +class Solution(object): def fourSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[List[int]] + """ + nums.sort() + res = [] + for i in xrange(len(nums) - 3): + if i and nums[i] == nums[i - 1]: + continue + for j in xrange(i + 1, len(nums) - 2): + if j != i + 1 and nums[j] == nums[j - 1]: + continue + sum = target - nums[i] - nums[j] + left, right = j + 1, len(nums) - 1 + while left < right: + if nums[left] + nums[right] == sum: + res.append([nums[i], nums[j], nums[left], nums[right]]) + right -= 1 + left += 1 + while left < right and nums[left] == nums[left - 1]: + left += 1 + while left < right and nums[right] == nums[right + 1]: + right -= 1 + elif nums[left] + nums[right] > sum: + right -= 1 + else: + left += 1 + return res + + +# Time: O(n^2 * p) +# Space: O(n^2 * p) +# Hash solution. (224ms) +class Solution2(object): + def fourSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[List[int]] + """ nums, result, lookup = sorted(nums), [], collections.defaultdict(list) for i in xrange(0, len(nums) - 1): for j in xrange(i + 1, len(nums)): @@ -42,11 +83,16 @@ def fourSum(self, nums, target): 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]] +class Solution3(object): def fourSum(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[List[int]] + """ nums, result, lookup = sorted(nums), [], collections.defaultdict(list) for i in xrange(0, len(nums) - 1): for j in xrange(i + 1, len(nums)): @@ -63,6 +109,7 @@ def fourSum(self, nums, target): result.append(quad) return sorted(result) + if __name__ == '__main__': result = Solution().fourSum([1, 0, -1, 0, -2, 2], 0) print result From 781591f9cef34dfd7f00c1bd2fb406f402994e71 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 22:40:41 +0800 Subject: [PATCH 2076/4971] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 02640d683..424c872f9 100644 --- a/README.md +++ b/README.md @@ -59,8 +59,9 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Array # | 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 || +15 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || Two Pointers +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 || Two Pointers +18| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(1)_ | Medium || Two Pointers 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 @@ -190,7 +191,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [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/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || -18| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(1)_ | 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| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(nlogg)_ | _O(n)_ | Medium || From f70bf2fcbdbf3da3fc0675fa8d2abdf6426f4277 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 22:42:34 +0800 Subject: [PATCH 2077/4971] Update 4sum.cpp --- C++/4sum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/4sum.cpp b/C++/4sum.cpp index 72e8cc5e7..8a142f908 100644 --- a/C++/4sum.cpp +++ b/C++/4sum.cpp @@ -69,7 +69,7 @@ class Solution2 { auto c = j->second.first; auto d = j->second.second; if (b < c) { - ans.push_back({num[a], num[b], num[c], num[d]}); + ans.emplace_back(move(vector{num[a], num[b], num[c], num[d]})); } } } From 55cc89ca6a1b619aeb43bd0f21507fdd4d91527c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 22:51:33 +0800 Subject: [PATCH 2078/4971] Update 4sum.cpp --- C++/4sum.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/4sum.cpp b/C++/4sum.cpp index 8a142f908..00f25fc61 100644 --- a/C++/4sum.cpp +++ b/C++/4sum.cpp @@ -54,18 +54,18 @@ class Solution2 { sort(num.begin(), num.end()); unordered_multimap> cache; - for (int i = 0; i + 1 < num.size(); ++i) { + for (int i = 0; i < num.size(); ++i) { for (int j = i + 1; j < num.size(); ++j) { cache.emplace(num[i] + num[j], make_pair(i, j)); } } for (auto i = cache.begin(); i != cache.end(); ++i) { + auto a = i->second.first; + auto b = i->second.second; int x = target - i->first; auto range = cache.equal_range(x); for (auto j = range.first; j != range.second; ++j) { - auto a = i->second.first; - auto b = i->second.second; auto c = j->second.first; auto d = j->second.second; if (b < c) { From ac2ee7fa90023dbe032f637b7762a4aae1d74a09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Apr 2016 22:52:03 +0800 Subject: [PATCH 2079/4971] Update 4sum.cpp --- C++/4sum.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/4sum.cpp b/C++/4sum.cpp index 00f25fc61..5048842e2 100644 --- a/C++/4sum.cpp +++ b/C++/4sum.cpp @@ -63,8 +63,7 @@ class Solution2 { for (auto i = cache.begin(); i != cache.end(); ++i) { auto a = i->second.first; auto b = i->second.second; - int x = target - i->first; - auto range = cache.equal_range(x); + auto range = cache.equal_range(target - i->first); for (auto j = range.first; j != range.second; ++j) { auto c = j->second.first; auto d = j->second.second; From 346bb4832fdbcf5672fc3e1cf8691ef66ebed3c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Apr 2016 22:07:39 +0800 Subject: [PATCH 2080/4971] Update and rename findSubstring.cpp to substring-with-concatenation-of-all-words.cpp --- C++/findSubstring.cpp | 32 --------------- ...string-with-concatenation-of-all-words.cpp | 39 +++++++++++++++++++ 2 files changed, 39 insertions(+), 32 deletions(-) delete mode 100644 C++/findSubstring.cpp create mode 100644 C++/substring-with-concatenation-of-all-words.cpp diff --git a/C++/findSubstring.cpp b/C++/findSubstring.cpp deleted file mode 100644 index 749cc5378..000000000 --- a/C++/findSubstring.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// Time Complexity: O((m - n * k) * n * k) ~ O(m * n * k), where m is string length, n is dict size, k is word length -// Space Complexity: O( n * k) -class Solution { - public: - vector findSubstring(string s, vector &dict) { - const size_t wordLength = dict.front().length(); - const size_t catLength = wordLength * dict.size(); - vector result; - - if(s.length() < catLength) return result; - - unordered_map wordCount; - - for(auto const & word : dict) ++wordCount[word]; - - for(auto i = begin(s); i <= prev(end(s), catLength); ++i) { - unordered_map unused(wordCount); - - for(auto j = i; j != next(i, catLength); j += wordLength) { - auto pos = unused.find(string(j, next(j, wordLength))); - - if(pos == unused.end()) break; - - if(--pos->second == 0) unused.erase(pos); - } - - if(unused.size() == 0) result.push_back(distance(begin(s), i)); - } - - return result; - } -}; diff --git a/C++/substring-with-concatenation-of-all-words.cpp b/C++/substring-with-concatenation-of-all-words.cpp new file mode 100644 index 000000000..c1356a90c --- /dev/null +++ b/C++/substring-with-concatenation-of-all-words.cpp @@ -0,0 +1,39 @@ +// Time: O((m - n * k) * n * k) ~ O(m * n * k), m is the length of the string, +// n is the size of the dictionary, +// k is the length of each word +// Space: O(n * k) + +class Solution { +public: + vector findSubstring(string s, vector& words) { + const auto word_length = words.front().length(); + const auto cat_length = word_length * words.size(); + vector result; + + if (s.length() < cat_length) { + return result; + } + + unordered_map wordCount; + for (const auto & word : words) { + ++wordCount[word]; + } + + for (auto it = s.begin(); it != prev(s.end(), cat_length - 1); ++it) { + unordered_map unused(wordCount); + for (auto jt = it; jt != next(it, cat_length); jt += word_length) { + auto pos = unused.find(string(jt, next(jt, word_length))); + if (pos == unused.end()) { + break; + } + if (--pos->second == 0) { + unused.erase(pos); + } + } + if (unused.empty()) { + result.emplace_back(distance(s.begin(), it)); + } + } + return result; + } +}; From a4e337636a8c485119691db397b65e9a0e59f91a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Apr 2016 22:08:17 +0800 Subject: [PATCH 2081/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 424c872f9..4097eeaa6 100644 --- a/README.md +++ b/README.md @@ -191,7 +191,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [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/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | 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 || +30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [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| [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 || From b54c5d9d9bc9e6306ea73467dfb82d15e22a4f5d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 Apr 2016 00:22:59 +0800 Subject: [PATCH 2082/4971] Update implement-stack-using-queues.cpp --- C++/implement-stack-using-queues.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/implement-stack-using-queues.cpp b/C++/implement-stack-using-queues.cpp index a344f90e6..baf0b5789 100644 --- a/C++/implement-stack-using-queues.cpp +++ b/C++/implement-stack-using-queues.cpp @@ -14,7 +14,7 @@ class Stack { } } - // Removes the element on top of the stack. + // Remove the element on top of the stack. void pop() { // O(1) q_.pop(); } @@ -43,7 +43,7 @@ class Stack2 { top_ = x; } - // Removes the element on top of the stack. + // Remove the element on top of the stack. void pop() { // O(n) for (int i = 0; i < q_.size() - 1; ++i) { top_ = q_.front(); From 95e55e2d6c7d61e2a6d536439f93d08ed4ab7386 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Apr 2016 11:19:20 +0800 Subject: [PATCH 2083/4971] Update and rename isValidSudoku.cpp to valid-sudoku.cpp --- C++/isValidSudoku.cpp | 47 ----------------------------------------- C++/valid-sudoku.cpp | 49 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 47 deletions(-) delete mode 100644 C++/isValidSudoku.cpp create mode 100644 C++/valid-sudoku.cpp diff --git a/C++/isValidSudoku.cpp b/C++/isValidSudoku.cpp deleted file mode 100644 index 021c8fa83..000000000 --- a/C++/isValidSudoku.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// Time Complexity: O(n^2) -// Space Complexity: O(n) - -class Solution { - public: - bool isValidSudoku(vector > &board) { - bool used[9]; - - for(int i = 0; i < 9; ++i) { - fill(used, used + 9, false); - for(int j = 0; j < 9; ++j) { - if(!check(board[i][j], used)) - return false; - } - - fill(used, used + 9, false); - for(int j = 0; j < 9; ++j) { - if(!check(board[j][i], used)) - return false; - } - } - - for(int r = 0; r < 3; ++r) { - for(int c = 0; c < 3; ++c) { - fill(used, used + 9, false); - for(int i = 3 * r; i < 3 * (r + 1); ++i) { - for(int j = 3 * c; j < 3 * (c + 1); ++j) { - if(!check(board[i][j], used)) - return false; - } - } - } - } - - return true; - } - - private: - bool check(char c, bool used[9]) { - if(c != '.') { - if(used[c - '1']) - return false; - used[c - '1'] = true; - } - return true; - } -}; diff --git a/C++/valid-sudoku.cpp b/C++/valid-sudoku.cpp new file mode 100644 index 000000000..c974d9d36 --- /dev/null +++ b/C++/valid-sudoku.cpp @@ -0,0 +1,49 @@ +// Time: O(9^2) +// Space: O(9) + +class Solution { +public: + bool isValidSudoku(const vector>& board) { + // Check row constraints. + for (int i = 0; i < board.size(); ++i) { + if (anyDuplicate(board, i, i + 1, 0, board.size(), board.size())) { + return false; + } + } + + // Check column constraints. + for (int j = 0; j < board.size(); ++j) { + if (anyDuplicate(board, 0, board.size(), j, j + 1, board.size())) { + return false; + } + } + + // Check region constraints. + int region_size = sqrt(board.size()); + for (int i = 0; i < region_size; ++i) { + for (int j = 0; j < region_size; ++j) { + if (anyDuplicate(board, region_size * i, region_size * (i + 1), + region_size * j, region_size * (j + 1), board.size())) { + return false; + } + } + } + return true; + } + + // Return true if subarray board[start_row : end_row - 1][start_col : end_col - 1] + // contains any duplicates in [1 : num_elements]; otherwise return false. + bool anyDuplicate(const vector>& board, int start_row, int end_row, + int start_col, int end_col, int num_elements) { + deque is_present(num_elements + 1, false); + for (int i = start_row; i < end_row; ++i) { + for (int j = start_col; j < end_col; ++j) { + if (board[i][j] != '.' && is_present[board[i][j] - '0']) { + return true; + } + is_present[board[i][j] - '0'] = true; + } + } + return false; + } +}; From c61abea0f6487ec7aba61c7d6e59732023f0c7ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Apr 2016 11:36:21 +0800 Subject: [PATCH 2084/4971] Update valid-sudoku.cpp --- C++/valid-sudoku.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/C++/valid-sudoku.cpp b/C++/valid-sudoku.cpp index c974d9d36..d4fdce8bd 100644 --- a/C++/valid-sudoku.cpp +++ b/C++/valid-sudoku.cpp @@ -35,13 +35,16 @@ class Solution { // contains any duplicates in [1 : num_elements]; otherwise return false. bool anyDuplicate(const vector>& board, int start_row, int end_row, int start_col, int end_col, int num_elements) { - deque is_present(num_elements + 1, false); + vector is_present(num_elements + 1, false); + for (int i = start_row; i < end_row; ++i) { for (int j = start_col; j < end_col; ++j) { - if (board[i][j] != '.' && is_present[board[i][j] - '0']) { - return true; + if (board[i][j] != '.') { + if (is_present[board[i][j]]) { + return true; + } + is_present[board[i][j]] = true; } - is_present[board[i][j] - '0'] = true; } } return false; From 83031c023112025787bd70a03a24ad7f4b2103f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Apr 2016 11:37:18 +0800 Subject: [PATCH 2085/4971] Update valid-sudoku.cpp --- C++/valid-sudoku.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/valid-sudoku.cpp b/C++/valid-sudoku.cpp index d4fdce8bd..56cb94dfb 100644 --- a/C++/valid-sudoku.cpp +++ b/C++/valid-sudoku.cpp @@ -36,7 +36,6 @@ class Solution { bool anyDuplicate(const vector>& board, int start_row, int end_row, int start_col, int end_col, int num_elements) { vector is_present(num_elements + 1, false); - for (int i = start_row; i < end_row; ++i) { for (int j = start_col; j < end_col; ++j) { if (board[i][j] != '.') { From cfe0867effff83cdc92a91968e252653f81b28f6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Apr 2016 11:43:16 +0800 Subject: [PATCH 2086/4971] Update valid-sudoku.cpp --- C++/valid-sudoku.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/valid-sudoku.cpp b/C++/valid-sudoku.cpp index 56cb94dfb..dc013487d 100644 --- a/C++/valid-sudoku.cpp +++ b/C++/valid-sudoku.cpp @@ -39,10 +39,10 @@ class Solution { for (int i = start_row; i < end_row; ++i) { for (int j = start_col; j < end_col; ++j) { if (board[i][j] != '.') { - if (is_present[board[i][j]]) { + if (is_present[board[i][j] - '0']) { return true; } - is_present[board[i][j]] = true; + is_present[board[i][j] - '0'] = true; } } } From f8e49247f35516d9ce2dc298ee85f0064c1e2383 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Apr 2016 11:44:28 +0800 Subject: [PATCH 2087/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4097eeaa6..6d62e4460 100644 --- a/README.md +++ b/README.md @@ -192,7 +192,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [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/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [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 || +36| [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || 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 || From 4639226ca46619893ea28553c9f6c8ea212f9145 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Apr 2016 11:48:32 +0800 Subject: [PATCH 2088/4971] Update valid-sudoku.py --- Python/valid-sudoku.py | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/Python/valid-sudoku.py b/Python/valid-sudoku.py index 7de8b05c5..610964276 100644 --- a/Python/valid-sudoku.py +++ b/Python/valid-sudoku.py @@ -1,27 +1,32 @@ -# Time: O(n^2) -# Space: O(n) +# Time: O(9^2) +# Space: O(9) + +# Determine if a Sudoku is valid, +# according to: Sudoku Puzzles - The Rules. +# +# The Sudoku board could be partially filled, +# where empty cells are filled with the character '.'. # -# Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. -# -# The Sudoku board could be partially filled, where empty cells are filled with the character '.'. -# -# # A partially filled sudoku which is valid. -# -# Note: -# A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. # +# Note: +# A valid Sudoku board (partially filled) is not necessarily solvable. +# Only the filled cells need to be validated. -class Solution: - # @param board, a 9x9 2D array - # @return a boolean +class Solution(object): def isValidSudoku(self, board): + """ + :type board: List[List[str]] + :rtype: bool + """ for i in xrange(9): - if not self.isValidList([board[i][j] for j in xrange(9)]) or not self.isValidList([board[j][i] for j in xrange(9)]): + if not self.isValidList([board[i][j] for j in xrange(9)]) or \ + not self.isValidList([board[j][i] for j in xrange(9)]): return False for i in xrange(3): for j in xrange(3): - if not self.isValidList([board[m][n] for n in xrange(3 * j, 3 * j + 3) for m in xrange(3 * i, 3 * i + 3)]): + if not self.isValidList([board[m][n] for n in xrange(3 * j, 3 * j + 3) \ + for m in xrange(3 * i, 3 * i + 3)]): return False return True @@ -29,6 +34,7 @@ def isValidList(self, xs): xs = filter(lambda x: x != '.', xs) return len(set(xs)) == len(xs) + if __name__ == "__main__": board = [[1, '.', '.', '.', '.', '.', '.', '.', '.'], ['.', 2, '.', '.', '.', '.', '.', '.', '.'], From 671157f900e76781fe3b08fa01f4977c0dbf8f04 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Apr 2016 12:00:22 +0800 Subject: [PATCH 2089/4971] Update valid-sudoku.cpp --- C++/valid-sudoku.cpp | 53 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/C++/valid-sudoku.cpp b/C++/valid-sudoku.cpp index dc013487d..a39290e46 100644 --- a/C++/valid-sudoku.cpp +++ b/C++/valid-sudoku.cpp @@ -1,7 +1,60 @@ // Time: O(9^2) // Space: O(9) +// Better performance solution. class Solution { +public: + bool isValidSudoku(const vector>& board) { + // Check row constraints. + for (int i = 0; i < 9; ++i) { + if (anyDuplicate(board, i, i + 1, 0, 9)) { + return false; + } + } + + // Check column constraints. + for (int j = 0; j < board.size(); ++j) { + if (anyDuplicate(board, 0, 9, j, j + 1)) { + return false; + } + } + + // Check region constraints. + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + if (anyDuplicate(board, 3 * i, 3 * (i + 1), + 3 * j, 3 * (j + 1))) { + return false; + } + } + } + return true; + } + + // Return true if subarray board[start_row : end_row - 1][start_col : end_col - 1] + // contains any duplicates in [1 : num_elements]; otherwise return false. + bool anyDuplicate(const vector>& board, int start_row, int end_row, + int start_col, int end_col) { + bitset<9> is_present; + for (int i = start_row; i < end_row; ++i) { + for (int j = start_col; j < end_col; ++j) { + if (board[i][j] != '.') { + if (is_present[board[i][j] - '1']) { + return true; + } + is_present.flip(board[i][j] - '1'); + } + } + } + return false; + } +}; + + +// Time: O(9^2) +// Space: O(9) +// More generic solutoin. +class Solution2 { public: bool isValidSudoku(const vector>& board) { // Check row constraints. From 6880bd7bb8cf75ccbb0da6a7006b345941a3efc1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Apr 2016 12:00:45 +0800 Subject: [PATCH 2090/4971] Update valid-sudoku.cpp --- C++/valid-sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/valid-sudoku.cpp b/C++/valid-sudoku.cpp index a39290e46..b8d0c1e4a 100644 --- a/C++/valid-sudoku.cpp +++ b/C++/valid-sudoku.cpp @@ -53,7 +53,7 @@ class Solution { // Time: O(9^2) // Space: O(9) -// More generic solutoin. +// More generic solution. class Solution2 { public: bool isValidSudoku(const vector>& board) { From aa8c95abbd53ffc47840545a8d460cd765c8674e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Apr 2016 12:01:09 +0800 Subject: [PATCH 2091/4971] Update valid-sudoku.cpp --- C++/valid-sudoku.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/C++/valid-sudoku.cpp b/C++/valid-sudoku.cpp index b8d0c1e4a..707925622 100644 --- a/C++/valid-sudoku.cpp +++ b/C++/valid-sudoku.cpp @@ -31,6 +31,7 @@ class Solution { return true; } +private: // Return true if subarray board[start_row : end_row - 1][start_col : end_col - 1] // contains any duplicates in [1 : num_elements]; otherwise return false. bool anyDuplicate(const vector>& board, int start_row, int end_row, @@ -84,6 +85,7 @@ class Solution2 { return true; } +private: // Return true if subarray board[start_row : end_row - 1][start_col : end_col - 1] // contains any duplicates in [1 : num_elements]; otherwise return false. bool anyDuplicate(const vector>& board, int start_row, int end_row, From 7086d143786c4bf001c8c08527b4858fd5d7ce0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Apr 2016 12:15:00 +0800 Subject: [PATCH 2092/4971] Update valid-sudoku.cpp --- C++/valid-sudoku.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/C++/valid-sudoku.cpp b/C++/valid-sudoku.cpp index 707925622..07a4c043e 100644 --- a/C++/valid-sudoku.cpp +++ b/C++/valid-sudoku.cpp @@ -20,10 +20,9 @@ class Solution { } // Check region constraints. - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 3; ++j) { - if (anyDuplicate(board, 3 * i, 3 * (i + 1), - 3 * j, 3 * (j + 1))) { + for (int i = 0; i < 9; i += 3) { + for (int j = 0; j < 9; j += 3) { + if (anyDuplicate(board, i, i + 3, j, j + 3)) { return false; } } @@ -74,10 +73,12 @@ class Solution2 { // Check region constraints. int region_size = sqrt(board.size()); - for (int i = 0; i < region_size; ++i) { - for (int j = 0; j < region_size; ++j) { - if (anyDuplicate(board, region_size * i, region_size * (i + 1), - region_size * j, region_size * (j + 1), board.size())) { + for (int i = 0; i < board.size(); i += region_size) { + for (int j = 0; j < board.size(); j += region_size) { + if (anyDuplicate(board, + i, i + region_size, + j, j + region_size, + board.size())) { return false; } } From 2765474d9951d3230033d4a45169d40aca950c65 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 May 2016 19:41:04 +0800 Subject: [PATCH 2093/4971] Create moving-average-from-data-stream.cpp --- C++/moving-average-from-data-stream.cpp | 31 +++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/moving-average-from-data-stream.cpp diff --git a/C++/moving-average-from-data-stream.cpp b/C++/moving-average-from-data-stream.cpp new file mode 100644 index 000000000..e4ac8d76e --- /dev/null +++ b/C++/moving-average-from-data-stream.cpp @@ -0,0 +1,31 @@ +// Time: O(1) +// Space: O(w) + +class MovingAverage { +public: + /** Initialize your data structure here. */ + MovingAverage(int size) : size_(size), sum_(0) { + } + + double next(int val) { + if (q_.size() == size_) { + sum_ -= q_.front(); + q_.pop(); + } + q_.emplace(val); + sum_ += val; + return 1.0 * sum_ / q_.size(); + } + +private: + int size_; + int sum_; + queue q_; +}; + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage obj = new MovingAverage(size); + * double param_1 = obj.next(val); + */ + From a1a4bb41ac2d2d7c4650ee956fcc4f73c4965e9b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 May 2016 19:44:45 +0800 Subject: [PATCH 2094/4971] Create moving-average-from-data-stream.py --- Python/moving-average-from-data-stream.py | 31 +++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/moving-average-from-data-stream.py diff --git a/Python/moving-average-from-data-stream.py b/Python/moving-average-from-data-stream.py new file mode 100644 index 000000000..d61bdaded --- /dev/null +++ b/Python/moving-average-from-data-stream.py @@ -0,0 +1,31 @@ +# Time: O(1) +# Space: O(w) + +from collections import deque + +class MovingAverage(object): + + def __init__(self, size): + """ + Initialize your data structure here. + :type size: int + """ + self.__size = size + self.__sum = 0 + self.__q = deque([]) + + def next(self, val): + """ + :type val: int + :rtype: float + """ + if len(self.__q) == self.__size: + self.__sum -= self.__q.popleft() + self.__sum += val + self.__q.append(val) + return 1.0 * self.__sum / len(self.__q) + + +# Your MovingAverage object will be instantiated and called as such: +# obj = MovingAverage(size) +# param_1 = obj.next(val) From 4a8c155d989d2b5fd6588d9661a0ef644ab6d6a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 May 2016 19:46:18 +0800 Subject: [PATCH 2095/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6d62e4460..77c4e2c8b 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-345%20%2F%20345-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-346%20%2F%20346-ff69b4.svg) -Up to date (2016-04-23), there are `328` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-05-01), there are `329` 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 `345` questions. +Here is the classification of all `346` 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. ) @@ -162,6 +162,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 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 |📖|| +346| [Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/)| [C++](./C++/moving-average-from-data-stream.cpp) [Python](./Python/moving-average-from-data-stream.py) | _O(1)_ | _O(w)_ | Easy |📖|| ## Heap # | Title | Solution | Time | Space | Difficulty | Tag | Note From a9e0b9741cccf87f6d105981f378d820c6c52d41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 May 2016 10:09:28 +0800 Subject: [PATCH 2096/4971] Create top-k-frequent-elements.cpp --- C++/top-k-frequent-elements.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/top-k-frequent-elements.cpp diff --git a/C++/top-k-frequent-elements.cpp b/C++/top-k-frequent-elements.cpp new file mode 100644 index 000000000..a5971fe31 --- /dev/null +++ b/C++/top-k-frequent-elements.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map counts; + for (int i = 0; i < nums.size(); ++i) { + ++counts[nums[i]]; + } + vector> p; + for (auto it = counts.begin(); it != counts.end(); ++it) { + p.emplace_back(-(it->second), it->first); + } + nth_element(p.begin(), p.begin() + k - 1, p.end()); + + vector result; + for (int i = 0; i < k; ++i) { + result.emplace_back(p[i].second); + } + return result; + } +}; From de3bd390a23f3fc0b6fb2e4a458cf61356868fc8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 May 2016 10:13:33 +0800 Subject: [PATCH 2097/4971] Update top-k-frequent-elements.cpp --- C++/top-k-frequent-elements.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/top-k-frequent-elements.cpp b/C++/top-k-frequent-elements.cpp index a5971fe31..217a176d0 100644 --- a/C++/top-k-frequent-elements.cpp +++ b/C++/top-k-frequent-elements.cpp @@ -5,8 +5,8 @@ class Solution { public: vector topKFrequent(vector& nums, int k) { unordered_map counts; - for (int i = 0; i < nums.size(); ++i) { - ++counts[nums[i]]; + for (const auto& i : nums) { + ++counts[i]; } vector> p; for (auto it = counts.begin(); it != counts.end(); ++it) { From 1cde379dc3c0bfd703c86e392b2a7859898dc040 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 May 2016 10:34:05 +0800 Subject: [PATCH 2098/4971] Create top-k-frequent-elements.py --- Python/top-k-frequent-elements.py | 65 +++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Python/top-k-frequent-elements.py diff --git a/Python/top-k-frequent-elements.py b/Python/top-k-frequent-elements.py new file mode 100644 index 000000000..c5184c649 --- /dev/null +++ b/Python/top-k-frequent-elements.py @@ -0,0 +1,65 @@ +# Time: O(n) +# Space: O(n) + +# Given a non-empty array of integers, +# return the k most frequent elements. +# +# For example, +# Given [1,1,1,2,2,3] and k = 2, return [1,2]. +# +# Note: +# You may assume k is always valid, +# 1 <= k <= number of unique elements. +# Your algorithm's time complexity must be better +# than O(n log n), where n is the array's size. + +from random import randint + +class Solution(object): + def topKFrequent(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + counts = collections.defaultdict(int) + for i in nums: + counts[i] += 1 + + p = [] + for key, val in counts.iteritems(): + p.append((val, key)) + + self.kthElement(p, k); + + result = [] + for i in xrange(k): + result.append(p[i][1]) + + return result + + + def kthElement(self, nums, k): + def PartitionAroundPivot(left, right, pivot_idx, nums): + pivot_value = nums[pivot_idx][0] + new_pivot_idx = left + nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx] + for i in xrange(left, right): + if nums[i][0] > 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 + + 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 + elif new_pivot_idx > k - 1: + right = new_pivot_idx - 1 + else: # new_pivot_idx < k - 1. + left = new_pivot_idx + 1 + From 5f5121a75a5f972dc42bac0c037238cfa91619b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 May 2016 10:38:18 +0800 Subject: [PATCH 2099/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 77c4e2c8b..d4083d5d6 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-346%20%2F%20346-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-347%20%2F%20347-ff69b4.svg) -Up to date (2016-05-01), there are `329` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-05-02), there are `330` 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 `346` questions. +Here is the classification of all `347` 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. ) @@ -270,6 +270,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | +347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(1)_ | Medium | | Partition Sort | ## Two Pointers # | Title | Solution | Time | Space | Difficulty | Tag | Note From 056a1b769db7f05402b41ffdcb565585db06bf97 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 May 2016 10:39:28 +0800 Subject: [PATCH 2100/4971] Update top-k-frequent-elements.py --- Python/top-k-frequent-elements.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/Python/top-k-frequent-elements.py b/Python/top-k-frequent-elements.py index c5184c649..40179730b 100644 --- a/Python/top-k-frequent-elements.py +++ b/Python/top-k-frequent-elements.py @@ -29,13 +29,11 @@ def topKFrequent(self, nums, k): p = [] for key, val in counts.iteritems(): p.append((val, key)) - self.kthElement(p, k); result = [] for i in xrange(k): result.append(p[i][1]) - return result From 684297a9236df4f9a2fd39c18138d08e098694af Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 May 2016 21:44:56 -0500 Subject: [PATCH 2101/4971] Update top-k-frequent-elements.cpp --- C++/top-k-frequent-elements.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/top-k-frequent-elements.cpp b/C++/top-k-frequent-elements.cpp index 217a176d0..59292d1ca 100644 --- a/C++/top-k-frequent-elements.cpp +++ b/C++/top-k-frequent-elements.cpp @@ -8,6 +8,7 @@ class Solution { for (const auto& i : nums) { ++counts[i]; } + vector> p; for (auto it = counts.begin(); it != counts.end(); ++it) { p.emplace_back(-(it->second), it->first); From 341d72f0d72db807c7d73861c638fde2e2bbbc7d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 May 2016 21:07:23 +0800 Subject: [PATCH 2102/4971] Update top-k-frequent-elements.py --- Python/top-k-frequent-elements.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Python/top-k-frequent-elements.py b/Python/top-k-frequent-elements.py index 40179730b..881e0c77d 100644 --- a/Python/top-k-frequent-elements.py +++ b/Python/top-k-frequent-elements.py @@ -61,3 +61,15 @@ def PartitionAroundPivot(left, right, pivot_idx, nums): else: # new_pivot_idx < k - 1. left = new_pivot_idx + 1 + +# Time: O(nlogk) +# Space: O(n) +class Solution2(object): + def topKFrequent(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + return [key for key, _ in collections.Counter(nums).most_common(k)] + From 6510540c949af271f20777e9c92d3864ba66ac59 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 May 2016 00:45:08 +0800 Subject: [PATCH 2103/4971] Update subsets-ii.py --- Python/subsets-ii.py | 70 ++++++++++++++++++++++++++++++-------------- 1 file changed, 48 insertions(+), 22 deletions(-) diff --git a/Python/subsets-ii.py b/Python/subsets-ii.py index 7690e96a8..c0f54a42e 100644 --- a/Python/subsets-ii.py +++ b/Python/subsets-ii.py @@ -1,6 +1,6 @@ # Time: O(n * 2^n) # Space: O(1) -# + # Given a collection of integers that might contain duplicates, S, return all possible subsets. # # Note: @@ -17,41 +17,67 @@ # [1,2], # [] # ] -# -class Solution: - # @param num, a list of integer - # @return a list of lists of integer - def subsetsWithDup(self, S): +class Solution(object): + def subsetsWithDup(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + nums.sort() + result = [[]] + previous_size = 0 + for i in xrange(len(nums)): + size = len(result) + for j in xrange(size): + # Only union non-duplicate element or new union set. + if i == 0 or nums[i] != nums[i - 1] or j >= previous_size: + result.append(list(result[j])) + result[-1].append(nums[i]) + previous_size = size + return result + + +class Solution2(object): + def subsetsWithDup(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ result = [] - i, count = 0, 1 << len(S) - S = sorted(S) + i, count = 0, 1 << len(nums) + nums.sort() while i < count: cur = [] - for j in xrange(len(S)): + for j in xrange(len(nums)): if i & 1 << j: - cur.append(S[j]) + cur.append(nums[j]) if cur not in result: result.append(cur) i += 1 return result -class Solution2: - # @param num, a list of integer - # @return a list of lists of integer - def subsetsWithDup(self, S): + +class Solution3(object): + def subsetsWithDup(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ result = [] - self.subsetsWithDupRecu(result, [], sorted(S)) + self.subsetsWithDupRecu(result, [], sorted(nums)) return result - def subsetsWithDupRecu(self, result, cur, S): - if len(S) == 0 and cur not in result: - result.append(cur) - elif S: - self.subsetsWithDupRecu(result, cur, S[1:]) - self.subsetsWithDupRecu(result, cur + [S[0]], S[1:]) - + def subsetsWithDupRecu(self, result, cur, nums): + if not nums: + if cur not in result: + result.append(cur) + else: + self.subsetsWithDupRecu(result, cur, nums[1:]) + self.subsetsWithDupRecu(result, cur + [nums[0]], nums[1:]) + + if __name__ == "__main__": print Solution().subsetsWithDup([1, 2, 2]) From 09b4eb727ae58dbdfc4250627a5d8fc2c8d2f07b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 May 2016 00:51:08 +0800 Subject: [PATCH 2104/4971] Update subsets.py --- Python/subsets.py | 63 +++++++++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 19 deletions(-) diff --git a/Python/subsets.py b/Python/subsets.py index eefdb0a55..113b810e7 100644 --- a/Python/subsets.py +++ b/Python/subsets.py @@ -1,6 +1,6 @@ # Time: O(n * 2^n) # Space: O(1) -# + # Given a set of distinct integers, S, return all possible subsets. # # Note: @@ -19,37 +19,62 @@ # [1,2], # [] # ] -# -class Solution: - # @param S, a list of integer - # @return a list of lists of integer - def subsets(self, S): +class Solution(object): + def subsets(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + nums.sort() + result = [[]] + for i in xrange(len(nums)): + size = len(result) + for j in xrange(size): + result.append(list(result[j])) + result[-1].append(nums[i]) + return result + + +# Time: O(n * 2^n) +# Space: O(1) +class Solution2(object): + def subsets(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ result = [] - i, count = 0, 1 << len(S) - S = sorted(S) + i, count = 0, 1 << len(nums) + nums.sort() while i < count: cur = [] - for j in xrange(len(S)): + for j in xrange(len(nums)): if i & 1 << j: - cur.append(S[j]) + cur.append(nums[j]) result.append(cur) i += 1 return result -class Solution2: - # @param S, a list of integer - # @return a list of lists of integer - def subsets(self, S): - return self.subsetsRecu([], sorted(S)) + +# Time: O(n * 2^n) +# Space: O(1) +class Solution3(object): + def subsets(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + return self.subsetsRecu([], sorted(nums)) - def subsetsRecu(self, cur, S): - if not S: + def subsetsRecu(self, cur, nums): + if not nums: return [cur] - return self.subsetsRecu(cur, S[1:]) + self.subsetsRecu(cur + [S[0]], S[1:]) - + return self.subsetsRecu(cur, nums[1:]) + self.subsetsRecu(cur + [nums[0]], nums[1:]) + + if __name__ == "__main__": print Solution().subsets([1, 2, 3]) From 870c85b67070719523a44ffcd111de1a9ea44951 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 May 2016 00:59:37 +0800 Subject: [PATCH 2105/4971] Update subsets-ii.py --- Python/subsets-ii.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Python/subsets-ii.py b/Python/subsets-ii.py index c0f54a42e..f30e20486 100644 --- a/Python/subsets-ii.py +++ b/Python/subsets-ii.py @@ -38,6 +38,8 @@ def subsetsWithDup(self, nums): return result +# Time: O(n * 2^n) ~ O((n * 2^n)^2) +# Space: O(1) class Solution2(object): def subsetsWithDup(self, nums): """ @@ -60,6 +62,8 @@ def subsetsWithDup(self, nums): return result +# Time: O(n * 2^n) ~ O((n * 2^n)^2) +# Space: O(1) class Solution3(object): def subsetsWithDup(self, nums): """ From 9d96abf6905b0c190b55eea70277bd61185a4ff7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 May 2016 01:05:20 +0800 Subject: [PATCH 2106/4971] Update subsets.cpp --- C++/subsets.cpp | 49 ++++++++++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/C++/subsets.cpp b/C++/subsets.cpp index 9b99a3809..9c0d9d0c3 100644 --- a/C++/subsets.cpp +++ b/C++/subsets.cpp @@ -1,25 +1,36 @@ -// Time Complexity: O(2^n) -// Space Complexity: O(1) +// Time: O(n * 2^n) +// Space: O(1) class Solution { - public: - vector > subsets(vector &S) { - const int size = S.size(); - const int setSize = 1 << size; - vector > ans; - vector v; - - sort(S.begin(), S.end()); - - for(int i = 0; i < setSize; ++i) { - for(int j = 0; j < size; j++) { - if(i & (1 << j)) - v.push_back(S[j]); - } - ans.push_back(v); - v.clear(); +public: + vector > subsets(vector &nums) { + vector> result(1); + sort(nums.begin(), nums.end()); + for (size_t i = 0; i < nums.size(); ++i) { + const size_t size = result.size(); + for (size_t j = 0; j < size; ++j) { + result.emplace_back(result[j]); + result.back().emplace_back(nums[i]); } + } + return result; + } +}; - return ans; +// Time: O(n * 2^n) +// Space: O(1) +class Solution2 { +public: + vector > subsets(vector &nums) { + vector> result(1); + sort(nums.begin(), nums.end()); + for (size_t i = 0; i < nums.size(); ++i) { + const size_t size = result.size(); + for (size_t j = 0; j < size; ++j) { + result.emplace_back(result[j]); + result.back().emplace_back(nums[i]); + } } + return result; + } }; From f2ab3e1651b88c25756e6c9008e177a2b5e3d465 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 May 2016 01:08:30 +0800 Subject: [PATCH 2107/4971] Update subsetsWithDup.cpp --- C++/subsetsWithDup.cpp | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/C++/subsetsWithDup.cpp b/C++/subsetsWithDup.cpp index 36907d1a3..2a6b1cd3b 100644 --- a/C++/subsetsWithDup.cpp +++ b/C++/subsetsWithDup.cpp @@ -1,23 +1,23 @@ -// Time Complexity: O(2^n) -// Space Complexity: O(1) +// Time: O(n * 2^n) +// Space: O(1) class Solution { - public: - vector > subsetsWithDup(vector &S) { - sort(S.begin(), S.end()); - vector > result(1); - size_t previous_size = 0; - for (size_t i = 0; i < S.size(); ++i) { - const size_t size = result.size(); - for (size_t j = 0; j < size; ++j) { - // only union non-duplicate element or new union set - if (i == 0 || S[i] != S[i-1] || j >= previous_size) { - result.push_back(result[j]); - result.back().push_back(S[i]); - } +public: + vector> subsetsWithDup(vector &nums) { + vector> result(1); + sort(nums.begin(), nums.end()); + size_t previous_size = 0; + for (size_t i = 0; i < nums.size(); ++i) { + const size_t size = result.size(); + for (size_t j = 0; j < size; ++j) { + // Only union non-duplicate element or new union set. + if (i == 0 || nums[i] != nums[i - 1] || j >= previous_size) { + result.emplace_back(result[j]); + result.back().emplace_back(nums[i]); } - previous_size = size; } - return result; + previous_size = size; } + return result; + } }; From b6540ca3b092f837987d5e2a84f7968ea4073ea2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 May 2016 01:08:42 +0800 Subject: [PATCH 2108/4971] Rename subsetsWithDup.cpp to subsets-ii.cpp --- C++/{subsetsWithDup.cpp => subsets-ii.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{subsetsWithDup.cpp => subsets-ii.cpp} (100%) diff --git a/C++/subsetsWithDup.cpp b/C++/subsets-ii.cpp similarity index 100% rename from C++/subsetsWithDup.cpp rename to C++/subsets-ii.cpp From 03fb1ab523a8c007f57f10c7534234f168b795b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 May 2016 01:09:47 +0800 Subject: [PATCH 2109/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d4083d5d6..f10eb046d 100644 --- a/README.md +++ b/README.md @@ -390,8 +390,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || -90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +78| [Subsets](https://leetcode.com/problems/subsets/) | [C++](./C++/subsets.cpp) [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [C++](./C++/subsets-ii.cpp) [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 || From 17690adedd32dbedd34f34db0d467a6179cd47a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 May 2016 20:49:56 +0800 Subject: [PATCH 2110/4971] Create design-tic-tac-toe.cpp --- C++/design-tic-tac-toe.cpp | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 C++/design-tic-tac-toe.cpp diff --git a/C++/design-tic-tac-toe.cpp b/C++/design-tic-tac-toe.cpp new file mode 100644 index 000000000..1dbd1bd53 --- /dev/null +++ b/C++/design-tic-tac-toe.cpp @@ -0,0 +1,45 @@ +// Time: O(1), per move. +// Space: O(n^2) + +class TicTacToe { +public: + /** Initialize your data structure here. */ + TicTacToe(int n) : rows_(n, {0, 0}), cols_(n, {0, 0}), + diagonal_(2, 0), anti_diagonal_(2, 0) { + } + + /** Player {player} makes a move at ({row}, {col}). + @param row The row of the board. + @param col The column of the board. + @param player The player, can be either 1 or 2. + @return The current winning condition, can be either: + 0: No one wins. + 1: Player 1 wins. + 2: Player 2 wins. */ + int move(int row, int col, int player) { + ++rows_[row][player - 1], ++cols_[col][player - 1]; + if (row == col) { + ++diagonal_[player - 1]; + } + if (col == rows_.size() - row - 1) { + ++anti_diagonal_[player - 1]; + } + if (rows_[row][player - 1] == rows_.size() || + cols_[col][player - 1] == cols_.size() || + diagonal_[player - 1] == rows_.size() || + anti_diagonal_[player - 1] == cols_.size()) { + return player; + } + return 0; + } + +private: + vector> rows_, cols_; + vector diagonal_, anti_diagonal_; +}; + +/** + * Your TicTacToe object will be instantiated and called as such: + * TicTacToe obj = new TicTacToe(n); + * int param_1 = obj.move(row,col,player); + */ From 3e189cc6613b7e51d9f173857657139ac555fa6b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 May 2016 21:01:19 +0800 Subject: [PATCH 2111/4971] Create design-tic-tac-toe.py --- Python/design-tic-tac-toe.py | 49 ++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/design-tic-tac-toe.py diff --git a/Python/design-tic-tac-toe.py b/Python/design-tic-tac-toe.py new file mode 100644 index 000000000..9d214a983 --- /dev/null +++ b/Python/design-tic-tac-toe.py @@ -0,0 +1,49 @@ +# Time: O(1), per move. +# Space: O(n^2) + +class TicTacToe(object): + + def __init__(self, n): + """ + Initialize your data structure here. + :type n: int + """ + self.__rows = [[0, 0] for _ in xrange(n)] + self.__cols = [[0, 0] for _ in xrange(n)] + self.__diagonal = [0, 0] + self.__anti_diagonal = [0, 0] + + + def move(self, row, col, player): + """ + Player {player} makes a move at ({row}, {col}). + @param row The row of the board. + @param col The column of the board. + @param player The player, can be either 1 or 2. + @return The current winning condition, can be either: + 0: No one wins. + 1: Player 1 wins. + 2: Player 2 wins. + :type row: int + :type col: int + :type player: int + :rtype: int + """ + self.__rows[row][player - 1] += 1 + self.__cols[col][player - 1] += 1 + if row == col: + self.__diagonal[player - 1] += 1 + if col == len(self.__rows) - row - 1: + self.__anti_diagonal[player - 1] += 1 + if any([self.__rows[row][player - 1] == len(self.__rows), \ + self.__cols[col][player - 1] == len(self.__cols), \ + self.__diagonal[player - 1] == len(self.__rows), \ + self.__anti_diagonal[player - 1] == len(self.__cols)]): + return player + + return 0 + + +# Your TicTacToe object will be instantiated and called as such: +# obj = TicTacToe(n) +# param_1 = obj.move(row,col,player) From 1f2f7fde39dcb30a871892fb5801eedf056cd625 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 May 2016 21:04:10 +0800 Subject: [PATCH 2112/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f10eb046d..1416c4024 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-347%20%2F%20347-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-348%20%2F%20348-ff69b4.svg) -Up to date (2016-05-02), there are `330` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-05-05), there are `331` 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 `347` questions. +Here is the classification of all `348` 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. ) @@ -460,6 +460,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | 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 || +348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_| _O(n^2)_| Medium |📖|| ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From 65ca7c254eef8e9a2901a2ea3ac76ee607d065d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 May 2016 21:06:47 +0800 Subject: [PATCH 2113/4971] Update design-tic-tac-toe.cpp --- C++/design-tic-tac-toe.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/C++/design-tic-tac-toe.cpp b/C++/design-tic-tac-toe.cpp index 1dbd1bd53..51aea9391 100644 --- a/C++/design-tic-tac-toe.cpp +++ b/C++/design-tic-tac-toe.cpp @@ -17,17 +17,18 @@ class TicTacToe { 1: Player 1 wins. 2: Player 2 wins. */ int move(int row, int col, int player) { - ++rows_[row][player - 1], ++cols_[col][player - 1]; + const int i = player - 1; + ++rows_[row][i], ++cols_[col][i]; if (row == col) { - ++diagonal_[player - 1]; + ++diagonal_[i]; } if (col == rows_.size() - row - 1) { - ++anti_diagonal_[player - 1]; + ++anti_diagonal_[i]; } - if (rows_[row][player - 1] == rows_.size() || - cols_[col][player - 1] == cols_.size() || - diagonal_[player - 1] == rows_.size() || - anti_diagonal_[player - 1] == cols_.size()) { + if (rows_[row][i] == rows_.size() || + cols_[col][i] == cols_.size() || + diagonal_[i] == rows_.size() || + anti_diagonal_[i] == cols_.size()) { return player; } return 0; From 8f4bfe6dfe017bb1697207e4fc2fa422edbb20d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 May 2016 21:07:38 +0800 Subject: [PATCH 2114/4971] Update design-tic-tac-toe.py --- Python/design-tic-tac-toe.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Python/design-tic-tac-toe.py b/Python/design-tic-tac-toe.py index 9d214a983..6d40a6f2d 100644 --- a/Python/design-tic-tac-toe.py +++ b/Python/design-tic-tac-toe.py @@ -29,16 +29,17 @@ def move(self, row, col, player): :type player: int :rtype: int """ - self.__rows[row][player - 1] += 1 - self.__cols[col][player - 1] += 1 + i = player - 1 + self.__rows[row][i] += 1 + self.__cols[col][i] += 1 if row == col: - self.__diagonal[player - 1] += 1 + self.__diagonal[i] += 1 if col == len(self.__rows) - row - 1: - self.__anti_diagonal[player - 1] += 1 - if any([self.__rows[row][player - 1] == len(self.__rows), \ - self.__cols[col][player - 1] == len(self.__cols), \ - self.__diagonal[player - 1] == len(self.__rows), \ - self.__anti_diagonal[player - 1] == len(self.__cols)]): + self.__anti_diagonal[i] += 1 + if any([self.__rows[row][i] == len(self.__rows), \ + self.__cols[col][i] == len(self.__cols), \ + self.__diagonal[i] == len(self.__rows), \ + self.__anti_diagonal[i] == len(self.__cols)]): return player return 0 From 352c00cbb9c2ef497ef6aabe6bd8cb65d258c329 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 May 2016 21:10:21 +0800 Subject: [PATCH 2115/4971] Update design-tic-tac-toe.cpp --- C++/design-tic-tac-toe.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/design-tic-tac-toe.cpp b/C++/design-tic-tac-toe.cpp index 51aea9391..48d826e0b 100644 --- a/C++/design-tic-tac-toe.cpp +++ b/C++/design-tic-tac-toe.cpp @@ -22,7 +22,7 @@ class TicTacToe { if (row == col) { ++diagonal_[i]; } - if (col == rows_.size() - row - 1) { + if (col == rows_.size() - row - 1) { ++anti_diagonal_[i]; } if (rows_[row][i] == rows_.size() || From aedf0e67c697f51369e6658084e1db1d446f6695 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 May 2016 06:26:09 -0500 Subject: [PATCH 2116/4971] Update design-tic-tac-toe.cpp --- C++/design-tic-tac-toe.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/design-tic-tac-toe.cpp b/C++/design-tic-tac-toe.cpp index 48d826e0b..c1c98efb0 100644 --- a/C++/design-tic-tac-toe.cpp +++ b/C++/design-tic-tac-toe.cpp @@ -17,7 +17,7 @@ class TicTacToe { 1: Player 1 wins. 2: Player 2 wins. */ int move(int row, int col, int player) { - const int i = player - 1; + const auto i = player - 1; ++rows_[row][i], ++cols_[col][i]; if (row == col) { ++diagonal_[i]; From 67aae509280f646dbfa5af6f62eb3a49de86172d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 May 2016 20:59:59 -0500 Subject: [PATCH 2117/4971] Update implement-strstr.cpp --- C++/implement-strstr.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/C++/implement-strstr.cpp b/C++/implement-strstr.cpp index ca1140f77..831645f8b 100644 --- a/C++/implement-strstr.cpp +++ b/C++/implement-strstr.cpp @@ -52,10 +52,6 @@ class Solution { 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; From 376cc13b3770cc6d2a741731e7f798ee7dd24653 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 May 2016 21:51:19 -0500 Subject: [PATCH 2118/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1416c4024..c87b1f35e 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 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/)| [C++](./C++/maximal-rectangle.cpp) [Python](./Python/maximal-rectangle.py)| _O(m * n)_ | _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 | EPI | 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/) | [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 From f135882ddd51d1a46f80535e38a9414c220f7a2c Mon Sep 17 00:00:00 2001 From: Xiao Liu Date: Sun, 8 May 2016 10:46:43 +0100 Subject: [PATCH 2119/4971] Update LICENSE.md --- LICENSE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE.md b/LICENSE.md index b0d82f1f5..2288c82f8 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015 https://github.com/kamyu104/LeetCode +Copyright (c) 2016 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 From fe99a346b984830169324d3ea86d95131ee87341 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 21:27:48 +0800 Subject: [PATCH 2120/4971] Update binary-tree-postorder-traversal.cpp --- C++/binary-tree-postorder-traversal.cpp | 27 +++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/C++/binary-tree-postorder-traversal.cpp b/C++/binary-tree-postorder-traversal.cpp index 15f071465..fe84b13fb 100644 --- a/C++/binary-tree-postorder-traversal.cpp +++ b/C++/binary-tree-postorder-traversal.cpp @@ -52,3 +52,30 @@ class Solution { return res; } }; + +// Time: O(n) +// Space: O(h) +class Solution2 { +public: + vector postorderTraversal(TreeNode* root) { + vector res; + stack> s; + s.emplace(root, false); + bool visited; + while (!s.empty()) { + tie(root, visited) = s.top(); + s.pop(); + if (root == nullptr) { + continue; + } + if (visited) { + res.emplace_back(root->val); + } else { + s.emplace(root, true); + s.emplace(root->right, false); + s.emplace(root->left, false); + } + } + return res; + } +}; From cdd38e4e0796b1d7e5bd48539b8aa11b2d3e0f69 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 21:31:27 +0800 Subject: [PATCH 2121/4971] Update binary-tree-inorder-traversal.cpp --- C++/binary-tree-inorder-traversal.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/C++/binary-tree-inorder-traversal.cpp b/C++/binary-tree-inorder-traversal.cpp index 48334250d..80b5fa22c 100644 --- a/C++/binary-tree-inorder-traversal.cpp +++ b/C++/binary-tree-inorder-traversal.cpp @@ -40,3 +40,30 @@ class Solution { return res; } }; + +// Time: O(n) +// Space: O(h) +class Solution2 { +public: + vector inorderTraversal(TreeNode* root) { + vector res; + stack> s; + s.emplace(root, false); + bool visited; + while (!s.empty()) { + tie(root, visited) = s.top(); + s.pop(); + if (root == nullptr) { + continue; + } + if (visited) { + res.emplace_back(root->val); + } else { + s.emplace(root->right, false); + s.emplace(root, true); + s.emplace(root->left, false); + } + } + return res; + } +}; From 7c93469b7a4f7cf7b10721d15e59e5c9317631a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 21:33:51 +0800 Subject: [PATCH 2122/4971] Update binary-tree-preorder-traversal.cpp --- C++/binary-tree-preorder-traversal.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/C++/binary-tree-preorder-traversal.cpp b/C++/binary-tree-preorder-traversal.cpp index 27425c540..cadfd922d 100644 --- a/C++/binary-tree-preorder-traversal.cpp +++ b/C++/binary-tree-preorder-traversal.cpp @@ -40,3 +40,28 @@ class Solution { return res; } }; + +class Solution2 { +public: + vector preorderTraversal(TreeNode* root) { + vector res; + stack> s; + s.emplace(root, false); + bool visited; + while (!s.empty()) { + tie(root, visited) = s.top(); + s.pop(); + if (root == nullptr) { + continue; + } + if (visited) { + res.emplace_back(root->val); + } else { + s.emplace(root->right, false); + s.emplace(root->left, false); + s.emplace(root, true); + } + } + return res; + } +}; From 3bada11b713ae388ffc5b6d178d9158cd15d2f0b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 21:34:43 +0800 Subject: [PATCH 2123/4971] Update binary-tree-preorder-traversal.cpp --- C++/binary-tree-preorder-traversal.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/C++/binary-tree-preorder-traversal.cpp b/C++/binary-tree-preorder-traversal.cpp index cadfd922d..ba63b2eeb 100644 --- a/C++/binary-tree-preorder-traversal.cpp +++ b/C++/binary-tree-preorder-traversal.cpp @@ -41,6 +41,8 @@ class Solution { } }; +// Time: O(n) +// Space: O(h) class Solution2 { public: vector preorderTraversal(TreeNode* root) { From f98471bf35271da504691ee946825651b5ff635b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 22:02:07 +0800 Subject: [PATCH 2124/4971] Update binary-tree-preorder-traversal.py --- Python/binary-tree-preorder-traversal.py | 55 ++++++++++-------------- 1 file changed, 22 insertions(+), 33 deletions(-) diff --git a/Python/binary-tree-preorder-traversal.py b/Python/binary-tree-preorder-traversal.py index 51146c7bd..8c9b48e77 100644 --- a/Python/binary-tree-preorder-traversal.py +++ b/Python/binary-tree-preorder-traversal.py @@ -23,10 +23,12 @@ def __init__(self, x): self.right = None # Morris Traversal Solution -class Solution: - # @param root, a tree node - # @return a list of integers +class Solution(object): def preorderTraversal(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ result, prev, cur = [], None, root while cur: if cur.left is None: @@ -49,42 +51,29 @@ def preorderTraversal(self, root): return result + # Time: O(n) -# Space: O(n) +# Space: O(h) # Stack Solution -class Solution2: - # @param root, a tree node - # @return a list of integers +class Solution2(object): 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 + """ + :type root: TreeNode + :rtype: List[int] + """ + result, stack = [], [(root, False)] + while stack: + root, is_visited = stack.pop() + if root is None: + continue + if is_visited: + result.append(root.val) else: - parent = stack[-1] - if parent.right in (None, last_traversed): - last_traversed = stack.pop() - else: - current = parent.right + stack.append((root.right, False)) + stack.append((root.left, False)) + stack.append((root, True)) 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) From 12a285855ff1ee32972a144674ff27b9cc4e263e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 22:04:04 +0800 Subject: [PATCH 2125/4971] Update binary-tree-inorder-traversal.py --- Python/binary-tree-inorder-traversal.py | 59 ++++++++++--------------- 1 file changed, 24 insertions(+), 35 deletions(-) diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py index 094ed428b..f277d51a6 100644 --- a/Python/binary-tree-inorder-traversal.py +++ b/Python/binary-tree-inorder-traversal.py @@ -22,11 +22,14 @@ 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 +class Solution(object): def inorderTraversal(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ result, prev, cur = [], None, root while cur: if cur.left is None: @@ -49,43 +52,29 @@ def inorderTraversal(self, root): return result + # Time: O(n) -# Space: O(n) -# Stack Solution -class Solution2: - # @param root, a tree node - # @return a list of integers +# Space: O(h) +# Stack Solution +class Solution2(object): def inorderTraversal(self, root): - result, stack, current, last_traversed = [], [], root, None - while stack or current: - if current: - stack.append(current) - current = current.left + """ + :type root: TreeNode + :rtype: List[int] + """ + result, stack = [], [(root, False)] + while stack: + root, is_visited = stack.pop() + if root is None: + continue + if is_visited: + result.append(root.val) else: - parent = stack[-1] - if parent.right in (None, last_traversed): - if parent.right is None: - result.append(parent.val) - last_traversed = stack.pop() - else: - result.append(parent.val) - current = parent.right + stack.append((root.right, False)) + stack.append((root, True)) + stack.append((root.left, False)) return result -class Solution3: - # @param root, a tree node - # @return a list of integers - def inorderTraversal(self, root): - result, stack, current = [], [], root - while stack or current: - if current: - stack.append(current) - current = current.left - else: - current = stack.pop() - result.append(current.val) - current = current.right - return result if __name__ == "__main__": root = TreeNode(1) From d12e30ce35373c378cb07014934f68599984442e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 22:06:04 +0800 Subject: [PATCH 2126/4971] Update binary-tree-postorder-traversal.py --- Python/binary-tree-postorder-traversal.py | 44 +++++++++++++---------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/Python/binary-tree-postorder-traversal.py b/Python/binary-tree-postorder-traversal.py index aa93e11fc..c5a47b0c8 100644 --- a/Python/binary-tree-postorder-traversal.py +++ b/Python/binary-tree-postorder-traversal.py @@ -22,11 +22,14 @@ 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 +class Solution(object): def postorderTraversal(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ dummy = TreeNode(0) dummy.left = root result, cur = [], dummy @@ -57,30 +60,33 @@ def traceBack(self, frm, to): result.reverse() return result + # Time: O(n) -# Space: O(n) +# Space: O(h) # Stack Solution -class Solution2: - # @param root, a tree node - # @return a list of integers +class Solution2(object): def postorderTraversal(self, root): - result, stack, current, last_traversed = [], [], root, None - while stack or current: - if current: - stack.append(current) - current = current.left + """ + :type root: TreeNode + :rtype: List[int] + """ + result, stack = [], [(root, False)] + while stack: + root, is_visited = stack.pop() + if root is None: + continue + if is_visited: + result.append(root.val) else: - parent = stack[-1] - if parent.right in (None, last_traversed): - result.append(parent.val) - last_traversed = stack.pop() - else: - current = parent.right + stack.append((root, True)) + stack.append((root.right, False)) + stack.append((root.left, False)) return result + if __name__ == "__main__": root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) result = Solution().postorderTraversal(root) - print result \ No newline at end of file + print result From 88a8ae9ac43dca7aad2baeafb04f6d737def1349 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 22:06:28 +0800 Subject: [PATCH 2127/4971] Update binary-tree-preorder-traversal.py --- Python/binary-tree-preorder-traversal.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/binary-tree-preorder-traversal.py b/Python/binary-tree-preorder-traversal.py index 8c9b48e77..a49e4142b 100644 --- a/Python/binary-tree-preorder-traversal.py +++ b/Python/binary-tree-preorder-traversal.py @@ -22,6 +22,7 @@ def __init__(self, x): self.left = None self.right = None + # Morris Traversal Solution class Solution(object): def preorderTraversal(self, root): From 006b8a8b9a737a2cda8b1b87e036150f1914f66d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 22:43:38 +0800 Subject: [PATCH 2128/4971] Update binary-tree-inorder-traversal.cpp --- C++/binary-tree-inorder-traversal.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/binary-tree-inorder-traversal.cpp b/C++/binary-tree-inorder-traversal.cpp index 80b5fa22c..911853025 100644 --- a/C++/binary-tree-inorder-traversal.cpp +++ b/C++/binary-tree-inorder-traversal.cpp @@ -49,8 +49,8 @@ class Solution2 { vector res; stack> s; s.emplace(root, false); - bool visited; while (!s.empty()) { + bool visited; tie(root, visited) = s.top(); s.pop(); if (root == nullptr) { From 75ebc4b8e88e53cc847a4a532353403db7c9a705 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 22:43:57 +0800 Subject: [PATCH 2129/4971] Update binary-tree-preorder-traversal.cpp --- C++/binary-tree-preorder-traversal.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/binary-tree-preorder-traversal.cpp b/C++/binary-tree-preorder-traversal.cpp index ba63b2eeb..6603df016 100644 --- a/C++/binary-tree-preorder-traversal.cpp +++ b/C++/binary-tree-preorder-traversal.cpp @@ -49,8 +49,8 @@ class Solution2 { vector res; stack> s; s.emplace(root, false); - bool visited; while (!s.empty()) { + bool visited; tie(root, visited) = s.top(); s.pop(); if (root == nullptr) { From 7e3da5a866d7e2c895c4b6e7ee484d41098dfc1b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 May 2016 22:44:28 +0800 Subject: [PATCH 2130/4971] Update binary-tree-postorder-traversal.cpp --- C++/binary-tree-postorder-traversal.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/binary-tree-postorder-traversal.cpp b/C++/binary-tree-postorder-traversal.cpp index fe84b13fb..c3e127e7b 100644 --- a/C++/binary-tree-postorder-traversal.cpp +++ b/C++/binary-tree-postorder-traversal.cpp @@ -61,8 +61,8 @@ class Solution2 { vector res; stack> s; s.emplace(root, false); - bool visited; while (!s.empty()) { + bool visited; tie(root, visited) = s.top(); s.pop(); if (root == nullptr) { From f4b8a3a6d52c55bccdc2129b61ae6a9007dd80d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 02:31:35 +0800 Subject: [PATCH 2131/4971] Update search-in-rotated-sorted-array.py --- Python/search-in-rotated-sorted-array.py | 38 +++++++++++------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/Python/search-in-rotated-sorted-array.py b/Python/search-in-rotated-sorted-array.py index fc35c8073..d95d92382 100644 --- a/Python/search-in-rotated-sorted-array.py +++ b/Python/search-in-rotated-sorted-array.py @@ -10,34 +10,30 @@ # You may assume no duplicate exists in the array. # -class Solution: - # @param A, a list of integers - # @param target, an integer to be searched - # @return an integer - def search(self, A, target): - low, high = 0, len(A) +class Solution(object): + def search(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + left, right = 0, len(nums) - 1 - while low < high: - mid = low + (high - low) / 2 + while left <= right: + mid = left + (right - left) / 2 - if A[mid] == target: + if nums[mid] == target: return mid - - if A[low] <= A[mid]: - if A[low] <= target and target < A[mid]: - high = mid - else: - low = mid + 1 + elif (nums[mid] >= nums[left] and nums[left] <= target < nums[mid]) or \ + (nums[mid] < nums[left] and not (nums[mid] < target <= nums[right])): + right = mid - 1 else: - if A[mid] < target and target <= A[high - 1]: - low = mid + 1 - else: - high = mid - + left = mid + 1 + return -1 if __name__ == "__main__": print Solution().search([3, 5, 1], 3) print Solution().search([1], 1) - print Solution().search([4, 5, 6, 7, 0, 1, 2], 5) \ No newline at end of file + print Solution().search([4, 5, 6, 7, 0, 1, 2], 5) From c0bfa6f3042fa8e0121cd498981757e02aa2488f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 02:41:00 +0800 Subject: [PATCH 2132/4971] Update search-in-rotated-sorted-array-ii.py --- Python/search-in-rotated-sorted-array-ii.py | 42 ++++++++++----------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/Python/search-in-rotated-sorted-array-ii.py b/Python/search-in-rotated-sorted-array-ii.py index cd623c3c9..e201dedb2 100644 --- a/Python/search-in-rotated-sorted-array-ii.py +++ b/Python/search-in-rotated-sorted-array-ii.py @@ -9,36 +9,32 @@ # Write a function to determine if a given target is in the array. # -class Solution: - # @param A a list of integers - # @param target an integer - # @return a boolean - def search(self, A, target): - low, high = 0, len(A) +class Solution(object): + def search(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + left, right = 0, len(nums) - 1 - while low < high: - mid = low + (high - low) / 2 + while left <= right: + mid = left + (right - left) / 2 - if A[mid] == target: + if nums[mid] == target: return True - - if A[low] < A[mid]: - if A[low] <= target and target < A[mid]: - high = mid - else: - low = mid + 1 - elif A[low] > A[mid]: - if A[mid] < target and target <= A[high - 1]: - low = mid + 1 - else: - high = mid + if nums[mid] == nums[left]: + left += 1 + elif (nums[mid] > nums[left] and nums[left] <= target < nums[mid]) or \ + (nums[mid] < nums[left] and not (nums[mid] < target <= nums[right])): + right = mid - 1 else: - low += 1 - + left = mid + 1 + return False if __name__ == "__main__": print Solution().search([3, 5, 1], 3) print Solution().search([2, 2, 3, 3, 4, 1], 1) - print Solution().search([4, 4, 5, 6, 7, 0, 1, 2], 5) \ No newline at end of file + print Solution().search([4, 4, 5, 6, 7, 0, 1, 2], 5) From 486f358272523aecb288b89c608483e882f9447b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 02:41:33 +0800 Subject: [PATCH 2133/4971] Update search-in-rotated-sorted-array-ii.py --- Python/search-in-rotated-sorted-array-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/search-in-rotated-sorted-array-ii.py b/Python/search-in-rotated-sorted-array-ii.py index e201dedb2..8649ec528 100644 --- a/Python/search-in-rotated-sorted-array-ii.py +++ b/Python/search-in-rotated-sorted-array-ii.py @@ -23,7 +23,7 @@ def search(self, nums, target): if nums[mid] == target: return True - if nums[mid] == nums[left]: + elif nums[mid] == nums[left]: left += 1 elif (nums[mid] > nums[left] and nums[left] <= target < nums[mid]) or \ (nums[mid] < nums[left] and not (nums[mid] < target <= nums[right])): From ac2f7e33ba0d52e88ef0e5e44c0f65d112da1226 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 03:08:50 +0800 Subject: [PATCH 2134/4971] Update find-minimum-in-rotated-sorted-array-ii.py --- ...find-minimum-in-rotated-sorted-array-ii.py | 53 +++++++++---------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/Python/find-minimum-in-rotated-sorted-array-ii.py b/Python/find-minimum-in-rotated-sorted-array-ii.py index 0340791a2..ff6895dc6 100644 --- a/Python/find-minimum-in-rotated-sorted-array-ii.py +++ b/Python/find-minimum-in-rotated-sorted-array-ii.py @@ -14,46 +14,43 @@ # The array may contain duplicates. # +class Solution(object): + def findMin(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + left, right = 0, len(nums) - 1 + while left < right: + mid = left + (right - left) / 2 -class Solution: - # @param num, a list of integer - # @return an integer - def findMin(self, num): - low, high = 0, len(num) - - while low < high - 1 and num[low] >= num[high - 1]: - mid = low + (high - low) / 2 - - if num[mid] > num[low]: - low = mid + 1 - elif num[mid] < num[low]: - if mid == high - 1: - return num[mid] - else: - high = mid + 1 + if nums[mid] == nums[right]: + right -= 1 + elif nums[mid] < nums[right]: + right = mid else: - low += 1 + left = mid + 1 + + return nums[left] - return num[low] -class Solution2: - # @param num, a list of integer - # @return an integer - def findMin(self, num): - low, high = 0, len(num) - 1 +class Solution2(object): + def findMin(self, nums): + low, high = 0, len(nums) - 1 - while low < high and num[low] >= num[high]: + while low < high and nums[low] >= nums[high]: mid = low + (high - low) / 2 - if num[mid] > num[low]: + if nums[mid] > nums[low]: low = mid + 1 - elif num[mid] < num[low]: + elif nums[mid] < nums[low]: high = mid else: low += 1 - return num[low] + return nums[low] + if __name__ == "__main__": print Solution().findMin([3, 1, 1, 2, 2, 3]) - print Solution2().findMin([2, 2, 2, 3, 3, 1]) \ No newline at end of file + print Solution2().findMin([2, 2, 2, 3, 3, 1]) From 689f5850d27118d5a172201a604106181fed815f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 03:09:51 +0800 Subject: [PATCH 2135/4971] Update find-minimum-in-rotated-sorted-array-ii.py --- .../find-minimum-in-rotated-sorted-array-ii.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Python/find-minimum-in-rotated-sorted-array-ii.py b/Python/find-minimum-in-rotated-sorted-array-ii.py index ff6895dc6..5b1436086 100644 --- a/Python/find-minimum-in-rotated-sorted-array-ii.py +++ b/Python/find-minimum-in-rotated-sorted-array-ii.py @@ -36,19 +36,19 @@ def findMin(self, nums): class Solution2(object): def findMin(self, nums): - low, high = 0, len(nums) - 1 + left, right = 0, len(nums) - 1 - while low < high and nums[low] >= nums[high]: - mid = low + (high - low) / 2 + while left < right and nums[left] >= nums[right]: + mid = left + (right - left) / 2 - if nums[mid] > nums[low]: - low = mid + 1 - elif nums[mid] < nums[low]: - high = mid + if nums[mid] > nums[left]: + left = mid + 1 + elif nums[mid] < nums[left]: + right = mid else: - low += 1 + left += 1 - return nums[low] + return nums[left] if __name__ == "__main__": From a1e74d0f5ab20e3c3d30fdeb3a05b37547987d68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 03:10:50 +0800 Subject: [PATCH 2136/4971] Update find-minimum-in-rotated-sorted-array-ii.py --- Python/find-minimum-in-rotated-sorted-array-ii.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Python/find-minimum-in-rotated-sorted-array-ii.py b/Python/find-minimum-in-rotated-sorted-array-ii.py index 5b1436086..4d3fd26f6 100644 --- a/Python/find-minimum-in-rotated-sorted-array-ii.py +++ b/Python/find-minimum-in-rotated-sorted-array-ii.py @@ -36,8 +36,11 @@ def findMin(self, nums): class Solution2(object): def findMin(self, nums): + """ + :type nums: List[int] + :rtype: int + """ left, right = 0, len(nums) - 1 - while left < right and nums[left] >= nums[right]: mid = left + (right - left) / 2 From 0de1e9db6ccf8ae554b13a0575e7fccf51fc0f1b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 03:12:22 +0800 Subject: [PATCH 2137/4971] Update find-minimum-in-rotated-sorted-array-ii.py --- Python/find-minimum-in-rotated-sorted-array-ii.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/find-minimum-in-rotated-sorted-array-ii.py b/Python/find-minimum-in-rotated-sorted-array-ii.py index 4d3fd26f6..fcb09d212 100644 --- a/Python/find-minimum-in-rotated-sorted-array-ii.py +++ b/Python/find-minimum-in-rotated-sorted-array-ii.py @@ -44,12 +44,12 @@ def findMin(self, nums): while left < right and nums[left] >= nums[right]: mid = left + (right - left) / 2 - if nums[mid] > nums[left]: - left = mid + 1 + if nums[mid] == nums[left]: + left += 1 elif nums[mid] < nums[left]: right = mid else: - left += 1 + left = mid + 1 return nums[left] From 95741a949a30a0ff53135b0ab4e726cfa042dcb3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 03:14:32 +0800 Subject: [PATCH 2138/4971] Update find-minimum-in-rotated-sorted-array.py --- .../find-minimum-in-rotated-sorted-array.py | 67 +++++++++---------- 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/Python/find-minimum-in-rotated-sorted-array.py b/Python/find-minimum-in-rotated-sorted-array.py index b54c78042..f5a984a8e 100644 --- a/Python/find-minimum-in-rotated-sorted-array.py +++ b/Python/find-minimum-in-rotated-sorted-array.py @@ -10,46 +10,45 @@ # You may assume no duplicate exists in the array. # -class Solution: - # @param num, a list of integer - # @return an integer - def findMin(self, num): - low, high = 0, len(num) - - while low < high - 1 and num[low] >= num[high - 1]: - mid = low + (high - low) / 2 - - if num[mid] > num[low]: - low = mid + 1 - elif num[mid] < num[low]: - if mid == high - 1: - return num[mid] - else: - high = mid + 1 +class Solution(object): + def findMin(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + left, right = 0, len(nums) - 1 + while left < right: + mid = left + (right - left) / 2 + + if nums[mid] < nums[right]: + right = mid else: - return num[mid] - - return num[low] - -class Solution2: - # @param num, a list of integer - # @return an integer - def findMin(self, num): - low, high = 0, len(num) - 1 - - while low < high and num[low] >= num[high]: - mid = low + (high - low) / 2 - - if num[mid] >= num[low]: - low = mid + 1 + left = mid + 1 + + return nums[left] + + +class Solution2(object): + def findMin(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + left, right = 0, len(nums) - 1 + while left < right and nums[left] >= nums[right]: + mid = left + (right - left) / 2 + + if nums[mid] < nums[left]: + right = mid else: - high = mid + left = mid + 1 + + return nums[left] - return num[low] if __name__ == "__main__": print Solution().findMin([1]) print Solution().findMin([1, 2]) print Solution().findMin([2, 1]) print Solution().findMin([3, 1, 2]) - print Solution().findMin([2, 3, 1]) \ No newline at end of file + print Solution().findMin([2, 3, 1]) From 046e23b1e370b414a7828b1c644338e677153437 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 20:24:27 +0800 Subject: [PATCH 2139/4971] Update search-for-a-range.py --- Python/search-for-a-range.py | 75 +++++++++++++++++++----------------- 1 file changed, 39 insertions(+), 36 deletions(-) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 6e6c84d7b..526ada9ab 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -12,48 +12,51 @@ # return [3, 4]. # -class Solution: - # @param A, a list of integers - # @param target, an integer to be searched - # @return a list of length 2, [index1, index2] - def searchRange(self, 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: +class Solution(object): + def searchRange(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + # Find the first index where target <= nums[idx] + left = self.binarySearch(lambda x, y: x <= y, nums, target) + if left >= len(nums) or nums[left] != target: return [-1, -1] - # Find the first index where target < A[idx] - right = self.binarySearch(lambda x, y: x < y, A, target) + # Find the first index where target < nums[idx] + right = self.binarySearch(lambda x, y: x < y, nums, target) return [left, right - 1] - def binarySearch(self, compare, A, target): - start, end = 0, len(A) - while start < end: - mid = start + (end - start) / 2 - if compare(target, A[mid]): - end = mid + def binarySearch(self, compare, nums, target): + left, right = 0, len(nums) + while left < right: + mid = left + (right - left) / 2 + if compare(target, nums[mid]): + right = 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 + left = mid + 1 + return left + + def binarySearch2(self, compare, nums, target): + left, right = 0, len(nums) - 1 + while left <= right: + mid = left + (right - left) / 2 + if compare(target, nums[mid]): + right = mid - 1 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 + left = mid + 1 + return left + + def binarySearch3(self, compare, nums, target): + left, right = -1, len(nums) + while right - left > 1: + mid = left + (right - left) / 2 + if compare(target, nums[mid]): + right = mid else: - start = mid - return end + left = mid + return right + if __name__ == "__main__": print Solution().searchRange([2, 2], 3) From 6a4eff4f25b8493b2ae1c49b4c838bb7047cafb5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 20:27:17 +0800 Subject: [PATCH 2140/4971] Update search-insert-position.py --- Python/search-insert-position.py | 34 +++++++++++++++++--------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/Python/search-insert-position.py b/Python/search-insert-position.py index be71509c7..fcc5a628d 100644 --- a/Python/search-insert-position.py +++ b/Python/search-insert-position.py @@ -14,26 +14,28 @@ # [1,3,5,6], 0 -> 0 # -class Solution: - # @param A, a list of integers - # @param target, an integer to be inserted - # @return integer - def searchInsert(self, A, target): - low, high = 0, len(A) - 1 - - while low <= high: - mid = low + (high - low) / 2 - if A[mid] == target: +class Solution(object): + def searchInsert(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + left, right = 0, len(nums) - 1 + while left <= right: + mid = left + (right - left) / 2 + if nums[mid] == target: return mid - elif A[mid] < target: - low = mid + 1 + elif nums[mid] < target: + left = mid + 1 else: - high = mid - 1 - - return low + right = mid - 1 + + return left + if __name__ == "__main__": print Solution().searchInsert([1, 3, 5, 6], 5) print Solution().searchInsert([1, 3, 5, 6], 2) print Solution().searchInsert([1, 3, 5, 6], 7) - print Solution().searchInsert([1, 3, 5, 6], 0) \ No newline at end of file + print Solution().searchInsert([1, 3, 5, 6], 0) From 5ad1d4fbf22e5be39a1102125edc0dc23ad60d5a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 20:28:45 +0800 Subject: [PATCH 2141/4971] Update search-insert-position.py --- Python/search-insert-position.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Python/search-insert-position.py b/Python/search-insert-position.py index fcc5a628d..a5be023ed 100644 --- a/Python/search-insert-position.py +++ b/Python/search-insert-position.py @@ -24,12 +24,10 @@ def searchInsert(self, nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = left + (right - left) / 2 - if nums[mid] == target: - return mid - elif nums[mid] < target: - left = mid + 1 - else: + if nums[mid] >= target: right = mid - 1 + else: + left = mid + 1 return left From 90b461a17fd1d81a53d8463b4d9d803fe4d808d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 20:35:50 +0800 Subject: [PATCH 2142/4971] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 130 ++++---------------------- 1 file changed, 16 insertions(+), 114 deletions(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 24b51a481..d2f089a51 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -1,18 +1,23 @@ # Time: O(log(min(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)). -# + +# There are two sorted arrays nums1 and nums2 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) +class Solution(object): + def findMedianSortedArrays(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: float + """ + len1, len2 = len(nums1), len(nums2) + if (len1 + len2) % 2 == 1: + return self.getKth(nums1, nums2, (len1 + len2)/2 + 1) else: - return (self.getKth(A, B, (lenA + lenB)/2) + self.getKth(A, B, (lenA + lenB)/2 + 1)) * 0.5 + return (self.getKth(nums1, nums2, (len1 + len2)/2) + \ + self.getKth(nums1, nums2, (len1 + len2)/2 + 1)) * 0.5 def getKth(self, A, B, k): m, n = len(A), len(B) @@ -35,110 +40,7 @@ def getKth(self, A, B, k): 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) - 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 Solution3: - # @return a float - def findMedianSortedArrays(self, A, B): - lenA, lenB = len(A), len(B) - if (lenA + lenB) % 2 == 1: - return self.getKth(A, 0, B, 0, (lenA + lenB)/2 + 1) - else: - return (self.getKth(A, 0, B, 0, (lenA + lenB)/2) + self.getKth(A, 0, B, 0, (lenA + lenB)/2 + 1)) * 0.5 - - def getKth(self, A, i, B, j, k): - lenA, lenB = len(A) - i, len(B) - j - if lenA > lenB: - return self.getKth(B, j, A, i, k) - - if lenA == 0: - return B[j + k - 1] - - if k == 1: - return min(A[i], B[j]) - - pa = min(k/2, lenA) - pb = k - pa - - if A[i + pa - 1] < B[j + pb - 1]: - return self.getKth(A, i + pa, B, j , k - pa) - elif A[i + pa - 1] > B[j + pb - 1]: - return self.getKth(A, i, B, j + pb, k - pb) - else: - return A[i + pa - 1] -# using list slicing (O(k)) may be slower than Solution3 -class Solution4: - # @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): - lenA, lenB = len(A), len(B) - if lenA > lenB: - return self.getKth(B, A, k) - - if lenA == 0: - return B[k - 1] - - if k == 1: - return min(A[0], B[0]) - - pa = min(k/2, lenA) - pb = k - pa - - if A[pa - 1] < B[pb - 1]: - return self.getKth(A[pa:], B, k - pa) - elif A[pa - 1] > B[pb - 1]: - return self.getKth(A, B[pb:], k - pb) - else: - return A[pa - 1] if __name__ == "__main__": print Solution().findMedianSortedArrays([1, 3, 5, 7], [2, 4, 6]) From 7b94f0f6ab58f6f75c4b94311801f805655d623a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 20:45:11 +0800 Subject: [PATCH 2143/4971] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index d2f089a51..86c8e3ac0 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -18,31 +18,27 @@ def findMedianSortedArrays(self, nums1, nums2): else: return (self.getKth(nums1, nums2, (len1 + len2)/2) + \ self.getKth(nums1, nums2, (len1 + len2)/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 0 <= j < n and A[mid] >= B[j]: + if 0 <= k - 1 - mid < n and A[mid] >= B[k - 1 - mid]: right = mid else: left = mid + 1 - - 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] - + + Ai_minus_1 = A[left - 1] if left - 1 >= 0 else float("-inf") + Bj = B[k - 1 - left] if k - 1 - left >= 0 else float("-inf") + return max(Ai_minus_1, Bj) - + if __name__ == "__main__": print Solution().findMedianSortedArrays([1, 3, 5, 7], [2, 4, 6]) print Solution().findMedianSortedArrays([1, 3, 5], [2, 4, 6]) - + From d0f018940304a8eb31466d311c796686ae4d1659 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 20:52:13 +0800 Subject: [PATCH 2144/4971] Update powx-n.py --- Python/powx-n.py | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/Python/powx-n.py b/Python/powx-n.py index 02672df29..a11cd2112 100644 --- a/Python/powx-n.py +++ b/Python/powx-n.py @@ -1,28 +1,27 @@ # Time: O(logn) -# Space: O(logn) +# Space: O(1) # # Implement pow(x, n). # -class Solution: - # @param x, a float - # @param n, a integer - # @return a float - def pow(self, x, n): - if n < 0: - return 1 / self.powRecu(x, -n) - - return self.powRecu(x, n) - - def powRecu(self, x, n): - if n == 0: - return 1.0 - - if n % 2 == 0: - return self.powRecu(x * x, n / 2) - else: - return x * self.powRecu(x * x, n / 2) +class Solution(object): + def myPow(self, x, n): + """ + :type x: float + :type n: int + :rtype: float + """ + res = 1 + abs_n = abs(n) + while abs_n: + if abs_n & 1: + res *= x + abs_n >>= 1 + x *= x + + return 1 / res if n < 0 else res + if __name__ == "__main__": print Solution().pow(3, 5) - print Solution().pow(3, -5) \ No newline at end of file + print Solution().pow(3, -5) From f46dd11dfe4be8caf595ffba56889e4d27cb93bd Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 20:53:04 +0800 Subject: [PATCH 2145/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c87b1f35e..a85289a4d 100644 --- a/README.md +++ b/README.md @@ -233,6 +233,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || +50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [Python](./Python/powx-n.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 || @@ -318,7 +319,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || From b65b8ca6b5b32957f519490f890a8d12eb08d7ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 20:53:41 +0800 Subject: [PATCH 2146/4971] Update powx-n.py --- Python/powx-n.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/powx-n.py b/Python/powx-n.py index a11cd2112..44fdae013 100644 --- a/Python/powx-n.py +++ b/Python/powx-n.py @@ -1,8 +1,7 @@ # Time: O(logn) # Space: O(1) -# + # Implement pow(x, n). -# class Solution(object): def myPow(self, x, n): From afa90d4e2b77551007175bdf1f635874d5ad5592 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 21:01:14 +0800 Subject: [PATCH 2147/4971] Update and rename pow.cpp to powx-n.cpp --- C++/pow.cpp | 24 ------------------------ C++/powx-n.cpp | 18 ++++++++++++++++++ 2 files changed, 18 insertions(+), 24 deletions(-) delete mode 100644 C++/pow.cpp create mode 100644 C++/powx-n.cpp diff --git a/C++/pow.cpp b/C++/pow.cpp deleted file mode 100644 index 4877d7443..000000000 --- a/C++/pow.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// Time Complexity: O(logn) -// Space Complexity: O(logn) - -class Solution { - public: - double pow(double x, int n) { - if(n < 0) - return 1.0 / power(x, -n); // be careful: -1 * -2147483648 is still -2147483648 - else - return power(x, n); - } - - private: - double power(double x, int n) { - if(n == 0) - return 1; - double v = power(x, n / 2); - - if(n % 2 != 0) - return v * v * x; - else - return v * v; - } -}; diff --git a/C++/powx-n.cpp b/C++/powx-n.cpp new file mode 100644 index 000000000..79df9e460 --- /dev/null +++ b/C++/powx-n.cpp @@ -0,0 +1,18 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + double myPow(double x, int n) { + double res = 1; + long abs_n = abs(static_cast(n)); + while (abs_n > 0) { + if (abs_n & 1) { + res *= x; + } + abs_n >>= 1; + x *= x; + } + return n < 0 ? 1 / res : res; + } +}; From 9e1311de5a561161d12f5d6adc479f981f83d277 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 21:01:54 +0800 Subject: [PATCH 2148/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a85289a4d..5250ac418 100644 --- a/README.md +++ b/README.md @@ -233,7 +233,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || -50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [Python](./Python/powx-n.py) | _O(logn)_ | _O(1)_ | Medium || +50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.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 || From 199a1f26f16cd56772ab1065b9693ee85bff0a58 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 21:15:35 +0800 Subject: [PATCH 2149/4971] Update sqrtx.py --- Python/sqrtx.py | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/Python/sqrtx.py b/Python/sqrtx.py index aab364874..9fd3679f8 100644 --- a/Python/sqrtx.py +++ b/Python/sqrtx.py @@ -1,27 +1,30 @@ # Time: O(logn) # Space: O(1) -# + # Implement int sqrt(int x). # # Compute and return the square root of x. -# -class Solution: - # @param x, an integer - # @return an integer - def sqrt(self, x): +class Solution(object): + def mySqrt(self, x): + """ + :type x: int + :rtype: int + """ if x < 2: return x - low, high = 1, x / 2 - while high >= low: - mid = low + (high - low) / 2 - if x / mid < mid: - high = mid - 1 + left, right = 1, x / 2 + while left <= right: + mid = left + (right - left) / 2 + if mid > x / mid: + right = mid - 1 else: - low = mid + 1 - return high + left = mid + 1 + + return left - 1 + if __name__ == "__main__": print Solution().sqrt(10) - \ No newline at end of file + From e39216a1ea4a298f9aed2310f1e123394c82a7af Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 21:22:05 +0800 Subject: [PATCH 2150/4971] Update search-a-2d-matrix.py --- Python/search-a-2d-matrix.py | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/Python/search-a-2d-matrix.py b/Python/search-a-2d-matrix.py index 712bc4dc1..46f85d228 100644 --- a/Python/search-a-2d-matrix.py +++ b/Python/search-a-2d-matrix.py @@ -17,26 +17,25 @@ # Given target = 3, return true. # -class Solution: - # @param matrix, a list of lists of integers - # @param target, an integer - # @return a boolean +class Solution(object): def searchMatrix(self, matrix, target): - m = len(matrix) - n = len(matrix[0]) - i, j = 0, m * n - - while i < j: - mid = i + (j - i) / 2 - val = matrix[mid / n][mid % n] - if val == target: - return True - elif val < target: - i = mid + 1 + """ + :type matrix: List[List[int]] + :type target: int + :rtype: bool + """ + m, n = len(matrix), len(matrix[0]) + left, right = 0, m * n + while left < right: + mid = left + (right - left) / 2 + if matrix[mid / n][mid % n] >= target: + right = mid else: - j = mid - return False + left = mid + 1 + + return left < m * n and matrix[left / n][left % n] == target + if __name__ == "__main__": matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]] - print Solution().searchMatrix(matrix, 3) \ No newline at end of file + print Solution().searchMatrix(matrix, 3) From eb3f93ac64953eacecdd48e2cb8d5ca80554a95b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 21:26:42 +0800 Subject: [PATCH 2151/4971] Update search-for-a-range.py --- Python/search-for-a-range.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 526ada9ab..088473598 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -20,18 +20,18 @@ def searchRange(self, nums, target): :rtype: List[int] """ # Find the first index where target <= nums[idx] - left = self.binarySearch(lambda x, y: x <= y, nums, target) + left = self.binarySearch(lambda x, y: x >= y, nums, target) if left >= len(nums) or nums[left] != target: return [-1, -1] # Find the first index where target < nums[idx] - right = self.binarySearch(lambda x, y: x < y, nums, target) + right = self.binarySearch(lambda x, y: x > y, nums, target) return [left, right - 1] def binarySearch(self, compare, nums, target): left, right = 0, len(nums) while left < right: mid = left + (right - left) / 2 - if compare(target, nums[mid]): + if compare(nums[mid], target): right = mid else: left = mid + 1 @@ -41,7 +41,7 @@ def binarySearch2(self, compare, nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = left + (right - left) / 2 - if compare(target, nums[mid]): + if compare(nums[mid], target): right = mid - 1 else: left = mid + 1 @@ -49,9 +49,9 @@ def binarySearch2(self, compare, nums, target): def binarySearch3(self, compare, nums, target): left, right = -1, len(nums) - while right - left > 1: + while left + 1 < right: mid = left + (right - left) / 2 - if compare(target, nums[mid]): + if compare(nums[mid], target): right = mid else: left = mid From f0b6349158198566ecee6a764a7a79f58b37b43c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 21:59:28 +0800 Subject: [PATCH 2152/4971] Update find-peak-element.py --- Python/find-peak-element.py | 43 +++++++++++++++++++++---------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/Python/find-peak-element.py b/Python/find-peak-element.py index 1fe1ac83b..510b1feea 100644 --- a/Python/find-peak-element.py +++ b/Python/find-peak-element.py @@ -1,38 +1,43 @@ # Time: O(logn) # Space: O(1) -# + # A peak element is an element that is greater than its neighbors. # -# Given an input array where num[i] != num[i+1], find a peak element and return its index. +# Given an input array where num[i] != num[i+1], +# find a peak element and return its index. # -# The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. +# The array may contain multiple peaks, in that case +# return the index to any one of the peaks is fine. # # You may imagine that num[-1] = num[n] = -infinite. # -# For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. +# For example, in array [1, 2, 3, 1], 3 is a peak element +# and your function should return the index number 2. # # Note: # Your solution should be in logarithmic complexity. -# -class Solution: - # @param num, a list of integer - # @return an integer - def findPeakElement(self, num): - low, high = 0, len(num) - 1 + +class Solution(object): + def findPeakElement(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + left, right = 0, len(nums) - 1 - while low < high: - mid = low + (high - low) / 2 - if (mid == 0 or num[mid - 1] <= num[mid]) and \ - (mid == len(num) - 1 or num[mid + 1] <= num[mid]): + while left < right: + mid = left + (right - left) / 2 + if nums[mid - 1] <= nums[mid] >= nums[mid + 1]: return mid - elif mid > 0 and num[mid - 1] > num[mid]: - high = mid - 1 + elif mid > 0 and nums[mid - 1] > nums[mid]: + right = mid else: - low = mid + 1 + left = mid + 1 - return low + return left + if __name__ == "__main__": # print Solution().findPeakElement([1,2,1]) - print Solution().findPeakElement([1,2,3, 1]) + print Solution().findPeakElement([1,2,3,1]) From 068432d6c2df77701953194a3094ebdb73f3b8bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 22:04:48 +0800 Subject: [PATCH 2153/4971] Update find-peak-element.py --- Python/find-peak-element.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/find-peak-element.py b/Python/find-peak-element.py index 510b1feea..7216279c1 100644 --- a/Python/find-peak-element.py +++ b/Python/find-peak-element.py @@ -28,7 +28,8 @@ def findPeakElement(self, nums): while left < right: mid = left + (right - left) / 2 - if nums[mid - 1] <= nums[mid] >= nums[mid + 1]: + if (mid == 0 or nums[mid - 1] <= nums[mid]) and \ + (mid == len(nums) - 1 or nums[mid + 1] <= nums[mid]): return mid elif mid > 0 and nums[mid - 1] > nums[mid]: right = mid From 8115591f98e0f4009c5b06a2c0c4377b74e0bf98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 22:07:40 +0800 Subject: [PATCH 2154/4971] Update find-peak-element.py --- Python/find-peak-element.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/find-peak-element.py b/Python/find-peak-element.py index 7216279c1..84a319cee 100644 --- a/Python/find-peak-element.py +++ b/Python/find-peak-element.py @@ -28,10 +28,10 @@ def findPeakElement(self, nums): while left < right: mid = left + (right - left) / 2 - if (mid == 0 or nums[mid - 1] <= nums[mid]) and \ - (mid == len(nums) - 1 or nums[mid + 1] <= nums[mid]): + if (mid == 0 or nums[mid - 1] < nums[mid]) and \ + (mid + 1 == len(nums) or nums[mid] > nums[mid + 1]): return mid - elif mid > 0 and nums[mid - 1] > nums[mid]: + elif not (mid == 0 or nums[mid - 1] <= nums[mid]): right = mid else: left = mid + 1 From 52c44d24b1b68d592de9a244d4a5f212911ecb1c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 22:12:00 +0800 Subject: [PATCH 2155/4971] Update find-peak-element.py --- Python/find-peak-element.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/find-peak-element.py b/Python/find-peak-element.py index 84a319cee..03b265932 100644 --- a/Python/find-peak-element.py +++ b/Python/find-peak-element.py @@ -31,7 +31,7 @@ def findPeakElement(self, nums): if (mid == 0 or nums[mid - 1] < nums[mid]) and \ (mid + 1 == len(nums) or nums[mid] > nums[mid + 1]): return mid - elif not (mid == 0 or nums[mid - 1] <= nums[mid]): + elif not (mid == 0 or nums[mid - 1] < nums[mid]): right = mid else: left = mid + 1 From 6887955dc47aa09df51bf46d450f4f13438e5eb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 22:13:19 +0800 Subject: [PATCH 2156/4971] Create find-peak-element.cpp --- C++/find-peak-element.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/find-peak-element.cpp diff --git a/C++/find-peak-element.cpp b/C++/find-peak-element.cpp new file mode 100644 index 000000000..8e9dc8bf2 --- /dev/null +++ b/C++/find-peak-element.cpp @@ -0,0 +1,23 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int findPeakElement(vector& nums) { + int left = 0, right = nums.size() - 1; + + while (left < right) { + const auto mid = left + (right - left) / 2; + if ((mid == 0 || nums[mid - 1] < nums[mid]) && + (mid + 1 == nums.size() || nums[mid] > nums[mid + 1])) { + return mid; + } else if (!(mid == 0 || nums[mid - 1] < nums[mid])) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; + } +}; From 46419d5de4264d9db5b2aa9d1939ae665080975b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 22:14:02 +0800 Subject: [PATCH 2157/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5250ac418..894050bb1 100644 --- a/README.md +++ b/README.md @@ -324,7 +324,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || +162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [C++](./C++/find-peak-element.cpp) [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 | LintCode || From e9fadf2cbbed6a2085cc3db3d0bc7fa176ded3f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 23:01:57 +0800 Subject: [PATCH 2158/4971] Create search-in-rotated-sorted-array.cpp --- C++/search-in-rotated-sorted-array.cpp | 44 ++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C++/search-in-rotated-sorted-array.cpp diff --git a/C++/search-in-rotated-sorted-array.cpp b/C++/search-in-rotated-sorted-array.cpp new file mode 100644 index 000000000..25578bc87 --- /dev/null +++ b/C++/search-in-rotated-sorted-array.cpp @@ -0,0 +1,44 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int search(vector& nums, int target) { + int left = 0, right = nums.size() - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) { + return mid; + } else if ((nums[mid] >= nums[left] && nums[left] <= target && target < nums[mid]) || + (nums[mid] < nums[left] && !(nums[mid] < target && target <= nums[right]))) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + return -1; + } +}; + +class Solution2 { +public: + int search(vector& nums, int target) { + int left = 0, right = nums.size(); + + while (left < right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) { + return mid; + } else if ((nums[left] <= nums[mid] && nums[left] <= target && target < nums[mid]) || + (nums[left] > nums[mid] && !(nums[mid] < target && target <= nums[right - 1]))) { + right = mid; + } else { + left = mid + 1; + } + } + + return -1; + } +}; From 95fae0f3555f4416dbd01c8eadc897ccd2d39c95 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 23:03:35 +0800 Subject: [PATCH 2159/4971] Update search.cpp --- C++/search.cpp | 67 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 43 insertions(+), 24 deletions(-) diff --git a/C++/search.cpp b/C++/search.cpp index 60f5babe4..8b03c92b5 100644 --- a/C++/search.cpp +++ b/C++/search.cpp @@ -1,29 +1,48 @@ -// Time Complexity: O(logn) -// O(n) if duplicates are allowed -// Space Complexity: O(1) +// Time: O(logn) +// Space: O(1) class Solution { - public: - bool search(int A[], int n, int target) { - for(int start = 0, end = n; start < end; ) { - const int mid = (start + end) / 2; - if(A[mid] == target) - return true; - if(A[start] < A[mid]) { - if(A[start] <= target && target < A[mid]) - end = mid; - else - start = mid + 1; - } - else if(A[start] > A[mid]) { - if(A[mid] < target && target <= A[end - 1]) - start = mid + 1; - else - end = mid; - } - else - ++start; +public: + bool search(vector &nums, int target) { + int left = 0, right = nums.size() - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) { + return true; + } else if (nums[mid] == nums[left]) { + ++left; + } else if ((nums[mid] > nums[left] && nums[left] <= target && target < nums[mid]) || + (nums[mid] < nums[left] && !(nums[mid] < target && target <= nums[right]))) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + return false; + } +}; + +class Solution2 { +public: + bool search(vector &nums, int target) { + int left = 0, right = nums.size(); + + while (left < right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) { + return true; + } else if (nums[mid] == nums[left]) { + ++left; + } else if ((nums[left] <= nums[mid] && nums[left] <= target && target < nums[mid]) || + (nums[left] > nums[mid] && !(nums[mid] < target && target <= nums[right - 1]))) { + right = mid; + } else { + left = mid + 1; } - return false; } + + return false; + } }; From f2144493946002ca201a7ddd036cdf98e5588bcb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 23:04:34 +0800 Subject: [PATCH 2160/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 894050bb1..98dd3b438 100644 --- a/README.md +++ b/README.md @@ -316,12 +316,12 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | 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 || +33| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [C++](./C++/search-in-rotated-sorted-array.cpp) [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 || 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 || +81| [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) | [C++](./C++/search-in-rotated-sorted-array-ii.cpp) [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/) | [C++](./C++/find-peak-element.cpp) [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || From c496fb72a369c527ed0166c610522e8a7fc982e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 23:05:28 +0800 Subject: [PATCH 2161/4971] Rename search.cpp to search-in-rotated-sorted-array-ii.cpp --- C++/{search.cpp => search-in-rotated-sorted-array-ii.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{search.cpp => search-in-rotated-sorted-array-ii.cpp} (100%) diff --git a/C++/search.cpp b/C++/search-in-rotated-sorted-array-ii.cpp similarity index 100% rename from C++/search.cpp rename to C++/search-in-rotated-sorted-array-ii.cpp From 3e3e4efe48c7106b87658de738a078ec20e27029 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 23:19:14 +0800 Subject: [PATCH 2162/4971] Update and rename findMinimumInRotatedSortedArray.cpp to find-minimum-in-rotated-sorted-array.cpp --- C++/find-minimum-in-rotated-sorted-array.cpp | 22 +++++++++++++++ C++/findMinimumInRotatedSortedArray.cpp | 29 -------------------- 2 files changed, 22 insertions(+), 29 deletions(-) create mode 100644 C++/find-minimum-in-rotated-sorted-array.cpp delete mode 100644 C++/findMinimumInRotatedSortedArray.cpp diff --git a/C++/find-minimum-in-rotated-sorted-array.cpp b/C++/find-minimum-in-rotated-sorted-array.cpp new file mode 100644 index 000000000..12bc3fa78 --- /dev/null +++ b/C++/find-minimum-in-rotated-sorted-array.cpp @@ -0,0 +1,22 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int findMin(vector& nums) { + int left = 0, right = nums.size() - 1; + + // Find min left s.t. nums[left] < nums[left']. + while (left < right && nums[left] >= nums[right]) { + int mid = left + (right - left) / 2; + if (nums[mid] < nums[left]) { + right = mid; + } else { + left = mid + 1; + } + } + + return nums[left]; + + } +}; diff --git a/C++/findMinimumInRotatedSortedArray.cpp b/C++/findMinimumInRotatedSortedArray.cpp deleted file mode 100644 index 8fd41d8b8..000000000 --- a/C++/findMinimumInRotatedSortedArray.cpp +++ /dev/null @@ -1,29 +0,0 @@ -// LeetCode, SFind Minimum in Rotated Sorted Array -// Complexity: -// O(logn) time -// O(1) space - -class Solution { -public: - int findMin(vector &num) { - int start = 0, end = num.size(); - - while (start < end) { - if (num[start] <= num[end - 1]) - return num[start]; - - int mid = start + (end - start)/2; - - if (num[mid] >= num[start]) { - start = mid + 1; - } else { - if (mid == end - 1) - return num[mid]; - else - end = mid + 1; - } - } - - return num[start]; - } -}; \ No newline at end of file From 37a89d2d89010140ffbd46a43fcd31c4ef9f372f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 23:21:56 +0800 Subject: [PATCH 2163/4971] Create find-minimum-in-rotated-sorted-array-ii.cpp --- ...ind-minimum-in-rotated-sorted-array-ii.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/find-minimum-in-rotated-sorted-array-ii.cpp diff --git a/C++/find-minimum-in-rotated-sorted-array-ii.cpp b/C++/find-minimum-in-rotated-sorted-array-ii.cpp new file mode 100644 index 000000000..98a4e465a --- /dev/null +++ b/C++/find-minimum-in-rotated-sorted-array-ii.cpp @@ -0,0 +1,24 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int findMin(vector& nums) { + int left = 0, right = nums.size() - 1; + + // Find min left s.t. nums[left] < nums[left']. + while (left < right && nums[left] >= nums[right]) { + int mid = left + (right - left) / 2; + if (nums[mid] == nums[left]) { + ++left; + } else if (nums[mid] < nums[left]) { + right = mid; + } else { + left = mid + 1; + } + } + + return nums[left]; + + } +}; From 828b796d4ff90daf320f90d53fcef71f796cbcaa Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 23:22:26 +0800 Subject: [PATCH 2164/4971] Update find-minimum-in-rotated-sorted-array-ii.cpp --- C++/find-minimum-in-rotated-sorted-array-ii.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/find-minimum-in-rotated-sorted-array-ii.cpp b/C++/find-minimum-in-rotated-sorted-array-ii.cpp index 98a4e465a..970ce0da1 100644 --- a/C++/find-minimum-in-rotated-sorted-array-ii.cpp +++ b/C++/find-minimum-in-rotated-sorted-array-ii.cpp @@ -19,6 +19,5 @@ class Solution { } return nums[left]; - } }; From 00af47b6f217f230cd743e2f8887ed94d87d63ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 23:22:41 +0800 Subject: [PATCH 2165/4971] Update find-minimum-in-rotated-sorted-array.cpp --- C++/find-minimum-in-rotated-sorted-array.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/find-minimum-in-rotated-sorted-array.cpp b/C++/find-minimum-in-rotated-sorted-array.cpp index 12bc3fa78..79e571a3a 100644 --- a/C++/find-minimum-in-rotated-sorted-array.cpp +++ b/C++/find-minimum-in-rotated-sorted-array.cpp @@ -17,6 +17,5 @@ class Solution { } return nums[left]; - } }; From 6d38b461e8e048896afb9796759c4f2c35edbf01 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 23:23:35 +0800 Subject: [PATCH 2166/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 98dd3b438..cf45b4646 100644 --- a/README.md +++ b/README.md @@ -322,8 +322,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/) | [C++](./C++/search-in-rotated-sorted-array-ii.cpp) [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 || +153| [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [C++](./C++/find-minimum-in-rotated-sorted-array.cpp) [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/) | [C++](./C++/find-minimum-in-rotated-sorted-array-ii.cpp) [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/) | [C++](./C++/find-peak-element.cpp) [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 | From 1d419648402d2f60efa3300f449808f40ce98fea Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 May 2016 23:50:37 +0800 Subject: [PATCH 2167/4971] Update contains-duplicate-iii.cpp --- C++/contains-duplicate-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/contains-duplicate-iii.cpp b/C++/contains-duplicate-iii.cpp index 0231eb157..a8e790d61 100644 --- a/C++/contains-duplicate-iii.cpp +++ b/C++/contains-duplicate-iii.cpp @@ -17,7 +17,7 @@ class Solution { window.pop(); bst.erase(bst.find(num)); } - // Every search costs time: O(logn). + // Every search costs time: O(logk). const auto it = bst.lower_bound(nums[i] - t); if (it == bst.cend() || (*it - nums[i]) > t) { // Not found. From 62d3d8521e1ca1ca913e62d0bacabc39ec33db36 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 May 2016 00:16:02 +0800 Subject: [PATCH 2168/4971] Update symmetric-tree.cpp --- C++/symmetric-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/symmetric-tree.cpp b/C++/symmetric-tree.cpp index 22c4a3feb..e3808f89d 100644 --- a/C++/symmetric-tree.cpp +++ b/C++/symmetric-tree.cpp @@ -31,7 +31,7 @@ class Solution { if (!left && !right) { continue; } - if (!left || !right || left->val != right->val) { + if (!left || !right || left->val != right->val) { return false; } // isSymmetricHelper(left->right, right->left) From 2c7aef2c0dbae34d3654d5e47ce6871b55f2f576 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 May 2016 11:54:50 +0800 Subject: [PATCH 2169/4971] Update find-minimum-in-rotated-sorted-array.py --- Python/find-minimum-in-rotated-sorted-array.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Python/find-minimum-in-rotated-sorted-array.py b/Python/find-minimum-in-rotated-sorted-array.py index f5a984a8e..87bf741e8 100644 --- a/Python/find-minimum-in-rotated-sorted-array.py +++ b/Python/find-minimum-in-rotated-sorted-array.py @@ -16,11 +16,13 @@ def findMin(self, nums): :type nums: List[int] :rtype: int """ - left, right = 0, len(nums) - 1 + left, right = 0, len(nums) + target = nums[-1] + while left < right: mid = left + (right - left) / 2 - if nums[mid] < nums[right]: + if nums[mid] <= target: right = mid else: left = mid + 1 From 7df3084efc98370e31db9f51adc3ec51d62e46bf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 May 2016 22:57:29 +0800 Subject: [PATCH 2170/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cf45b4646..b0610f5d9 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 |📖|| +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 42698f8ac3f4515a8d54e17829abb712b4ab8da8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 May 2016 10:40:50 +0800 Subject: [PATCH 2171/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b0610f5d9..0141a515c 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ 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) -* [Divide and Conquer](https://github.com/kamyu104/LeetCode#divide-and-conquer) +* [Recursion](https://github.com/kamyu104/LeetCode#recursion) * [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) @@ -288,7 +288,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | -## Divide and Conquer +## Recursion # | 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 || From 181b8a835b09344c854a4980434fbbb219388478 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 May 2016 10:41:24 +0800 Subject: [PATCH 2172/4971] 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 af65f6921..d01235a99 100644 --- a/C++/lowest-common-ancestor-of-a-binary-tree.cpp +++ b/C++/lowest-common-ancestor-of-a-binary-tree.cpp @@ -1,4 +1,4 @@ -// Time: O(h) +// Time: O(n) // Space: O(h) /** From 049a80bfb932fc76a8a85d4c0611ace90d550799 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 May 2016 10:41:40 +0800 Subject: [PATCH 2173/4971] 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 1b5e75d47..190662c69 100644 --- a/Python/lowest-common-ancestor-of-a-binary-tree.py +++ b/Python/lowest-common-ancestor-of-a-binary-tree.py @@ -1,4 +1,4 @@ -# Time: O(h) +# Time: O(n) # Space: O(h) # # Given a binary tree, find the lowest common ancestor (LCA) From 8c95ad12e65dc3ef136c2c6cc37994348c3f4d1a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 May 2016 10:42:07 +0800 Subject: [PATCH 2174/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0141a515c..7f37caed7 100644 --- a/README.md +++ b/README.md @@ -365,7 +365,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || 200| [Number of Islands](https://leetcode.com/problems/number-of-islands/) | [Python](./Python/number-of-islands.py) | _O(m * n)_ | _O(m * n)_| 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 | +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(n)_ | _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 |📖|| 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 19ebf135fb7ee2c637ac63e529cc6906c6dc880b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 May 2016 12:21:00 +0800 Subject: [PATCH 2175/4971] Update binary-tree-level-order-traversal-ii.py --- .../binary-tree-level-order-traversal-ii.py | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/Python/binary-tree-level-order-traversal-ii.py b/Python/binary-tree-level-order-traversal-ii.py index 07e9995bc..a03432a5d 100644 --- a/Python/binary-tree-level-order-traversal-ii.py +++ b/Python/binary-tree-level-order-traversal-ii.py @@ -1,6 +1,6 @@ # Time: O(n) # Space: O(n) -# + # Given a binary tree, return the bottom-up level order traversal of its nodes' values. # (ie, from left to right, level by level from leaf to root). # @@ -17,20 +17,24 @@ # [9,20], # [3] # ] -# + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: - # @param root, a tree node - # @return a list of lists of integers + +class Solution(object): def levelOrderBottom(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ if root is None: return [] + result, current = [], [root] while current: next_level, vals = [], [] @@ -41,8 +45,10 @@ def levelOrderBottom(self, root): if node.right: next_level.append(node.right) current = next_level - result.insert(0, vals) - return result + result.append(vals) + + return result[::-1] + if __name__ == "__main__": root = TreeNode(3) @@ -51,4 +57,4 @@ def levelOrderBottom(self, root): root.right.left = TreeNode(15) root.right.right = TreeNode(7) result = Solution().levelOrderBottom(root) - print result \ No newline at end of file + print result From 625f57ec683e0503928ffee2377b5c152b2e65f4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 May 2016 22:22:37 +0800 Subject: [PATCH 2176/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f37caed7..33d551fab 100644 --- a/README.md +++ b/README.md @@ -271,7 +271,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | -347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(1)_ | Medium | | Partition Sort | +347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(1)_ | Medium | | Quick Select | ## Two Pointers # | Title | Solution | Time | Space | Difficulty | Tag | Note From 613438e83877c4a2914154acff93224cc3cfebd4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 May 2016 09:22:48 +0800 Subject: [PATCH 2177/4971] Update word-search-ii.py --- Python/word-search-ii.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Python/word-search-ii.py b/Python/word-search-ii.py index 36b7afe93..4c6acdaac 100644 --- a/Python/word-search-ii.py +++ b/Python/word-search-ii.py @@ -19,7 +19,8 @@ # Note: # You may assume that all inputs are consist of lowercase letters a-z. # -class TrieNode: + +class TrieNode(object): # Initialize your data structure here. def __init__(self): self.is_string = False @@ -34,11 +35,14 @@ def insert(self, word): cur = cur.leaves[c] cur.is_string = True -class Solution: - # @param {character[][]} board - # @param {string[]} words - # @return {string[]} + +class Solution(object): def findWords(self, board, words): + """ + :type board: List[List[str]] + :type words: List[str] + :rtype: List[str] + """ visited = [[False for j in xrange(len(board[0]))] for i in xrange(len(board))] result = {} trie = TrieNode() @@ -71,4 +75,3 @@ def findWordsRecu(self, board, trie, cur, i, j, 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 86cd5dabe07b61ff8b685f9737bb27895406ca3f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 May 2016 19:55:38 +0800 Subject: [PATCH 2178/4971] Update integer-break.cpp --- C++/integer-break.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/integer-break.cpp b/C++/integer-break.cpp index 82a06b323..824ae28ea 100644 --- a/C++/integer-break.cpp +++ b/C++/integer-break.cpp @@ -1,5 +1,5 @@ // Time: O(logn), pow is O(logn). -// Space: O(logn) +// Space: O(1) class Solution { public: @@ -44,7 +44,7 @@ class Solution { }; // Time: O(n) -// Space: O(logn) +// Space: O(1) // DP solution. class Solution2 { public: From af7f6a04413b515ab529582a379eb5a9fca3f19e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 May 2016 19:55:56 +0800 Subject: [PATCH 2179/4971] Update integer-break.py --- Python/integer-break.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/integer-break.py b/Python/integer-break.py index e074792d0..c2127f3e9 100644 --- a/Python/integer-break.py +++ b/Python/integer-break.py @@ -1,5 +1,5 @@ # Time: O(logn), pow is O(logn). -# Space: O(logn) +# Space: O(1) # Given a positive integer n, break it into the sum of # at least two positive integers and maximize the product @@ -59,7 +59,7 @@ def integerBreak(self, n): # Time: O(n) -# Space: O(logn) +# Space: O(1) # DP solution. class Solution2(object): def integerBreak(self, n): From ffb3971f42f53b413b4eee4fbc70ac9605adda93 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 May 2016 19:56:15 +0800 Subject: [PATCH 2180/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 33d551fab..018cbf1d0 100644 --- a/README.md +++ b/README.md @@ -251,7 +251,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 ||| 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 ||| -343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(logn)_ | Medium || Tricky, DP | +343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(1)_ | Medium || Tricky, DP | ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From 6ddef9f561cce8a0fb630f988317f8ddce1c7860 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 May 2016 21:44:51 +0800 Subject: [PATCH 2181/4971] Update course-schedule.py --- Python/course-schedule.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Python/course-schedule.py b/Python/course-schedule.py index 395adba24..158d6a9d0 100644 --- a/Python/course-schedule.py +++ b/Python/course-schedule.py @@ -30,18 +30,20 @@ # of Topological Sort. # Topological sort could also be done via BFS. # -class Solution: - # @param {integer} numCourses - # @param {integer[][]} prerequisites - # @return {boolean} +class Solution(object): def canFinish(self, numCourses, prerequisites): + """ + :type numCourses: int + :type prerequisites: List[List[int]] + :rtype: bool + """ zero_in_degree_queue, in_degree, out_degree = collections.deque(), {}, {} for i, j in prerequisites: if i not in in_degree: - in_degree[i] = sets.Set() + in_degree[i] = set() if j not in out_degree: - out_degree[j] = sets.Set() + out_degree[j] = set() in_degree[i].add(j) out_degree[j].add(i) @@ -65,5 +67,6 @@ def canFinish(self, numCourses, prerequisites): return True + if __name__ == "__main__": print Solution().canFinish(1, []) From 5f771c646f9d9e5f97876fc2094212d80ccb2a43 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 May 2016 21:46:16 +0800 Subject: [PATCH 2182/4971] Update course-schedule-ii.py --- Python/course-schedule-ii.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Python/course-schedule-ii.py b/Python/course-schedule-ii.py index 0bffc2a61..c7e9c290b 100644 --- a/Python/course-schedule-ii.py +++ b/Python/course-schedule-ii.py @@ -35,18 +35,20 @@ # Topological sort could also be done via BFS. # -class Solution: - # @param {integer} numCourses - # @param {integer[][]} prerequisites - # @return {integer[]} +class Solution(object): def findOrder(self, numCourses, prerequisites): + """ + :type numCourses: int + :type prerequisites: List[List[int]] + :rtype: List[int] + """ res, zero_in_degree_queue, in_degree, out_degree = [], collections.deque(), {}, {} for i, j in prerequisites: if i not in in_degree: - in_degree[i] = sets.Set() + in_degree[i] = set() if j not in out_degree: - out_degree[j] = sets.Set() + out_degree[j] = set() in_degree[i].add(j) out_degree[j].add(i) From a0984419f6b053bbb866ea17205e2233c887aa52 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 May 2016 13:17:39 +0800 Subject: [PATCH 2183/4971] Create intersection-of-two-arrays.cpp --- C++/intersection-of-two-arrays.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/intersection-of-two-arrays.cpp diff --git a/C++/intersection-of-two-arrays.cpp b/C++/intersection-of-two-arrays.cpp new file mode 100644 index 000000000..a5f4a8ff6 --- /dev/null +++ b/C++/intersection-of-two-arrays.cpp @@ -0,0 +1,25 @@ +// Time: O(nlogn) +// Space: O(1) + +class Solution { +public: + vector intersection(vector& nums1, vector& nums2) { + vector res; + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + auto it1 = nums1.cbegin(), it2 = nums2.cbegin(); + while (it1 != nums1.cend() && it2 != nums2.cend()) { + if (*it1 < *it2) { + ++it1; + } else if (*it1 > *it2) { + ++it2; + } else { + if (res.empty() || res.back() != *it1) { + res.emplace_back(*it1); + } + ++it1, ++it2; + } + } + return res; + } +}; From ffc8bad9ec66b72a1947e1e54efda2d1ececb882 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 May 2016 13:23:30 +0800 Subject: [PATCH 2184/4971] Create intersection-of-two-arrays.py --- Python/intersection-of-two-arrays.py | 35 ++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/intersection-of-two-arrays.py diff --git a/Python/intersection-of-two-arrays.py b/Python/intersection-of-two-arrays.py new file mode 100644 index 000000000..4447aa9cd --- /dev/null +++ b/Python/intersection-of-two-arrays.py @@ -0,0 +1,35 @@ +# Time: O(nlogn) +# Space: O(1) + +# Given two arrays, write a function to compute their intersection. +# +# Example: +# Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. +# +# Note: +# Each element in the result must be unique. +# The result can be in any order. + +class Solution(object): + def intersection(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: List[int] + """ + nums1.sort(), nums2.sort() + res = [] + + it1, it2 = 0, 0 + while it1 < len(nums1) and it2 < len(nums2): + if nums1[it1] < nums2[it2]: + it1 += 1 + elif nums1[it1] > nums2[it2]: + it2 += 1 + else: + if not res or res[-1] != nums1[it1]: + res += nums1[it1], + it1 += 1 + it2 += 1 + + return res From fb13419efcc17b039bcdb280fa5c89c4084c6912 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 May 2016 13:25:50 +0800 Subject: [PATCH 2185/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 018cbf1d0..10ea2a6b0 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-348%20%2F%20348-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-349%20%2F%20349-ff69b4.svg) -Up to date (2016-05-05), there are `331` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-05-18), there are `332` 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 `348` questions. +Here is the classification of all `349` 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. ) @@ -287,6 +287,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 | 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | +349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(nlogn)_ | _O(1)_ | Easy | | ## Recursion # | Title | Solution | Time | Space | Difficulty | Tag | Note From d08afc8ccea1522dd5e4805847dd33476dd00b25 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 May 2016 02:46:07 -0500 Subject: [PATCH 2186/4971] Update anagrams.py --- Python/anagrams.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/anagrams.py b/Python/anagrams.py index a9e815abe..3bff0a0eb 100644 --- a/Python/anagrams.py +++ b/Python/anagrams.py @@ -1,5 +1,5 @@ -# Time: O(nlogg) = O(n / g * glogg), g is max size of groups -# Space: O(n) +# Time: O(n * llogl), l is the max length of strings. +# Space: O(n * l) # # Given an array of strings, return all groups of strings that are anagrams. # @@ -17,7 +17,7 @@ def groupAnagrams(self, strs): sorted_str = ("").join(sorted(s)) anagrams_map[sorted_str].append(s) for anagram in anagrams_map.values(): - anagram.sort() + # anagram.sort() result.append(anagram) return result From 362c8a52981763fc7288e7b9509b551e995ef787 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 May 2016 02:47:23 -0500 Subject: [PATCH 2187/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 10ea2a6b0..dd961d484 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [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/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || -49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(nlogg)_ | _O(n)_ | Medium || +49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n * llogl)_ | _O(n * l)_ | 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/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| From 54a2d575f596659d3f623eda7bff6436be616277 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 May 2016 02:53:23 -0500 Subject: [PATCH 2188/4971] Update anagrams.py --- Python/anagrams.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Python/anagrams.py b/Python/anagrams.py index 3bff0a0eb..74ce78394 100644 --- a/Python/anagrams.py +++ b/Python/anagrams.py @@ -1,5 +1,5 @@ -# Time: O(n * llogl), l is the max length of strings. -# Space: O(n * l) +# Time: O(n * glogg), g is the max size of groups. +# Space: O(n) # # Given an array of strings, return all groups of strings that are anagrams. # @@ -17,10 +17,11 @@ def groupAnagrams(self, strs): sorted_str = ("").join(sorted(s)) anagrams_map[sorted_str].append(s) for anagram in anagrams_map.values(): - # anagram.sort() + anagram.sort() result.append(anagram) return result - + + if __name__ == "__main__": result = Solution().anagrams(["cat", "dog", "act", "mac"]) print result From dbc60853b67ccd334c68e4f230e7a40ef19c1c98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 May 2016 02:54:15 -0500 Subject: [PATCH 2189/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dd961d484..e8881102c 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [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/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || -49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n * llogl)_ | _O(n * l)_ | Medium || +49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n * glogg)_ | _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/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| From 2e59d0a3ca5b7b8a9879d7daa6da020972c67b77 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 19 May 2016 21:02:06 +0800 Subject: [PATCH 2190/4971] Update anagrams.cpp --- C++/anagrams.cpp | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/C++/anagrams.cpp b/C++/anagrams.cpp index 1ca89dc01..dbac16f6a 100644 --- a/C++/anagrams.cpp +++ b/C++/anagrams.cpp @@ -1,22 +1,26 @@ -// Time Complexity: O(klogk * n) ~= O(n), k is length of string, n is number of strings -// Space Complexity: O(k * n) ~= O(n) +// Time: O(n * glogg), g is the max size of groups. +// Space: O(n) class Solution { - public: - vector anagrams(vector &strs) { - vector ans; - unordered_map > group; - for(auto s : strs) { - string k = s; - sort(k.begin(), k.end()); - group[k].push_back(s); - } +public: + vector> groupAnagrams(vector& strs) { + unordered_map> groups; + for (const auto& str : strs) { + string tmp{str}; + sort(tmp.begin(), tmp.end()); + groups[tmp].emplace_back(str); + } - for(auto it = group.cbegin(); it != group.cend(); ++it) { - if(it->second.size() > 1) - ans.insert(ans.end(), it->second.begin(), it->second.end()); + vector> anagrams; + for (const auto& kvp : groups) { + vector group; + for (const auto& str : kvp.second) { + group.emplace_back(str); } - - return ans; + sort(group.begin(), group.end()); + anagrams.emplace_back(move(group)); } -};` + + return anagrams; + } +}; From ffa82cff633db49b340d68e186bf55200b26d566 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 19 May 2016 21:02:52 +0800 Subject: [PATCH 2191/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e8881102c..4d6fa8d2b 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [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/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || -49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [Python](./Python/anagrams.py) | _O(n * glogg)_ | _O(n)_ | Medium || +49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [C++](./C++/anagrams.cpp) [Python](./Python/anagrams.py) | _O(n * glogg)_ | _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/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| From 052222e172725242ba32546eb3dfc5e5c0b12282 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 20 May 2016 13:15:02 +0800 Subject: [PATCH 2192/4971] Update and rename minWindow.cpp to minimum-window-substring.cpp --- C++/minWindow.cpp | 41 ------------------------- C++/minimum-window-substring.cpp | 51 ++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 41 deletions(-) delete mode 100644 C++/minWindow.cpp create mode 100644 C++/minimum-window-substring.cpp diff --git a/C++/minWindow.cpp b/C++/minWindow.cpp deleted file mode 100644 index 0f24c2a75..000000000 --- a/C++/minWindow.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// Time Complexity: O(n), where n is string length -// Space Complexity: O(m), where m is alphabet size - -class Solution { - public: - string minWindow(string S, string T) { - if(S.empty() || S.length() < T.length()) return ""; - const int ASCII_MAX = 256; - - vector expCnt(ASCII_MAX, 0); - vector curCnt(ASCII_MAX, 0); - int cnt = 0; - int start = 0; - int min_width = INT_MAX; - int min_start = 0; - - for(auto const &c : T) ++expCnt[c]; - - for(int i = 0; i < S.length(); ++i) { - if(expCnt[S[i]] > 0) { - ++curCnt[S[i]]; - if(curCnt[S[i]] <= expCnt[S[i]]) // counting expected elements - ++cnt; - } - if(cnt == T.size()) { // if window meets the requirement - while(expCnt[S[start]] == 0 || curCnt[S[start]] > expCnt[S[start]]) { // adjust left bound of window - --curCnt[S[start]]; - ++start; - } - - if(min_width > i - start + 1) { // update minimum window - min_width = i - start + 1; - min_start = start; - } - } - } - - if(min_width == INT_MAX) return ""; - return S.substr(min_start, min_width); - } -}; diff --git a/C++/minimum-window-substring.cpp b/C++/minimum-window-substring.cpp new file mode 100644 index 000000000..769d2fe4c --- /dev/null +++ b/C++/minimum-window-substring.cpp @@ -0,0 +1,51 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string minWindow(string s, string t) { + if (s.empty() || s.length() < t.length()) { + return ""; + } + + const int ASCII_MAX = 256; + vector exp_cnt(ASCII_MAX, 0); + vector cur_cnt(ASCII_MAX, 0); + + int cnt = 0; + int start = 0; + int min_start = 0; + int min_width = numeric_limits::max(); + + for (const auto& c : t) { + ++exp_cnt[c]; + } + + for (int i = 0; i < s.length(); ++i) { + if (exp_cnt[s[i]] > 0) { + ++cur_cnt[s[i]]; + if (cur_cnt[s[i]] <= exp_cnt[s[i]]) { // Counting expected elements. + ++cnt; + } + } + if (cnt == t.size()) { // If window meets the requirement. + while (exp_cnt[s[start]] == 0 || // Adjust left bound of window. + cur_cnt[s[start]] > exp_cnt[s[start]]) { + --cur_cnt[s[start]]; + ++start; + } + + if (min_width > i - start + 1) { // Update minimum window. + min_width = i - start + 1; + min_start = start; + } + } + } + + if (min_width == numeric_limits::max()) { + return ""; + } + + return s.substr(min_start, min_width); + } +}; From fa3b2fcaf82d6d27772db6dcde25d3956cff2a34 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 20 May 2016 13:16:19 +0800 Subject: [PATCH 2193/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d6fa8d2b..2d28bd862 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 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [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/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || 49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [C++](./C++/anagrams.cpp) [Python](./Python/anagrams.py) | _O(n * glogg)_ | _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 || +76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [C++](./C++/minimum-window-substring.cpp) [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/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _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 | 📖 | From 26adcfbd6890c047249a89b4ea59e46dbb9439a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 20 May 2016 13:16:52 +0800 Subject: [PATCH 2194/4971] Update minimum-window-substring.cpp --- C++/minimum-window-substring.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/minimum-window-substring.cpp b/C++/minimum-window-substring.cpp index 769d2fe4c..cf593f4b4 100644 --- a/C++/minimum-window-substring.cpp +++ b/C++/minimum-window-substring.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(1) +// Space: O(k) class Solution { public: From 2d42da99e7b00f41e8ae3532c70cb0bc5fbbd65d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 20 May 2016 13:21:44 +0800 Subject: [PATCH 2195/4971] Update minimum-window-substring.py --- Python/minimum-window-substring.py | 41 +++++++++++++++++------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/Python/minimum-window-substring.py b/Python/minimum-window-substring.py index 687402e30..1467c783e 100644 --- a/Python/minimum-window-substring.py +++ b/Python/minimum-window-substring.py @@ -1,7 +1,8 @@ # Time: O(n) # 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). + +# 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). # # For example, # S = "ADOBECODEBANC" @@ -9,30 +10,35 @@ # Minimum window is "BANC". # # Note: -# If there is no such window in S that covers all characters in T, return the emtpy string "". +# If there is no such window in S that covers all characters in T, +# return the emtpy string "". # -# If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S. -# +# If there are multiple such windows, you are guaranteed that +# there will always be only one unique minimum window in S. -class Solution: - # @return a string - def minWindow(self, S, T): +class Solution(object): + def minWindow(self, s, t): + """ + :type s: str + :type t: str + :rtype: str + """ current_count = [0 for i in xrange(52)] expected_count = [0 for i in xrange(52)] - for char in T: + for char in t: expected_count[ord(char) - ord('a')] += 1 i, count, start, min_width, min_start = 0, 0, 0, float("inf"), 0 - while i < len(S): - current_count[ord(S[i]) - ord('a')] += 1 - if current_count[ord(S[i]) - ord('a')] <= expected_count[ord(S[i]) - ord('a')]: + while i < len(s): + current_count[ord(s[i]) - ord('a')] += 1 + if current_count[ord(s[i]) - ord('a')] <= expected_count[ord(s[i]) - ord('a')]: count += 1 - if count == len(T): - while expected_count[ord(S[start]) - ord('a')] == 0 or\ - current_count[ord(S[start]) - ord('a')] > expected_count[ord(S[start]) - ord('a')]: - current_count[ord(S[start]) - ord('a')] -= 1 + if count == len(t): + while expected_count[ord(s[start]) - ord('a')] == 0 or\ + current_count[ord(s[start]) - ord('a')] > expected_count[ord(s[start]) - ord('a')]: + current_count[ord(s[start]) - ord('a')] -= 1 start += 1 if min_width > i - start + 1: @@ -43,7 +49,8 @@ def minWindow(self, S, T): if min_width == float("inf"): return "" - return S[min_start:min_start + min_width] + return s[min_start:min_start + min_width] + if __name__ == "__main__": print Solution().minWindow("ADOBECODEBANC", "ABC") From 7d430dbedf83eaafa79e306873a1455ee6c11ec7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 20 May 2016 13:22:05 +0800 Subject: [PATCH 2196/4971] 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 1467c783e..d006f4f1e 100644 --- a/Python/minimum-window-substring.py +++ b/Python/minimum-window-substring.py @@ -36,7 +36,7 @@ def minWindow(self, s, t): count += 1 if count == len(t): - while expected_count[ord(s[start]) - ord('a')] == 0 or\ + while expected_count[ord(s[start]) - ord('a')] == 0 or \ current_count[ord(s[start]) - ord('a')] > expected_count[ord(s[start]) - ord('a')]: current_count[ord(s[start]) - ord('a')] -= 1 start += 1 From 330043d955acb0da2dab4d15c2af0535096ac7c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:01:00 +0800 Subject: [PATCH 2197/4971] Create intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 59 +++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/intersection-of-two-arrays-ii.py diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py new file mode 100644 index 000000000..a2ca570f8 --- /dev/null +++ b/Python/intersection-of-two-arrays-ii.py @@ -0,0 +1,59 @@ +# If the given array is not sorted and the memory is unlimited. +# Time: O(m + n) +# Space: O(min(m, n)) +# Hash solution. +class Solution(object): + def intersect(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: List[int] + """ + if len(nums1) > len(nums2): + return self.intersect(nums2, nums1) + + lookup = collections.defaultdict(int) + for n in nums1: + lookup[n] += 1 + + res = [] + for n in nums2: + if lookup[n] > 0: + res += n, + lookup[n] -= 1 + + return res + + +# If the given array is already sorted, and memory is limited, and m ~ n: +# Time: O(m + n) +# Soace: O(1) +# Two pointer solution. +class Solution(object): + def intersect(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: List[int] + """ + nums1.sort(), nums2.sort() # Make sure it is sorted. + + res = [] + + it1, it2 = 0, 0 + while it1 < len(nums1) and it2 < len(nums2): + if nums1[it1] < nums2[it2]: + it1 += 1 + elif nums1[it1] > nums2[it2]: + it2 += 1 + else: + res += nums1[it1], + it1 += 1 + it2 += 1 + + return res + + +# If the given array is already sorted, and momory is limited, and m << n +# Time: O(mlogn) +# Space: O(1) From d3692fc74cd60ac56eb585088368282078561122 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:15:01 +0800 Subject: [PATCH 2198/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 61 ++++++++++++++++++++----- 1 file changed, 49 insertions(+), 12 deletions(-) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index a2ca570f8..f0ac54e21 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -13,19 +13,61 @@ def intersect(self, nums1, nums2): return self.intersect(nums2, nums1) lookup = collections.defaultdict(int) - for n in nums1: - lookup[n] += 1 + for i in nums1: + lookup[i] += 1 res = [] - for n in nums2: - if lookup[n] > 0: - res += n, - lookup[n] -= 1 + for i in nums2: + if lookup[i] > 0: + res += i, + lookup[i] -= 1 return res -# If the given array is already sorted, and memory is limited, and m ~ n: +# If the given array is already sorted, and m << n +# Time: O(min(m, n) * log(max(m, n))) +# Space: O(min(m, n)) +# Binary search solution. +class Solution(object): + def intersect(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: List[int] + """ + if len(nums1) > len(nums2): + return self.intersect(nums2, nums1) + + def count_of_num(nums, target): + def binary_search(compare, nums, target): + left, right = 0, len(nums) + while left < right: + mid = left + (right - left) / 2 + if compare(nums[mid], target): + right = mid + else: + left = mid + 1 + return left + + left = binary_search(lambda x, y: x >= y, nums, target) + right = binary_search(lambda x, y: x > y, nums, target) + return right - left + + nums1.sort(), nums2.sort() # Make sure it is sorted. + + cnts = collections.defaultdict(int) + for i in nums1: + cnt = count_of_num(nums2, i) + if cnt > 0 and cnts[i] < cnt: + cnts[i] += 1 + res = [] + for k, v in cnts.iteritems(): + res += [k] * v + + return res + +# If the given array is already sorted, and memory is limited or m ~ n # Time: O(m + n) # Soace: O(1) # Two pointer solution. @@ -52,8 +94,3 @@ def intersect(self, nums1, nums2): it2 += 1 return res - - -# If the given array is already sorted, and momory is limited, and m << n -# Time: O(mlogn) -# Space: O(1) From bf677ca5439b2fdb8b0e7a07c513cf3828a3ba9a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:16:31 +0800 Subject: [PATCH 2199/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index f0ac54e21..778a2b505 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -25,7 +25,7 @@ def intersect(self, nums1, nums2): return res -# If the given array is already sorted, and m << n +# If the given array is already sorted, and the memory is unlimited, and (m << n or m >> n) # Time: O(min(m, n) * log(max(m, n))) # Space: O(min(m, n)) # Binary search solution. @@ -67,10 +67,11 @@ def binary_search(compare, nums, target): return res + # If the given array is already sorted, and memory is limited or m ~ n # Time: O(m + n) # Soace: O(1) -# Two pointer solution. +# Two pointers solution. class Solution(object): def intersect(self, nums1, nums2): """ From 887e06ca823d64fa10ca23a935ed3bea72249acb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:29:55 +0800 Subject: [PATCH 2200/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 66 +++++++++++++++++++++++-- 1 file changed, 62 insertions(+), 4 deletions(-) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index 778a2b505..87db2436c 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -1,3 +1,33 @@ +# If the given array is not sorted and the memory is unlimited: +# - Time: O(m + n) +# - Space: O(min(m, n)) +# elif the given array is already sorted: +# if the memory is unlimited, and (m << n or m >> n) +# - Time: O(min(m, n) * log(max(m, n))) +# - Space: O(min(m, n)) +# else: +# - Time: O(m + n) +# - Soace: O(1) +# elif the memory is limited: +# - Time: O(max(m, n) * log(max(m, n))) +# - Space: O(max(m, n)) + +# Given two arrays, write a function to compute their intersection. +# +# Example: +# Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. +# +# Note: +# Each element in the result should appear as many times as it shows in both arrays. +# The result can be in any order. +# +# Follow up: +# - What if the given array is already sorted? How would you optimize your algorithm? +# - What if nums1's size is small compared to num2's size? Which algorithm is better? +# - What if elements of nums2 are stored on disk, and the memory is limited such that +# you cannot load all elements into the memory at once? + + # If the given array is not sorted and the memory is unlimited. # Time: O(m + n) # Space: O(min(m, n)) @@ -25,7 +55,7 @@ def intersect(self, nums1, nums2): return res -# If the given array is already sorted, and the memory is unlimited, and (m << n or m >> n) +# If the given array is already sorted, and the memory is unlimited, and (m << n or m >> n). # Time: O(min(m, n) * log(max(m, n))) # Space: O(min(m, n)) # Binary search solution. @@ -54,7 +84,7 @@ def binary_search(compare, nums, target): right = binary_search(lambda x, y: x > y, nums, target) return right - left - nums1.sort(), nums2.sort() # Make sure it is sorted. + nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time. cnts = collections.defaultdict(int) for i in nums1: @@ -68,7 +98,7 @@ def binary_search(compare, nums, target): return res -# If the given array is already sorted, and memory is limited or m ~ n +# If the given array is already sorted, and the memory is limited or m ~ n. # Time: O(m + n) # Soace: O(1) # Two pointers solution. @@ -79,7 +109,35 @@ def intersect(self, nums1, nums2): :type nums2: List[int] :rtype: List[int] """ - nums1.sort(), nums2.sort() # Make sure it is sorted. + nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time. + + res = [] + + it1, it2 = 0, 0 + while it1 < len(nums1) and it2 < len(nums2): + if nums1[it1] < nums2[it2]: + it1 += 1 + elif nums1[it1] > nums2[it2]: + it2 += 1 + else: + res += nums1[it1], + it1 += 1 + it2 += 1 + + return res + +# If the given array is not sorted, and the memory is limited. +# Time: O(max(m, n) * log(max(m, n))) +# Space: O(max(m, n)) +# Two pointers solution. +class Solution(object): + def intersect(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: List[int] + """ + nums1.sort(), nums2.sort() # O(max(m, n) * log(max(m, n))) res = [] From 1e2dba48d6060cf06b972adcf727864d5eeefe00 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:30:12 +0800 Subject: [PATCH 2201/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index 87db2436c..97bf6002b 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -126,6 +126,7 @@ def intersect(self, nums1, nums2): return res + # If the given array is not sorted, and the memory is limited. # Time: O(max(m, n) * log(max(m, n))) # Space: O(max(m, n)) From 0e1c14cb3c890a8e7e291119ce1e14fb7f8c227a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:39:52 +0800 Subject: [PATCH 2202/4971] Update README.md --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2d28bd862..096d3d55b 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-349%20%2F%20349-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-350%20%2F%20350-ff69b4.svg) -Up to date (2016-05-18), there are `332` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-05-21), there are `333` 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 `349` questions. +Here is the classification of all `350` 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. ) @@ -287,7 +287,8 @@ 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 | 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | -349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(nlogn)_ | _O(1)_ | Easy | | +349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | | +350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | | ## Recursion # | Title | Solution | Time | Space | Difficulty | Tag | Note From a1a8938e48aea752229268aedfb59726c155b62d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:41:07 +0800 Subject: [PATCH 2203/4971] Update intersection-of-two-arrays.py --- Python/intersection-of-two-arrays.py | 29 ++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/Python/intersection-of-two-arrays.py b/Python/intersection-of-two-arrays.py index 4447aa9cd..0a5d01448 100644 --- a/Python/intersection-of-two-arrays.py +++ b/Python/intersection-of-two-arrays.py @@ -1,5 +1,5 @@ -# Time: O(nlogn) -# Space: O(1) +# Time: O(m + n) +# Space: O(min(m, n)) # Given two arrays, write a function to compute their intersection. # @@ -11,6 +11,31 @@ # The result can be in any order. class Solution(object): + def intersection(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: List[int] + """ + if len(nums1) > len(nums2): + return self.intersection(nums2, nums1) + + lookup = set() + for i in nums1: + lookup.add(i) + + res = [] + for i in nums2: + if i in lookup: + res += i, + lookup.discard(i) + + return res + + +# Time: O(nlogn) +# Space: O(1) +class Solution2(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] From 29885263cb9f060dfe038b413f50715741fa55b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:42:05 +0800 Subject: [PATCH 2204/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 096d3d55b..f7713ef09 100644 --- a/README.md +++ b/README.md @@ -287,8 +287,8 @@ 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 | 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | -349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | | -350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | | +349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | Hash | +350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | Hash | ## Recursion # | Title | Solution | Time | Space | Difficulty | Tag | Note From 0ff520e67349985a2cef6f0ba4bb33679914dba7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:46:05 +0800 Subject: [PATCH 2205/4971] Update intersection-of-two-arrays.cpp --- C++/intersection-of-two-arrays.cpp | 33 ++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/C++/intersection-of-two-arrays.cpp b/C++/intersection-of-two-arrays.cpp index a5f4a8ff6..323500eef 100644 --- a/C++/intersection-of-two-arrays.cpp +++ b/C++/intersection-of-two-arrays.cpp @@ -1,7 +1,36 @@ -// Time: O(nlogn) -// Space: O(1) +// Time: O(m + n) +// Space: O(min(m, n)) +// Hash solution. class Solution { +public: + vector intersection(vector& nums1, vector& nums2) { + if (nums1.size() > nums2.size()) { + return intersection(nums2, nums1); + } + + unordered_set lookup; + for (const auto& i : nums1) { + lookup.emplace(i); + } + + vector result; + for (const auto& i : nums2) { + if (lookup.count(i)) { + result.emplace_back(i); + lookup.erase(i); + } + } + + return result; + } +}; + + +// Time: O(max(m, n) * log(max(m, n))) +// Space: O(1) +// Two pointer solution. +class Solution2 { public: vector intersection(vector& nums1, vector& nums2) { vector res; From 6d10e653576b0abeca5bca41396be407ca18387d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:46:33 +0800 Subject: [PATCH 2206/4971] Update intersection-of-two-arrays.py --- Python/intersection-of-two-arrays.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/intersection-of-two-arrays.py b/Python/intersection-of-two-arrays.py index 0a5d01448..bd56f9373 100644 --- a/Python/intersection-of-two-arrays.py +++ b/Python/intersection-of-two-arrays.py @@ -33,7 +33,7 @@ def intersection(self, nums1, nums2): return res -# Time: O(nlogn) +# Time: O(max(m, n) * log(max(m, n))) # Space: O(1) class Solution2(object): def intersection(self, nums1, nums2): From 744d81752673bb2bb7c5bccf1414f0ac2781f48a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:49:50 +0800 Subject: [PATCH 2207/4971] Create intersection-of-two-arrays-ii.cpp --- C++/intersection-of-two-arrays-ii.cpp | 42 +++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/intersection-of-two-arrays-ii.cpp diff --git a/C++/intersection-of-two-arrays-ii.cpp b/C++/intersection-of-two-arrays-ii.cpp new file mode 100644 index 000000000..2466ea872 --- /dev/null +++ b/C++/intersection-of-two-arrays-ii.cpp @@ -0,0 +1,42 @@ +// If the given array is not sorted and the memory is unlimited: +// - Time: O(m + n) +// - Space: O(min(m, n)) +// elif the given array is already sorted: +// if the memory is unlimited, and (m << n or m >> n) +// - Time: O(min(m, n) * log(max(m, n))) +// - Space: O(min(m, n)) +// else: +// - Time: O(m + n) +// - Soace: O(1) +// elif the memory is limited: +// - Time: O(max(m, n) * log(max(m, n))) +// - Space: O(max(m, n)) + +# If the given array is not sorted and the memory is unlimited. +# Time: O(m + n) +# Space: O(min(m, n)) +# Hash solution. +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + if (nums1.size() > nums2.size()) { + return intersect(nums2, nums1); + } + + unordered_map lookup; + for (const auto& i : nums1) { + ++lookup[i]; + } + + vector result; + for (const auto& i : nums2) { + if (lookup[i] > 0) { + result.emplace_back(i); + --lookup[i]; + } + } + + return result; + } +}; + From e4ad75258dded3fe670c87d5acfb281caf74edc4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 17:54:44 +0800 Subject: [PATCH 2208/4971] Update intersection-of-two-arrays-ii.cpp --- C++/intersection-of-two-arrays-ii.cpp | 61 +++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 4 deletions(-) diff --git a/C++/intersection-of-two-arrays-ii.cpp b/C++/intersection-of-two-arrays-ii.cpp index 2466ea872..de187b78b 100644 --- a/C++/intersection-of-two-arrays-ii.cpp +++ b/C++/intersection-of-two-arrays-ii.cpp @@ -12,10 +12,10 @@ // - Time: O(max(m, n) * log(max(m, n))) // - Space: O(max(m, n)) -# If the given array is not sorted and the memory is unlimited. -# Time: O(m + n) -# Space: O(min(m, n)) -# Hash solution. +// If the given array is not sorted and the memory is unlimited. +// Time: O(m + n) +// Space: O(min(m, n)) +// Hash solution. class Solution { public: vector intersect(vector& nums1, vector& nums2) { @@ -40,3 +40,56 @@ class Solution { } }; + +// If the given array is already sorted, and the memory is limited or m ~ n. +// Time: O(m + n) +// Soace: O(1) +// Two pointers solution. +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + vector result; + // Make sure it is sorted, doesn't count in time. + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + auto it1 = nums1.cbegin(), it2 = nums2.cbegin(); + while (it1 != nums1.cend() && it2 != nums2.cend()) { + if (*it1 < *it2) { + ++it1; + } else if (*it1 > *it2) { + ++it2; + } else { + result.emplace_back(*it1); + ++it1, ++it2; + } + } + return result; + } +}; + + +// If the given array is not sorted, and the memory is limited. +// Time: O(max(m, n) * log(max(m, n))) +// Space: O(1) +// Two pointer solution. +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + vector result; + // O(max(m, n) * log(max(m, n))) + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + auto it1 = nums1.cbegin(), it2 = nums2.cbegin(); + while (it1 != nums1.cend() && it2 != nums2.cend()) { + if (*it1 < *it2) { + ++it1; + } else if (*it1 > *it2) { + ++it2; + } else { + result.emplace_back(*it1); + ++it1, ++it2; + } + } + return result; + } +}; From e63eaa3ffb0597e89bb11abe167fecae03496705 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:08:13 +0800 Subject: [PATCH 2209/4971] Update intersection-of-two-arrays-ii.cpp --- C++/intersection-of-two-arrays-ii.cpp | 36 +++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/C++/intersection-of-two-arrays-ii.cpp b/C++/intersection-of-two-arrays-ii.cpp index de187b78b..01c338b53 100644 --- a/C++/intersection-of-two-arrays-ii.cpp +++ b/C++/intersection-of-two-arrays-ii.cpp @@ -41,6 +41,42 @@ class Solution { }; +// If the given array is already sorted, and the memory is unlimited, and (m << n or m >> n). +// Time: O(min(m, n) * log(max(m, n))) +// Space: O(min(m, n)) +// Binary search solution. +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + if (nums1.size() > nums2.size()) { + return intersect(nums2, nums1); + } + + // Make sure it is sorted, doesn't count in time. + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + + unordered_map cnts; + for (const auto& i : nums1) { + const auto left_it = lower_bound(nums2.cbegin(), nums2.cend(), i); + const auto right_it = upper_bound(nums2.cbegin(), nums2.cend(), i); + const auto cnt = right_it - left_it; + if (cnts[i] < cnt) { + ++cnts[i]; + } + } + + vector result; + for (const auto& kvp : cnts) { + vector tmp(kvp.second, kvp.first); + move(tmp.begin(), tmp.end(), back_inserter(result)); + } + + return result; + } +}; + + // If the given array is already sorted, and the memory is limited or m ~ n. // Time: O(m + n) // Soace: O(1) From 18a05d50287812f98a3882a808a0a0c63f43e199 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:09:11 +0800 Subject: [PATCH 2210/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index 97bf6002b..040c248d0 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -89,7 +89,7 @@ def binary_search(compare, nums, target): cnts = collections.defaultdict(int) for i in nums1: cnt = count_of_num(nums2, i) - if cnt > 0 and cnts[i] < cnt: + if cnts[i] < cnt: cnts[i] += 1 res = [] for k, v in cnts.iteritems(): From de2e7dfe33a5d4d94f0574ac64b86e1ec02f7afd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:09:45 +0800 Subject: [PATCH 2211/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index 040c248d0..40ae1f04d 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -91,6 +91,7 @@ def binary_search(compare, nums, target): cnt = count_of_num(nums2, i) if cnts[i] < cnt: cnts[i] += 1 + res = [] for k, v in cnts.iteritems(): res += [k] * v From 5692e7504aa4bb30e41ae3b91ede45f4e2533fe7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:10:46 +0800 Subject: [PATCH 2212/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index 40ae1f04d..52d8a807d 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -8,7 +8,7 @@ # else: # - Time: O(m + n) # - Soace: O(1) -# elif the memory is limited: +# else: (the memory is limited) # - Time: O(max(m, n) * log(max(m, n))) # - Space: O(max(m, n)) From da95d6cd89421b72ba69d5f15c6baa47a5e40e52 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:11:00 +0800 Subject: [PATCH 2213/4971] Update intersection-of-two-arrays-ii.cpp --- C++/intersection-of-two-arrays-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/intersection-of-two-arrays-ii.cpp b/C++/intersection-of-two-arrays-ii.cpp index 01c338b53..6bcd50601 100644 --- a/C++/intersection-of-two-arrays-ii.cpp +++ b/C++/intersection-of-two-arrays-ii.cpp @@ -8,7 +8,7 @@ // else: // - Time: O(m + n) // - Soace: O(1) -// elif the memory is limited: +// else: (the memory is limited) // - Time: O(max(m, n) * log(max(m, n))) // - Space: O(max(m, n)) From d1aec9d0bf7a254f4a4207630c12ca63ea323c01 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:11:29 +0800 Subject: [PATCH 2214/4971] Update intersection-of-two-arrays-ii.cpp --- C++/intersection-of-two-arrays-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/intersection-of-two-arrays-ii.cpp b/C++/intersection-of-two-arrays-ii.cpp index 6bcd50601..591353c61 100644 --- a/C++/intersection-of-two-arrays-ii.cpp +++ b/C++/intersection-of-two-arrays-ii.cpp @@ -10,7 +10,7 @@ // - Soace: O(1) // else: (the memory is limited) // - Time: O(max(m, n) * log(max(m, n))) -// - Space: O(max(m, n)) +// - Space: O(1) // If the given array is not sorted and the memory is unlimited. // Time: O(m + n) From 3bbc6099656d30e2f77c8b8562c573d9e3adf56b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:11:45 +0800 Subject: [PATCH 2215/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index 52d8a807d..e63687b57 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -10,7 +10,7 @@ # - Soace: O(1) # else: (the memory is limited) # - Time: O(max(m, n) * log(max(m, n))) -# - Space: O(max(m, n)) +# - Space: O(1) # Given two arrays, write a function to compute their intersection. # From 5ac9d18907584005791b6b3bf3592d247b55ba16 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:12:36 +0800 Subject: [PATCH 2216/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index e63687b57..aeeb7cec2 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -130,7 +130,7 @@ def intersect(self, nums1, nums2): # If the given array is not sorted, and the memory is limited. # Time: O(max(m, n) * log(max(m, n))) -# Space: O(max(m, n)) +# Space: O(1) # Two pointers solution. class Solution(object): def intersect(self, nums1, nums2): From 554e0bb0175094bf196e21824cd52fe145accd32 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:15:27 +0800 Subject: [PATCH 2217/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f7713ef09..af7d18a93 100644 --- a/README.md +++ b/README.md @@ -287,8 +287,8 @@ 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 | 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | -349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | Hash | -350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | Hash | +349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | | Hash +350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | | Hash ## Recursion # | Title | Solution | Time | Space | Difficulty | Tag | Note From 622c3cec242d54938d0da75bb4a5bebe19eb50bd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:17:15 +0800 Subject: [PATCH 2218/4971] Update intersection-of-two-arrays.py --- Python/intersection-of-two-arrays.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Python/intersection-of-two-arrays.py b/Python/intersection-of-two-arrays.py index bd56f9373..af8e57382 100644 --- a/Python/intersection-of-two-arrays.py +++ b/Python/intersection-of-two-arrays.py @@ -10,6 +10,7 @@ # Each element in the result must be unique. # The result can be in any order. +# Hash solution. class Solution(object): def intersection(self, nums1, nums2): """ @@ -35,6 +36,7 @@ def intersection(self, nums1, nums2): # Time: O(max(m, n) * log(max(m, n))) # Space: O(1) +# Two pointers solution. class Solution2(object): def intersection(self, nums1, nums2): """ From 94867488e78e03538a9502ca4ebf34d4b9d751a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:17:30 +0800 Subject: [PATCH 2219/4971] Update intersection-of-two-arrays.cpp --- C++/intersection-of-two-arrays.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/intersection-of-two-arrays.cpp b/C++/intersection-of-two-arrays.cpp index 323500eef..d0f0c42a0 100644 --- a/C++/intersection-of-two-arrays.cpp +++ b/C++/intersection-of-two-arrays.cpp @@ -29,7 +29,7 @@ class Solution { // Time: O(max(m, n) * log(max(m, n))) // Space: O(1) -// Two pointer solution. +// Two pointers solution. class Solution2 { public: vector intersection(vector& nums1, vector& nums2) { From 2edbef73e153022787a902e84a40717cc4bb81e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:18:05 +0800 Subject: [PATCH 2220/4971] Update intersection-of-two-arrays.cpp --- C++/intersection-of-two-arrays.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/intersection-of-two-arrays.cpp b/C++/intersection-of-two-arrays.cpp index d0f0c42a0..2c38521cb 100644 --- a/C++/intersection-of-two-arrays.cpp +++ b/C++/intersection-of-two-arrays.cpp @@ -33,7 +33,7 @@ class Solution { class Solution2 { public: vector intersection(vector& nums1, vector& nums2) { - vector res; + vector result; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); auto it1 = nums1.cbegin(), it2 = nums2.cbegin(); @@ -43,12 +43,12 @@ class Solution2 { } else if (*it1 > *it2) { ++it2; } else { - if (res.empty() || res.back() != *it1) { - res.emplace_back(*it1); + if (result.empty() || result.back() != *it1) { + result.emplace_back(*it1); } ++it1, ++it2; } } - return res; + return result; } }; From 6f4e75c26aae7131ec5be321c1b18396dbf231cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:30:25 +0800 Subject: [PATCH 2221/4971] Update intersection-of-two-arrays-ii.cpp --- C++/intersection-of-two-arrays-ii.cpp | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/C++/intersection-of-two-arrays-ii.cpp b/C++/intersection-of-two-arrays-ii.cpp index 591353c61..dfa809c7c 100644 --- a/C++/intersection-of-two-arrays-ii.cpp +++ b/C++/intersection-of-two-arrays-ii.cpp @@ -2,13 +2,13 @@ // - Time: O(m + n) // - Space: O(min(m, n)) // elif the given array is already sorted: -// if the memory is unlimited, and (m << n or m >> n) +// if m << n or m >> n: // - Time: O(min(m, n) * log(max(m, n))) -// - Space: O(min(m, n)) +// - Space: O(1) // else: // - Time: O(m + n) // - Soace: O(1) -// else: (the memory is limited) +// else: (the given array is not sorted and the memory is limited) // - Time: O(max(m, n) * log(max(m, n))) // - Space: O(1) @@ -41,9 +41,9 @@ class Solution { }; -// If the given array is already sorted, and the memory is unlimited, and (m << n or m >> n). +// If the given array is already sorted, and the memory is limited, and (m << n or m >> n). // Time: O(min(m, n) * log(max(m, n))) -// Space: O(min(m, n)) +// Space: O(1) // Binary search solution. class Solution { public: @@ -56,21 +56,14 @@ class Solution { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); - unordered_map cnts; + vector result; + auto it = nums2.cbegin(); for (const auto& i : nums1) { - const auto left_it = lower_bound(nums2.cbegin(), nums2.cend(), i); - const auto right_it = upper_bound(nums2.cbegin(), nums2.cend(), i); - const auto cnt = right_it - left_it; - if (cnts[i] < cnt) { - ++cnts[i]; + it = lower_bound(it, nums2.cend(), i); + if (it != nums2.end() && *it == i) { + result.emplace_back(*it++); } } - - vector result; - for (const auto& kvp : cnts) { - vector tmp(kvp.second, kvp.first); - move(tmp.begin(), tmp.end(), back_inserter(result)); - } return result; } From baf7b14a37fa60eb4d50394b3e5c579389e9336c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:35:43 +0800 Subject: [PATCH 2222/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 44 ++++++++++--------------- 1 file changed, 18 insertions(+), 26 deletions(-) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index aeeb7cec2..6f4994d5b 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -2,9 +2,9 @@ # - Time: O(m + n) # - Space: O(min(m, n)) # elif the given array is already sorted: -# if the memory is unlimited, and (m << n or m >> n) +# if m << n or m >> n: # - Time: O(min(m, n) * log(max(m, n))) -# - Space: O(min(m, n)) +# - Space: O(1) # else: # - Time: O(m + n) # - Soace: O(1) @@ -55,9 +55,9 @@ def intersect(self, nums1, nums2): return res -# If the given array is already sorted, and the memory is unlimited, and (m << n or m >> n). +# If the given array is already sorted, and the memory is limited, and (m << n or m >> n). # Time: O(min(m, n) * log(max(m, n))) -# Space: O(min(m, n)) +# Space: O(1) # Binary search solution. class Solution(object): def intersect(self, nums1, nums2): @@ -69,32 +69,24 @@ def intersect(self, nums1, nums2): if len(nums1) > len(nums2): return self.intersect(nums2, nums1) - def count_of_num(nums, target): - def binary_search(compare, nums, target): - left, right = 0, len(nums) - while left < right: - mid = left + (right - left) / 2 - if compare(nums[mid], target): - right = mid - else: - left = mid + 1 - return left - - left = binary_search(lambda x, y: x >= y, nums, target) - right = binary_search(lambda x, y: x > y, nums, target) - return right - left + def binary_search(compare, nums, left, right, target): + while left < right: + mid = left + (right - left) / 2 + if compare(nums[mid], target): + right = mid + else: + left = mid + 1 + return left nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time. - cnts = collections.defaultdict(int) - for i in nums1: - cnt = count_of_num(nums2, i) - if cnts[i] < cnt: - cnts[i] += 1 - res = [] - for k, v in cnts.iteritems(): - res += [k] * v + left = 0 + for i in nums1: + left = binary_search(lambda x, y: x >= y, nums2, left, len(nums2), i) + if left != len(nums2) and nums2[left] == i: + res += i, + left += 1 return res From c0ba78e41db7bcb209392d51c94678b23ec784f7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 18:37:48 +0800 Subject: [PATCH 2223/4971] Update intersection-of-two-arrays-ii.py --- Python/intersection-of-two-arrays-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index 6f4994d5b..5dcaad0dc 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -8,7 +8,7 @@ # else: # - Time: O(m + n) # - Soace: O(1) -# else: (the memory is limited) +# else: (the given array is not sorted and the memory is limited) # - Time: O(max(m, n) * log(max(m, n))) # - Space: O(1) From 15ebaf11d343a278189ca5a62485e5df370391e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 20:38:01 +0800 Subject: [PATCH 2224/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index af7d18a93..f0455d13c 100644 --- a/README.md +++ b/README.md @@ -287,8 +287,8 @@ 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 | 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | -349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | | Hash -350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | | Hash +349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI | Hash +350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash ## Recursion # | Title | Solution | Time | Space | Difficulty | Tag | Note From 287c71a608f6deca067b030016abce1f53915984 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 May 2016 20:42:02 +0800 Subject: [PATCH 2225/4971] Update intersection-of-two-arrays-ii.cpp --- C++/intersection-of-two-arrays-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/intersection-of-two-arrays-ii.cpp b/C++/intersection-of-two-arrays-ii.cpp index dfa809c7c..c79fd27cc 100644 --- a/C++/intersection-of-two-arrays-ii.cpp +++ b/C++/intersection-of-two-arrays-ii.cpp @@ -100,7 +100,7 @@ class Solution { // If the given array is not sorted, and the memory is limited. // Time: O(max(m, n) * log(max(m, n))) // Space: O(1) -// Two pointer solution. +// Two pointers solution. class Solution { public: vector intersect(vector& nums1, vector& nums2) { From e9ed28f31fc3a82ea9afbc5290775c30d2d743f8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 May 2016 11:42:46 +0800 Subject: [PATCH 2226/4971] Update and rename wordBreak.cpp to word-break.cpp --- C++/word-break.cpp | 27 +++++++++++++++++++++++++++ C++/wordBreak.cpp | 19 ------------------- 2 files changed, 27 insertions(+), 19 deletions(-) create mode 100644 C++/word-break.cpp delete mode 100644 C++/wordBreak.cpp diff --git a/C++/word-break.cpp b/C++/word-break.cpp new file mode 100644 index 000000000..c3305a139 --- /dev/null +++ b/C++/word-break.cpp @@ -0,0 +1,27 @@ +// Time: O(n * l^2), l is the max length of the words. +// Space: O(n) + +class Solution { +public: + bool wordBreak(string s, unordered_set& wordDict) { + const int n = s.length(); + + size_t max_len = 0; + for (const auto& str: wordDict) { + max_len = max(max_len, str.length()); + } + + vector canBreak(n + 1, false); + canBreak[0] = true; + for (int i = 1; i <= n; ++i) { + for (int l = 1; l <= max_len && i - l >= 0; ++l) { + if (canBreak[i - l] && wordDict.count(s.substr(i - l, l))) { + canBreak[i] = true; + break; + } + } + } + + return canBreak[n]; + } +}; diff --git a/C++/wordBreak.cpp b/C++/wordBreak.cpp deleted file mode 100644 index 4b4d6d9be..000000000 --- a/C++/wordBreak.cpp +++ /dev/null @@ -1,19 +0,0 @@ -// Time Complexity: O(n^2) -// Space Complexity: O(n) - -class Solution { - public: - bool wordBreak(string s, unordered_set &dict) { - vector f(s.size() + 1, false); - f[0] = true; // null string - for(int i = 1; i <= s.size(); ++i) { - for(int j = i - 1; j >= 0; --j) { - if(f[j] && dict.find(s.substr(j, i - j)) != dict.end()) { - f[i] = true; - break; - } - } - } - return f[s.size()]; - } -}; From 36fc8706a052d24630ed1e0c09cbaecc09b3e1f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 May 2016 11:44:25 +0800 Subject: [PATCH 2227/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f0455d13c..872da60c7 100644 --- a/README.md +++ b/README.md @@ -424,7 +424,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || +139| [Word Break](https://leetcode.com/problems/word-break/) | [C++](./C++/word-break.cpp) [Python](./Python/word-break.py) | _O(n * l^2)_ | _O(n)_ | Medium || 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 || From 1f117188114475dd8c9708ce3e6495f2c01a8bc0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 May 2016 12:00:41 +0800 Subject: [PATCH 2228/4971] Update word-break.py --- Python/word-break.py | 66 +++++++++++++++----------------------------- 1 file changed, 22 insertions(+), 44 deletions(-) diff --git a/Python/word-break.py b/Python/word-break.py index b1f9ad9ee..e7857f57f 100644 --- a/Python/word-break.py +++ b/Python/word-break.py @@ -1,6 +1,6 @@ -# Time: O(n^2) +# Time: O(n * l^2) # Space: O(n) -# + # Given a string s and a dictionary of words dict, # determine if s can be segmented into a space-separated sequence of one or more dictionary words. # @@ -9,52 +9,30 @@ # dict = ["leet", "code"]. # # Return true because "leetcode" can be segmented as "leet code". -# -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 - +class Solution(object): + def wordBreak(self, s, wordDict): + """ + :type s: str + :type wordDict: Set[str] + :rtype: bool + """ 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 - def wordBreak(self, s, dict): - n = len(s) - possible = [False for _ in xrange(n)] - for i in xrange(n): - if s[:i+1] in dict: - possible[i] = True - for j in xrange(i): - if possible[j] and s[j+1:i+1] in dict: - possible[i] = True + max_len = 0 + for str in wordDict: + max_len = max(max_len, len(str)) + + can_break = [False for _ in xrange(n + 1)] + can_break[0] = True + for i in xrange(1, n + 1): + for l in xrange(1, min(i, max_len) + 1): + if can_break[i-l] and s[i-l:i] in wordDict: + can_break[i] = True break - - return possible[n-1] + + return can_break[-1] + if __name__ == "__main__": print Solution().wordBreak("leetcode", ["leet", "code"]) From 118c04fedfb6eedaa57626af878a0cb74e03ec7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 May 2016 12:54:28 +0800 Subject: [PATCH 2229/4971] Update word-break.py --- Python/word-break.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/word-break.py b/Python/word-break.py index e7857f57f..e64e5631e 100644 --- a/Python/word-break.py +++ b/Python/word-break.py @@ -20,8 +20,8 @@ def wordBreak(self, s, wordDict): n = len(s) max_len = 0 - for str in wordDict: - max_len = max(max_len, len(str)) + for string in wordDict: + max_len = max(max_len, len(string)) can_break = [False for _ in xrange(n + 1)] can_break[0] = True From d855199d7dff8e89b97f774cd9a0885b3ed4f8e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 May 2016 12:56:02 +0800 Subject: [PATCH 2230/4971] Update word-break.py --- Python/word-break.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Python/word-break.py b/Python/word-break.py index e64e5631e..e17d0e413 100644 --- a/Python/word-break.py +++ b/Python/word-break.py @@ -19,9 +19,7 @@ def wordBreak(self, s, wordDict): """ n = len(s) - max_len = 0 - for string in wordDict: - max_len = max(max_len, len(string)) + max_len = max(wordDict, len) can_break = [False for _ in xrange(n + 1)] can_break[0] = True From 710e2450ebafb9f61945de8c799217551985f292 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 May 2016 13:01:01 +0800 Subject: [PATCH 2231/4971] Update word-break.py --- Python/word-break.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Python/word-break.py b/Python/word-break.py index e17d0e413..e64e5631e 100644 --- a/Python/word-break.py +++ b/Python/word-break.py @@ -19,7 +19,9 @@ def wordBreak(self, s, wordDict): """ n = len(s) - max_len = max(wordDict, len) + max_len = 0 + for string in wordDict: + max_len = max(max_len, len(string)) can_break = [False for _ in xrange(n + 1)] can_break[0] = True From 84436aca2f540f55c244642d7e827131e1c22dc4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 May 2016 21:41:12 +0800 Subject: [PATCH 2232/4971] Create android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 65 +++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 C++/android-unlock-patterns.cpp diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp new file mode 100644 index 000000000..3c5e1e57e --- /dev/null +++ b/C++/android-unlock-patterns.cpp @@ -0,0 +1,65 @@ +// Time: O(n!) +// Space: O(n) + +class Solution { +public: + int numberOfPatterns(int m, int n) { + int count = 0; + bool visited[9] = {false}; + // 1, 3, 7, 9 + numberOfPatternsHelper(m, n, 0, 0, 1, visited, &count); + // 2, 4, 6, 8 + numberOfPatternsHelper(m, n, 0, 1, 1, visited, &count); + count *= 4; + // 5 + numberOfPatternsHelper(m, n, 1, 1, 1, visited, &count); + return count; + } + +private: + const vector> directions = { + {1, 0}, {-1, 0}, {0, 1}, {0, -1}, + {1, 1}, {-1, -1}, {1, -1}, {-1, 1}, + {2, 1}, {2, -1}, {-2, -1}, {-2, 1}, + {1, 2}, {-1, 2}, {1, -2}, {-1, -2} + }; + + void numberOfPatternsHelper(int m, int n, int i, int j, int level, + bool visited[], int *count) { + if (level > n) { + return; + } + + if (level >= m) { + ++(*count); + } + + visited[convert(i, j)] = true; + + for (const auto& direction : directions) { + auto x = i + direction[0]; + auto y = j + direction[1]; + if (valid(x, y)) { + if (!visited[convert(x, y)]) { + numberOfPatternsHelper(m, n, x, y, level + 1, visited, count); + } else { + x += direction[0]; + y += direction[1]; + if (valid(x, y) && !visited[convert(x, y)]) { + numberOfPatternsHelper(m, n, x, y, level + 1, visited, count); + } + } + } + } + + visited[convert(i, j)] = false; + } + + int convert(int i, int j) { + return 3 * i + j; + } + + bool valid(int i, int j) { + return i >= 0 && i < 3 && j >= 0 && j < 3; + } +}; From 15903de4aab44c56d465da189c9cb193ab5ea9e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 May 2016 23:30:27 +0800 Subject: [PATCH 2233/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 79 +++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 4 deletions(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 3c5e1e57e..67b6fe7d0 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -1,7 +1,78 @@ -// Time: O(n!) -// Space: O(n) +// Time: O(9 * 2^9) +// Space: O(9 * 2^9) class Solution { +public: + int numberOfPatterns(int m, int n) { + // dp[i][j]: i is the set of the numbers in binary presentation, + // d[i][j] is the number of ways ending with the number j. + vector> dp(1 << 9 , vector(9, 0)); + for (int i = 0; i < 9; ++i) { + dp[merge(0, i)][i] = 1; + } + + vector keys(9, 0); + for (int i = 0; i < dp.size(); ++i) { + const auto count = number_of_key(i); + if (count > n) { + continue; + } + for (int j = 0; j < 9; ++j) { + if (!contain(i, j)) { + continue; + } + keys[count - 1] += dp[i][j]; + + const auto x1 = j / 3; + const auto y1 = j % 3; + for (int k = 0; k < 9; ++k) { + if (contain(i, k)) { + continue; + } + const auto x2 = k / 3; + const auto y2 = k % 3; + if (((x1 == x2 && abs(y1 - y2) == 2) || + (y1 == y2 && abs(x1 - x2) == 2) || + (abs(x1 - x2) == 2 && abs(y1 - y2) == 2)) && + !(contain(i, convert((x1 + x2) / 2, (y1 + y2) / 2)))) { + continue; + } + dp[merge(i, k)][k] += dp[i][j]; + } + } + } + int res = 0; + for (int i = m - 1; i < n; ++i) { + res += keys[i]; + } + return res; + } + +private: + inline int merge(int i, int j) { + return i | (1 << j); + } + + inline int number_of_key(int i) { + int count = 0; + for (; i; i &= i - 1) { + ++count; + } + return count; + } + + inline bool contain(int i, int j) { + return i & (1 << j); + } + + inline int convert(int i, int j) { + return 3 * i + j; + } +}; + +// Time: O(9!) +// Space: O(9) +class Solution2 { public: int numberOfPatterns(int m, int n) { int count = 0; @@ -55,11 +126,11 @@ class Solution { visited[convert(i, j)] = false; } - int convert(int i, int j) { + inline int convert(int i, int j) { return 3 * i + j; } - bool valid(int i, int j) { + inline bool valid(int i, int j) { return i >= 0 && i < 3 && j >= 0 && j < 3; } }; From 1802343a3d6587cf220accab31d05479f4b2f8ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 May 2016 23:32:06 +0800 Subject: [PATCH 2234/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 67b6fe7d0..864e6798c 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -1,6 +1,7 @@ // Time: O(9 * 2^9) // Space: O(9 * 2^9) +// DP solution. class Solution { public: int numberOfPatterns(int m, int n) { @@ -70,8 +71,10 @@ class Solution { } }; + // Time: O(9!) // Space: O(9) +// Backtracking solution. class Solution2 { public: int numberOfPatterns(int m, int n) { From e2de929d64f4e0fd43cffcf253ac7069ed88318e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 May 2016 23:50:28 +0800 Subject: [PATCH 2235/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 864e6798c..9bebca8fd 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -14,15 +14,15 @@ class Solution { vector keys(9, 0); for (int i = 0; i < dp.size(); ++i) { - const auto count = number_of_key(i); - if (count > n) { + const auto number = number_of_key(i); + if (number > n) { continue; } for (int j = 0; j < 9; ++j) { if (!contain(i, j)) { continue; } - keys[count - 1] += dp[i][j]; + keys[number - 1] += dp[i][j]; const auto x1 = j / 3; const auto y1 = j % 3; @@ -55,11 +55,11 @@ class Solution { } inline int number_of_key(int i) { - int count = 0; + int number = 0; for (; i; i &= i - 1) { - ++count; + ++number; } - return count; + return number; } inline bool contain(int i, int j) { @@ -78,16 +78,16 @@ class Solution { class Solution2 { public: int numberOfPatterns(int m, int n) { - int count = 0; + int number = 0; bool visited[9] = {false}; // 1, 3, 7, 9 - numberOfPatternsHelper(m, n, 0, 0, 1, visited, &count); + numberOfPatternsHelper(m, n, 0, 0, 1, visited, &number); // 2, 4, 6, 8 - numberOfPatternsHelper(m, n, 0, 1, 1, visited, &count); - count *= 4; + numberOfPatternsHelper(m, n, 0, 1, 1, visited, &number); + number *= 4; // 5 - numberOfPatternsHelper(m, n, 1, 1, 1, visited, &count); - return count; + numberOfPatternsHelper(m, n, 1, 1, 1, visited, &number); + return number; } private: @@ -99,13 +99,13 @@ class Solution2 { }; void numberOfPatternsHelper(int m, int n, int i, int j, int level, - bool visited[], int *count) { + bool visited[], int *number) { if (level > n) { return; } if (level >= m) { - ++(*count); + ++(*number); } visited[convert(i, j)] = true; @@ -115,12 +115,12 @@ class Solution2 { auto y = j + direction[1]; if (valid(x, y)) { if (!visited[convert(x, y)]) { - numberOfPatternsHelper(m, n, x, y, level + 1, visited, count); + numberOfPatternsHelper(m, n, x, y, level + 1, visited, number); } else { x += direction[0]; y += direction[1]; if (valid(x, y) && !visited[convert(x, y)]) { - numberOfPatternsHelper(m, n, x, y, level + 1, visited, count); + numberOfPatternsHelper(m, n, x, y, level + 1, visited, number); } } } From 2d63a3684400434c7baec1f5c8e7f783e5e001b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 May 2016 23:54:46 +0800 Subject: [PATCH 2236/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 9bebca8fd..707c6c22f 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -13,32 +13,32 @@ class Solution { } vector keys(9, 0); - for (int i = 0; i < dp.size(); ++i) { - const auto number = number_of_key(i); + for (int used = 0; used < dp.size(); ++used) { + const auto number = number_of_key(used); if (number > n) { continue; } - for (int j = 0; j < 9; ++j) { - if (!contain(i, j)) { + for (int i = 0; i < 9; ++i) { + if (!contain(used, i)) { continue; } - keys[number - 1] += dp[i][j]; + keys[number - 1] += dp[used][i]; - const auto x1 = j / 3; - const auto y1 = j % 3; - for (int k = 0; k < 9; ++k) { - if (contain(i, k)) { + const auto x1 = i / 3; + const auto y1 = i % 3; + for (int j = 0; j < 9; ++j) { + if (contain(used, j)) { continue; } - const auto x2 = k / 3; - const auto y2 = k % 3; + const auto x2 = j / 3; + const auto y2 = j % 3; if (((x1 == x2 && abs(y1 - y2) == 2) || (y1 == y2 && abs(x1 - x2) == 2) || (abs(x1 - x2) == 2 && abs(y1 - y2) == 2)) && - !(contain(i, convert((x1 + x2) / 2, (y1 + y2) / 2)))) { + !(contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)))) { continue; } - dp[merge(i, k)][k] += dp[i][j]; + dp[merge(used, j)][j] += dp[used][i]; } } } From c3f08d32222d344e64a728b6df2ec6560654f3c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:08:16 +0800 Subject: [PATCH 2237/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 70 +++++++++++++++------------------ 1 file changed, 31 insertions(+), 39 deletions(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 707c6c22f..e8c03d000 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -79,61 +79,53 @@ class Solution2 { public: int numberOfPatterns(int m, int n) { int number = 0; - bool visited[9] = {false}; - // 1, 3, 7, 9 - numberOfPatternsHelper(m, n, 0, 0, 1, visited, &number); + // 1, 3, 5, 7 + number += 4 * numberOfPatternsHelper(m, n, 1, merge(0, 0), 0); // 2, 4, 6, 8 - numberOfPatternsHelper(m, n, 0, 1, 1, visited, &number); - number *= 4; + number += 4 * numberOfPatternsHelper(m, n, 1, merge(0, 1), 1); // 5 - numberOfPatternsHelper(m, n, 1, 1, 1, visited, &number); + number += numberOfPatternsHelper(m, n, 1, merge(0, 4), 4); return number; } - private: - const vector> directions = { - {1, 0}, {-1, 0}, {0, 1}, {0, -1}, - {1, 1}, {-1, -1}, {1, -1}, {-1, 1}, - {2, 1}, {2, -1}, {-2, -1}, {-2, 1}, - {1, 2}, {-1, 2}, {1, -2}, {-1, -2} - }; - - void numberOfPatternsHelper(int m, int n, int i, int j, int level, - bool visited[], int *number) { + int numberOfPatternsHelper(int m, int n, int level, int used, int i) { + int number = 0; if (level > n) { - return; + return number; } - if (level >= m) { - ++(*number); + ++number; } - visited[convert(i, j)] = true; - - for (const auto& direction : directions) { - auto x = i + direction[0]; - auto y = j + direction[1]; - if (valid(x, y)) { - if (!visited[convert(x, y)]) { - numberOfPatternsHelper(m, n, x, y, level + 1, visited, number); - } else { - x += direction[0]; - y += direction[1]; - if (valid(x, y) && !visited[convert(x, y)]) { - numberOfPatternsHelper(m, n, x, y, level + 1, visited, number); - } - } + const auto x1 = i / 3; + const auto y1 = i % 3; + for (int j = 0; j < 9; ++j) { + if (contain(used, j)) { + continue; } + const auto x2 = j / 3; + const auto y2 = j % 3; + if (((x1 == x2 && abs(y1 - y2) == 2) || + (y1 == y2 && abs(x1 - x2) == 2) || + (abs(x1 - x2) == 2 && abs(y1 - y2) == 2)) && + !(contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)))) { + continue; + } + number += numberOfPatternsHelper(m, n, level + 1, merge(used, j), j); } + return number; + } - visited[convert(i, j)] = false; +private: + inline int merge(int i, int j) { + return i | (1 << j); } - inline int convert(int i, int j) { - return 3 * i + j; + inline bool contain(int i, int j) { + return i & (1 << j); } - inline bool valid(int i, int j) { - return i >= 0 && i < 3 && j >= 0 && j < 3; + inline int convert(int i, int j) { + return 3 * i + j; } }; From 537058c4d0e1479e1a23a81f6713abc575f3eaa7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:10:25 +0800 Subject: [PATCH 2238/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index e8c03d000..8c33ae8d9 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -42,10 +42,12 @@ class Solution { } } } + int res = 0; for (int i = m - 1; i < n; ++i) { res += keys[i]; } + return res; } @@ -113,6 +115,7 @@ class Solution2 { } number += numberOfPatternsHelper(m, n, level + 1, merge(used, j), j); } + return number; } From a31428c8dd2b82a97fdcd75e364c663e6deb26d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:10:52 +0800 Subject: [PATCH 2239/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 8c33ae8d9..49faf7dc9 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -47,7 +47,6 @@ class Solution { for (int i = m - 1; i < n; ++i) { res += keys[i]; } - return res; } From 9b7672b8f1237bcccd8e372dea2b94fa1d369488 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:11:56 +0800 Subject: [PATCH 2240/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 49faf7dc9..3fd9972a1 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -88,6 +88,7 @@ class Solution2 { number += numberOfPatternsHelper(m, n, 1, merge(0, 4), 4); return number; } + private: int numberOfPatternsHelper(int m, int n, int level, int used, int i) { int number = 0; From c7570ba3ea385a9f52c0a4675cbff0e1a0f3465b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:20:15 +0800 Subject: [PATCH 2241/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 3fd9972a1..47228f7b8 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -35,7 +35,7 @@ class Solution { if (((x1 == x2 && abs(y1 - y2) == 2) || (y1 == y2 && abs(x1 - x2) == 2) || (abs(x1 - x2) == 2 && abs(y1 - y2) == 2)) && - !(contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)))) { + !contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2))) { continue; } dp[merge(used, j)][j] += dp[used][i]; @@ -110,7 +110,7 @@ class Solution2 { if (((x1 == x2 && abs(y1 - y2) == 2) || (y1 == y2 && abs(x1 - x2) == 2) || (abs(x1 - x2) == 2 && abs(y1 - y2) == 2)) && - !(contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)))) { + !contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2))) { continue; } number += numberOfPatternsHelper(m, n, level + 1, merge(used, j), j); From 4cf096a771cbf7a0c6486d37903f09ff71ee5db0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:27:34 +0800 Subject: [PATCH 2242/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 47228f7b8..c55f410bd 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -14,7 +14,7 @@ class Solution { vector keys(9, 0); for (int used = 0; used < dp.size(); ++used) { - const auto number = number_of_key(used); + const auto number = number_of_keys(used); if (number > n) { continue; } @@ -55,7 +55,7 @@ class Solution { return i | (1 << j); } - inline int number_of_key(int i) { + inline int number_of_keys(int i) { int number = 0; for (; i; i &= i - 1) { ++number; From 792d3dfcb956c50e606d36bad1f8475b0cc0b73a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:34:09 +0800 Subject: [PATCH 2243/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index c55f410bd..daa5e4361 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -12,7 +12,7 @@ class Solution { dp[merge(0, i)][i] = 1; } - vector keys(9, 0); + int res = 0; for (int used = 0; used < dp.size(); ++used) { const auto number = number_of_keys(used); if (number > n) { @@ -22,7 +22,9 @@ class Solution { if (!contain(used, i)) { continue; } - keys[number - 1] += dp[used][i]; + if (m <= number && number <= n) { + res += dp[used][i]; + } const auto x1 = i / 3; const auto y1 = i % 3; @@ -43,10 +45,6 @@ class Solution { } } - int res = 0; - for (int i = m - 1; i < n; ++i) { - res += keys[i]; - } return res; } From 59ba5196ffb0a9040227ea7be1303ff31a00232e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:35:50 +0800 Subject: [PATCH 2244/4971] Create android-unlock-patterns.py --- Python/android-unlock-patterns.py | 113 ++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 Python/android-unlock-patterns.py diff --git a/Python/android-unlock-patterns.py b/Python/android-unlock-patterns.py new file mode 100644 index 000000000..030efd8a4 --- /dev/null +++ b/Python/android-unlock-patterns.py @@ -0,0 +1,113 @@ +# Time: O(9 * 2^9) +# Space: O(9 * 2^9) + +class Solution(object): + def numberOfPatterns(self, m, n): + """ + :type m: int + :type n: int + :rtype: int + """ + def merge(used, i): + return used | (1 << i) + + def number_of_keys(i): + number = 0 + while i > 0: + i &= i - 1 + number += 1 + return number + + def contain(used, i): + return bool(used & (1 << i)) + + def convert(i, j): + return 3 * i + j + + # dp[i][j]: i is the set of the numbers in binary presentation, + # d[i][j] is the number of ways ending with the number j. + dp = [[0] * 9 for _ in xrange(1 << 9)] + for i in xrange(9): + dp[merge(0, i)][i] = 1 + + res = 0 + for used in xrange(len(dp)): + number = number_of_keys(used) + if number > n: + continue + + for i in xrange(9): + if not contain(used, i): + continue + + if m <= number <= n: + res += dp[used][i] + + x1, y1 = i / 3, i % 3 + for j in xrange(9): + if contain(used, j): + continue + + x2, y2 = j / 3, j % 3 + if ((x1 == x2 and abs(y1 - y2) == 2) or \ + (y1 == y2 and abs(x1 - x2) == 2) or \ + (abs(x1 - x2) == 2 and abs(y1 - y2) == 2)) and \ + not contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)): + continue + + dp[merge(used, j)][j] += dp[used][i] + + return res + + +# Time: O(9!) +# Space: O(9) +# Backtracking solution. (TLE) +class Solution_TLE(object): + def numberOfPatterns(self, m, n): + """ + :type m: int + :type n: int + :rtype: int + """ + def merge(used, i): + return used | (1 << i) + + def contain(used, i): + return bool(used & (1 << i)) + + def convert(i, j): + return 3 * i + j + + def numberOfPatternsHelper(m, n, level, used, i): + number = 0 + if level > n: + return number + + if m <= level <= n: + number += 1 + + x1, y1 = i / 3, i % 3; + for j in xrange(9): + if contain(used, j): + continue + + x2, y2 = j / 3, j % 3; + if ((x1 == x2 and abs(y1 - y2) == 2) or \ + (y1 == y2 and abs(x1 - x2) == 2) or \ + (abs(x1 - x2) == 2 and abs(y1 - y2) == 2)) and \ + not contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)): + continue; + number += numberOfPatternsHelper(m, n, level + 1, merge(used, j), j); + + return number + + + number = 0 + # 1, 3, 7, 9 + number += 4 * numberOfPatternsHelper(m, n, 1, merge(0, 0), 0) + # 2, 4, 6, 8 + number += 4 * numberOfPatternsHelper(m, n, 1, merge(0, 1), 1) + # 5 + number += numberOfPatternsHelper(m, n, 1, merge(0, 4), 4) + return number From 57849e775cddad7acc76c80c99afbb51109745f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:38:11 +0800 Subject: [PATCH 2245/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 872da60c7..bfec89e91 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-350%20%2F%20350-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-351%20%2F%20351-ff69b4.svg) -Up to date (2016-05-21), there are `333` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-05-23), there are `334` 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 `350` questions. +Here is the classification of all `351` 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. ) @@ -440,6 +440,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 || +351| [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) | [C++](./C++/android-unlock-patterns.cpp) [Python](./Python/android-unlock-patterns.py) | _O(9 * 2^9)_ | _O(9 * 2^9)_ | Medium | 📖 | Backtracking | ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From bb9c231bbab8742bfaa828ddedbfa191f726eee8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:39:39 +0800 Subject: [PATCH 2246/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index daa5e4361..6fe103300 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -5,7 +5,7 @@ class Solution { public: int numberOfPatterns(int m, int n) { - // dp[i][j]: i is the set of the numbers in binary presentation, + // dp[i][j]: i is the set of the numbers in binary representation, // d[i][j] is the number of ways ending with the number j. vector> dp(1 << 9 , vector(9, 0)); for (int i = 0; i < 9; ++i) { From 320268ab8e04608197a0ea63d9e3c0a694b88c3d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:40:09 +0800 Subject: [PATCH 2247/4971] Update android-unlock-patterns.py --- Python/android-unlock-patterns.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/android-unlock-patterns.py b/Python/android-unlock-patterns.py index 030efd8a4..8921cdda8 100644 --- a/Python/android-unlock-patterns.py +++ b/Python/android-unlock-patterns.py @@ -24,8 +24,8 @@ def contain(used, i): def convert(i, j): return 3 * i + j - # dp[i][j]: i is the set of the numbers in binary presentation, - # d[i][j] is the number of ways ending with the number j. + # dp[i][j]: i is the set of the numbers in binary representation, + # d[i][j] is the number of ways ending with the number j. dp = [[0] * 9 for _ in xrange(1 << 9)] for i in xrange(9): dp[merge(0, i)][i] = 1 From f3eea37ee27f9e44ca0da01b1d4407644c599d7d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:42:52 +0800 Subject: [PATCH 2248/4971] Update android-unlock-patterns.py --- Python/android-unlock-patterns.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/android-unlock-patterns.py b/Python/android-unlock-patterns.py index 8921cdda8..369f96753 100644 --- a/Python/android-unlock-patterns.py +++ b/Python/android-unlock-patterns.py @@ -25,7 +25,7 @@ def convert(i, j): return 3 * i + j # dp[i][j]: i is the set of the numbers in binary representation, - # d[i][j] is the number of ways ending with the number j. + # dp[i][j] is the number of ways ending with the number j. dp = [[0] * 9 for _ in xrange(1 << 9)] for i in xrange(9): dp[merge(0, i)][i] = 1 From 85d704c5a4ecc1d35a487ee9ee22f1effadbf12b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 00:43:13 +0800 Subject: [PATCH 2249/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 6fe103300..a77a8d91e 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -6,7 +6,7 @@ class Solution { public: int numberOfPatterns(int m, int n) { // dp[i][j]: i is the set of the numbers in binary representation, - // d[i][j] is the number of ways ending with the number j. + // dp[i][j] is the number of ways ending with the number j. vector> dp(1 << 9 , vector(9, 0)); for (int i = 0; i < 9; ++i) { dp[merge(0, i)][i] = 1; From ce684485879d9a2d706fcb6fa27df3bc5406744e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 01:18:33 +0800 Subject: [PATCH 2250/4971] Update android-unlock-patterns.py --- Python/android-unlock-patterns.py | 66 +++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/Python/android-unlock-patterns.py b/Python/android-unlock-patterns.py index 369f96753..38e4e4680 100644 --- a/Python/android-unlock-patterns.py +++ b/Python/android-unlock-patterns.py @@ -1,6 +1,7 @@ # Time: O(9 * 2^9) # Space: O(9 * 2^9) +# DP solution. class Solution(object): def numberOfPatterns(self, m, n): """ @@ -60,6 +61,71 @@ def convert(i, j): return res +# Time: O(9 * 2^9) +# Space: O(9 * 2^9) +# DP solution. +class Solution2(object): + def numberOfPatterns(self, m, n): + """ + :type m: int + :type n: int + :rtype: int + """ + def merge(used, i): + return used | (1 << i) + + def number_of_keys(i): + number = 0 + while i > 0: + i &= i - 1 + number += 1 + return number + + def exclude(used, i): + return used & ~(1 << i) + + def contain(used, i): + return bool(used & (1 << i)) + + def convert(i, j): + return 3 * i + j + + # dp[i][j]: i is the set of the numbers in binary representation, + # d[i][j] is the number of ways ending with the number j. + dp = [[0] * 9 for _ in xrange(1 << 9)] + for i in xrange(9): + dp[merge(0, i)][i] = 1 + + res = 0 + for used in xrange(len(dp)): + number = number_of_keys(used) + if number > n: + continue + + for i in xrange(9): + if not contain(used, i): + continue + + x1, y1 = i / 3, i % 3 + for j in xrange(9): + if i == j or not contain(used, j): + continue + + x2, y2 = j / 3, j % 3 + if ((x1 == x2 and abs(y1 - y2) == 2) or \ + (y1 == y2 and abs(x1 - x2) == 2) or \ + (abs(x1 - x2) == 2 and abs(y1 - y2) == 2)) and \ + not contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)): + continue + + dp[used][i] += dp[exclude(used, i)][j] + + if m <= number <= n: + res += dp[used][i] + + return res + + # Time: O(9!) # Space: O(9) # Backtracking solution. (TLE) From af0ce1d763346f07b6af061951dd14c8636b3977 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 01:21:16 +0800 Subject: [PATCH 2251/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 78 ++++++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index a77a8d91e..7dc8b13dd 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -71,10 +71,86 @@ class Solution { }; +// Time: O(9 * 2^9) +// Space: O(9 * 2^9) +// DP solution. +class Solution2 { +public: + int numberOfPatterns(int m, int n) { + // dp[i][j]: i is the set of the numbers in binary representation, + // dp[i][j] is the number of ways ending with the number j. + vector> dp(1 << 9 , vector(9, 0)); + for (int i = 0; i < 9; ++i) { + dp[merge(0, i)][i] = 1; + } + + int res = 0; + for (int used = 0; used < dp.size(); ++used) { + const auto number = number_of_keys(used); + if (number > n) { + continue; + } + for (int i = 0; i < 9; ++i) { + if (!contain(used, i)) { + continue; + } + + const auto x1 = i / 3; + const auto y1 = i % 3; + for (int j = 0; j < 9; ++j) { + if (!contain(used, j)) { + continue; + } + const auto x2 = j / 3; + const auto y2 = j % 3; + if (((x1 == x2 && abs(y1 - y2) == 2) || + (y1 == y2 && abs(x1 - x2) == 2) || + (abs(x1 - x2) == 2 && abs(y1 - y2) == 2)) && + !contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2))) { + continue; + } + dp[used][i] += dp[exclude(used, i)][j]; + } + if (m <= number && number <= n) { + res += dp[used][i]; + } + } + } + + return res; + } + +private: + inline int merge(int i, int j) { + return i | (1 << j); + } + + inline int number_of_keys(int i) { + int number = 0; + for (; i; i &= i - 1) { + ++number; + } + return number; + } + + inline bool contain(int i, int j) { + return i & (1 << j); + } + + inline int exclude(int i, int j) { + return i & ~(1 << j); + } + + inline int convert(int i, int j) { + return 3 * i + j; + } +}; + + // Time: O(9!) // Space: O(9) // Backtracking solution. -class Solution2 { +class Solution3 { public: int numberOfPatterns(int m, int n) { int number = 0; From 7880753decbc82ba13ab1d89ffc69296c2db7647 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 01:22:34 +0800 Subject: [PATCH 2252/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 7dc8b13dd..5434f52e9 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -98,7 +98,7 @@ class Solution2 { const auto x1 = i / 3; const auto y1 = i % 3; for (int j = 0; j < 9; ++j) { - if (!contain(used, j)) { + if (i == j or !contain(used, j)) { continue; } const auto x2 = j / 3; From c20935641f75d4d2c8eddd09211d9d9bb2fa8803 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 01:27:00 +0800 Subject: [PATCH 2253/4971] Update android-unlock-patterns.py --- Python/android-unlock-patterns.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Python/android-unlock-patterns.py b/Python/android-unlock-patterns.py index 38e4e4680..f943d3846 100644 --- a/Python/android-unlock-patterns.py +++ b/Python/android-unlock-patterns.py @@ -153,18 +153,19 @@ def numberOfPatternsHelper(m, n, level, used, i): if m <= level <= n: number += 1 - x1, y1 = i / 3, i % 3; + x1, y1 = i / 3, i % 3 for j in xrange(9): if contain(used, j): continue - x2, y2 = j / 3, j % 3; + x2, y2 = j / 3, j % 3 if ((x1 == x2 and abs(y1 - y2) == 2) or \ (y1 == y2 and abs(x1 - x2) == 2) or \ (abs(x1 - x2) == 2 and abs(y1 - y2) == 2)) and \ not contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)): - continue; - number += numberOfPatternsHelper(m, n, level + 1, merge(used, j), j); + continue + + number += numberOfPatternsHelper(m, n, level + 1, merge(used, j), j) return number From c3ca05e33bef021bcdc9ac8c1583f94b95d91275 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 01:36:21 +0800 Subject: [PATCH 2254/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bfec89e91..9c5b504b9 100644 --- a/README.md +++ b/README.md @@ -440,7 +440,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 || -351| [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) | [C++](./C++/android-unlock-patterns.cpp) [Python](./Python/android-unlock-patterns.py) | _O(9 * 2^9)_ | _O(9 * 2^9)_ | Medium | 📖 | Backtracking | +351| [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) | [C++](./C++/android-unlock-patterns.cpp) [Python](./Python/android-unlock-patterns.py) | _O(9^2 * 2^9)_ | _O(9 * 2^9)_ | Medium | 📖 | Backtracking | ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 458d10b227e379c3696a908c7c4f8f5dfb740700 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 01:36:46 +0800 Subject: [PATCH 2255/4971] Update android-unlock-patterns.py --- Python/android-unlock-patterns.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/android-unlock-patterns.py b/Python/android-unlock-patterns.py index f943d3846..baed693d8 100644 --- a/Python/android-unlock-patterns.py +++ b/Python/android-unlock-patterns.py @@ -1,4 +1,4 @@ -# Time: O(9 * 2^9) +# Time: O(9^2 * 2^9) # Space: O(9 * 2^9) # DP solution. @@ -61,7 +61,7 @@ def convert(i, j): return res -# Time: O(9 * 2^9) +# Time: O(9^2 * 2^9) # Space: O(9 * 2^9) # DP solution. class Solution2(object): From df3172c719b89c54a19aae1fe720781043e914ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 May 2016 01:37:30 +0800 Subject: [PATCH 2256/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 5434f52e9..6d8de94ac 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -1,4 +1,4 @@ -// Time: O(9 * 2^9) +// Time: O(9^2 * 2^9) // Space: O(9 * 2^9) // DP solution. @@ -71,7 +71,7 @@ class Solution { }; -// Time: O(9 * 2^9) +// Time: O(9^2 * 2^9) // Space: O(9 * 2^9) // DP solution. class Solution2 { From 3255716b3d8e4cf12434905f9e9a3073ea050cf4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 27 May 2016 21:41:58 +0800 Subject: [PATCH 2257/4971] Update candy.cpp --- C++/candy.cpp | 35 ++++++++++++++--------------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/C++/candy.cpp b/C++/candy.cpp index e1f297fc1..40680ca0e 100644 --- a/C++/candy.cpp +++ b/C++/candy.cpp @@ -1,28 +1,21 @@ -// Time Complexity: O(n) -// Space Complexity: O(n) +// Time: O(n) +// Space: O(n) class Solution { - public: - int candy(vector &ratings) { - const int n = ratings.size(); - vector increment(n, 0); - - // left to right - for(int i = 1, inc = 0; i < n; ++i) { - if(ratings[i] > ratings[i - 1]) - increment[i] = max(++inc, increment[i]); - else - inc = 0; +public: + int candy(vector& ratings) { + vector candies(ratings.size(), 1); + for (int i = 1; i < ratings.size(); ++i) { + if (ratings[i] > ratings[i - 1]) { + candies[i] = candies[i - 1] + 1; } + } - // right to left - for(int i = n - 2, inc = 0; i >= 0; --i) { - if(ratings[i] > ratings[i + 1]) - increment[i] = max(++inc, increment[i]); - else - inc = 0; + for (int i = ratings.size() - 2; i >= 0; --i) { + if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) { + candies[i] = candies[i + 1] + 1; } - - return accumulate(increment.begin(), increment.end(), n); } + return accumulate(candies.cbegin(), candies.cend(), 0); + } }; From b184988cb430cb870155e47ba52a8ec994b8a3a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 May 2016 08:11:40 +0800 Subject: [PATCH 2258/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c5b504b9..4894ca7dd 100644 --- a/README.md +++ b/README.md @@ -453,7 +453,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || +135| [Candy](https://leetcode.com/problems/candy/)| [C++](./C++/candy.cpp) [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 || From a354c862520ae99a3dc7e1621475b8a8422b3e2b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 May 2016 08:12:06 +0800 Subject: [PATCH 2259/4971] Update candy.cpp --- C++/candy.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/candy.cpp b/C++/candy.cpp index 40680ca0e..fb0cc4180 100644 --- a/C++/candy.cpp +++ b/C++/candy.cpp @@ -10,7 +10,6 @@ class Solution { candies[i] = candies[i - 1] + 1; } } - for (int i = ratings.size() - 2; i >= 0; --i) { if (ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) { candies[i] = candies[i + 1] + 1; From 905d09708a612ce507f0e28a431168aa6a4221a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 May 2016 21:26:55 +0800 Subject: [PATCH 2260/4971] Update median-of-two-sorted-arrays.cpp --- C++/median-of-two-sorted-arrays.cpp | 56 +++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/C++/median-of-two-sorted-arrays.cpp b/C++/median-of-two-sorted-arrays.cpp index 9bbd45091..88ca89bf3 100644 --- a/C++/median-of-two-sorted-arrays.cpp +++ b/C++/median-of-two-sorted-arrays.cpp @@ -42,3 +42,59 @@ class Solution { return max(Ai_minus_1, Bj); } }; + +// Time: O(log(max(m, n)) * log(max_val - min_val)) +// Space: O(1) +// Generic solution. +class Solution_Generic { +public: + double findMedianSortedArrays(vector& nums1, vector& nums2) { + vector *> arrays{&nums1, &nums2}; + if ((nums1.size() + nums2.size()) % 2 == 1) { + return findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2 + 1); + } else { + return (findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2) + + findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0; + } + } + +private: + int findKthInSortedArrays(const vector *>& arrays, int k) { + int left = numeric_limits::max(); + int right = numeric_limits::min(); + for (const auto array : arrays) { + if (!array->empty()) { + left = min(left, array->front()); + right = max(right, array->back()); + } + } + // left xxxxxxxooooooo right, find first xo or oo + while (left + 1 < right) { + const auto mid = left + (right - left) / 2; + if (match(arrays, mid, k)) { + right = mid; + } else { + left = mid; + } + } + // case: xoo + // ^^ + if (match(arrays, left, k)) { + return left; + } + // case: xo + // ^^ + return right; + } + + bool match(const vector *>& arrays, int target, int k) { + int res = 0; + for (const auto array : arrays) { + if (!array->empty()) { + res += distance(upper_bound(array->cbegin(), array->cend(), target), + array->cend()); + } + } + return res < k; + } +}; From cd1903334eda56792b3068ded6eae17753a2844e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 May 2016 22:08:49 +0800 Subject: [PATCH 2261/4971] Update median-of-two-sorted-arrays.py --- Python/median-of-two-sorted-arrays.py | 46 ++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 86c8e3ac0..657aa2088 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -37,7 +37,51 @@ def getKth(self, A, B, k): return max(Ai_minus_1, Bj) - + +# Time: O(log(max(m, n)) * log(max_val - min_val)) +# Space: O(1) +# Generic solution. +class Solution_Generic(object): + def findMedianSortedArrays(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: float + """ + len1, len2 = len(nums1), len(nums2) + if (len1 + len2) % 2 == 1: + return self.getKth([nums1, nums2], (len1 + len2)/2 + 1) + else: + return (self.getKth([nums1, nums2], (len1 + len2)/2) + \ + self.getKth([nums1, nums2], (len1 + len2)/2 + 1)) * 0.5 + + def getKth(self, arrays, k): + def binary_search(array, left, right, target, compare): + while left <= right: + mid = left + (right - left) / 2 + if compare(array, mid, target): + right = mid - 1 + else: + left = mid + 1 + return left + + def match(arrays, target, k): + res = 0 + for array in arrays: + if array: + res += len(array) - binary_search(array, 0, len(array) - 1, target, \ + lambda array, x, y: array[x] > y) + return res < k + + left, right = float("inf"), float("-inf") + for array in arrays: + if array: + left = min(left, array[0]) + right = max(right, array[-1]) + + return binary_search(arrays, left, right, k, match) + + if __name__ == "__main__": print Solution().findMedianSortedArrays([1, 3, 5, 7], [2, 4, 6]) print Solution().findMedianSortedArrays([1, 3, 5], [2, 4, 6]) From d7bbdabff77d93aaa2620c9d685378bdfde94b45 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 May 2016 22:17:12 +0800 Subject: [PATCH 2262/4971] 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 657aa2088..14ce80108 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -65,13 +65,13 @@ def binary_search(array, left, right, target, compare): left = mid + 1 return left - def match(arrays, target, k): + def match(arrays, num, target): res = 0 for array in arrays: if array: - res += len(array) - binary_search(array, 0, len(array) - 1, target, \ + res += len(array) - binary_search(array, 0, len(array) - 1, num, \ lambda array, x, y: array[x] > y) - return res < k + return res < target left, right = float("inf"), float("-inf") for array in arrays: From 6b6e331a99caabc079ad0369986251fd67733e22 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 May 2016 22:18:40 +0800 Subject: [PATCH 2263/4971] Update median-of-two-sorted-arrays.cpp --- C++/median-of-two-sorted-arrays.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/median-of-two-sorted-arrays.cpp b/C++/median-of-two-sorted-arrays.cpp index 88ca89bf3..fd47192ae 100644 --- a/C++/median-of-two-sorted-arrays.cpp +++ b/C++/median-of-two-sorted-arrays.cpp @@ -87,14 +87,14 @@ class Solution_Generic { return right; } - bool match(const vector *>& arrays, int target, int k) { + bool match(const vector *>& arrays, int num, int target) { int res = 0; for (const auto array : arrays) { if (!array->empty()) { - res += distance(upper_bound(array->cbegin(), array->cend(), target), + res += distance(upper_bound(array->cbegin(), array->cend(), num), array->cend()); } } - return res < k; + return res < target; } }; From 4406cef9bc9beb1eec42b020dce237c69e00ac7a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 31 May 2016 20:39:08 +0800 Subject: [PATCH 2264/4971] Update merge-intervals.py --- Python/merge-intervals.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Python/merge-intervals.py b/Python/merge-intervals.py index f62b3f0a1..c79765b13 100644 --- a/Python/merge-intervals.py +++ b/Python/merge-intervals.py @@ -17,15 +17,18 @@ def __init__(self, s=0, e=0): def __repr__(self): return "[{}, {}]".format(self.start, self.end) -class Solution: - # @param intervals, a list of Interval - # @return a list of Interval + +class Solution(object): def merge(self, intervals): + """ + :type intervals: List[Interval] + :rtype: List[Interval] + """ 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) @@ -33,5 +36,6 @@ def merge(self, intervals): result.append(current) return result + if __name__ == "__main__": print Solution().merge([Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15,18)]) From 60f0772dc099e19a3555162210a109ae10ca1848 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 31 May 2016 20:39:49 +0800 Subject: [PATCH 2265/4971] 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 c79765b13..953798275 100644 --- a/Python/merge-intervals.py +++ b/Python/merge-intervals.py @@ -26,7 +26,7 @@ def merge(self, intervals): """ if not intervals: return intervals - intervals.sort(key = lambda x: x.start) + intervals.sort(key=lambda x: x.start) result = [intervals[0]] for i in xrange(1, len(intervals)): prev, current = result[-1], intervals[i] From 7e0d4069915c71b6e4d8b7c55238f59c1c29cbe9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 31 May 2016 22:25:50 +0800 Subject: [PATCH 2266/4971] Create data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 54 +++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 C++/data-stream-as-disjoint-intervals.cpp diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp new file mode 100644 index 000000000..9a2a3c9b4 --- /dev/null +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -0,0 +1,54 @@ +// Time: addNum: O(logn), getIntervals: O(n) +// 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 SummaryRanges { +public: + /** Initialize your data structure here. */ + SummaryRanges() { + + } + + void addNum(int val) { + nums_.emplace(val); + } + + vector getIntervals() { + vector result; + if (nums_.empty()) { + return result; + } + auto start = *nums_.begin(), end = *nums_.begin(); + for (auto it = next(nums_.begin()); it != nums_.end(); ++it) { + if (it != nums_.end() && *it == end + 1) { + end = *it; + } else { + result.emplace_back(start, end); + if (it != nums_.end()) { + start = end = *it; + } + } + } + result.emplace_back(start, end); + return result; + } + +private: + set nums_; +}; + +/** + * Your SummaryRanges object will be instantiated and called as such: + * SummaryRanges obj = new SummaryRanges(); + * obj.addNum(val); + * vector param_2 = obj.getIntervals(); + */ + From 5ec615fb74133e61555032e0d6bd740f5b79b7fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 31 May 2016 22:56:05 +0800 Subject: [PATCH 2267/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 48 ++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index 9a2a3c9b4..408c7584d 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -1,4 +1,4 @@ -// Time: addNum: O(logn), getIntervals: O(n) +// Time: addNum: O(n), getIntervals: O(n), i is the number of disjoint intervals. // Space: O(n) /** @@ -17,6 +17,52 @@ class SummaryRanges { } + void addNum(int val) { + Interval newInterval(val, val); + size_t i = 0; + vector result; + // Insert intervals appeared before newInterval. + while (i < intervals_.size() && intervals_[i].end + 1 < newInterval.start) { + result.emplace_back(intervals_[i++]); + } + + // Merge intervals that overlap with newInterval. + while (i < intervals_.size() && newInterval.end + 1 >= intervals_[i].start) { + newInterval = {min(newInterval.start, intervals_[i].start), + max(newInterval.end, intervals_[i].end)}; + ++i; + } + result.emplace_back(newInterval); + + // Insert intervals appearing after newInterval. + result.insert(result.end(), intervals_.cbegin() + i, intervals_.cend()); + swap(result, intervals_); + } + + vector getIntervals() { + return intervals_; + } + +private: + vector intervals_; +}; + +/** + * Your SummaryRanges object will be instantiated and called as such: + * SummaryRanges obj = new SummaryRanges(); + * obj.addNum(val); + * vector param_2 = obj.getIntervals(); + */ + +// Time: addNum: O(logs), getIntervals: O(s), s is the data stream's size. +// Space: O(s) +class SummaryRanges2 { +public: + /** Initialize your data structure here. */ + SummaryRanges() { + + } + void addNum(int val) { nums_.emplace(val); } From 8561a431277f1033e85f0f26608f76be8e9572b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 31 May 2016 22:56:20 +0800 Subject: [PATCH 2268/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index 408c7584d..155d8d4dc 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -47,12 +47,6 @@ class SummaryRanges { vector intervals_; }; -/** - * Your SummaryRanges object will be instantiated and called as such: - * SummaryRanges obj = new SummaryRanges(); - * obj.addNum(val); - * vector param_2 = obj.getIntervals(); - */ // Time: addNum: O(logs), getIntervals: O(s), s is the data stream's size. // Space: O(s) From eae72e311969a904a2ab188e5667665f6dd294e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 31 May 2016 23:55:40 +0800 Subject: [PATCH 2269/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 41 +++++++++++++---------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index 155d8d4dc..750237417 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -18,25 +18,30 @@ class SummaryRanges { } void addNum(int val) { - Interval newInterval(val, val); - size_t i = 0; - vector result; - // Insert intervals appeared before newInterval. - while (i < intervals_.size() && intervals_[i].end + 1 < newInterval.start) { - result.emplace_back(intervals_[i++]); - } - - // Merge intervals that overlap with newInterval. - while (i < intervals_.size() && newInterval.end + 1 >= intervals_[i].start) { - newInterval = {min(newInterval.start, intervals_[i].start), - max(newInterval.end, intervals_[i].end)}; - ++i; + auto ub_cmp = [](int d, const Interval& x) { return d < x.start; }; + if (intervals_.empty()) { + intervals_.emplace_back(val, val); + } else { + auto it = upper_bound(intervals_.begin(), intervals_.end(), val, ub_cmp); + if (it == intervals_.end()) { + if (prev(it)->end + 1 == val) { + prev(it)->end = val; + } else if (prev(it)->end + 1 < val) { + intervals_.insert(it, Interval(val, val)); + } + } else { + if (it != intervals_.begin() && prev(it)->end + 1 == val) { + prev(it)->end = val; + } else if (it == intervals_.begin() || prev(it)->end + 1 < val) { + intervals_.insert(it, Interval(val, val)); + } + it = upper_bound(intervals_.begin(), intervals_.end(), val, ub_cmp); + if (prev(it)->end + 1 == it->start) { + prev(it)->end = it->end; + intervals_.erase(it); + } + } } - result.emplace_back(newInterval); - - // Insert intervals appearing after newInterval. - result.insert(result.end(), intervals_.cbegin() + i, intervals_.cend()); - swap(result, intervals_); } vector getIntervals() { From 547ee85574d296d9d3da3f0e8caf29fd6572682d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 00:00:32 +0800 Subject: [PATCH 2270/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index 750237417..99845786c 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -1,4 +1,4 @@ -// Time: addNum: O(n), getIntervals: O(n), i is the number of disjoint intervals. +// Time: addNum: O(n), getIntervals: O(n), n is the number of disjoint intervals. // Space: O(n) /** From f35e7a56c75b8059ab5d6f9a4fdfa40041517c51 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 00:06:06 +0800 Subject: [PATCH 2271/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index 99845786c..3a1082c81 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -18,11 +18,11 @@ class SummaryRanges { } void addNum(int val) { - auto ub_cmp = [](int d, const Interval& x) { return d < x.start; }; if (intervals_.empty()) { intervals_.emplace_back(val, val); } else { - auto it = upper_bound(intervals_.begin(), intervals_.end(), val, ub_cmp); + auto it = upper_bound(intervals_.begin(), intervals_.end(), val, + [](int d, const Interval& x) { return d < x.start; }); if (it == intervals_.end()) { if (prev(it)->end + 1 == val) { prev(it)->end = val; From 608fdd2a8aedacae9938588b6015d37a170aa9e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 00:07:37 +0800 Subject: [PATCH 2272/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index 3a1082c81..b51c526ef 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -21,8 +21,8 @@ class SummaryRanges { if (intervals_.empty()) { intervals_.emplace_back(val, val); } else { - auto it = upper_bound(intervals_.begin(), intervals_.end(), val, - [](int d, const Interval& x) { return d < x.start; }); + const auto ub_cmp = [](int d, const Interval& x) { return d < x.start; }; + auto it = upper_bound(intervals_.begin(), intervals_.end(), val, ub_cmp); if (it == intervals_.end()) { if (prev(it)->end + 1 == val) { prev(it)->end = val; @@ -58,7 +58,7 @@ class SummaryRanges { class SummaryRanges2 { public: /** Initialize your data structure here. */ - SummaryRanges() { + SummaryRanges2() { } From 2cf38edae94478d3ae7aa3bbe55ef381334dfa48 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 00:12:44 +0800 Subject: [PATCH 2273/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 53 +++++++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index b51c526ef..b86b8c129 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -1,4 +1,4 @@ -// Time: addNum: O(n), getIntervals: O(n), n is the number of disjoint intervals. +// Time: addNum: O(logn), getIntervals: O(n), n is the number of disjoint intervals. // Space: O(n) /** @@ -17,6 +17,53 @@ class SummaryRanges { } + void addNum(int val) { + if (intervals_.empty()) { + intervals_.emplace(val, val); + } else { + auto it = intervals_.upper_bound(val); + if (it == intervals_.end()) { + if (prev(it)->second + 1 == val) { + prev(it)->second = val; + } else if (prev(it)->second + 1 < val) { + intervals_[val] = val; + } + } else { + if (it != intervals_.begin() && prev(it)->second + 1 == val) { + prev(it)->second = val; + } else if (it == intervals_.begin() || prev(it)->second + 1 < val) { + intervals_[val] = val; + } + it = intervals_.upper_bound(val); + if (prev(it)->second + 1 == it->first) { + prev(it)->second = it->second; + intervals_.erase(it); + } + } + } + } + + vector getIntervals() { + vector result; + for (const auto& kvp : intervals_) { + result.emplace_back(kvp.first, kvp.second); + } + return result; + } + +private: + map intervals_; +}; + +// Time: addNum: O(n), getIntervals: O(n), n is the number of disjoint intervals. +// Space: O(n) +class SummaryRanges2 { +public: + /** Initialize your data structure here. */ + SummaryRanges2() { + + } + void addNum(int val) { if (intervals_.empty()) { intervals_.emplace_back(val, val); @@ -55,10 +102,10 @@ class SummaryRanges { // Time: addNum: O(logs), getIntervals: O(s), s is the data stream's size. // Space: O(s) -class SummaryRanges2 { +class SummaryRanges3 { public: /** Initialize your data structure here. */ - SummaryRanges2() { + SummaryRanges3() { } From 310253366be7279b82e1652ee2511fe441d54b87 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 00:13:51 +0800 Subject: [PATCH 2274/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index b86b8c129..ef45f02b9 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -55,6 +55,7 @@ class SummaryRanges { map intervals_; }; + // Time: addNum: O(n), getIntervals: O(n), n is the number of disjoint intervals. // Space: O(n) class SummaryRanges2 { From 5366e06e1fb924483410953e15cd3b69e790d778 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 00:32:16 +0800 Subject: [PATCH 2275/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 57 +++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index ef45f02b9..bb4cb6f63 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -10,6 +10,7 @@ * Interval(int s, int e) : start(s), end(e) {} * }; */ +// Using map. class SummaryRanges { public: /** Initialize your data structure here. */ @@ -56,6 +57,62 @@ class SummaryRanges { }; +// Using set. +class SummaryRanges { +public: + struct Compare { + bool operator() (const Interval& a, const Interval& b) { + return a.start < b.start; + } + }; + + /** Initialize your data structure here. */ + SummaryRanges() { + + } + + void addNum(int val) { + if (intervals_.empty()) { + intervals_.emplace(val, val); + } else { + auto it = intervals_.upper_bound(Interval(val, val)); + if (it == intervals_.end()) { + if (prev(it)->end + 1 == val) { + const auto start = prev(it)->start; + intervals_.erase(prev(it)); + intervals_.emplace(start, val); + } else if (prev(it)->end + 1 < val) { + intervals_.emplace(val, val); + } + } else { + if (it != intervals_.begin() && prev(it)->end + 1 == val) { + const auto start = prev(it)->start; + intervals_.erase(prev(it)); + intervals_.emplace(start, val); + } else if (it == intervals_.begin() || prev(it)->end + 1 < val) { + intervals_.emplace(val, val); + } + it = intervals_.upper_bound(Interval(val, val)); + if (prev(it)->end + 1 == it->start) { + const auto start = prev(it)->start; + const auto end = it->end; + it = intervals_.erase(prev(it)); + intervals_.erase(it); + intervals_.emplace(start, end); + } + } + } + } + + vector getIntervals() { + return vector(intervals_.begin(), intervals_.end()); + } + +private: + set intervals_; +}; + + // Time: addNum: O(n), getIntervals: O(n), n is the number of disjoint intervals. // Space: O(n) class SummaryRanges2 { From 334cd13ca4c81b0c38780dff3eaded3a6743ecf6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 00:35:45 +0800 Subject: [PATCH 2276/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4894ca7dd..5eb5ae1c7 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-351%20%2F%20351-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-352%20%2F%20352-ff69b4.svg) -Up to date (2016-05-23), there are `334` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-05-23), there are `335` 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 `351` questions. +Here is the classification of all `352` 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 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | 📖 | +352 | [Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/) | [C++](./C++/data-stream-as-disjoint-intervals.cpp) [Python](./Python/data-stream-as-disjoint-intervals.py) | _O(logn)_ | _O(n)_ | Hard | | ## Breadth-First Search # | Title | Solution | Time | Space | Difficulty | Tag | Note From 904cf0a54e3cac2a9c882f200dcaf81becfb31b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 00:55:23 +0800 Subject: [PATCH 2277/4971] Create data-stream-as-disjoint-intervals.py --- Python/data-stream-as-disjoint-intervals.py | 78 +++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Python/data-stream-as-disjoint-intervals.py diff --git a/Python/data-stream-as-disjoint-intervals.py b/Python/data-stream-as-disjoint-intervals.py new file mode 100644 index 000000000..510851f14 --- /dev/null +++ b/Python/data-stream-as-disjoint-intervals.py @@ -0,0 +1,78 @@ +# Time: addNum: O(n), getIntervals: O(n), n is the number of disjoint intervals. +# Space: O(n) + +# Given a data stream input of non-negative integers a1, a2, ..., an, ..., +# summarize the numbers seen so far as a list of disjoint intervals. +# +# For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, +# ..., then the summary will be: +# +# [1, 1] +# [1, 1], [3, 3] +# [1, 1], [3, 3], [7, 7] +# [1, 3], [7, 7] +# [1, 3], [6, 7] +# +# Follow up: +# What if there are lots of merges and the number of disjoint intervals +# are small compared to the data stream's size? + +# Definition for an interval. +# class Interval(object): +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class SummaryRanges(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.__intervals = [] + + def addNum(self, val): + """ + :type val: int + :rtype: void + """ + def upper_bound(nums, target): + left, right = 0, len(nums) - 1 + while left <= right: + mid = left + (right - left) / 2 + if nums[mid].start > target: + right = mid - 1 + else: + left = mid + 1 + return left + + if not self.__intervals: + self.__intervals.append(Interval(val, val)) + else: + i = upper_bound(self.__intervals, val) + if i == len(self.__intervals): + if self.__intervals[i - 1].end + 1 == val: + self.__intervals[i - 1].end = val + elif self.__intervals[i - 1].end + 1 < val: + self.__intervals.insert(i, Interval(val, val)) + else: + if i != 0 and self.__intervals[i - 1].end + 1 == val: + self.__intervals[i - 1].end = val + elif i == 0 or self.__intervals[i - 1].end + 1 < val: + self.__intervals.insert(i, Interval(val, val)) + i = upper_bound(self.__intervals, val) + if self.__intervals[i - 1].end + 1 == self.__intervals[i].start: + self.__intervals[i - 1].end = self.__intervals[i].end + del self.__intervals[i] + + def getIntervals(self): + """ + :rtype: List[Interval] + """ + return self.__intervals + + +# Your SummaryRanges object will be instantiated and called as such: +# obj = SummaryRanges() +# obj.addNum(val) +# param_2 = obj.getIntervals() From c74520953d9f2cd41072cfa8fd43ea36ca7de5da Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 01:04:10 +0800 Subject: [PATCH 2278/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5eb5ae1c7..38b0706ef 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-352%20%2F%20352-ff69b4.svg) -Up to date (2016-05-23), there are `335` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-05-31), there are `335` 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 `352` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 2ead143978ec8952adebb4f941b6034bcee6b033 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 01:09:51 +0800 Subject: [PATCH 2279/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index bb4cb6f63..d28f23bae 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -34,8 +34,8 @@ class SummaryRanges { prev(it)->second = val; } else if (it == intervals_.begin() || prev(it)->second + 1 < val) { intervals_[val] = val; + it = intervals_.upper_bound(val); } - it = intervals_.upper_bound(val); if (prev(it)->second + 1 == it->first) { prev(it)->second = it->second; intervals_.erase(it); @@ -91,8 +91,8 @@ class SummaryRanges { intervals_.emplace(start, val); } else if (it == intervals_.begin() || prev(it)->end + 1 < val) { intervals_.emplace(val, val); + it = intervals_.upper_bound(Interval(val, val)); } - it = intervals_.upper_bound(Interval(val, val)); if (prev(it)->end + 1 == it->start) { const auto start = prev(it)->start; const auto end = it->end; @@ -139,8 +139,8 @@ class SummaryRanges2 { prev(it)->end = val; } else if (it == intervals_.begin() || prev(it)->end + 1 < val) { intervals_.insert(it, Interval(val, val)); + it = upper_bound(intervals_.begin(), intervals_.end(), val, ub_cmp); } - it = upper_bound(intervals_.begin(), intervals_.end(), val, ub_cmp); if (prev(it)->end + 1 == it->start) { prev(it)->end = it->end; intervals_.erase(it); From 6a6ae793b5b65e45cc2dfa24c8cb4dca6dd4081e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 01:10:36 +0800 Subject: [PATCH 2280/4971] Update data-stream-as-disjoint-intervals.py --- Python/data-stream-as-disjoint-intervals.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/data-stream-as-disjoint-intervals.py b/Python/data-stream-as-disjoint-intervals.py index 510851f14..f491141ea 100644 --- a/Python/data-stream-as-disjoint-intervals.py +++ b/Python/data-stream-as-disjoint-intervals.py @@ -60,7 +60,7 @@ def upper_bound(nums, target): self.__intervals[i - 1].end = val elif i == 0 or self.__intervals[i - 1].end + 1 < val: self.__intervals.insert(i, Interval(val, val)) - i = upper_bound(self.__intervals, val) + i = upper_bound(self.__intervals, val) if self.__intervals[i - 1].end + 1 == self.__intervals[i].start: self.__intervals[i - 1].end = self.__intervals[i].end del self.__intervals[i] From 76cf2619fa8d4c71bbc3edbb429ee609bea848cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 01:14:54 +0800 Subject: [PATCH 2281/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index d28f23bae..b4422aa4b 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -34,7 +34,6 @@ class SummaryRanges { prev(it)->second = val; } else if (it == intervals_.begin() || prev(it)->second + 1 < val) { intervals_[val] = val; - it = intervals_.upper_bound(val); } if (prev(it)->second + 1 == it->first) { prev(it)->second = it->second; @@ -91,7 +90,6 @@ class SummaryRanges { intervals_.emplace(start, val); } else if (it == intervals_.begin() || prev(it)->end + 1 < val) { intervals_.emplace(val, val); - it = intervals_.upper_bound(Interval(val, val)); } if (prev(it)->end + 1 == it->start) { const auto start = prev(it)->start; From 3db19d15633b8ccc42bcbb735ba3e0a04e4247f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 02:26:53 +0800 Subject: [PATCH 2282/4971] Update insert-interval.py --- Python/insert-interval.py | 43 ++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/Python/insert-interval.py b/Python/insert-interval.py index 82e27eb9a..16cf7c0a7 100644 --- a/Python/insert-interval.py +++ b/Python/insert-interval.py @@ -1,8 +1,8 @@ # Time: O(n) # Space: O(1) -# -# Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). -# + +# Given a set of non-overlapping intervals, insert a new interval into the +# intervals (merge if necessary). # You may assume that the intervals were initially sorted according to their start times. # # Example 1: @@ -12,7 +12,6 @@ # Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. # # This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. -# # Definition for an interval. class Interval: @@ -23,25 +22,27 @@ def __init__(self, s=0, e=0): def __repr__(self): return "[{}, {}]".format(self.start, self.end) -class Solution: - # @param intervals, a list of Intervals - # @param newInterval, a Interval - # @return a list of Interval + +class Solution(object): def insert(self, intervals, newInterval): - return self.merge(intervals + [newInterval]) - - def merge(self, intervals): - if not intervals: - return intervals - intervals.sort(key = lambda x: x.start) - result = [intervals[0]] - 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) - else: - result.append(current) + """ + :type intervals: List[Interval] + :type newInterval: Interval + :rtype: List[Interval] + """ + result = [] + i = 0 + while i < len(intervals) and newInterval.start > intervals[i].end: + result += intervals[i], + i += 1 + while i < len(intervals) and newInterval.end >= intervals[i].start: + newInterval = Interval(min(newInterval.start, intervals[i].start), \ + max(newInterval.end, intervals[i].end)) + i += 1 + result += newInterval, + result += intervals[i:] 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)) From 6ccc9d0aceffdc90d944d035bd49c16fa1d87ee0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 21:05:26 +0800 Subject: [PATCH 2283/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 51 +++++++---------------- 1 file changed, 16 insertions(+), 35 deletions(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index b4422aa4b..002cf96ff 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -59,54 +59,35 @@ class SummaryRanges { // Using set. class SummaryRanges { public: - struct Compare { - bool operator() (const Interval& a, const Interval& b) { - return a.start < b.start; - } - }; - /** Initialize your data structure here. */ SummaryRanges() { } void addNum(int val) { - if (intervals_.empty()) { - intervals_.emplace(val, val); - } else { - auto it = intervals_.upper_bound(Interval(val, val)); - if (it == intervals_.end()) { - if (prev(it)->end + 1 == val) { - const auto start = prev(it)->start; - intervals_.erase(prev(it)); - intervals_.emplace(start, val); - } else if (prev(it)->end + 1 < val) { - intervals_.emplace(val, val); - } - } else { - if (it != intervals_.begin() && prev(it)->end + 1 == val) { - const auto start = prev(it)->start; - intervals_.erase(prev(it)); - intervals_.emplace(start, val); - } else if (it == intervals_.begin() || prev(it)->end + 1 < val) { - intervals_.emplace(val, val); - } - if (prev(it)->end + 1 == it->start) { - const auto start = prev(it)->start; - const auto end = it->end; - it = intervals_.erase(prev(it)); - intervals_.erase(it); - intervals_.emplace(start, end); - } - } + auto it = intervals_.upper_bound(Interval(val, val)); + int start = val, end = val; + if (it != intervals_.begin() && prev(it)->end + 1 >= val) { + --it; + } + while (it != intervals_.end() && end + 1 >= it->start) { + start = min(start, it->start); + end = max(end, it->end); + it = intervals_.erase(it); } + intervals_.insert(it, Interval(start, end)); } - + vector getIntervals() { return vector(intervals_.begin(), intervals_.end()); } private: + struct Compare { + bool operator() (const Interval& a, const Interval& b) { + return a.start < b.start; + } + }; set intervals_; }; From dd64e40495997aab70f6fce99f74e6e714bf3d44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 21:19:35 +0800 Subject: [PATCH 2284/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 41 ++++++++++------------- 1 file changed, 17 insertions(+), 24 deletions(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index 002cf96ff..1e9658c0f 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -95,6 +95,7 @@ class SummaryRanges { // Time: addNum: O(n), getIntervals: O(n), n is the number of disjoint intervals. // Space: O(n) class SummaryRanges2 { +public: public: /** Initialize your data structure here. */ SummaryRanges2() { @@ -102,37 +103,29 @@ class SummaryRanges2 { } void addNum(int val) { - if (intervals_.empty()) { - intervals_.emplace_back(val, val); - } else { - const auto ub_cmp = [](int d, const Interval& x) { return d < x.start; }; - auto it = upper_bound(intervals_.begin(), intervals_.end(), val, ub_cmp); - if (it == intervals_.end()) { - if (prev(it)->end + 1 == val) { - prev(it)->end = val; - } else if (prev(it)->end + 1 < val) { - intervals_.insert(it, Interval(val, val)); - } - } else { - if (it != intervals_.begin() && prev(it)->end + 1 == val) { - prev(it)->end = val; - } else if (it == intervals_.begin() || prev(it)->end + 1 < val) { - intervals_.insert(it, Interval(val, val)); - it = upper_bound(intervals_.begin(), intervals_.end(), val, ub_cmp); - } - if (prev(it)->end + 1 == it->start) { - prev(it)->end = it->end; - intervals_.erase(it); - } - } + auto it = upper_bound(intervals_.begin(), intervals_.end(), Interval(val, val), Compare()); + int start = val, end = val; + if (it != intervals_.begin() && prev(it)->end + 1 >= val) { + --it; } + while (it != intervals_.end() && end + 1 >= it->start) { + start = min(start, it->start); + end = max(end, it->end); + it = intervals_.erase(it); + } + intervals_.insert(it, Interval(start, end)); } - + vector getIntervals() { return intervals_; } private: + struct Compare { + bool operator() (const Interval& a, const Interval& b) { + return a.start < b.start; + } + }; vector intervals_; }; From c0e671b115c1b90d6835c8a23769133417423daa Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 21:24:07 +0800 Subject: [PATCH 2285/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 75 ++++++++++------------- 1 file changed, 32 insertions(+), 43 deletions(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index 1e9658c0f..18dee3946 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -10,7 +10,7 @@ * Interval(int s, int e) : start(s), end(e) {} * }; */ -// Using map. +// Using set. class SummaryRanges { public: /** Initialize your data structure here. */ @@ -19,44 +19,34 @@ class SummaryRanges { } void addNum(int val) { - if (intervals_.empty()) { - intervals_.emplace(val, val); - } else { - auto it = intervals_.upper_bound(val); - if (it == intervals_.end()) { - if (prev(it)->second + 1 == val) { - prev(it)->second = val; - } else if (prev(it)->second + 1 < val) { - intervals_[val] = val; - } - } else { - if (it != intervals_.begin() && prev(it)->second + 1 == val) { - prev(it)->second = val; - } else if (it == intervals_.begin() || prev(it)->second + 1 < val) { - intervals_[val] = val; - } - if (prev(it)->second + 1 == it->first) { - prev(it)->second = it->second; - intervals_.erase(it); - } - } + auto it = intervals_.upper_bound(Interval(val, val)); + int start = val, end = val; + if (it != intervals_.begin() && prev(it)->end + 1 >= val) { + --it; + } + while (it != intervals_.end() && end + 1 >= it->start) { + start = min(start, it->start); + end = max(end, it->end); + it = intervals_.erase(it); } + intervals_.insert(it, Interval(start, end)); } - + vector getIntervals() { - vector result; - for (const auto& kvp : intervals_) { - result.emplace_back(kvp.first, kvp.second); - } - return result; + return vector(intervals_.begin(), intervals_.end()); } private: - map intervals_; + struct Compare { + bool operator() (const Interval& a, const Interval& b) { + return a.start < b.start; + } + }; + set intervals_; }; -// Using set. +// Using map. class SummaryRanges { public: /** Initialize your data structure here. */ @@ -65,30 +55,29 @@ class SummaryRanges { } void addNum(int val) { - auto it = intervals_.upper_bound(Interval(val, val)); + auto it = intervals_.upper_bound(val); int start = val, end = val; - if (it != intervals_.begin() && prev(it)->end + 1 >= val) { + if (it != intervals_.begin() && prev(it)->second + 1 >= val) { --it; } - while (it != intervals_.end() && end + 1 >= it->start) { - start = min(start, it->start); - end = max(end, it->end); + while (it != intervals_.end() && end + 1 >= it->first) { + start = min(start, it->first); + end = max(end, it->second); it = intervals_.erase(it); } - intervals_.insert(it, Interval(start, end)); + intervals_[start] = end; } vector getIntervals() { - return vector(intervals_.begin(), intervals_.end()); + vector result; + for (const auto& kvp : intervals_) { + result.emplace_back(kvp.first, kvp.second); + } + return result; } private: - struct Compare { - bool operator() (const Interval& a, const Interval& b) { - return a.start < b.start; - } - }; - set intervals_; + map intervals_; }; From cc1a101c87e467418724a29316340106bdfa6cab Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Jun 2016 21:31:01 +0800 Subject: [PATCH 2286/4971] Update data-stream-as-disjoint-intervals.py --- Python/data-stream-as-disjoint-intervals.py | 28 ++++++++------------- 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/Python/data-stream-as-disjoint-intervals.py b/Python/data-stream-as-disjoint-intervals.py index f491141ea..48b6188a8 100644 --- a/Python/data-stream-as-disjoint-intervals.py +++ b/Python/data-stream-as-disjoint-intervals.py @@ -46,24 +46,16 @@ def upper_bound(nums, target): left = mid + 1 return left - if not self.__intervals: - self.__intervals.append(Interval(val, val)) - else: - i = upper_bound(self.__intervals, val) - if i == len(self.__intervals): - if self.__intervals[i - 1].end + 1 == val: - self.__intervals[i - 1].end = val - elif self.__intervals[i - 1].end + 1 < val: - self.__intervals.insert(i, Interval(val, val)) - else: - if i != 0 and self.__intervals[i - 1].end + 1 == val: - self.__intervals[i - 1].end = val - elif i == 0 or self.__intervals[i - 1].end + 1 < val: - self.__intervals.insert(i, Interval(val, val)) - i = upper_bound(self.__intervals, val) - if self.__intervals[i - 1].end + 1 == self.__intervals[i].start: - self.__intervals[i - 1].end = self.__intervals[i].end - del self.__intervals[i] + i = upper_bound(self.__intervals, val) + start, end = val, val + if i != 0 and self.__intervals[i-1].end + 1 >= val: + i -= 1 + while i != len(self.__intervals) and \ + end + 1 >= self.__intervals[i].start: + start = min(start, self.__intervals[i].start) + end = max(end, self.__intervals[i].end); + del self.__intervals[i] + self.__intervals.insert(i, Interval(start, end)) def getIntervals(self): """ From 44ceb7529d1c65bd105fc12e9bec1b6734a88c09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 3 Jun 2016 23:41:44 +0800 Subject: [PATCH 2287/4971] Create design-snake-game.cpp --- C++/design-snake-game.cpp | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 C++/design-snake-game.cpp diff --git a/C++/design-snake-game.cpp b/C++/design-snake-game.cpp new file mode 100644 index 000000000..ba904a362 --- /dev/null +++ b/C++/design-snake-game.cpp @@ -0,0 +1,59 @@ +// Time: O(s) per move, S is current length of the snake. +// Space: O(s) + +class SnakeGame { +public: + /** Initialize your data structure here. + @param width - screen width + @param height - screen height + @param food - A list of food positions + E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */ + SnakeGame(int width, int height, vector> food) : + width_{width}, height_{height}, score_{0}, + food_{food.begin(), food.end()}, snake_{{0, 0}} { + } + + /** Moves the snake. + @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down + @return The game's score after the move. Return -1 if game over. + Game over when snake crosses the screen boundary or bites its body. */ + int move(string direction) { + const auto x = snake_.back().first + direction_[direction[0]].first; + const auto y = snake_.back().second + direction_[direction[0]].second; + const auto tail = snake_.back(); + + snake_.pop_front(); + if (!valid(x, y)) { + return -1; + } else if (!food_.empty() && food_.front().first == x && food_.front().second == y) { + ++score_; + food_.pop_front(); + snake_.push_front(tail); + } + snake_.push_back({x, y}); + return score_; + } + +private: + bool valid(int x, int y) { + if (x < 0 || x >= height_ || y < 0 || y >= width_) { + return false; + } + for (const auto& p : snake_) { + if (x == p.first && y == p.second) { + return false; + } + } + return true; + } + int width_, height_, score_; + deque> food_, snake_; + unordered_map> direction_ = {{'U', {-1, 0}}, {'L', {0, -1}}, + {'R', {0, 1}}, {'D', {1, 0}}}; +}; + +/** + * Your SnakeGame object will be instantiated and called as such: + * SnakeGame obj = new SnakeGame(width, height, food); + * int param_1 = obj.move(direction); + */ From 03db9537f665f4b6c41c75066c73011ac5f4a4ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 3 Jun 2016 23:44:37 +0800 Subject: [PATCH 2288/4971] Update design-snake-game.cpp --- C++/design-snake-game.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/C++/design-snake-game.cpp b/C++/design-snake-game.cpp index ba904a362..d977b1c95 100644 --- a/C++/design-snake-game.cpp +++ b/C++/design-snake-game.cpp @@ -18,8 +18,8 @@ class SnakeGame { @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. */ int move(string direction) { - const auto x = snake_.back().first + direction_[direction[0]].first; - const auto y = snake_.back().second + direction_[direction[0]].second; + const auto x = snake_.back().first + direction_[direction].first; + const auto y = snake_.back().second + direction_[direction].second; const auto tail = snake_.back(); snake_.pop_front(); @@ -48,8 +48,8 @@ class SnakeGame { } int width_, height_, score_; deque> food_, snake_; - unordered_map> direction_ = {{'U', {-1, 0}}, {'L', {0, -1}}, - {'R', {0, 1}}, {'D', {1, 0}}}; + unordered_map> direction_ = {{"U", {-1, 0}}, {"L", {0, -1}}, + {"R", {0, 1}}, {"D", {1, 0}}}; }; /** @@ -57,3 +57,5 @@ class SnakeGame { * SnakeGame obj = new SnakeGame(width, height, food); * int param_1 = obj.move(direction); */ + + From f3ca2235efc210ecd9ab708235ff3ec8fffcbf96 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 3 Jun 2016 23:45:59 +0800 Subject: [PATCH 2289/4971] Update design-snake-game.cpp --- C++/design-snake-game.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/design-snake-game.cpp b/C++/design-snake-game.cpp index d977b1c95..808d255e3 100644 --- a/C++/design-snake-game.cpp +++ b/C++/design-snake-game.cpp @@ -1,4 +1,4 @@ -// Time: O(s) per move, S is current length of the snake. +// Time: O(s) per move, s is current length of the snake. // Space: O(s) class SnakeGame { From 9f9fe3266b094c459b68ae5f3d3524c36cf48cd6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 3 Jun 2016 23:46:10 +0800 Subject: [PATCH 2290/4971] Update design-snake-game.cpp --- C++/design-snake-game.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/design-snake-game.cpp b/C++/design-snake-game.cpp index 808d255e3..b3946edc2 100644 --- a/C++/design-snake-game.cpp +++ b/C++/design-snake-game.cpp @@ -1,4 +1,4 @@ -// Time: O(s) per move, s is current length of the snake. +// Time: O(s) per move, s is the current length of the snake. // Space: O(s) class SnakeGame { From 414a012a85bd88d2747fe4bb3d0e7076fc14ff9f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 00:06:12 +0800 Subject: [PATCH 2291/4971] Create design-snake-game.py --- Python/design-snake-game.py | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/design-snake-game.py diff --git a/Python/design-snake-game.py b/Python/design-snake-game.py new file mode 100644 index 000000000..37253802d --- /dev/null +++ b/Python/design-snake-game.py @@ -0,0 +1,56 @@ +# Time: O(s) per move, s is the current length of the snake. +# Space: O(s) + +from collections import deque + +class SnakeGame(object): + + def __init__(self, width,height,food): + """ + Initialize your data structure here. + @param width - screen width + @param height - screen height + @param food - A list of food positions + E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. + :type width: int + :type height: int + :type food: List[List[int]] + """ + self.__width = width + self.__height = height + self.__score = 0 + self.__food = deque(food) + self.__snake = deque([(0, 0)]) + self.__direction = {"U":(-1, 0), "L":(0, -1), "R":(0, 1), "D":(1, 0)}; + + + def move(self, direction): + """ + Moves the snake. + @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down + @return The game's score after the move. Return -1 if game over. + Game over when snake crosses the screen boundary or bites its body. + :type direction: str + :rtype: int + """ + def valid(x, y): + return 0 <= x < self.__height and \ + 0 <= y < self.__width and \ + (x, y) not in self.__snake + d = self.__direction[direction] + x, y = self.__snake[-1][0] + d[0], self.__snake[-1][1] + d[1] + tail = self.__snake[-1] + self.__snake.popleft() + if not valid(x, y): + return -1 + elif self.__food and (self.__food[0][0], self.__food[0][1]) == (x, y): + self.__score += 1 + self.__food.popleft() + self.__snake.appendleft(tail) + self.__snake += (x, y), + return self.__score + + +# Your SnakeGame object will be instantiated and called as such: +# obj = SnakeGame(width, height, food) +# param_1 = obj.move(direction) From ce7630a838429448de0162092db01f2ee8692e46 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 00:10:09 +0800 Subject: [PATCH 2292/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 38b0706ef..b02947951 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-352%20%2F%20352-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-353%20%2F%20353-ff69b4.svg) -Up to date (2016-05-31), there are `335` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-03), there are `336` 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 `352` questions. +Here is the classification of all `353` 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. ) @@ -465,6 +465,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 284| [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [C++](./C++/peeking-iterator.cpp) [Python](./Python/peeking-iterator.py) | _O(1)_ | _O(1)_ | Medium || 348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_| _O(n^2)_| Medium |📖|| +353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(s)_| _O(s)_| Medium |📖| Deque | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From bf6b58025e94a3883f0c33573e8c66e7159bae12 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 00:18:40 +0800 Subject: [PATCH 2293/4971] Update design-snake-game.py --- Python/design-snake-game.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/design-snake-game.py b/Python/design-snake-game.py index 37253802d..50e4d3d76 100644 --- a/Python/design-snake-game.py +++ b/Python/design-snake-game.py @@ -47,7 +47,7 @@ def valid(x, y): self.__score += 1 self.__food.popleft() self.__snake.appendleft(tail) - self.__snake += (x, y), + self.__snake.append((x, y)) return self.__score From 7c5bd8dd4da4b21940513bbb3d07962aea415665 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 00:19:12 +0800 Subject: [PATCH 2294/4971] Update design-snake-game.py --- Python/design-snake-game.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/design-snake-game.py b/Python/design-snake-game.py index 50e4d3d76..ff62d38ba 100644 --- a/Python/design-snake-game.py +++ b/Python/design-snake-game.py @@ -37,6 +37,7 @@ def valid(x, y): return 0 <= x < self.__height and \ 0 <= y < self.__width and \ (x, y) not in self.__snake + d = self.__direction[direction] x, y = self.__snake[-1][0] + d[0], self.__snake[-1][1] + d[1] tail = self.__snake[-1] From b6d70cdb0b408a62ec84ad492a867aa248b91f25 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 11:53:27 +0800 Subject: [PATCH 2295/4971] Update merge-two-sorted-lists.py --- Python/merge-two-sorted-lists.py | 34 +++++++++++++++----------------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/Python/merge-two-sorted-lists.py b/Python/merge-two-sorted-lists.py index 609c90a57..0d965d2b9 100644 --- a/Python/merge-two-sorted-lists.py +++ b/Python/merge-two-sorted-lists.py @@ -6,38 +6,36 @@ # # 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: return "{} -> {}".format(self.val, self.next) -class Solution: - # @param two ListNodes - # @return a ListNode + +class Solution(object): def mergeTwoLists(self, l1, l2): - dummy = ListNode(0) - current = dummy - + """ + :type l1: ListNode + :type l2: ListNode + :rtype: ListNode + """ + curr = dummy = ListNode(0) while l1 and l2: if l1.val < l2.val: - current.next = l1 + curr.next = l1 l1 = l1.next else: - current.next = l2 + curr.next = l2 l2 = l2.next - current = current.next - - if l1: - current.next = l1 - else: - current.next = l2 - + curr = curr.next + curr.next = l1 or l2 return dummy.next + if __name__ == "__main__": l1 = ListNode(0) l1.next = ListNode(1) @@ -45,4 +43,4 @@ def mergeTwoLists(self, l1, l2): l2.next = ListNode(3) print Solution().mergeTwoLists(l1, l2) - \ No newline at end of file + From 79a6f541a9ae5c93e4d9c9af5e638ed8e034f5fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:13:15 +0800 Subject: [PATCH 2296/4971] Update merge-k-sorted-lists.cpp --- C++/merge-k-sorted-lists.cpp | 138 ++++++++++++++++++++++------------- 1 file changed, 86 insertions(+), 52 deletions(-) diff --git a/C++/merge-k-sorted-lists.cpp b/C++/merge-k-sorted-lists.cpp index b7b6fa031..86efc5235 100644 --- a/C++/merge-k-sorted-lists.cpp +++ b/C++/merge-k-sorted-lists.cpp @@ -1,5 +1,5 @@ // Time: O(n * logk) -// Space: O(k) +// Space: O(1) /** * Definition for singly-linked list. @@ -9,7 +9,92 @@ * ListNode(int x) : val(x), next(NULL) {} * }; */ + +// Merge two by two solution. class Solution { +public: + ListNode *mergeKLists(vector &lists) { + if (lists.empty()) { + return nullptr; + } + + int left = 0, right = lists.size() - 1; + while (right > 0) { + if (left >= right) { + left = 0; + } else { + lists[left] = mergeTwoLists(lists[left], lists[right]); + ++left; + --right; + } + } + return lists[0]; + } + +private: + ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { + ListNode dummy = ListNode(0); + auto *curr = &dummy; + while (l1 && l2) { + if (l1->val <= l2->val) { + curr->next = l1; + l1 = l1->next; + } else { + curr->next = l2; + l2 = l2->next; + } + curr = curr->next; + } + curr->next = l1 ? l1 : l2; + return dummy.next; + } +}; + +// Time: O(n * logk) +// Space: O(logk) +// Divide and conquer solution. +class Solution2 { +public: + ListNode *mergeKLists(vector &lists) { + return mergeKListsHelper(lists, 0, lists.size() - 1); + } + +private: + ListNode *mergeKListsHelper(const vector &lists, int begin, int end) { + if (begin > end) { + return nullptr; + } + if (begin == end) { + return lists[begin]; + } + return mergeTwoLists(mergeKListsHelper(lists, begin, (begin + end) / 2), + mergeKListsHelper(lists, (begin + end) / 2 + 1, end)); + } + +private: + ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { + ListNode dummy = ListNode(0); + auto *curr = &dummy; + while (l1 && l2) { + if (l1->val <= l2->val) { + curr->next = l1; + l1 = l1->next; + } else { + curr->next = l2; + l2 = l2->next; + } + curr = curr->next; + } + curr->next = l1 ? l1 : l2; + return dummy.next; + } +}; + + +// Time: O(n * logk) +// Space: O(k) +// Heap solution. +class Solution3 { public: ListNode* mergeKLists(vector& lists) { ListNode dummy(0); @@ -43,54 +128,3 @@ class Solution { return dummy.next; } }; - - -// Time: O(n * logk) -// Space: O(k) -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution2 { -public: - ListNode *mergeKLists(vector &lists) { - return mergeKLists(lists, 0, lists.size() - 1); - } - -private: - ListNode *mergeKLists(const vector &lists, int begin, int end) { - if (begin > end) { - return nullptr; - } - if (begin == end) { - return lists[begin]; - } - return mergeTwoLists(mergeKLists(lists, begin, (begin + end) / 2), - mergeKLists(lists, (begin + end) / 2 + 1, end)); - } - - ListNode *mergeTwoLists(ListNode *left, ListNode *right) { - ListNode dummy(0); - auto *p = &dummy; - for (; left && right; p = p->next) { - if(left->val < right->val) { - p->next = left; - left = left->next; - } else { - p->next = right; - right = right->next; - } - } - if (left) { - p->next = left; - } else { - p->next = right; - } - return dummy.next; - } -}; - From 6d76236a786027982a1dc8d4872dc067444738f4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:14:20 +0800 Subject: [PATCH 2297/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b02947951..4cc3b9828 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,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 || +23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | Heap, Divide and Conquer | 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 || @@ -167,7 +168,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Heap # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [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 | From f9033c1faa5a25aaa7274b556673fc52d3a667fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:15:20 +0800 Subject: [PATCH 2298/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4cc3b9828..5efcd6f4d 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,6 @@ 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 || -23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | Heap, Divide and Conquer | 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 || @@ -257,6 +256,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | 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 || +23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | Heap, Divide and Conquer | 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/) | [C++](./C++/sort-colors.cpp) [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || Tri Partition From 3a9bb097238eef26ec1a6db63ed6f0a3c9c79fb6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:17:08 +0800 Subject: [PATCH 2299/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5efcd6f4d..e5b64465e 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,8 @@ 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 || +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 || +23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | Heap, Divide and Conquer | 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 || @@ -255,8 +257,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Sort # | 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 || -23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | Heap, Divide and Conquer | 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/) | [C++](./C++/sort-colors.cpp) [Python](./Python/sort-colors.py) | _O(n)_ | _O(1)_ | Medium || Tri Partition From ab1eddd40e0b9506abc0eede04f75da8b2d6bac5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:22:04 +0800 Subject: [PATCH 2300/4971] Create merge-two-sorted-lists.cpp --- C++/merge-two-sorted-lists.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/merge-two-sorted-lists.cpp diff --git a/C++/merge-two-sorted-lists.cpp b/C++/merge-two-sorted-lists.cpp new file mode 100644 index 000000000..885cc9db1 --- /dev/null +++ b/C++/merge-two-sorted-lists.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 *mergeTwoLists(ListNode *l1, ListNode *l2) { + ListNode dummy = ListNode(0); + auto *curr = &dummy; + while (l1 && l2) { + if (l1->val <= l2->val) { + curr->next = l1; + l1 = l1->next; + } else { + curr->next = l2; + l2 = l2->next; + } + curr = curr->next; + } + curr->next = l1 ? l1 : l2; + return dummy.next; + } +}; From 107190193d59dbd019595aa5672c2c38ca19cdfa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:22:47 +0800 Subject: [PATCH 2301/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e5b64465e..4178c2347 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 # | 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 || -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 || +21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./C++/merge-two-sorted-lists.cpp) [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | Heap, Divide and Conquer | 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 || From 0b294b27a964117b542896163c4329800ec8f6c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:23:30 +0800 Subject: [PATCH 2302/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4178c2347..e41b9fd51 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 -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 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 || 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./C++/merge-two-sorted-lists.cpp) [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || -23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | Heap, Divide and Conquer | +23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | | Heap, Divide and Conquer 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 || From 2e41812498f5cecb8cd613cfef85913c0167b68b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:29:52 +0800 Subject: [PATCH 2303/4971] Update merge-k-sorted-lists.py --- Python/merge-k-sorted-lists.py | 59 ++++++++++++++++++++++++++++------ 1 file changed, 49 insertions(+), 10 deletions(-) diff --git a/Python/merge-k-sorted-lists.py b/Python/merge-k-sorted-lists.py index 8003ec215..3a1ecb9d8 100644 --- a/Python/merge-k-sorted-lists.py +++ b/Python/merge-k-sorted-lists.py @@ -1,20 +1,58 @@ # Time: O(nlogk) -# Space: O(k) -# -# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. -import heapq +# Space: O(1) + +# Merge k sorted linked lists and return it as one sorted list. +# Analyze and describe its complexity. # 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: - return "{} -> {}".format(self.val, repr(self.next)) -class Solution: + def __repr__(self): + if self: + return "{} -> {}".format(self.val, + + +# Merge two by two solution. +class Solution(object): + def mergeKLists(self, lists): + """ + :type lists: List[ListNode] + :rtype: ListNode + """ + def mergeTwoLists(l1, l2): + curr = dummy = ListNode(0) + while l1 and l2: + if l1.val < l2.val: + curr.next = l1 + l1 = l1.next + else: + curr.next = l2 + l2 = l2.next + curr = curr.next + curr.next = l1 or l2 + return dummy.next + + if not lists: + return None + left, right = 0, len(lists) - 1; + while right > 0: + if left >= right: + left = 0 + else: + lists[left] = mergeTwoLists(lists[left], lists[right]) + left += 1 + right -= 1 + return lists[0] + + +# Time: O(nlogk) +# Space: O(k) +# Heap solution. +import heapq +class Solution3: # @param a list of ListNode # @return a ListNode def mergeKLists(self, lists): @@ -35,6 +73,7 @@ def mergeKLists(self, lists): return dummy.next + if __name__ == "__main__": list1 = ListNode(1) list1.next = ListNode(3) From b5df9e60b74ececc346148300fd58b99352534d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:34:51 +0800 Subject: [PATCH 2304/4971] Update merge-k-sorted-lists.py --- Python/merge-k-sorted-lists.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Python/merge-k-sorted-lists.py b/Python/merge-k-sorted-lists.py index 3a1ecb9d8..584c2c17b 100644 --- a/Python/merge-k-sorted-lists.py +++ b/Python/merge-k-sorted-lists.py @@ -48,6 +48,37 @@ def mergeTwoLists(l1, l2): return lists[0] +# Time: O(nlogk) +# Space: O(logk) +# Divide and Conquer solution. +class Solution2: + # @param a list of ListNode + # @return a ListNode + def mergeKLists(self, lists): + def mergeTwoLists(l1, l2): + curr = dummy = ListNode(0) + while l1 and l2: + if l1.val < l2.val: + curr.next = l1 + l1 = l1.next + else: + curr.next = l2 + l2 = l2.next + curr = curr.next + curr.next = l1 or l2 + return dummy.next + + def mergeKListsHelper(lists, begin, end): + if begin > end: + return None + if begin == end: + return lists[begin] + return mergeTwoLists(mergeKListsHelper(lists, begin, (begin + end) / 2), \ + mergeKListsHelper(lists, (begin + end) / 2 + 1, end)) + + return mergeKListsHelper(lists, 0, len(lists) - 1) + + # Time: O(nlogk) # Space: O(k) # Heap solution. From 2aa437737e5ecbee29b282b564c485002d7b40b4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:35:07 +0800 Subject: [PATCH 2305/4971] Update merge-k-sorted-lists.cpp --- C++/merge-k-sorted-lists.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/merge-k-sorted-lists.cpp b/C++/merge-k-sorted-lists.cpp index 86efc5235..7bf50bb96 100644 --- a/C++/merge-k-sorted-lists.cpp +++ b/C++/merge-k-sorted-lists.cpp @@ -52,7 +52,7 @@ class Solution { // Time: O(n * logk) // Space: O(logk) -// Divide and conquer solution. +// Divide and Conquer solution. class Solution2 { public: ListNode *mergeKLists(vector &lists) { From 2b3c7f92f414966d8896d2edc20d191febb07afa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:36:02 +0800 Subject: [PATCH 2306/4971] Update merge-k-sorted-lists.cpp --- C++/merge-k-sorted-lists.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/merge-k-sorted-lists.cpp b/C++/merge-k-sorted-lists.cpp index 7bf50bb96..7f6fc872c 100644 --- a/C++/merge-k-sorted-lists.cpp +++ b/C++/merge-k-sorted-lists.cpp @@ -50,6 +50,7 @@ class Solution { } }; + // Time: O(n * logk) // Space: O(logk) // Divide and Conquer solution. From 0fb78cfe7ab4b3c76ed6d15b700e600a8d3932c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 12:37:47 +0800 Subject: [PATCH 2307/4971] Update merge-k-sorted-lists.cpp --- C++/merge-k-sorted-lists.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/merge-k-sorted-lists.cpp b/C++/merge-k-sorted-lists.cpp index 7f6fc872c..cf790e8af 100644 --- a/C++/merge-k-sorted-lists.cpp +++ b/C++/merge-k-sorted-lists.cpp @@ -72,7 +72,6 @@ class Solution2 { mergeKListsHelper(lists, (begin + end) / 2 + 1, end)); } -private: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode dummy = ListNode(0); auto *curr = &dummy; From 8c52ffb6eb3531a8b740c3467f7a2053d791e444 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 13:16:22 +0800 Subject: [PATCH 2308/4971] Update merge-k-sorted-lists.cpp --- C++/merge-k-sorted-lists.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/C++/merge-k-sorted-lists.cpp b/C++/merge-k-sorted-lists.cpp index cf790e8af..79d149250 100644 --- a/C++/merge-k-sorted-lists.cpp +++ b/C++/merge-k-sorted-lists.cpp @@ -35,6 +35,7 @@ class Solution { ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode dummy = ListNode(0); auto *curr = &dummy; + while (l1 && l2) { if (l1->val <= l2->val) { curr->next = l1; @@ -46,6 +47,7 @@ class Solution { curr = curr->next; } curr->next = l1 ? l1 : l2; + return dummy.next; } }; @@ -75,6 +77,7 @@ class Solution2 { ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode dummy = ListNode(0); auto *curr = &dummy; + while (l1 && l2) { if (l1->val <= l2->val) { curr->next = l1; @@ -86,6 +89,7 @@ class Solution2 { curr = curr->next; } curr->next = l1 ? l1 : l2; + return dummy.next; } }; From a333848726be42ce07f92c478f77929b0337cae8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 13:17:29 +0800 Subject: [PATCH 2309/4971] Update merge-two-sorted-lists.cpp --- C++/merge-two-sorted-lists.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/C++/merge-two-sorted-lists.cpp b/C++/merge-two-sorted-lists.cpp index 885cc9db1..acd59112b 100644 --- a/C++/merge-two-sorted-lists.cpp +++ b/C++/merge-two-sorted-lists.cpp @@ -14,6 +14,7 @@ class Solution { ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode dummy = ListNode(0); auto *curr = &dummy; + while (l1 && l2) { if (l1->val <= l2->val) { curr->next = l1; @@ -25,6 +26,7 @@ class Solution { curr = curr->next; } curr->next = l1 ? l1 : l2; + return dummy.next; } }; From 2bee7108abb5f239c7f33c9be6871eec2934a131 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 13:37:20 +0800 Subject: [PATCH 2310/4971] Update intersection-of-two-arrays.cpp --- C++/intersection-of-two-arrays.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/C++/intersection-of-two-arrays.cpp b/C++/intersection-of-two-arrays.cpp index 2c38521cb..a8ada0ba8 100644 --- a/C++/intersection-of-two-arrays.cpp +++ b/C++/intersection-of-two-arrays.cpp @@ -9,10 +9,7 @@ class Solution { return intersection(nums2, nums1); } - unordered_set lookup; - for (const auto& i : nums1) { - lookup.emplace(i); - } + unordered_set lookup{nums1.cbegin(), nums1.cend()}; vector result; for (const auto& i : nums2) { From b1846b07d48e416fbaf68b5e55da252c11a0f834 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 13:46:34 +0800 Subject: [PATCH 2311/4971] Update intersection-of-two-arrays.cpp --- C++/intersection-of-two-arrays.cpp | 31 +++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/C++/intersection-of-two-arrays.cpp b/C++/intersection-of-two-arrays.cpp index a8ada0ba8..abbe6d450 100644 --- a/C++/intersection-of-two-arrays.cpp +++ b/C++/intersection-of-two-arrays.cpp @@ -24,10 +24,39 @@ class Solution { }; +// Time: O(min(m, n) * log(max(m, n))) +// Space: O(1) +// Binary search solution. +class Solution2 { +public: + vector intersection(vector& nums1, vector& nums2) { + if (nums1.size() > nums2.size()) { + return intersection(nums2, nums1); + } + + // Make sure it is sorted, doesn't count in time. + sort(nums1.begin(), nums1.end()); + sort(nums2.begin(), nums2.end()); + + vector result; + auto it = nums2.cbegin(); + for (const auto& i : nums1) { + it = lower_bound(it, nums2.cend(), i); + if (it != nums2.end() && *it == i) { + result.emplace_back(*it); + it = upper_bound(it, nums2.cend(), i); + } + } + + return result; + } +}; + + // Time: O(max(m, n) * log(max(m, n))) // Space: O(1) // Two pointers solution. -class Solution2 { +class Solution3 { public: vector intersection(vector& nums1, vector& nums2) { vector result; From 0731aa4dcd593f920d3758080b1760973a764413 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 13:53:21 +0800 Subject: [PATCH 2312/4971] Update intersection-of-two-arrays.py --- Python/intersection-of-two-arrays.py | 37 +++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/Python/intersection-of-two-arrays.py b/Python/intersection-of-two-arrays.py index af8e57382..ee1ad5976 100644 --- a/Python/intersection-of-two-arrays.py +++ b/Python/intersection-of-two-arrays.py @@ -34,10 +34,45 @@ def intersection(self, nums1, nums2): return res +# Time: O(min(m, n) * log(max(m, n))) +# Space: O(1) +# Binary search solution. +class Solution2(object): + def intersection(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: List[int] + """ + if len(nums1) > len(nums2): + return self.intersection(nums2, nums1) + + def binary_search(compare, nums, left, right, target): + while left < right: + mid = left + (right - left) / 2 + if compare(nums[mid], target): + right = mid + else: + left = mid + 1 + return left + + nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time. + + res = [] + left = 0 + for i in nums1: + left = binary_search(lambda x, y: x >= y, nums2, left, len(nums2), i) + if left != len(nums2) and nums2[left] == i: + res += i, + left = binary_search(lambda x, y: x > y, nums2, left, len(nums2), i) + + return res + + # Time: O(max(m, n) * log(max(m, n))) # Space: O(1) # Two pointers solution. -class Solution2(object): +class Solution3(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] From f4295d8c822b18fd305f96504eee2d28a461cc9e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 13:57:14 +0800 Subject: [PATCH 2313/4971] Update intersection-of-two-arrays.cpp --- C++/intersection-of-two-arrays.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/intersection-of-two-arrays.cpp b/C++/intersection-of-two-arrays.cpp index abbe6d450..1ea39aeaf 100644 --- a/C++/intersection-of-two-arrays.cpp +++ b/C++/intersection-of-two-arrays.cpp @@ -24,7 +24,7 @@ class Solution { }; -// Time: O(min(m, n) * log(max(m, n))) +// Time: O(max(m, n) * log(max(m, n))) // Space: O(1) // Binary search solution. class Solution2 { From 9f3ac1768e3ac2aade769d50ac59e597b2099121 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 13:57:41 +0800 Subject: [PATCH 2314/4971] Update intersection-of-two-arrays.py --- Python/intersection-of-two-arrays.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/intersection-of-two-arrays.py b/Python/intersection-of-two-arrays.py index ee1ad5976..9388a45b1 100644 --- a/Python/intersection-of-two-arrays.py +++ b/Python/intersection-of-two-arrays.py @@ -34,7 +34,7 @@ def intersection(self, nums1, nums2): return res -# Time: O(min(m, n) * log(max(m, n))) +# Time: O(max(m, n) * log(max(m, n))) # Space: O(1) # Binary search solution. class Solution2(object): @@ -56,7 +56,7 @@ def binary_search(compare, nums, left, right, target): left = mid + 1 return left - nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time. + nums1.sort(), nums2.sort() res = [] left = 0 From e6719d7efc159225c93422f9d34db9cfcd10a63b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 13:58:16 +0800 Subject: [PATCH 2315/4971] Update intersection-of-two-arrays.cpp --- C++/intersection-of-two-arrays.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/intersection-of-two-arrays.cpp b/C++/intersection-of-two-arrays.cpp index 1ea39aeaf..a9f84bfc4 100644 --- a/C++/intersection-of-two-arrays.cpp +++ b/C++/intersection-of-two-arrays.cpp @@ -34,7 +34,6 @@ class Solution2 { return intersection(nums2, nums1); } - // Make sure it is sorted, doesn't count in time. sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); From c5bbcde1cbd114176cc471296116bd1cee27bdd8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 14:05:09 +0800 Subject: [PATCH 2316/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e41b9fd51..acb16882a 100644 --- a/README.md +++ b/README.md @@ -287,8 +287,8 @@ 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 | 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | -349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI | Hash -350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash +349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI | Hash, Binary Search +350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash, Binary Search ## Recursion # | Title | Solution | Time | Space | Difficulty | Tag | Note From b3a0e2a78a1c28b8741cced4f9e42da6838c702c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 14:29:56 +0800 Subject: [PATCH 2317/4971] Update copy-list-with-random-pointer.cpp --- C++/copy-list-with-random-pointer.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/C++/copy-list-with-random-pointer.cpp b/C++/copy-list-with-random-pointer.cpp index c730b93a2..e894b1c75 100644 --- a/C++/copy-list-with-random-pointer.cpp +++ b/C++/copy-list-with-random-pointer.cpp @@ -13,26 +13,26 @@ 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; + for (auto *curr = head; curr; curr = curr->next->next) { + auto *node = new RandomListNode(curr->label); + node->next = curr->next; + curr->next = node; } // Update random node. - for (auto *cur = head; cur; cur = cur->next->next) { - if (cur->random) { - cur->next->random = cur->random->next; + for (auto *curr = head; curr; curr = curr->next->next) { + if (curr->random) { + curr->next->random = curr->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; + RandomListNode dummy(0); + for (auto *curr = head, *copy_curr = &dummy; + curr; + copy_curr = copy_curr->next, curr = curr->next) { + copy_curr->next = curr->next; + curr->next = curr->next->next; } return dummy.next; From 80bb0e105717d18fa3b0b07e6e4a79f1ff9c789e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 14:50:40 +0800 Subject: [PATCH 2318/4971] Update reverse-linked-list.cpp --- C++/reverse-linked-list.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/reverse-linked-list.cpp b/C++/reverse-linked-list.cpp index edf8ecd92..1a71d4e1f 100644 --- a/C++/reverse-linked-list.cpp +++ b/C++/reverse-linked-list.cpp @@ -12,15 +12,15 @@ class Solution { public: ListNode* reverseList(ListNode* head) { - auto *dummy_head = new ListNode(0); + auto dummy = ListNode(0); while (head) { - auto *tmp = head->next; - head->next = dummy_head->next; - dummy_head->next = head; + auto tmp = head->next; + head->next = dummy.next; + dummy.next = head; head = tmp; } - return dummy_head->next; + return dummy.next; } }; From 8e63eaec7b8067c7f75895cf49e256dba3628302 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:00:07 +0800 Subject: [PATCH 2319/4971] Update reverse-linked-list.cpp --- C++/reverse-linked-list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/reverse-linked-list.cpp b/C++/reverse-linked-list.cpp index 1a71d4e1f..06ed186a7 100644 --- a/C++/reverse-linked-list.cpp +++ b/C++/reverse-linked-list.cpp @@ -12,7 +12,7 @@ class Solution { public: ListNode* reverseList(ListNode* head) { - auto dummy = ListNode(0); + auto dummy = ListNode{0}; while (head) { auto tmp = head->next; From eacddcd7f6f9c2e1a8ca18700730117e3d9e1d03 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:37:12 +0800 Subject: [PATCH 2320/4971] Update and rename sortList.cpp to sort-list.cpp --- C++/sort-list.cpp | 52 +++++++++++++++++++++++++++++++++++++++++ C++/sortList.cpp | 59 ----------------------------------------------- 2 files changed, 52 insertions(+), 59 deletions(-) create mode 100644 C++/sort-list.cpp delete mode 100644 C++/sortList.cpp diff --git a/C++/sort-list.cpp b/C++/sort-list.cpp new file mode 100644 index 000000000..b8baaf707 --- /dev/null +++ b/C++/sort-list.cpp @@ -0,0 +1,52 @@ +// Time: O(nlogn) +// Space: O(logn) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* sortList(ListNode* head) { + if (!head || !head->next) { + return head; + } + + auto slow = head, fast = head; + while (fast->next && fast->next->next) { + slow = slow->next; + fast = fast->next->next; + } + + // Split linked list. + fast = slow; + slow = slow->next; + fast->next = nullptr; + + return mergeTwoLists(sortList(head), sortList(slow)); + } + +private: + ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { + ListNode dummy = ListNode{0}; + auto *curr = &dummy; + + while (l1 && l2) { + if (l1->val <= l2->val) { + curr->next = l1; + l1 = l1->next; + } else { + curr->next = l2; + l2 = l2->next; + } + curr = curr->next; + } + curr->next = l1 ? l1 : l2; + + return dummy.next; + } +}; diff --git a/C++/sortList.cpp b/C++/sortList.cpp deleted file mode 100644 index da85f13f2..000000000 --- a/C++/sortList.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// Time Complexity: O(nlogn) -// 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 *sortList(ListNode *head) { - if(!head || !head->next) return head; - - ListNode *slow = head; - ListNode *fast = head; - - while(fast->next && fast->next->next) { - slow = slow->next; - fast = fast->next->next; - } - - // split linked list - fast = slow; - slow = slow->next; - fast->next = nullptr; - - return mergeList(sortList(head), sortList(slow)); // merge sorted list - } - - private: - ListNode *mergeList(ListNode *list1, ListNode *list2) { - ListNode dummy(INT_MIN); - dummy.next = nullptr; - ListNode *head = &dummy; - - for(;list1 && list2; head = head->next) { - if(list1->val <= list2->val) { - head->next = list1; - list1 = list1->next; - } - else { - head->next = list2; - list2 = list2->next; - } - } - - if(list1) { - head->next = list1; - } - else if(list2) { - head->next = list2; - } - - return dummy.next; - } -}; From 35156b69b02c74a12cdda2508ba914c06871a1f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:40:12 +0800 Subject: [PATCH 2321/4971] Update and rename insertionSortList.cpp to insertion-sort-list.cpp --- C++/insertion-sort-list.cpp | 37 ++++++++++++++++++++++++++++++++++++ C++/insertionSortList.cpp | 38 ------------------------------------- 2 files changed, 37 insertions(+), 38 deletions(-) create mode 100644 C++/insertion-sort-list.cpp delete mode 100644 C++/insertionSortList.cpp diff --git a/C++/insertion-sort-list.cpp b/C++/insertion-sort-list.cpp new file mode 100644 index 000000000..d329155e5 --- /dev/null +++ b/C++/insertion-sort-list.cpp @@ -0,0 +1,37 @@ +// Time: O(n^2) +// 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 *insertionSortList(ListNode *head) { + ListNode dummy{numeric_limits::min()}; + + auto curr = head; + ListNode *position = nullptr; + + while (curr) { + position = findInsertPosition(&dummy, curr->val); + ListNode *tmp = curr->next; + curr->next = position->next; + position->next = curr; + curr = tmp; + } + + return dummy.next; + } + + ListNode* findInsertPosition(ListNode *head, int x) { + ListNode *prev = nullptr; + for (auto curr = head; curr && curr->val <= x; + prev = curr, curr = curr->next); + return prev; + } +}; diff --git a/C++/insertionSortList.cpp b/C++/insertionSortList.cpp deleted file mode 100644 index 776d6ded6..000000000 --- a/C++/insertionSortList.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Time Complexity: O(n^2) -// 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 *insertionSortList(ListNode *head) { - ListNode dummy(INT_MIN); - - ListNode *cur = head; - ListNode *prev = NULL; - ListNode *pos = head; - - while(cur) { - pos = findInsertPos(&dummy, cur->val); - ListNode *tmp = cur->next; - cur->next = pos->next; - pos->next = cur; - cur = tmp; - } - - return dummy.next; - } - - ListNode* findInsertPos(ListNode *head, int x) { - ListNode *pre = NULL; - for (ListNode *cur = head; cur && cur->val <= x; - pre = cur, cur = cur->next); - return pre; - } -}; From 7474c18f4e494dd8eee208a2a4f9d5564f9fe441 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:41:04 +0800 Subject: [PATCH 2322/4971] Update and rename reorderList.cpp to reorder-list.cpp --- C++/reorder-list.cpp | 70 ++++++++++++++++++++++++++++++++++++++++++++ C++/reorderList.cpp | 69 ------------------------------------------- 2 files changed, 70 insertions(+), 69 deletions(-) create mode 100644 C++/reorder-list.cpp delete mode 100644 C++/reorderList.cpp diff --git a/C++/reorder-list.cpp b/C++/reorder-list.cpp new file mode 100644 index 000000000..8dc4f303f --- /dev/null +++ b/C++/reorder-list.cpp @@ -0,0 +1,70 @@ +// 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: + void reorderList(ListNode *head) { + if (!head) { + return; + } + + auto slow = head, fast = head; + + while (fast->next && fast->next->next) { + slow = slow->next; + fast = fast->next->next; + } + + // Split into two lists. + auto tmp = slow->next; + slow->next = nullptr; + slow = tmp; + + merge(head, reverse(slow)); + } + +private: + ListNode *reverse(ListNode *head) { + ListNode dummy{0}; + + while (head) { + auto tmp = head->next; + head->next = dummy.next; + dummy.next = head; + head = tmp; + } + + return dummy.next; + } + + ListNode *merge(ListNode *list1, ListNode *list2) { + ListNode dummy{0}; + auto ptr = &dummy; + + while (list1 && list2) { + auto tmp = list1->next; + + ptr->next = list1; + ptr = ptr->next; + ptr->next = list2; + ptr = ptr->next; + + list1 = tmp; + list2 = list2->next; + } + + if (list1) { + ptr->next = list1; + } + + return dummy.next; + } +}; diff --git a/C++/reorderList.cpp b/C++/reorderList.cpp deleted file mode 100644 index 7feadc471..000000000 --- a/C++/reorderList.cpp +++ /dev/null @@ -1,69 +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: - void reorderList(ListNode *head) { - if(!head) return; - - ListNode *slow = head; - ListNode *fast = head; - - while(fast->next && fast->next->next) { - slow = slow->next; - fast = fast->next->next; - } - - // split into two lists - ListNode *tmp = slow->next; - slow->next = nullptr; - slow = tmp; - - merge(head, reverse(slow)); - } - - private: - ListNode *reverse(ListNode *head) { - ListNode dummy(INT_MIN); - - while(head) { - ListNode *tmp = head->next; - - head->next = dummy.next; - dummy.next = head; - - head = tmp; - } - - return dummy.next; - } - - ListNode *merge(ListNode *list1, ListNode *list2) { - ListNode dummy(INT_MIN); - ListNode *ptr = &dummy; - - while(list1 && list2) { - ListNode *tmp = list1->next; // backup list1 next - - ptr->next = list1; - ptr = ptr->next; - ptr->next = list2; // list1 next is overwritten - ptr = ptr->next; - - list1 = tmp; - list2 = list2->next; - } - - if(list1) ptr->next = list1; // append remaining list1 - - return dummy.next; - } -}; From 3201c3087341e78f8925ea7a02c77025d6673bbe Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:42:38 +0800 Subject: [PATCH 2323/4971] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index acb16882a..a131279cc 100644 --- a/README.md +++ b/README.md @@ -261,8 +261,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/) | [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 || +147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[C++](./C++/insertion-sort-list.cpp) [Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || +148| [Sort List](https://leetcode.com/problems/sort-list/) | [C++](./C++/sort-list.cpp) [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| @@ -280,7 +280,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/)| [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 || +143| [Reorder List](https://leetcode.com/problems/reorder-list/)| [C++](./C++/reorder-list.cpp) [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 9db0f794d833f49badb39f37b05feeec69a582e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:44:13 +0800 Subject: [PATCH 2324/4971] Update reverse-nodes-in-k-group.cpp --- C++/reverse-nodes-in-k-group.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/reverse-nodes-in-k-group.cpp b/C++/reverse-nodes-in-k-group.cpp index a3d16c385..c7ee900d5 100644 --- a/C++/reverse-nodes-in-k-group.cpp +++ b/C++/reverse-nodes-in-k-group.cpp @@ -12,7 +12,7 @@ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { - ListNode dummy = ListNode(0); + ListNode dummy{0}; dummy.next = head; ListNode *cur = head, *cur_dummy = &dummy; int len = 0; From f05ca7533fcde4c94c17eb7fb220769c6ad4131b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:44:44 +0800 Subject: [PATCH 2325/4971] Update remove-linked-list-elements.cpp --- C++/remove-linked-list-elements.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/remove-linked-list-elements.cpp b/C++/remove-linked-list-elements.cpp index cbfc500f1..925e964eb 100644 --- a/C++/remove-linked-list-elements.cpp +++ b/C++/remove-linked-list-elements.cpp @@ -12,7 +12,7 @@ class Solution { public: ListNode* removeElements(ListNode* head, int val) { - auto dummy = ListNode(0); + ListNode dummy{0}; dummy.next = head; auto *prev = &dummy, *cur = dummy.next; From 83cf874ba6e53a37359646b9189ede1be46ce43a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:46:37 +0800 Subject: [PATCH 2326/4971] Update remove-duplicates-from-sorted-list-ii.cpp --- C++/remove-duplicates-from-sorted-list-ii.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/remove-duplicates-from-sorted-list-ii.cpp b/C++/remove-duplicates-from-sorted-list-ii.cpp index f7e70a2a6..5136aa0a4 100644 --- a/C++/remove-duplicates-from-sorted-list-ii.cpp +++ b/C++/remove-duplicates-from-sorted-list-ii.cpp @@ -12,18 +12,18 @@ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { - ListNode dummy = ListNode(0); - ListNode *pre = &dummy; + ListNode dummy{0}; + auto prev = &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; + prev->next = head; } else { - pre->next = head; - pre = head; + prev->next = head; + prev = head; head = head->next; } } From c5d6eb244bdf720bae30320adca0413d7322bdd3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:47:09 +0800 Subject: [PATCH 2327/4971] Update merge-two-sorted-lists.cpp --- C++/merge-two-sorted-lists.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/merge-two-sorted-lists.cpp b/C++/merge-two-sorted-lists.cpp index acd59112b..a11d16b63 100644 --- a/C++/merge-two-sorted-lists.cpp +++ b/C++/merge-two-sorted-lists.cpp @@ -12,8 +12,8 @@ class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { - ListNode dummy = ListNode(0); - auto *curr = &dummy; + ListNode dummy{0}; + auto curr = &dummy; while (l1 && l2) { if (l1->val <= l2->val) { From aac80889d1871af04d28afabf1b7ada25830150e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:48:04 +0800 Subject: [PATCH 2328/4971] Update swap-nodes-in-pairs.cpp --- C++/swap-nodes-in-pairs.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/swap-nodes-in-pairs.cpp b/C++/swap-nodes-in-pairs.cpp index 05fe77e0b..d9ae7ae75 100644 --- a/C++/swap-nodes-in-pairs.cpp +++ b/C++/swap-nodes-in-pairs.cpp @@ -12,17 +12,17 @@ class Solution { public: ListNode* swapPairs(ListNode* head) { - ListNode dummy = ListNode(0); + ListNode dummy{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; + auto curr = &dummy; + while (curr->next && curr->next->next) { + auto next_one = curr->next; + auto next_two = next_one->next; + auto next_three = next_two->next; + curr->next = next_two; next_two->next = next_one; next_one->next = next_three; - cur = next_one; + curr = next_one; } return dummy.next; } From 5c56a09cd30fa1c88232691db8d472f62ae57dcd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:55:21 +0800 Subject: [PATCH 2329/4971] Update add-two-numbers.cpp --- C++/add-two-numbers.cpp | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/C++/add-two-numbers.cpp b/C++/add-two-numbers.cpp index 800431821..1715de77e 100644 --- a/C++/add-two-numbers.cpp +++ b/C++/add-two-numbers.cpp @@ -12,26 +12,20 @@ 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; - } + ListNode dummy{0}; + auto curr = &dummy; + + auto carry = 0; + while (l1 || l2 || carry) { + auto a = l1? l1->val : 0, b = l2? l2->val : 0; + auto val = carry + a + b; + curr->next = new ListNode(val % 10); carry = val / 10; - cur->next = new ListNode(val % 10); - cur = cur->next; - } - if (carry) { - cur->next = new ListNode(carry); + l1 = l1 ? l1->next : nullptr; + l2 = l2 ? l2->next : nullptr; + curr = curr->next; } - return dummy.next; + + return dummy.next; } }; From 26a642b660dd0e505f1d4d7c850e8d3f21a07834 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:56:55 +0800 Subject: [PATCH 2330/4971] Update merge-k-sorted-lists.cpp --- C++/merge-k-sorted-lists.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/merge-k-sorted-lists.cpp b/C++/merge-k-sorted-lists.cpp index 79d149250..b508c84cf 100644 --- a/C++/merge-k-sorted-lists.cpp +++ b/C++/merge-k-sorted-lists.cpp @@ -33,8 +33,8 @@ class Solution { private: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { - ListNode dummy = ListNode(0); - auto *curr = &dummy; + ListNode dummy{0}; + auto curr = &dummy; while (l1 && l2) { if (l1->val <= l2->val) { @@ -75,8 +75,8 @@ class Solution2 { } ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { - ListNode dummy = ListNode(0); - auto *curr = &dummy; + ListNode dummy{0}; + auto curr = &dummy; while (l1 && l2) { if (l1->val <= l2->val) { From 94f7e44ae5b6f8ad710228f88b24927ccc1c12b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 15:57:18 +0800 Subject: [PATCH 2331/4971] Update sort-list.cpp --- C++/sort-list.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/sort-list.cpp b/C++/sort-list.cpp index b8baaf707..11320d427 100644 --- a/C++/sort-list.cpp +++ b/C++/sort-list.cpp @@ -32,8 +32,8 @@ class Solution { private: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { - ListNode dummy = ListNode{0}; - auto *curr = &dummy; + ListNode dummy{0}; + auto curr = &dummy; while (l1 && l2) { if (l1->val <= l2->val) { From 8e720eac670cb4e3cbce8d578fc70877ea199ad5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 18:01:39 +0800 Subject: [PATCH 2332/4971] Update reverse-nodes-in-k-group.cpp --- C++/reverse-nodes-in-k-group.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/C++/reverse-nodes-in-k-group.cpp b/C++/reverse-nodes-in-k-group.cpp index c7ee900d5..5c667d419 100644 --- a/C++/reverse-nodes-in-k-group.cpp +++ b/C++/reverse-nodes-in-k-group.cpp @@ -14,32 +14,32 @@ class Solution { ListNode* reverseKGroup(ListNode* head, int k) { ListNode dummy{0}; dummy.next = head; - ListNode *cur = head, *cur_dummy = &dummy; + auto curr = head, curr_dummy = &dummy; int len = 0; - while (cur) { - ListNode *next_cur = cur->next; + while (curr) { + auto next_curr = curr->next; len = (len + 1) % k; if (len == 0) { - ListNode *next_dummy = cur_dummy->next; - reverse(&cur_dummy, cur->next); - cur_dummy = next_dummy; + auto next_dummy = curr_dummy->next; + reverse(&curr_dummy, curr->next); + curr_dummy = next_dummy; } - cur = next_cur; + curr = next_curr; } return dummy.next; } void reverse(ListNode **begin, const ListNode *end) { ListNode *first = (*begin)->next; - ListNode *cur = first->next; + ListNode *curr = first->next; - while (cur != end) { - first->next = cur->next; - cur->next = (*begin)->next; - (*begin)->next = cur; - cur = first->next; + while (curr != end) { + first->next = curr->next; + curr->next = (*begin)->next; + (*begin)->next = curr; + curr = first->next; } } }; From 0d6569a008844c8933fc201e2d3e2e76b5d2ad9c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 18:02:30 +0800 Subject: [PATCH 2333/4971] Update rotate-list.cpp --- C++/rotate-list.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/rotate-list.cpp b/C++/rotate-list.cpp index c4dac2a4e..ba6f59d07 100644 --- a/C++/rotate-list.cpp +++ b/C++/rotate-list.cpp @@ -25,20 +25,20 @@ class Solution { } int n = 1; - ListNode *cur = head; - for (; cur->next; cur = cur->next) { + auto curr = head; + for (; curr->next; curr = curr->next) { ++n; } - cur->next = head; + curr->next = head; - ListNode *tail = cur; + auto tail = curr; k = n - k % n; - cur = head; - for (int i = 0; i < k; cur = cur->next, ++i) { - tail = cur; + curr = head; + for (int i = 0; i < k; curr = curr->next, ++i) { + tail = curr; } tail->next = nullptr; - return cur; + return curr; } }; From ec8c156dfe56a41eb801789ce6b1040d7923e8d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 18:03:51 +0800 Subject: [PATCH 2334/4971] Update odd-even-linked-list.cpp --- C++/odd-even-linked-list.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/odd-even-linked-list.cpp b/C++/odd-even-linked-list.cpp index 4c6efad0a..1897ec415 100644 --- a/C++/odd-even-linked-list.cpp +++ b/C++/odd-even-linked-list.cpp @@ -13,13 +13,13 @@ class Solution { public: ListNode* oddEvenList(ListNode* head) { if (head) { - for (ListNode *odd_tail = head, *cur = head->next; - cur && cur->next; - cur = cur->next) { + for (auto odd_tail = head, curr = head->next; + curr && curr->next; + curr = curr->next) { ListNode *even_head = odd_tail->next; - odd_tail->next = cur->next; + odd_tail->next = curr->next; odd_tail = odd_tail->next; - cur->next = odd_tail->next; + curr->next = odd_tail->next; odd_tail->next = even_head; } } From 0ab4bb2365d4cd6ff735c06b7676689bf0689dc5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Jun 2016 18:05:23 +0800 Subject: [PATCH 2335/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a131279cc..b98e2bcaa 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/) |[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` +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 | 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 | | @@ -138,7 +139,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | 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 From fbec506a7b3fbe3a6379366a8c51e614a7d28bcd Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Jun 2016 12:36:56 +0800 Subject: [PATCH 2336/4971] Update sliding-window-maximum.cpp --- C++/sliding-window-maximum.cpp | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-) diff --git a/C++/sliding-window-maximum.cpp b/C++/sliding-window-maximum.cpp index f92542a27..5960d102d 100644 --- a/C++/sliding-window-maximum.cpp +++ b/C++/sliding-window-maximum.cpp @@ -4,31 +4,20 @@ class Solution { public: vector maxSlidingWindow(vector& nums, int k) { - const int n = nums.size(); - deque q; + deque dq; vector max_numbers; - for (int i = 0; i < k; ++i) { - while (!q.empty() && nums[i] >= nums[q.back()]) { - q.pop_back(); + for (int i = 0; i < nums.size(); ++i) { + while (!dq.empty() && nums[i] >= nums[dq.back()]) { + dq.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(); + dq.emplace_back(i); + if (i >= k && !dq.empty() && dq.front() == i - k) { + dq.pop_front(); } - while (!q.empty() && q.front() <= i - k) { - q.pop_front(); + if (i >= k - 1) { + max_numbers.emplace_back(nums[dq.front()]); } - q.emplace_back(i); - } - - if (!q.empty()) { - max_numbers.emplace_back(nums[q.front()]); } return max_numbers; From af67cf3b44885c9e0a8ea79fc4334c957e2817ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Jun 2016 12:41:25 +0800 Subject: [PATCH 2337/4971] Update sliding-window-maximum.py --- Python/sliding-window-maximum.py | 43 +++++++++++++------------------- 1 file changed, 17 insertions(+), 26 deletions(-) diff --git a/Python/sliding-window-maximum.py b/Python/sliding-window-maximum.py index 1818c2a36..eeaffeedb 100644 --- a/Python/sliding-window-maximum.py +++ b/Python/sliding-window-maximum.py @@ -1,6 +1,6 @@ # 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. @@ -20,39 +20,30 @@ # 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. +# 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[]} +class Solution(object): def maxSlidingWindow(self, nums, k): - q = deque() + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + dq = 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]]) + for i in xrange(len(nums)): + while dq and nums[i] >= nums[dq[-1]]: + dq.pop() + dq.append(i) + if i >= k and dq and dq[0] <= i - k: + dq.popleft() + if i >= k - 1: + max_numbers.append(nums[dq[0]]) return max_numbers From cba75e62d9fc8c1850ea68828feb57f73f49e910 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Jun 2016 17:40:03 +0800 Subject: [PATCH 2338/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b98e2bcaa..28fce98f9 100644 --- a/README.md +++ b/README.md @@ -283,7 +283,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 143| [Reorder List](https://leetcode.com/problems/reorder-list/)| [C++](./C++/reorder-list.cpp) [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 | | +283 | [Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [C++](./C++/move-zeroes.cpp) [Python](./Python/move-zeroes.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 | 344| [Reverse String](https://leetcode.com/problems/reverse-string/) | [C++](./C++/reverse-string.cpp) [Python](./Python/reverse-string.py) | _O(n)_ | _O(1)_ | Easy | | 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | From 6a2f7320596acb80bafcc8e2b2c7314a14bcb51c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Jun 2016 17:40:40 +0800 Subject: [PATCH 2339/4971] Rename move-zeros.cpp to move-zeroes.cpp --- C++/{move-zeros.cpp => move-zeroes.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{move-zeros.cpp => move-zeroes.cpp} (100%) diff --git a/C++/move-zeros.cpp b/C++/move-zeroes.cpp similarity index 100% rename from C++/move-zeros.cpp rename to C++/move-zeroes.cpp From f7f4263c15a87b1587f5be168e71680dd82c28be Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Jun 2016 17:41:18 +0800 Subject: [PATCH 2340/4971] Update and rename move-zeros.py to move-zeroes.py --- Python/{move-zeros.py => move-zeroes.py} | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) rename Python/{move-zeros.py => move-zeroes.py} (99%) diff --git a/Python/move-zeros.py b/Python/move-zeroes.py similarity index 99% rename from Python/move-zeros.py rename to Python/move-zeroes.py index 820f2a5aa..40a30aa16 100644 --- a/Python/move-zeros.py +++ b/Python/move-zeroes.py @@ -1,6 +1,6 @@ # 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. @@ -11,7 +11,6 @@ # 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): From 84f22f1fa56c03145952d80291841d195f602cbd Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Jun 2016 17:59:30 +0800 Subject: [PATCH 2341/4971] Update move-zeroes.cpp --- C++/move-zeroes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/move-zeroes.cpp b/C++/move-zeroes.cpp index 8f984a02e..a8e0f0727 100644 --- a/C++/move-zeroes.cpp +++ b/C++/move-zeroes.cpp @@ -5,7 +5,7 @@ class Solution { public: void moveZeroes(vector& nums) { int pos = 0; - for (auto& num : nums) { + for (const auto& num : nums) { if (num) { swap(nums[pos++], num); } From e575c33f8d1da4b976917cee5ec6548a7a5c75df Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Jun 2016 18:00:01 +0800 Subject: [PATCH 2342/4971] Update move-zeroes.cpp --- C++/move-zeroes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/move-zeroes.cpp b/C++/move-zeroes.cpp index a8e0f0727..8f984a02e 100644 --- a/C++/move-zeroes.cpp +++ b/C++/move-zeroes.cpp @@ -5,7 +5,7 @@ class Solution { public: void moveZeroes(vector& nums) { int pos = 0; - for (const auto& num : nums) { + for (auto& num : nums) { if (num) { swap(nums[pos++], num); } From aab7cf9afeffd4a9b1f96c4ed0cb30bc941a4ef5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Jun 2016 23:55:43 +0800 Subject: [PATCH 2343/4971] Update zigzag-iterator.cpp --- C++/zigzag-iterator.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/zigzag-iterator.cpp b/C++/zigzag-iterator.cpp index 135c5de69..c2a470699 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.cbegin())); + q.emplace(v1.size(), v1.cbegin()); } if (!v2.empty()) { - q.emplace(make_pair(v2.size(), v2.cbegin())); + q.emplace(v2.size(), v2.cbegin()); } } @@ -17,7 +17,7 @@ class ZigzagIterator { const auto it = q.front().second; q.pop(); if (len > 1) { - q.emplace(make_pair(len - 1, it + 1)); + q.emplace(len - 1, it + 1); } return *it; } From a15a6f0607aa7dd63032d5a2b392fccdd1f78be3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Jun 2016 23:59:44 +0800 Subject: [PATCH 2344/4971] Update surrounded-regions.cpp --- C++/surrounded-regions.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/surrounded-regions.cpp b/C++/surrounded-regions.cpp index d7bfb0756..6ac13171c 100644 --- a/C++/surrounded-regions.cpp +++ b/C++/surrounded-regions.cpp @@ -10,14 +10,14 @@ class Solution { 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)); + q.emplace(i, 0); + q.emplace(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)); + q.emplace(0, j); + q.emplace(board.size() - 1, j); } + while (!q.empty()) { int i, j; tie(i, j) = q.front(); @@ -32,7 +32,7 @@ class Solution { 0 <= y && y < board[0].size() && board[x][y] == 'O') { board[x][y] = 'V'; - q.emplace(make_pair(x, y)); + q.emplace(x, y); } } } From 5d5c7a4501b20e5a169875b85d3d71ae09472428 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 00:01:18 +0800 Subject: [PATCH 2345/4971] 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 7a817a5c3..71d9f46e0 100644 --- a/C++/expression-add-operators.cpp +++ b/C++/expression-add-operators.cpp @@ -26,7 +26,7 @@ class Solution { const int& operand1, const int& operand2, vector *expr, vector *result) { if (pos == num.length() && operand1 + operand2 == target) { - result->emplace_back(move(join(*expr))); + result->emplace_back(join(*expr)); } else { int val = 0; string val_str; From 504cbf06bd4affe7d918da8052142ae792d82e66 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 00:05:47 +0800 Subject: [PATCH 2346/4971] Update 4sum.cpp --- C++/4sum.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/4sum.cpp b/C++/4sum.cpp index 5048842e2..3687abf2d 100644 --- a/C++/4sum.cpp +++ b/C++/4sum.cpp @@ -20,7 +20,7 @@ class Solution { left = j + 1, right = len - 1; while (left < right) { if (num[left] + num[right] == sum) { - res.emplace_back(move(vector{num[i], num[j], num[left], num[right]})); + res.push_back({num[i], num[j], num[left], num[right]}); ++left, --right; while (left < right && num[left] == num[left - 1]) { ++left; @@ -68,7 +68,7 @@ class Solution2 { auto c = j->second.first; auto d = j->second.second; if (b < c) { - ans.emplace_back(move(vector{num[a], num[b], num[c], num[d]})); + ans.push_back({num[a], num[b], num[c], num[d]}); } } } From 0a33eba8be22dbbe9e22094f499c50663dd749e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 01:11:08 +0800 Subject: [PATCH 2347/4971] Update summary-ranges.cpp --- C++/summary-ranges.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/summary-ranges.cpp b/C++/summary-ranges.cpp index 30b834516..b1a012967 100644 --- a/C++/summary-ranges.cpp +++ b/C++/summary-ranges.cpp @@ -14,7 +14,7 @@ class Solution { if (i < nums.size() && nums[i] == end + 1) { end = nums[i]; } else { - string range = to_string(start); + auto&& range = to_string(start); if (start != end) { range.append("->" + to_string(end)); } From d6ba7017de716c5b0f68a984e2faebde8decb851 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:02:17 +0800 Subject: [PATCH 2348/4971] Create russian-doll-envelopes.cpp --- C++/russian-doll-envelopes.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/russian-doll-envelopes.cpp diff --git a/C++/russian-doll-envelopes.cpp b/C++/russian-doll-envelopes.cpp new file mode 100644 index 000000000..5b4924b62 --- /dev/null +++ b/C++/russian-doll-envelopes.cpp @@ -0,0 +1,33 @@ +// Time: O(nlogn) +// Space: O(k), k is the max size of heights with the same width. + +class Solution { +public: + int maxEnvelopes(vector>& envelopes) { + vector result; + + sort(envelopes.begin(), envelopes.end()); + for (int i = 0; i < envelopes.size();) { + stack same_hs; + int w, h; + tie(w, h) = envelopes[i]; + while (i < envelopes.size() && envelopes[i].first == w) { + same_hs.emplace(distance(result.cbegin(), + lower_bound(result.cbegin(), result.cend(), envelopes[i++].second))); + } + int k = 0; + while (!same_hs.empty()) { + const auto target = envelopes[i - 1 - k++].second; + auto j = same_hs.top(); + same_hs.pop(); + if (j == result.size()) { + result.emplace_back(target); + } else { + result[j] = target; + } + } + } + + return result.size(); + } +}; From 3e8177a1b71eb08c571e629e9c9b9851c2dd54a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:18:08 +0800 Subject: [PATCH 2349/4971] Update russian-doll-envelopes.cpp --- C++/russian-doll-envelopes.cpp | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/C++/russian-doll-envelopes.cpp b/C++/russian-doll-envelopes.cpp index 5b4924b62..b87d06ec6 100644 --- a/C++/russian-doll-envelopes.cpp +++ b/C++/russian-doll-envelopes.cpp @@ -8,22 +8,20 @@ class Solution { sort(envelopes.begin(), envelopes.end()); for (int i = 0; i < envelopes.size();) { - stack same_hs; int w, h; tie(w, h) = envelopes[i]; + int same_count = 0; while (i < envelopes.size() && envelopes[i].first == w) { - same_hs.emplace(distance(result.cbegin(), - lower_bound(result.cbegin(), result.cend(), envelopes[i++].second))); + ++i, ++same_count; } - int k = 0; - while (!same_hs.empty()) { - const auto target = envelopes[i - 1 - k++].second; - auto j = same_hs.top(); - same_hs.pop(); - if (j == result.size()) { + + for (int j = i - 1; j >= i - same_count; --j) { + const auto target = envelopes[j].second; + auto it = lower_bound(result.begin(), result.end(), target); + if (it == result.end()) { result.emplace_back(target); } else { - result[j] = target; + *it = target; } } } From 2c8f049af856acb5d9368459f0ddb4ee558822af Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:18:52 +0800 Subject: [PATCH 2350/4971] Update russian-doll-envelopes.cpp --- C++/russian-doll-envelopes.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/russian-doll-envelopes.cpp b/C++/russian-doll-envelopes.cpp index b87d06ec6..15a832356 100644 --- a/C++/russian-doll-envelopes.cpp +++ b/C++/russian-doll-envelopes.cpp @@ -8,8 +8,7 @@ class Solution { sort(envelopes.begin(), envelopes.end()); for (int i = 0; i < envelopes.size();) { - int w, h; - tie(w, h) = envelopes[i]; + int w = envelopes[i].first; int same_count = 0; while (i < envelopes.size() && envelopes[i].first == w) { ++i, ++same_count; From bbe5ebb583bbaabce7e171c62d0d0b92a8e19992 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:20:36 +0800 Subject: [PATCH 2351/4971] Update russian-doll-envelopes.cpp --- C++/russian-doll-envelopes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/russian-doll-envelopes.cpp b/C++/russian-doll-envelopes.cpp index 15a832356..ceee6d263 100644 --- a/C++/russian-doll-envelopes.cpp +++ b/C++/russian-doll-envelopes.cpp @@ -14,7 +14,7 @@ class Solution { ++i, ++same_count; } - for (int j = i - 1; j >= i - same_count; --j) { + for (int j = i - 1; j >= i - same_count; --j) { // Insert from larger h. const auto target = envelopes[j].second; auto it = lower_bound(result.begin(), result.end(), target); if (it == result.end()) { From 2e940927574f3b88a4e9524d0343a0f6aa4e64dd Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:23:55 +0800 Subject: [PATCH 2352/4971] Update russian-doll-envelopes.cpp --- C++/russian-doll-envelopes.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/russian-doll-envelopes.cpp b/C++/russian-doll-envelopes.cpp index ceee6d263..df3aa8f45 100644 --- a/C++/russian-doll-envelopes.cpp +++ b/C++/russian-doll-envelopes.cpp @@ -1,4 +1,4 @@ -// Time: O(nlogn) +// Time: O(nlogn + nlogk) = O(nlogn) // Space: O(k), k is the max size of heights with the same width. class Solution { @@ -6,7 +6,7 @@ class Solution { int maxEnvelopes(vector>& envelopes) { vector result; - sort(envelopes.begin(), envelopes.end()); + sort(envelopes.begin(), envelopes.end()); // O(nlogn) for (int i = 0; i < envelopes.size();) { int w = envelopes[i].first; int same_count = 0; @@ -16,7 +16,7 @@ class Solution { for (int j = i - 1; j >= i - same_count; --j) { // Insert from larger h. const auto target = envelopes[j].second; - auto it = lower_bound(result.begin(), result.end(), target); + auto it = lower_bound(result.begin(), result.end(), target); // O(logk) if (it == result.end()) { result.emplace_back(target); } else { From dbf13d1cc5e38c289896a9c5dd2442a3eeb2383e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:30:33 +0800 Subject: [PATCH 2353/4971] Create russian-doll-envelopes.py --- Python/russian-doll-envelopes.py | 47 ++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/russian-doll-envelopes.py diff --git a/Python/russian-doll-envelopes.py b/Python/russian-doll-envelopes.py new file mode 100644 index 000000000..abe9c297d --- /dev/null +++ b/Python/russian-doll-envelopes.py @@ -0,0 +1,47 @@ +# Time: O(nlogn + nlogk) = O(nlogn) +# Space: O(k), k is the max size of heights with the same width. + +# You have a number of envelopes with widths and heights given +# as a pair of integers (w, h). One envelope can fit into another +# if and only if both the width and height of one envelope is greater +# than the width and height of the other envelope. +# +# What is the maximum number of envelopes can you Russian doll? +# (put one inside other) +# +# Example: +# Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number +# of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). + +class Solution(object): + def maxEnvelopes(self, envelopes): + """ + :type envelopes: max_envelopest[max_envelopest[int]] + :rtype: int + """ + def insert(target): + left, right = 0, len(result) - 1 + while left <= right: + mid = left + (right - left) / 2 + if result[mid] >= target: + right = mid - 1 + else: + left = mid + 1 + if left == len(result): + result.append(target) + else: + result[left] = target + + envelopes.sort() + result, i = [], 0 + while i < len(envelopes): + w = envelopes[i][0] + same_count = 0 + while i < len(envelopes) and envelopes[i][0] == w: + i += 1 + same_count += 1 + + for j in reversed(xrange(i-same_count, i)): # Insert from larger h. + insert(envelopes[j][1]) + + return len(result) From 01be8f7113782eaae9bfe51e6b224deea9088c22 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:32:09 +0800 Subject: [PATCH 2354/4971] Update russian-doll-envelopes.cpp --- C++/russian-doll-envelopes.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/C++/russian-doll-envelopes.cpp b/C++/russian-doll-envelopes.cpp index df3aa8f45..812f790a3 100644 --- a/C++/russian-doll-envelopes.cpp +++ b/C++/russian-doll-envelopes.cpp @@ -1,5 +1,5 @@ -// Time: O(nlogn + nlogk) = O(nlogn) -// Space: O(k), k is the max size of heights with the same width. +// Time: O(nlogn + nlogk) = O(nlogn), k is the max size of heights with the same width. +// Space: O(1) class Solution { public: @@ -8,8 +8,7 @@ class Solution { sort(envelopes.begin(), envelopes.end()); // O(nlogn) for (int i = 0; i < envelopes.size();) { - int w = envelopes[i].first; - int same_count = 0; + int w = envelopes[i].first, same_count = 0; while (i < envelopes.size() && envelopes[i].first == w) { ++i, ++same_count; } From b2c70a440d6e925a26188dec4fb7099933640262 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:33:11 +0800 Subject: [PATCH 2355/4971] Update russian-doll-envelopes.py --- Python/russian-doll-envelopes.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Python/russian-doll-envelopes.py b/Python/russian-doll-envelopes.py index abe9c297d..c0940d6e0 100644 --- a/Python/russian-doll-envelopes.py +++ b/Python/russian-doll-envelopes.py @@ -1,5 +1,5 @@ -# Time: O(nlogn + nlogk) = O(nlogn) -# Space: O(k), k is the max size of heights with the same width. +# Time: O(nlogn + nlogk) = O(nlogn), k is the max size of heights with the same width. +# Space: O(1) # You have a number of envelopes with widths and heights given # as a pair of integers (w, h). One envelope can fit into another @@ -35,8 +35,7 @@ def insert(target): envelopes.sort() result, i = [], 0 while i < len(envelopes): - w = envelopes[i][0] - same_count = 0 + w, same_count = envelopes[i][0], 0 while i < len(envelopes) and envelopes[i][0] == w: i += 1 same_count += 1 From 34c3db777fb4fb4d1cc94cb130125a388883ee4f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:35:52 +0800 Subject: [PATCH 2356/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 28fce98f9..021af4247 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-353%20%2F%20353-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-354%20%2F%20354-ff69b4.svg) -Up to date (2016-06-03), there are `336` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-07), there are `337` 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 `353` questions. +Here is the classification of all `354` 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 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | 📖 | +354| [Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes/) | [C++](./C++/russian-doll-envelopes.cpp) [Python](./Python/russian-doll-envelopes.py) | _O(nlogn)_ | _O(1)_ | Hard ||| ## Binary Search Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note From ef863a48f30087e8e791e23b08c7e267ea6ed1d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:38:56 +0800 Subject: [PATCH 2357/4971] Update russian-doll-envelopes.cpp --- C++/russian-doll-envelopes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/russian-doll-envelopes.cpp b/C++/russian-doll-envelopes.cpp index 812f790a3..bf7804f37 100644 --- a/C++/russian-doll-envelopes.cpp +++ b/C++/russian-doll-envelopes.cpp @@ -1,4 +1,4 @@ -// Time: O(nlogn + nlogk) = O(nlogn), k is the max size of heights with the same width. +// Time: O(nlogn + nlogk) = O(nlogn), k is the length of the result. // Space: O(1) class Solution { From c7ee9e3e8dec9ac7a1d858a6558f00c06f46b902 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 12:39:20 +0800 Subject: [PATCH 2358/4971] Update russian-doll-envelopes.py --- Python/russian-doll-envelopes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/russian-doll-envelopes.py b/Python/russian-doll-envelopes.py index c0940d6e0..ddc07aca7 100644 --- a/Python/russian-doll-envelopes.py +++ b/Python/russian-doll-envelopes.py @@ -1,4 +1,4 @@ -# Time: O(nlogn + nlogk) = O(nlogn), k is the max size of heights with the same width. +# Time: O(nlogn + nlogk) = O(nlogn), k is the length of the result. # Space: O(1) # You have a number of envelopes with widths and heights given From cbb58ceaaa4460713e914fb9d23c1f453f83ea1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 17:52:36 +0800 Subject: [PATCH 2359/4971] Update russian-doll-envelopes.cpp --- C++/russian-doll-envelopes.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/russian-doll-envelopes.cpp b/C++/russian-doll-envelopes.cpp index bf7804f37..8c3ec033a 100644 --- a/C++/russian-doll-envelopes.cpp +++ b/C++/russian-doll-envelopes.cpp @@ -8,7 +8,8 @@ class Solution { sort(envelopes.begin(), envelopes.end()); // O(nlogn) for (int i = 0; i < envelopes.size();) { - int w = envelopes[i].first, same_count = 0; + const auto w = envelopes[i].first; + int same_count = 0; while (i < envelopes.size() && envelopes[i].first == w) { ++i, ++same_count; } From 4029757ae72e08a7bcc4dbeb4ab8e6f60404fdf9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 17:53:41 +0800 Subject: [PATCH 2360/4971] Update russian-doll-envelopes.cpp --- C++/russian-doll-envelopes.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/russian-doll-envelopes.cpp b/C++/russian-doll-envelopes.cpp index 8c3ec033a..c7b2cc74b 100644 --- a/C++/russian-doll-envelopes.cpp +++ b/C++/russian-doll-envelopes.cpp @@ -9,7 +9,7 @@ class Solution { sort(envelopes.begin(), envelopes.end()); // O(nlogn) for (int i = 0; i < envelopes.size();) { const auto w = envelopes[i].first; - int same_count = 0; + auto same_count = 0; while (i < envelopes.size() && envelopes[i].first == w) { ++i, ++same_count; } From bbac9eb9f9ff300c0cd9c675ba808a2450b997b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 22:37:31 +0800 Subject: [PATCH 2361/4971] Update russian-doll-envelopes.py --- Python/russian-doll-envelopes.py | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/Python/russian-doll-envelopes.py b/Python/russian-doll-envelopes.py index ddc07aca7..37049b0f4 100644 --- a/Python/russian-doll-envelopes.py +++ b/Python/russian-doll-envelopes.py @@ -16,7 +16,7 @@ class Solution(object): def maxEnvelopes(self, envelopes): """ - :type envelopes: max_envelopest[max_envelopest[int]] + :type envelopes: List[List[int]] :rtype: int """ def insert(target): @@ -32,15 +32,9 @@ def insert(target): else: result[left] = target - envelopes.sort() + envelopes.sort(lambda x, y: y[1] - x[1] if x[0] == y[0] \ + else x[0] - y[0]) result, i = [], 0 - while i < len(envelopes): - w, same_count = envelopes[i][0], 0 - while i < len(envelopes) and envelopes[i][0] == w: - i += 1 - same_count += 1 - - for j in reversed(xrange(i-same_count, i)): # Insert from larger h. - insert(envelopes[j][1]) - + for envelope in envelopes: + insert(envelope[1]) return len(result) From ca5bc5d32f6ee10fec90520a0eb9dd9f0ff006d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 22:42:58 +0800 Subject: [PATCH 2362/4971] Update russian-doll-envelopes.cpp --- C++/russian-doll-envelopes.cpp | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/C++/russian-doll-envelopes.cpp b/C++/russian-doll-envelopes.cpp index c7b2cc74b..f1c3aa3f9 100644 --- a/C++/russian-doll-envelopes.cpp +++ b/C++/russian-doll-envelopes.cpp @@ -6,22 +6,20 @@ class Solution { int maxEnvelopes(vector>& envelopes) { vector result; - sort(envelopes.begin(), envelopes.end()); // O(nlogn) - for (int i = 0; i < envelopes.size();) { - const auto w = envelopes[i].first; - auto same_count = 0; - while (i < envelopes.size() && envelopes[i].first == w) { - ++i, ++same_count; - } - - for (int j = i - 1; j >= i - same_count; --j) { // Insert from larger h. - const auto target = envelopes[j].second; - auto it = lower_bound(result.begin(), result.end(), target); // O(logk) - if (it == result.end()) { - result.emplace_back(target); - } else { - *it = target; + sort(envelopes.begin(), envelopes.end(), // O(nlogn) + [](const pair& a, const pair& b) { + if (a.first == b.first) { + return a.second > b.second; } + return a.first < b.first; + }); + for (const auto& envelope : envelopes) { + const auto target = envelope.second; + auto it = lower_bound(result.begin(), result.end(), target); // O(logk) + if (it == result.end()) { + result.emplace_back(target); + } else { + *it = target; } } From aeb6741424c79a536575a510749e97bd5caee271 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Jun 2016 22:50:28 +0800 Subject: [PATCH 2363/4971] Update russian-doll-envelopes.py --- Python/russian-doll-envelopes.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Python/russian-doll-envelopes.py b/Python/russian-doll-envelopes.py index 37049b0f4..2f695b9c4 100644 --- a/Python/russian-doll-envelopes.py +++ b/Python/russian-doll-envelopes.py @@ -32,9 +32,11 @@ def insert(target): else: result[left] = target - envelopes.sort(lambda x, y: y[1] - x[1] if x[0] == y[0] \ - else x[0] - y[0]) - result, i = [], 0 + result = [] + + envelopes.sort(lambda x, y: y[1] - x[1] if x[0] == y[0] else \ + x[0] - y[0]) for envelope in envelopes: insert(envelope[1]) + return len(result) From 63adca5ffaf0d7df08f56580c2bc4252e2e43a9d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 9 Jun 2016 18:53:41 +0800 Subject: [PATCH 2364/4971] Create max-points-on-a-line.cpp --- C++/max-points-on-a-line.cpp | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C++/max-points-on-a-line.cpp diff --git a/C++/max-points-on-a-line.cpp b/C++/max-points-on-a-line.cpp new file mode 100644 index 000000000..816321f52 --- /dev/null +++ b/C++/max-points-on-a-line.cpp @@ -0,0 +1,44 @@ +// Time: O(n^2) +// Space: O(n) + +/** + * Definition for a point. + * struct Point { + * int x; + * int y; + * Point() : x(0), y(0) {} + * Point(int a, int b) : x(a), y(b) {} + * }; + */ +class Solution { +public: + int maxPoints(vector& points) { + int max_points = 0; + for (int i = 0; i < points.size(); ++i) { + unordered_map slope_count; + const auto& start = points[i]; + int same = 1; + + for (int j = i + 1; j < points.size(); ++j) { + const auto& end = points[j]; + if (start.x == end.x && start.y == end.y) { + ++same; + } else { + auto slope = numeric_limits::max(); + if (start.x - end.x != 0) { + slope = (start.y - end.y) * 1.0 / (start.x - end.x); + } + ++slope_count[slope]; + } + } + + int current_max = same; + for (const auto& kvp : slope_count) { + current_max = max(current_max, kvp.second + same); + } + max_points = max(max_points, current_max); + } + + return max_points; + } +}; From cc58a355d33273edc7f7026f52e6cf9b826637a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 9 Jun 2016 18:54:37 +0800 Subject: [PATCH 2365/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 021af4247..ef1b9a07b 100644 --- a/README.md +++ b/README.md @@ -197,7 +197,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 36| [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || 49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [C++](./C++/anagrams.cpp) [Python](./Python/anagrams.py) | _O(n * glogg)_ | _O(n)_ | Medium || 76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [C++](./C++/minimum-window-substring.cpp) [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 || +149| [Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) | [C++](./C++/max-points-on-a-line.cpp) [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/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _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 || From 97aaccb08df452f85d1e01b19187b44bc4b24b48 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 10 Jun 2016 00:52:26 -0500 Subject: [PATCH 2366/4971] Update min-stack.cpp --- C++/min-stack.cpp | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/C++/min-stack.cpp b/C++/min-stack.cpp index ede5da4a5..3f59d21a3 100644 --- a/C++/min-stack.cpp +++ b/C++/min-stack.cpp @@ -55,16 +55,12 @@ class MinStack2 { } void pop() { - if (!elements_.empty()) { - if (!cached_min_with_count_.empty() && - cached_min_with_count_.top().first == elements_.top()) { - if (--cached_min_with_count_.top().second == 0) { - cached_min_with_count_.pop(); - } + if (cached_min_with_count_.top().first == elements_.top()) { + if (--cached_min_with_count_.top().second == 0) { + cached_min_with_count_.pop(); } - auto number = elements_.top(); - elements_.pop(); } + elements_.pop(); } int top() { @@ -72,9 +68,7 @@ class MinStack2 { } int getMin() { - if (!cached_min_with_count_.empty()) { - return cached_min_with_count_.top().first; - } + return cached_min_with_count_.top().first; } private: From e0d022063e89eac5d646e17d5941ef9429817f5e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 13:13:30 +0800 Subject: [PATCH 2367/4971] Update maximal-rectangle.cpp --- C++/maximal-rectangle.cpp | 47 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/C++/maximal-rectangle.cpp b/C++/maximal-rectangle.cpp index 240cd6f70..c3fccafcb 100644 --- a/C++/maximal-rectangle.cpp +++ b/C++/maximal-rectangle.cpp @@ -1,7 +1,52 @@ // Time: O(m * n) // Space: O(n) +// Increasing stack solution. class Solution { +public: + int maximalRectangle(vector > &matrix) { + if (matrix.empty() || matrix[0].empty()) { + return 0; + } + + int res = 0; + vector height(matrix[0].size(), 0); + for (int i = 0; i < matrix.size(); ++i) { + for (int j = 0; j < matrix[0].size(); ++j) { + height[j] = matrix[i][j] == '1' ? height[j] + 1: 0; + } + res = max(res, largestRectangleArea(height)); + } + + return res; + } + +private: + int largestRectangleArea(const vector &height) { + stack increasing_height; + int max_area = 0; + + for (int i = 0; i <= height.size();) { + if (increasing_height.empty() || + (i < height.size() && height[i] > height[increasing_height.top()])) { + increasing_height.emplace(i); + ++i; + } else { + auto h = height[increasing_height.top()]; + increasing_height.pop(); + auto left = increasing_height.empty() ? -1 : increasing_height.top(); + max_area = max(max_area, h * (i - left - 1)); + } + } + + return max_area; + } +}; + +// Time: O(m * n) +// Space: O(n) +// DP solution. +class Solution2 { public: int maximalRectangle(vector > &matrix) { if (matrix.empty()) { @@ -13,7 +58,7 @@ class Solution { 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]. + vector R(n, n); // Right open bound of all ones rectangle include matrix[i][j]. for (int i = 0; i < m; ++i) { int left = 0, right = n; From 685469f0ac8573493abc47a1ae03718bb4d3557d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 13:27:19 +0800 Subject: [PATCH 2368/4971] Update maximal-rectangle.cpp --- C++/maximal-rectangle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/maximal-rectangle.cpp b/C++/maximal-rectangle.cpp index c3fccafcb..fd94cf0b2 100644 --- a/C++/maximal-rectangle.cpp +++ b/C++/maximal-rectangle.cpp @@ -13,7 +13,7 @@ class Solution { vector height(matrix[0].size(), 0); for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[0].size(); ++j) { - height[j] = matrix[i][j] == '1' ? height[j] + 1: 0; + height[j] = matrix[i][j] == '1' ? height[j] + 1 : 0; } res = max(res, largestRectangleArea(height)); } From 6328d4ed041389eff11c53d1fad8946da3a48f4b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 13:29:36 +0800 Subject: [PATCH 2369/4971] Update and rename largestRectangleArea.cpp to largest-rectangle-in-histogram.cpp --- C++/largest-rectangle-in-histogram.cpp | 25 +++++++++++++++++++++++++ C++/largestRectangleArea.cpp | 25 ------------------------- 2 files changed, 25 insertions(+), 25 deletions(-) create mode 100644 C++/largest-rectangle-in-histogram.cpp delete mode 100644 C++/largestRectangleArea.cpp diff --git a/C++/largest-rectangle-in-histogram.cpp b/C++/largest-rectangle-in-histogram.cpp new file mode 100644 index 000000000..42ca352da --- /dev/null +++ b/C++/largest-rectangle-in-histogram.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int largestRectangleArea(vector& heights) { + stack increasing_heights; + int max_area = 0; + + for (int i = 0; i <= heights.size();) { + if (increasing_heights.empty() || + (i < heights.size() && heights[i] > heights[increasing_heights.top()])) { + increasing_heights.emplace(i); + ++i; + } else { + auto h = heights[increasing_heights.top()]; + increasing_heights.pop(); + auto left = increasing_heights.empty() ? -1 : increasing_heights.top(); + max_area = max(max_area, h * (i - left - 1)); + } + } + + return max_area; + } +}; diff --git a/C++/largestRectangleArea.cpp b/C++/largestRectangleArea.cpp deleted file mode 100644 index 584336bd0..000000000 --- a/C++/largestRectangleArea.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(n) - -Solution { - public: - int largestRectangleArea(vector &height) { - const int n = height.size(); - stack s; - int ans = 0; - if(n == 0) return 0; - - height.push_back(0); - - for(int i = 0; i < n + 1;) { - if(s.empty() || height[s.top()] < height[i]) - s.push(i++); - else { - int tmp = s.top(); - s.pop(); - ans = max(ans, height[tmp] * (s.empty()? i : i - s.top() - 1)); - } - } - return ans; - } -}; From a3fe7d48218ad5544836731752e4b32e3a9815fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 13:33:49 +0800 Subject: [PATCH 2370/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ef1b9a07b..0e4112d1f 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || 32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./C++/longest-valid-parentheses.cpp) [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || 71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./C++/simplify-path.cpp) [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || +84| [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | [C++](./C++/largest-rectangle-in-histogram.cpp) [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Ascending Stack, DP +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 | EPI | Ascending Stack 101| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./C++/symmetric-tree.cpp) [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || 150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [C++](./C++/evaluate-reverse-polish-notation.cpp) [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || 155| [Min Stack](https://leetcode.com/problems/min-stack/) | [C++](./C++/min-stack.cpp) [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || @@ -417,7 +419,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/)| [C++](./C++/maximal-rectangle.cpp) [Python](./Python/maximal-rectangle.py)| _O(m * n)_ | _O(n)_ | Hard | EPI | 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/) | [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 @@ -452,7 +453,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/)| [C++](./C++/candy.cpp) [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || From 2771d4290c14f40daf115f1cbc5fb3bc312130c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 13:41:04 +0800 Subject: [PATCH 2371/4971] Update maximal-rectangle.py --- Python/maximal-rectangle.py | 48 +++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/Python/maximal-rectangle.py b/Python/maximal-rectangle.py index f667a4de2..85420c608 100644 --- a/Python/maximal-rectangle.py +++ b/Python/maximal-rectangle.py @@ -1,14 +1,52 @@ # Time: O(n^2) # Space: O(n) -# + # Given a 2D binary matrix filled with 0's and 1's, # find the largest rectangle containing all ones and return its area. -# -class Solution: - # @param matrix, a list of lists of 1 length string - # @return an integer +# Ascending stack solution. +class Solution(object): + def maximalRectangle(self, matrix): + """ + :type matrix: List[List[str]] + :rtype: int + """ + def largestRectangleArea(heights): + increasing, area, i = [], 0, 0 + while i <= len(heights): + if not increasing or (i < len(heights) and heights[i] > heights[increasing[-1]]): + increasing.append(i) + i += 1 + else: + last = increasing.pop() + if not increasing: + area = max(area, heights[last] * i) + else: + area = max(area, heights[last] * (i - increasing[-1] - 1 )) + return area + + if not matrix: + return 0 + + result = 0 + heights = [0] * len(matrix[0]) + for i in xrange(len(matrix)): + for j in xrange(len(matrix[0])): + heights[j] = heights[j] + 1 if matrix[i][j] == '1' else 0 + result = max(result, largestRectangleArea(heights)) + + return result + + +# Time: O(n^2) +# Space: O(n) +# DP solution. +class Solution2(object): def maximalRectangle(self, matrix): + """ + :type matrix: List[List[str]] + :rtype: int + """ if not matrix: return 0 From 0c316fe0d5a80f6c5609a43fb66470ce792adc7a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 13:42:08 +0800 Subject: [PATCH 2372/4971] Update maximal-rectangle.cpp --- C++/maximal-rectangle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/maximal-rectangle.cpp b/C++/maximal-rectangle.cpp index fd94cf0b2..1f127f593 100644 --- a/C++/maximal-rectangle.cpp +++ b/C++/maximal-rectangle.cpp @@ -1,7 +1,7 @@ // Time: O(m * n) // Space: O(n) -// Increasing stack solution. +// Ascending stack solution. class Solution { public: int maximalRectangle(vector > &matrix) { From 3fb6a8d559087609577b1388e430b660c04454f4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 18:50:52 +0800 Subject: [PATCH 2373/4971] Create design-twitter.cpp --- C++/design-twitter.cpp | 83 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 C++/design-twitter.cpp diff --git a/C++/design-twitter.cpp b/C++/design-twitter.cpp new file mode 100644 index 000000000..6c8c42782 --- /dev/null +++ b/C++/design-twitter.cpp @@ -0,0 +1,83 @@ +// Time: O(nlogf), n is most recently number of tweets, +// f is the number of followings. +// Space: O(u + t + r), u is the number of users, +// t is the total number of tweets, +// r is the number of followings. + +class Twitter { +public: + /** Initialize your data structure here. */ + Twitter() : time_(0) { + + } + + /** Compose a new tweet. */ + void postTweet(int userId, int tweetId) { + messages_[userId].emplace_back(make_pair(++time_, tweetId)); + } + + /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ + vector getNewsFeed(int userId) { + using RIT = deque>::reverse_iterator; + priority_queue> heap; + + if (messages_[userId].size()) { + heap.emplace(make_tuple(messages_[userId].rbegin()->first, + messages_[userId].rbegin(), + messages_[userId].rend())); + } + for (const auto& id : followings_[userId]) { + if (messages_[id].size()) { + heap.emplace(make_tuple(messages_[id].rbegin()->first, + messages_[id].rbegin(), + messages_[id].rend())); + } + } + vector res; + while (!heap.empty() && res.size() < number_of_most_recent_tweets_) { + const auto& top = heap.top(); + size_t t; + RIT begin, end; + tie(t, begin, end) = top; + heap.pop(); + + auto next = begin + 1; + if (next != end) { + heap.emplace(make_tuple(next->first, next, end)); + } + + res.emplace_back(begin->second); + } + return res; + } + + /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ + void follow(int followerId, int followeeId) { + if (followerId != followeeId && !followings_[followerId].count(followeeId)) { + followings_[followerId].emplace(followeeId); + } + } + + /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ + void unfollow(int followerId, int followeeId) { + if (followings_[followerId].count(followeeId)) { + followings_[followerId].erase(followeeId); + } + } + +private: + const size_t number_of_most_recent_tweets_ = 10; + unordered_map> followings_; + unordered_map>> messages_; + size_t time_; +}; + +/** + * Your Twitter object will be instantiated and called as such: + * Twitter obj = new Twitter(); + * obj.postTweet(userId,tweetId); + * vector param_2 = obj.getNewsFeed(userId); + * obj.follow(followerId,followeeId); + * obj.unfollow(followerId,followeeId); + */ + From 0a17117e4027a744b311b379815808fe7a825dfd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 19:08:32 +0800 Subject: [PATCH 2374/4971] Create line-reflection.cpp --- C++/line-reflection.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/line-reflection.cpp diff --git a/C++/line-reflection.cpp b/C++/line-reflection.cpp new file mode 100644 index 000000000..6f7354597 --- /dev/null +++ b/C++/line-reflection.cpp @@ -0,0 +1,29 @@ +// Time: O(nlogn) +// Space: O(1) + +class Solution { +public: + bool isReflected(vector>& points) { + if (points.empty()) { + return true; + } + sort(points.begin(), points.end()); + sort(points.begin(), points.begin() + distance(points.begin(), points.end()) / 2, + [](const pair& a, const pair& b) { + if (a.first == b.first) { + return a.second > b.second; + } + return a.first < b.first; + }); + + const auto mid = points.front().first + (points.back().first - points.front().first) / 2.0; + for (int left = 0, right = points.size() - 1; left <= right; ++left, --right) { + if ((mid != points[left].first + (points[right].first - points[left].first) / 2.0) || + (points[left].first != points[right].first && + points[left].second != points[right].second)) { + return false; + } + } + return true; + } +}; From 8527281d4611b031de4a18bdd8fed59e4503117d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 19:15:26 +0800 Subject: [PATCH 2375/4971] Update README.md --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0e4112d1f..64bab1a88 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-354%20%2F%20354-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-356%20%2F%20356-ff69b4.svg) -Up to date (2016-06-07), there are `337` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-11), there are `339` 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 `354` questions. +Here is the classification of all `356` 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. ) @@ -291,6 +291,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | 349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI | Hash, Binary Search 350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash, Binary Search +356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(nlogn)_| _O(n)_| Medium |📖| Hash | ## Recursion # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -461,12 +462,13 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 +## Design # | 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 || 348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_| _O(n^2)_| Medium |📖|| 353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(s)_| _O(s)_| Medium |📖| Deque | +355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.cpp) | _O(nlogf)_| _O(u + t + r)_| Hard | LintCode | Heap | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From f1f95f2c574041b931c620ad021a59bb02f95b4b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 06:26:41 -0500 Subject: [PATCH 2376/4971] Update line-reflection.cpp --- C++/line-reflection.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/line-reflection.cpp b/C++/line-reflection.cpp index 6f7354597..d6b1c825c 100644 --- a/C++/line-reflection.cpp +++ b/C++/line-reflection.cpp @@ -16,9 +16,9 @@ class Solution { return a.first < b.first; }); - const auto mid = points.front().first + (points.back().first - points.front().first) / 2.0; + const auto mid = points.front().first + points.back().first; for (int left = 0, right = points.size() - 1; left <= right; ++left, --right) { - if ((mid != points[left].first + (points[right].first - points[left].first) / 2.0) || + if ((mid != points[left].first + points[right].first) || (points[left].first != points[right].first && points[left].second != points[right].second)) { return false; From ddb06dd8a3e3a86a0b8d7441cdf92b1518578197 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 06:58:40 -0500 Subject: [PATCH 2377/4971] Update line-reflection.cpp --- C++/line-reflection.cpp | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/C++/line-reflection.cpp b/C++/line-reflection.cpp index d6b1c825c..17fb8afce 100644 --- a/C++/line-reflection.cpp +++ b/C++/line-reflection.cpp @@ -1,7 +1,37 @@ -// Time: O(nlogn) -// Space: O(1) +// Time: O(n) +// Space: O(n) +// Hash solution. class Solution { +public: + bool isReflected(vector>& points) { + if (points.empty()) { + return true; + } + unordered_map> groups_by_y; + int left = numeric_limits::max(); + int right = numeric_limits::min(); + for (const auto& p : points) { + groups_by_y[p.second].emplace(p.first); + left = min(left, p.first); + right = max(right, p.first); + } + const auto mid = left + right; + for (const auto& kvp : groups_by_y) { + for (const auto& x : kvp.second) { + if (2 * x != mid && kvp.second.count(mid - x) == 0) { + return false; + } + } + } + return true; + } +}; + +// Time: O(nlogn) +// Space: O(1) +// Two pointers solution. +class Solution2 { public: bool isReflected(vector>& points) { if (points.empty()) { From c07511ed73be5cab8e4bcf6cc30f840e6479eb3e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 07:00:05 -0500 Subject: [PATCH 2378/4971] Update line-reflection.cpp --- C++/line-reflection.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/line-reflection.cpp b/C++/line-reflection.cpp index 17fb8afce..d98f4114c 100644 --- a/C++/line-reflection.cpp +++ b/C++/line-reflection.cpp @@ -19,7 +19,7 @@ class Solution { const auto mid = left + right; for (const auto& kvp : groups_by_y) { for (const auto& x : kvp.second) { - if (2 * x != mid && kvp.second.count(mid - x) == 0) { + if (x != mid - x && kvp.second.count(mid - x) == 0) { return false; } } From 0ee836b4ff1cde2af72056e8672de94690c5f32a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 20:03:57 +0800 Subject: [PATCH 2379/4971] Update line-reflection.cpp --- C++/line-reflection.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/line-reflection.cpp b/C++/line-reflection.cpp index d98f4114c..986d8f904 100644 --- a/C++/line-reflection.cpp +++ b/C++/line-reflection.cpp @@ -19,7 +19,7 @@ class Solution { const auto mid = left + right; for (const auto& kvp : groups_by_y) { for (const auto& x : kvp.second) { - if (x != mid - x && kvp.second.count(mid - x) == 0) { + if (kvp.second.count(mid - x) == 0) { return false; } } From 9c385f4a128572ed023276ab44c9e0fd29be81fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 20:34:38 +0800 Subject: [PATCH 2380/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 64bab1a88..aaa4abb8c 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,7 @@ 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 | 📖 | 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 | | | 340| [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-k-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| +356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(nlogn)_| _O(n)_| Medium |📖| Hash, Two Pointers | ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -291,7 +292,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | 349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI | Hash, Binary Search 350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash, Binary Search -356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(nlogn)_| _O(n)_| Medium |📖| Hash | ## Recursion # | Title | Solution | Time | Space | Difficulty | Tag | Note From 34b5cb8bc990149c836c4c5fcb80c6dd11a47b9d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 20:34:57 +0800 Subject: [PATCH 2381/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index aaa4abb8c..bee289f38 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ 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 | 📖 | 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 | | | 340| [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-k-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| -356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(nlogn)_| _O(n)_| Medium |📖| Hash, Two Pointers | +356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(n)_| _O(n)_| Medium |📖| Hash, Two Pointers | ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note From 1bd7e4fc7ee6bfb1868b4a2e71a14b4586d020af Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 20:40:23 +0800 Subject: [PATCH 2382/4971] Create line-reflection.py --- Python/line-reflection.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Python/line-reflection.py diff --git a/Python/line-reflection.py b/Python/line-reflection.py new file mode 100644 index 000000000..b5106a13b --- /dev/null +++ b/Python/line-reflection.py @@ -0,0 +1,23 @@ +# Time: O(n) +# Space: O(n) + +# Hash solution. +class Solution(object): + def isReflected(self, points): + """ + :type points: List[List[int]] + :rtype: bool + """ + if not points: + return True + groups_by_y = collections.defaultdict(set) + left, right = float("inf"), float("-inf") + for p in points: + groups_by_y[p[1]].add(p[0]) + left, right = min(left, p[0]), max(right, p[0]) + mid = left + right + for group in groups_by_y.values(): + for x in group: + if mid - x not in group: + return False + return True From ab0cec7e575c91797674a19899ab70e4d4222846 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 20:53:14 +0800 Subject: [PATCH 2383/4971] Update line-reflection.py --- Python/line-reflection.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Python/line-reflection.py b/Python/line-reflection.py index b5106a13b..af6c76405 100644 --- a/Python/line-reflection.py +++ b/Python/line-reflection.py @@ -21,3 +21,30 @@ def isReflected(self, points): if mid - x not in group: return False return True + + +# Time: O(nlogn) +# Space: O(n) +# Hash solution. +class Solution2(object): + def isReflected(self, points): + """ + :type points: List[List[int]] + :rtype: bool + """ + if not points: + return True + points.sort() + points[len(points)/2:] = sorted(points[len(points)/2:], \ # Space: O(n) + lambda x, y: y[1] - x[1] if x[0] == y[0] else \ + x[0] - y[0]) + mid = points[0][0] + points[-1][0] + left, right = 0, len(points) - 1 + while left <= right: + if (mid != points[left][0] + points[right][0]) or \ + (points[left][0] != points[right][0] and \ + points[left][1] != points[right][1]): + return False + left += 1 + right -= 1 + return True From 44ef8bb86b907245b1cc29b7f2454a33a1ceaabd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 20:53:51 +0800 Subject: [PATCH 2384/4971] Update line-reflection.py --- Python/line-reflection.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/line-reflection.py b/Python/line-reflection.py index af6c76405..c1f3c8efa 100644 --- a/Python/line-reflection.py +++ b/Python/line-reflection.py @@ -35,7 +35,8 @@ def isReflected(self, points): if not points: return True points.sort() - points[len(points)/2:] = sorted(points[len(points)/2:], \ # Space: O(n) + # Space: O(n) + points[len(points)/2:] = sorted(points[len(points)/2:], \ lambda x, y: y[1] - x[1] if x[0] == y[0] else \ x[0] - y[0]) mid = points[0][0] + points[-1][0] From 0fe9f5f931f83713436f4fb2dede5ceabb420eb3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 20:55:09 +0800 Subject: [PATCH 2385/4971] Update line-reflection.py --- Python/line-reflection.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/line-reflection.py b/Python/line-reflection.py index c1f3c8efa..f52643319 100644 --- a/Python/line-reflection.py +++ b/Python/line-reflection.py @@ -43,8 +43,8 @@ def isReflected(self, points): left, right = 0, len(points) - 1 while left <= right: if (mid != points[left][0] + points[right][0]) or \ - (points[left][0] != points[right][0] and \ - points[left][1] != points[right][1]): + (points[left][0] != points[right][0] and \ + points[left][1] != points[right][1]): return False left += 1 right -= 1 From 62ea83d6eda586d6336232a8c470357daf4aa10a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 20:55:50 +0800 Subject: [PATCH 2386/4971] Update line-reflection.py --- Python/line-reflection.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/line-reflection.py b/Python/line-reflection.py index f52643319..2d508e2e4 100644 --- a/Python/line-reflection.py +++ b/Python/line-reflection.py @@ -25,7 +25,7 @@ def isReflected(self, points): # Time: O(nlogn) # Space: O(n) -# Hash solution. +# Two pointers solution. class Solution2(object): def isReflected(self, points): """ From babce0f4bb134850e106458904d59d3cf415f60a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 21:45:58 +0800 Subject: [PATCH 2387/4971] Create design-twitter.py --- Python/design-twitter.py | 77 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Python/design-twitter.py diff --git a/Python/design-twitter.py b/Python/design-twitter.py new file mode 100644 index 000000000..6f0f23efb --- /dev/null +++ b/Python/design-twitter.py @@ -0,0 +1,77 @@ +# Time: O(nlogf), n is most recently number of tweets, +# f is the number of followings. +# Space: O(u + t + r), u is the number of users, +# t is the total number of tweets, +# r is the number of followings. + +class Twitter(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.__number_of_most_recent_tweets = 10 + self.__followings = collections.defaultdict(set) + self.__messages = collections.defaultdict(list) + self.__time = 0 + + def postTweet(self, userId, tweetId): + """ + Compose a new tweet. + :type userId: int + :type tweetId: int + :rtype: void + """ + self.__time += 1 + self.__messages[userId].append((self.__time, tweetId)) + + + def getNewsFeed(self, userId): + """ + Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. + :type userId: int + :rtype: List[int] + """ + max_heap = [] + if self.__messages[userId]: + heapq.heappush(max_heap, (-self.__messages[userId][-1][0], userId, 0, len(self.__messages[userId]))) + for id in self.__followings[userId]: + if self.__messages[id]: + heapq.heappush(max_heap, (-self.__messages[id][-1][0], id, 0, len(self.__messages[id]))) + + result = [] + while max_heap and len(result) < self.__number_of_most_recent_tweets: + t, id, curr, end = heapq.heappop(max_heap) + nxt = curr + 1; + print t, id, curr, end + if nxt != end: + heapq.heappush(max_heap, (-self.__messages[id][-(nxt+1)][0], id, nxt, len(self.__messages[id]))) + result.append(self.__messages[id][-(curr+1)][1]); + return result + + def follow(self, followerId, followeeId): + """ + Follower follows a followee. If the operation is invalid, it should be a no-op. + :type followerId: int + :type followeeId: int + :rtype: void + """ + if followerId != followeeId: + self.__followings[followerId].add(followeeId) + + def unfollow(self, followerId, followeeId): + """ + Follower unfollows a followee. If the operation is invalid, it should be a no-op. + :type followerId: int + :type followeeId: int + :rtype: void + """ + self.__followings[followerId].discard(followeeId) + + +# Your Twitter object will be instantiated and called as such: +# obj = Twitter() +# obj.postTweet(userId,tweetId) +# param_2 = obj.getNewsFeed(userId) +# obj.follow(followerId,followeeId) +# obj.unfollow(followerId,followeeId) From a799cfe969a067ef066d28f9d6a86f11038f2680 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 21:47:06 +0800 Subject: [PATCH 2388/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bee289f38..37c79af2d 100644 --- a/README.md +++ b/README.md @@ -468,7 +468,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 284| [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [C++](./C++/peeking-iterator.cpp) [Python](./Python/peeking-iterator.py) | _O(1)_ | _O(1)_ | Medium || 348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_| _O(n^2)_| Medium |📖|| 353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(s)_| _O(s)_| Medium |📖| Deque | -355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.cpp) | _O(nlogf)_| _O(u + t + r)_| Hard | LintCode | Heap | +355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(nlogf)_| _O(u + t + r)_| Hard | LintCode | Heap | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From acb20ebdf9801eb9ae641fc81770a97772bcfe98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 21:52:01 +0800 Subject: [PATCH 2389/4971] Update design-twitter.py --- Python/design-twitter.py | 50 ++++++++++++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/Python/design-twitter.py b/Python/design-twitter.py index 6f0f23efb..f4d19958b 100644 --- a/Python/design-twitter.py +++ b/Python/design-twitter.py @@ -4,6 +4,43 @@ # t is the total number of tweets, # r is the number of followings. +# Design a simplified version of Twitter where users can post tweets, +# follow/unfollow another user and is able to see the 10 most recent +# tweets in the user's news feed. Your design should support the following methods: +# +# postTweet(userId, tweetId): Compose a new tweet. +# getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the user's +# news feed. Each item in the news feed must be posted by users who the user followed +# or by the user herself. Tweets must be ordered from most recent to least recent. +# follow(followerId, followeeId): Follower follows a followee. +# unfollow(followerId, followeeId): Follower unfollows a followee. +# Example: +# +# Twitter twitter = new Twitter(); +# +# // User 1 posts a new tweet (id = 5). +# twitter.postTweet(1, 5); +# +# // User 1's news feed should return a list with 1 tweet id -> [5]. +# twitter.getNewsFeed(1); +# +# // User 1 follows user 2. +# twitter.follow(1, 2); +# +# // User 2 posts a new tweet (id = 6). +# twitter.postTweet(2, 6); +# +# // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. +# // Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. +# twitter.getNewsFeed(1); +# +# // User 1 unfollows user 2. +# twitter.unfollow(1, 2); +# +# // User 1's news feed should return a list with 1 tweet id -> [5], +# // since user 1 is no longer following user 2. +# twitter.getNewsFeed(1); + class Twitter(object): def __init__(self): @@ -35,18 +72,17 @@ def getNewsFeed(self, userId): max_heap = [] if self.__messages[userId]: heapq.heappush(max_heap, (-self.__messages[userId][-1][0], userId, 0, len(self.__messages[userId]))) - for id in self.__followings[userId]: - if self.__messages[id]: - heapq.heappush(max_heap, (-self.__messages[id][-1][0], id, 0, len(self.__messages[id]))) + for uid in self.__followings[userId]: + if self.__messages[uid]: + heapq.heappush(max_heap, (-self.__messages[uid][-1][0], uid, 0, len(self.__messages[uid]))) result = [] while max_heap and len(result) < self.__number_of_most_recent_tweets: - t, id, curr, end = heapq.heappop(max_heap) + t, uid, curr, end = heapq.heappop(max_heap) nxt = curr + 1; - print t, id, curr, end if nxt != end: - heapq.heappush(max_heap, (-self.__messages[id][-(nxt+1)][0], id, nxt, len(self.__messages[id]))) - result.append(self.__messages[id][-(curr+1)][1]); + heapq.heappush(max_heap, (-self.__messages[uid][-(nxt+1)][0], uid, nxt, len(self.__messages[uid]))) + result.append(self.__messages[uid][-(curr+1)][1]); return result def follow(self, followerId, followeeId): From 2f37699187bc97196814e0928a74886a53091eb9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 21:53:50 +0800 Subject: [PATCH 2390/4971] Update design-twitter.py --- Python/design-twitter.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/design-twitter.py b/Python/design-twitter.py index f4d19958b..c3a017267 100644 --- a/Python/design-twitter.py +++ b/Python/design-twitter.py @@ -61,7 +61,6 @@ def postTweet(self, userId, tweetId): """ self.__time += 1 self.__messages[userId].append((self.__time, tweetId)) - def getNewsFeed(self, userId): """ From 4dc0d681d2214d54d1ad1aa75f3e01485feaa3e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 21:58:15 +0800 Subject: [PATCH 2391/4971] Update design-twitter.cpp --- C++/design-twitter.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/design-twitter.cpp b/C++/design-twitter.cpp index 6c8c42782..bf0ff7a0c 100644 --- a/C++/design-twitter.cpp +++ b/C++/design-twitter.cpp @@ -1,8 +1,8 @@ // Time: O(nlogf), n is most recently number of tweets, -// f is the number of followings. +// f is the number of user's following. // Space: O(u + t + r), u is the number of users, // t is the total number of tweets, -// r is the number of followings. +// r is the total number of followings. class Twitter { public: From afdbde1a2a664ebf5925f0a9c1eb3dfcf851577d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 21:58:54 +0800 Subject: [PATCH 2392/4971] Update design-twitter.py --- Python/design-twitter.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/design-twitter.py b/Python/design-twitter.py index c3a017267..4976ef4aa 100644 --- a/Python/design-twitter.py +++ b/Python/design-twitter.py @@ -1,8 +1,8 @@ # Time: O(nlogf), n is most recently number of tweets, -# f is the number of followings. +# f is the number of user's following. # Space: O(u + t + r), u is the number of users, # t is the total number of tweets, -# r is the number of followings. +# r is the total number of followings. # Design a simplified version of Twitter where users can post tweets, # follow/unfollow another user and is able to see the 10 most recent From db0287442f8b82fbac8a7239ef2922b57762fe41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 22:01:51 +0800 Subject: [PATCH 2393/4971] Update design-twitter.py --- Python/design-twitter.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Python/design-twitter.py b/Python/design-twitter.py index 4976ef4aa..f58775313 100644 --- a/Python/design-twitter.py +++ b/Python/design-twitter.py @@ -1,8 +1,7 @@ -# Time: O(nlogf), n is most recently number of tweets, -# f is the number of user's following. -# Space: O(u + t + r), u is the number of users, -# t is the total number of tweets, -# r is the total number of followings. +# Time: O(klogu), k is most recently number of tweets, +# u is the number of the user's following. +# Space: O(t + f), t is the total number of tweets, +# f is the total number of followings. # Design a simplified version of Twitter where users can post tweets, # follow/unfollow another user and is able to see the 10 most recent From efe8d1a39e0a1facdb91f4e0b4b67d61e0206770 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 22:02:26 +0800 Subject: [PATCH 2394/4971] Update design-twitter.cpp --- C++/design-twitter.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/C++/design-twitter.cpp b/C++/design-twitter.cpp index bf0ff7a0c..5a37925f6 100644 --- a/C++/design-twitter.cpp +++ b/C++/design-twitter.cpp @@ -1,8 +1,7 @@ -// Time: O(nlogf), n is most recently number of tweets, -// f is the number of user's following. -// Space: O(u + t + r), u is the number of users, -// t is the total number of tweets, -// r is the total number of followings. +// Time: O(klogu), k is most recently number of tweets, +// u is the number of the user's following. +// Space: O(t + f), t is the total number of tweets, +// f is the total number of followings. class Twitter { public: From 465f9bee8b10534899f3b3cd56120e343b593f34 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 22:02:55 +0800 Subject: [PATCH 2395/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 37c79af2d..ccc8c302e 100644 --- a/README.md +++ b/README.md @@ -468,7 +468,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 284| [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [C++](./C++/peeking-iterator.cpp) [Python](./Python/peeking-iterator.py) | _O(1)_ | _O(1)_ | Medium || 348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_| _O(n^2)_| Medium |📖|| 353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(s)_| _O(s)_| Medium |📖| Deque | -355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(nlogf)_| _O(u + t + r)_| Hard | LintCode | Heap | +355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_| _O(t + f)_| Hard | LintCode | Heap | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From 73ff711881475b8e18b7a569e9b6fc3e024b0119 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Jun 2016 00:19:25 +0800 Subject: [PATCH 2396/4971] Update design-twitter.py --- Python/design-twitter.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/design-twitter.py b/Python/design-twitter.py index f58775313..8fe5ee95a 100644 --- a/Python/design-twitter.py +++ b/Python/design-twitter.py @@ -69,17 +69,17 @@ def getNewsFeed(self, userId): """ max_heap = [] if self.__messages[userId]: - heapq.heappush(max_heap, (-self.__messages[userId][-1][0], userId, 0, len(self.__messages[userId]))) + heapq.heappush(max_heap, (-self.__messages[userId][-1][0], userId, 0)) for uid in self.__followings[userId]: if self.__messages[uid]: - heapq.heappush(max_heap, (-self.__messages[uid][-1][0], uid, 0, len(self.__messages[uid]))) + heapq.heappush(max_heap, (-self.__messages[uid][-1][0], uid, 0)) result = [] while max_heap and len(result) < self.__number_of_most_recent_tweets: - t, uid, curr, end = heapq.heappop(max_heap) + t, uid, curr = heapq.heappop(max_heap) nxt = curr + 1; - if nxt != end: - heapq.heappush(max_heap, (-self.__messages[uid][-(nxt+1)][0], uid, nxt, len(self.__messages[uid]))) + if nxt != len(self.__messages[uid]): + heapq.heappush(max_heap, (-self.__messages[uid][-(nxt+1)][0], uid, nxt)) result.append(self.__messages[uid][-(curr+1)][1]); return result From cad3823c77d3d165b6f37905da511080c93a677b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Jun 2016 21:00:46 -0500 Subject: [PATCH 2397/4971] Update android-unlock-patterns.cpp --- C++/android-unlock-patterns.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/android-unlock-patterns.cpp b/C++/android-unlock-patterns.cpp index 6d8de94ac..6e49d0f97 100644 --- a/C++/android-unlock-patterns.cpp +++ b/C++/android-unlock-patterns.cpp @@ -98,7 +98,7 @@ class Solution2 { const auto x1 = i / 3; const auto y1 = i % 3; for (int j = 0; j < 9; ++j) { - if (i == j or !contain(used, j)) { + if (i == j || !contain(used, j)) { continue; } const auto x2 = j / 3; From f9bd67803cef1abdb538e2c5f2a88e6deeaf93a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Jun 2016 12:04:50 +0800 Subject: [PATCH 2398/4971] Update permutations-ii.py --- Python/permutations-ii.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/Python/permutations-ii.py b/Python/permutations-ii.py index 8f1cd2889..2b98e265c 100644 --- a/Python/permutations-ii.py +++ b/Python/permutations-ii.py @@ -25,12 +25,13 @@ def permuteUniqueRecu(self, result, used, cur, 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.permuteUniqueRecu(result, used, cur, nums) - cur.pop() - used[i] = False + if used[i] or (i > 0 and nums[i-1] == nums[i] and not used[i-1]): + continue + used[i] = True + cur.append(nums[i]) + self.permuteUniqueRecu(result, used, cur, nums) + cur.pop() + used[i] = False class Solution2: # @param num, a list of integer From f5f95e13b5010c3195920bbd9191c62a59c9356c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Jun 2016 21:09:23 +0800 Subject: [PATCH 2399/4971] Update top-k-frequent-elements.cpp --- C++/top-k-frequent-elements.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/C++/top-k-frequent-elements.cpp b/C++/top-k-frequent-elements.cpp index 59292d1ca..4d724ebc0 100644 --- a/C++/top-k-frequent-elements.cpp +++ b/C++/top-k-frequent-elements.cpp @@ -22,3 +22,30 @@ class Solution { return result; } }; + +// Time: O(nlogk) +// Space: O(n) +// Heap solution. +class Solution2 { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map counts; + for (int i = 0; i < nums.size(); ++i) { + ++counts[nums[i]]; + } + priority_queue> heap; + for (auto it = counts.begin(); it != counts.end(); ++it) { + heap.emplace(-(it->second), it->first); + if (heap.size() == k + 1) { + heap.pop(); + } + } + vector result; + while (!heap.empty()) { + result.emplace_back(heap.top().second); + heap.pop(); + } + reverse(result.begin(), result.end()); + return result; + } +}; From a453434645471f44931aafbd0c356959581071c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Jun 2016 21:14:08 +0800 Subject: [PATCH 2400/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ccc8c302e..ab5043277 100644 --- a/README.md +++ b/README.md @@ -274,7 +274,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | -347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(1)_ | Medium | | Quick Select | +347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(1)_ | Medium | | Quick Select, Heap | ## Two Pointers # | Title | Solution | Time | Space | Difficulty | Tag | Note From cdeefed4d4f82b68862e07a4c554beb7f9429da1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Jun 2016 21:15:12 +0800 Subject: [PATCH 2401/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ab5043277..202fed0fd 100644 --- a/README.md +++ b/README.md @@ -274,7 +274,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | -347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(1)_ | Medium | | Quick Select, Heap | +347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(n)_ | Medium | | Quick Select, Heap | ## Two Pointers # | Title | Solution | Time | Space | Difficulty | Tag | Note From e4ae1f4367e02d45eb531be13c62bbbe03244bd2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Jun 2016 21:16:28 +0800 Subject: [PATCH 2402/4971] Update top-k-frequent-elements.cpp --- C++/top-k-frequent-elements.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/top-k-frequent-elements.cpp b/C++/top-k-frequent-elements.cpp index 4d724ebc0..dcda833a1 100644 --- a/C++/top-k-frequent-elements.cpp +++ b/C++/top-k-frequent-elements.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(n) ~ O(n^2), O(n) on average. // Space: O(n) class Solution { From ce4a883cb5976a00e0c96a46899fa5e1be108aa5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Jun 2016 21:16:42 +0800 Subject: [PATCH 2403/4971] Update top-k-frequent-elements.py --- Python/top-k-frequent-elements.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/top-k-frequent-elements.py b/Python/top-k-frequent-elements.py index 881e0c77d..bf3741127 100644 --- a/Python/top-k-frequent-elements.py +++ b/Python/top-k-frequent-elements.py @@ -1,4 +1,4 @@ -# Time: O(n) +# Time: O(n) ~ O(n^2), O(n) on average. # Space: O(n) # Given a non-empty array of integers, From 5d69f9e04ac9639d5e42a726fa17984bbecfd8aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jun 2016 09:26:33 +0800 Subject: [PATCH 2404/4971] Create count-numbers-with-unique-digits.cpp --- C++/count-numbers-with-unique-digits.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/count-numbers-with-unique-digits.cpp diff --git a/C++/count-numbers-with-unique-digits.cpp b/C++/count-numbers-with-unique-digits.cpp new file mode 100644 index 000000000..8bc95d88d --- /dev/null +++ b/C++/count-numbers-with-unique-digits.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int countNumbersWithUniqueDigits(int n) { + if (n == 0) { + return 1; + } + int count = 10; // f(1) = 10 + for (int k = 2, fk = 9; k <= n; ++k) { + // f(k) = f(k - 1) * (10 - (k - 1)) + fk *= 10 - (k - 1); + count += fk; + } + return count; // sum(f(i), i=1~n) + } +}; From 331510b3e2fbba729139fb3322e898148755e733 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jun 2016 09:33:12 +0800 Subject: [PATCH 2405/4971] Create count-numbers-with-unique-digits.py --- Python/count-numbers-with-unique-digits.py | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/count-numbers-with-unique-digits.py diff --git a/Python/count-numbers-with-unique-digits.py b/Python/count-numbers-with-unique-digits.py new file mode 100644 index 000000000..68812f89e --- /dev/null +++ b/Python/count-numbers-with-unique-digits.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(1) + +# Given an integer n, count all numbers with unique digits, x, where 0 <= x <= 10n. +# +# Example: +# Given n = 2, return 91. (The answer should be the total numbers in the range of 0 <= x <= 100, +# excluding [11,22,33,44,55,66,77,88,99,100]) +# +# Hint: +# 1. A direct way is to use the backtracking approach. +# 2. Backtracking should contains three states which are (the current number, +# number of steps to get that number and a bitmask which represent which +# number is marked as visited so far in the current number). +# Start with state (0,0,0) and count all valid number till we reach +# number of steps equals to 10n. +# 3. This problem can also be solved using a dynamic programming approach and +# some knowledge of combinatorics. +# 4. Let f(k) = count of numbers with unique digits with length equals k. +# 5. f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) +# [The first factor is 9 because a number cannot start with 0]. + +class Solution(object): + def countNumbersWithUniqueDigits(self, n): + """ + :type n: int + :rtype: int + """ + if n == 0: + return 1 + count, fk = 10, 9 + for k in xrange(2, n+1): + fk *= 10 - (k-1) + count += fk + return count From 57047d76bd4d446a4a4caa17fd6acae1cee35eac Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jun 2016 09:35:31 +0800 Subject: [PATCH 2406/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 202fed0fd..c8c557130 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-356%20%2F%20356-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-357%20%2F%20357-ff69b4.svg) -Up to date (2016-06-11), there are `339` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-12), there are `340` 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 `356` questions. +Here is the classification of all `357` 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. ) @@ -445,6 +445,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || 351| [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) | [C++](./C++/android-unlock-patterns.cpp) [Python](./Python/android-unlock-patterns.py) | _O(9^2 * 2^9)_ | _O(9 * 2^9)_ | Medium | 📖 | Backtracking | +357| [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | [C++](./C++/count-numbers-with-unique-digits.cpp) [Python](./Python/count-numbers-with-unique-digits.py) | _O(n)_ | _O(1)_ | Medium | Backtracking, Math | ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From b8f389353cf8bdd9eebab6373e695329898c1458 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jun 2016 09:36:05 +0800 Subject: [PATCH 2407/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c8c557130..83d46f105 100644 --- a/README.md +++ b/README.md @@ -445,7 +445,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || 351| [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) | [C++](./C++/android-unlock-patterns.cpp) [Python](./Python/android-unlock-patterns.py) | _O(9^2 * 2^9)_ | _O(9 * 2^9)_ | Medium | 📖 | Backtracking | -357| [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | [C++](./C++/count-numbers-with-unique-digits.cpp) [Python](./Python/count-numbers-with-unique-digits.py) | _O(n)_ | _O(1)_ | Medium | Backtracking, Math | +357| [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | [C++](./C++/count-numbers-with-unique-digits.cpp) [Python](./Python/count-numbers-with-unique-digits.py) | _O(n)_ | _O(1)_ | Medium || Backtracking, Math | ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 07880c5f5fe138e764878c7c64aac4875db45ae6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Jun 2016 12:32:13 +0800 Subject: [PATCH 2408/4971] Update count-numbers-with-unique-digits.cpp --- C++/count-numbers-with-unique-digits.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-numbers-with-unique-digits.cpp b/C++/count-numbers-with-unique-digits.cpp index 8bc95d88d..6b9b1e216 100644 --- a/C++/count-numbers-with-unique-digits.cpp +++ b/C++/count-numbers-with-unique-digits.cpp @@ -13,6 +13,6 @@ class Solution { fk *= 10 - (k - 1); count += fk; } - return count; // sum(f(i), i=1~n) + return count; // sum(f(k), k=1~n) } }; From 1fa79dca1cd0e4dd4ad0fb7e356352a291d03612 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 14 Jun 2016 13:54:44 +0800 Subject: [PATCH 2409/4971] Create rearrange-string-k-distance-apart.cpp --- C++/rearrange-string-k-distance-apart.cpp | 42 +++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/rearrange-string-k-distance-apart.cpp diff --git a/C++/rearrange-string-k-distance-apart.cpp b/C++/rearrange-string-k-distance-apart.cpp new file mode 100644 index 000000000..bf51084f9 --- /dev/null +++ b/C++/rearrange-string-k-distance-apart.cpp @@ -0,0 +1,42 @@ +// Time: O(nlogc), c is the count of unique characters. +// Space: O(c) + +class Solution { +public: + string rearrangeString(string str, int k) { + if (k == 0) { + return str; + } + + unordered_map cnts; + for (const auto& c : str) { + ++cnts[c]; + } + + priority_queue> heap; + for (const auto& kvp : cnts) { + heap.emplace(kvp.second, kvp.first); + } + + string result; + while (!heap.empty()) { + vector> used_cnt_chars; + int cnt = min(k, static_cast(str.length() - result.length())); + for (int i = 0; i < cnt; ++i) { + if (heap.empty()) { + return ""; + } + auto cnt_char = heap.top(); + heap.pop(); + result.push_back(cnt_char.second); + if (--cnt_char.first > 0) { + used_cnt_chars.emplace_back(move(cnt_char)); + } + } + for (auto& cnt_char: used_cnt_chars) { + heap.emplace(move(cnt_char)); + } + } + return result; + } +}; From cb2e969b3bc9e3a34de66842a8ae032c273c33ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 14 Jun 2016 14:11:33 +0800 Subject: [PATCH 2410/4971] Create rearrange-string-k-distance-apart.py --- Python/rearrange-string-k-distance-apart.py | 40 +++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/rearrange-string-k-distance-apart.py diff --git a/Python/rearrange-string-k-distance-apart.py b/Python/rearrange-string-k-distance-apart.py new file mode 100644 index 000000000..cbc7340df --- /dev/null +++ b/Python/rearrange-string-k-distance-apart.py @@ -0,0 +1,40 @@ +# Time: O(nlogc), c is the count of unique characters. +# Space: O(c) + +from collections import defaultdict +from heapq import heappush, heappop + +class Solution(object): + def rearrangeString(self, str, k): + """ + :type str: str + :type k: int + :rtype: str + """ + if k == 0: + return str + + cnts = defaultdict(int) + for c in str: + cnts[c] += 1 + + heap = [] + for c, cnt in cnts.iteritems(): + heappush(heap, [-cnt, c]) + + result = [] + while heap: + used_cnt_chars = [] + for _ in xrange(min(k, len(str) - len(result))): + if not heap: + return "" + cnt_char = heappop(heap) + result.append(cnt_char[1]) + cnt_char[0] += 1 + if cnt_char[0] < 0: + used_cnt_chars.append(cnt_char) + + for cnt_char in used_cnt_chars: + heappush(heap, cnt_char) + + return "".join(result) From 3918821842750c5e8af79599368e0aa064cab568 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 14 Jun 2016 14:14:04 +0800 Subject: [PATCH 2411/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 83d46f105..e3c918d43 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-357%20%2F%20357-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-358%20%2F%20358-ff69b4.svg) -Up to date (2016-06-12), there are `340` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-14), there are `341` 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 `357` questions. +Here is the classification of all `358` 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. ) @@ -174,6 +174,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | +358| [Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/)| [C++](./C++/rearrange-string-k-distance-apart.cpp) [Python](./Python/rearrange-string-k-distance-apart.py) | _O(nlogc)_ | _O(c)_ | Hard |📖| Greedy, Heap | ## Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note From e0286217c6fa4d054be301989124612fedd8e6cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 14 Jun 2016 14:15:38 +0800 Subject: [PATCH 2412/4971] Update rearrange-string-k-distance-apart.py --- Python/rearrange-string-k-distance-apart.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/rearrange-string-k-distance-apart.py b/Python/rearrange-string-k-distance-apart.py index cbc7340df..a4ef4e541 100644 --- a/Python/rearrange-string-k-distance-apart.py +++ b/Python/rearrange-string-k-distance-apart.py @@ -33,7 +33,6 @@ def rearrangeString(self, str, k): cnt_char[0] += 1 if cnt_char[0] < 0: used_cnt_chars.append(cnt_char) - for cnt_char in used_cnt_chars: heappush(heap, cnt_char) From 957ec93f533e45336ad995433af71cdb8ee58f17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 14 Jun 2016 23:30:07 +0800 Subject: [PATCH 2413/4971] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 21 +-------------------- 1 file changed, 1 insertion(+), 20 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 7891f8827..b81e45c96 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -14,7 +14,7 @@ class Solution { int j = k - i; vector tmp(k); merge(max_digits1[i], max_digits2[j], &tmp); - if (compareVector(tmp, res)) { + if (tmp > res) { res = tmp; } } @@ -58,25 +58,6 @@ class Solution { return res; } - // Time: O(k) - // Space: O(1) - 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) { - return true; - } else if (*first1 < *first2) { - return false; - } - } - if (first1 == last1) { - return false; - } else { - return true; - } - } - // Time: O(k) ~ O(k^2) // Space: O(1) void merge(const vector& vec1, const vector& vec2, vector *res) { From a59b283ea01bcad3963f356fa0aaf371dbed376e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 14 Jun 2016 23:37:54 +0800 Subject: [PATCH 2414/4971] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index b81e45c96..8eb1ed026 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -64,10 +64,12 @@ class Solution { auto first1 = vec1.begin(), last1 = vec1.end(), first2 = vec2.begin(), last2 = vec2.end(); auto result = res->begin(); - while (first1 != last1 && first2 != last2) { - if (*first2 > *first1) { + while (first1 != last1 || first2 != last2) { + int val1 = first1 != last1 ? *first1 : numeric_limits::min(); + int val2 = first2 != last2 ? *first2 : numeric_limits::min(); + if (val2 > val1) { *result++ = *first2++; - } else if (*first2 < *first1) { + } else if (val2 < val1) { *result++ = *first1++; } else { auto pos1 = first1, pos2 = first2; @@ -84,10 +86,5 @@ class Solution { } } } - if (first1 == last1) { - std::copy(first2, last2, result); - } else if (first2 == last2) { - std::copy(first1, last1, result); - } } }; From 93e21497460465dac1235564f508f51d0b1b1ea0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Jun 2016 00:11:20 +0800 Subject: [PATCH 2415/4971] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index 8eb1ed026..f386960d6 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -67,15 +67,15 @@ class Solution { while (first1 != last1 || first2 != last2) { int val1 = first1 != last1 ? *first1 : numeric_limits::min(); int val2 = first2 != last2 ? *first2 : numeric_limits::min(); - if (val2 > val1) { - *result++ = *first2++; - } else if (val2 < val1) { + if (val1 > val2) { *result++ = *first1++; + } else if (val1 < val2) { + *result++ = *first2++; } else { - auto pos1 = first1, pos2 = first2; - while (true) { // O(1) ~ O(k) time. - int val1 = (++pos1 != last1) ? *(pos1) : numeric_limits::min(); - int val2 = (++pos2 != last2) ? *(pos2) : numeric_limits::min(); + auto pos1 = first1 + 1, pos2 = first2 + 1; + while (pos1 != last1 || pos2 != last2) { // O(1) ~ O(k) time. + int val1 = (pos1 != last1) ? *(pos1) : numeric_limits::min(); + int val2 = (pos2 != last2) ? *(pos2) : numeric_limits::min(); if (val1 > val2) { *result++ = *first1++; break; @@ -83,6 +83,10 @@ class Solution { *result++ = *first2++; break; } + ++pos1, ++pos2; + } + if (pos1 == last1 && pos2 == last2) { + *result++ = *first2++; } } } From 184ea307e117375b420f4381f13a2b55fae72543 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Jun 2016 00:13:03 +0800 Subject: [PATCH 2416/4971] 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 f386960d6..e41d225bc 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -15,7 +15,7 @@ class Solution { vector tmp(k); merge(max_digits1[i], max_digits2[j], &tmp); if (tmp > res) { - res = tmp; + res = move(tmp); } } return res; From 15ab25a50a739fd2743f04f5ddaa78cde0b6e359 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Jun 2016 00:50:14 +0800 Subject: [PATCH 2417/4971] Update create-maximum-number.cpp --- C++/create-maximum-number.cpp | 59 ++++++++++++++--------------------- 1 file changed, 24 insertions(+), 35 deletions(-) diff --git a/C++/create-maximum-number.cpp b/C++/create-maximum-number.cpp index e41d225bc..18f03085b 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -1,37 +1,36 @@ // Time: O(k * (m + n + k)) ~ O(k * (m + n + k^2)) // Space: O(m + n + k^2) -// DP + Greedy solution. (48ms) +// DP + Greedy solution. class Solution { public: vector maxNumber(vector& nums1, vector& nums2, int k) { - vector res(k); const int m = nums1.size(), n = nums2.size(); - 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> max_numbers1(k + 1), max_numbers2(k + 1); + maxNumberDP(nums1, max(0, k - n), min(k, m), &max_numbers1); // O(k * m) time, O(m + k^2) space. + maxNumberDP(nums2, max(0, k - m), min(k, n), &max_numbers2); // O(k * n) time, O(n + k^2) space. + + vector res(k); + for (int i = max(0, k - n); i <= min(k, m); ++i) { // k * O(k) ~ k * O(k^2) time vector tmp(k); - merge(max_digits1[i], max_digits2[j], &tmp); + merge(max_numbers1[i], max_numbers2[k - i], &tmp); if (tmp > res) { res = move(tmp); } } return res; } - private: - void getMaxDigits(vector nums, int start, int end, vector> *maxDigits) { - (*maxDigits)[end] = maxDigit(nums, end); + void maxNumberDP(vector nums, int start, int end, vector> *max_numbers) { + (*max_numbers)[end] = maxNumber(nums, end); for (int i = end - 1; i >= start; --i) { - (*maxDigits)[i] = deleteDigit((*maxDigits)[i + 1]); + (*max_numbers)[i] = deleteNumber((*max_numbers)[i + 1]); } } // Time: O(n) // Space: O(n) - vector maxDigit(const vector& nums, int k) { + vector maxNumber(const vector& nums, int k) { vector res; int drop = nums.size() - k; for (const auto& num : nums) { @@ -47,7 +46,7 @@ class Solution { // Time: O(n) // Space: O(n) - vector deleteDigit(const vector& nums) { + vector deleteNumber(const vector& nums) { vector res(nums); for (int i = 0; i < res.size(); ++i) { if (i == res.size() - 1 || res[i] < res[i + 1]) { @@ -65,30 +64,20 @@ class Solution { first2 = vec2.begin(), last2 = vec2.end(); auto result = res->begin(); while (first1 != last1 || first2 != last2) { - int val1 = first1 != last1 ? *first1 : numeric_limits::min(); - int val2 = first2 != last2 ? *first2 : numeric_limits::min(); - if (val1 > val2) { + if (greater(first1, last1, first2, last2)) { *result++ = *first1++; - } else if (val1 < val2) { - *result++ = *first2++; } else { - auto pos1 = first1 + 1, pos2 = first2 + 1; - while (pos1 != last1 || pos2 != last2) { // O(1) ~ O(k) time. - int val1 = (pos1 != last1) ? *(pos1) : numeric_limits::min(); - int val2 = (pos2 != last2) ? *(pos2) : numeric_limits::min(); - if (val1 > val2) { - *result++ = *first1++; - break; - } else if (val1 < val2) { - *result++ = *first2++; - break; - } - ++pos1, ++pos2; - } - if (pos1 == last1 && pos2 == last2) { - *result++ = *first2++; - } + *result++ = *first2++; } } } + + template + bool greater(IT first1, IT last1, IT first2, IT last2) { + while (first1 != last1 && first2 != last2 && *first1 == *first2) { + ++first1; + ++first2; + } + return (first2 == last2) || (first1 != last1 && *first1 > *first2); + } }; From cd0c94cf1d651aa7eb6f0e3599b2e2493552e646 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Jun 2016 01:01:06 +0800 Subject: [PATCH 2418/4971] 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 18f03085b..4ebd28884 100644 --- a/C++/create-maximum-number.cpp +++ b/C++/create-maximum-number.cpp @@ -20,6 +20,7 @@ class Solution { } return res; } + private: void maxNumberDP(vector nums, int start, int end, vector> *max_numbers) { (*max_numbers)[end] = maxNumber(nums, end); From 43a845606b79b50b78ff3cc9816d753a5a4a76b9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Jun 2016 16:55:19 +0800 Subject: [PATCH 2419/4971] Update majority-element-ii.py --- Python/majority-element-ii.py | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/Python/majority-element-ii.py b/Python/majority-element-ii.py index 3a0d51fac..f3d1e072d 100644 --- a/Python/majority-element-ii.py +++ b/Python/majority-element-ii.py @@ -1,22 +1,20 @@ # 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[]} +class Solution(object): def majorityElement(self, nums): - k, n, hash = 3, len(nums), {} + """ + :type nums: List[int] + :rtype: List[int] + """ + k, n, hash = 3, len(nums), collections.defaultdict(int) for i in nums: - if i not in hash: - hash[i] = 1 - else: - hash[i] += 1 + 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. @@ -36,9 +34,9 @@ def majorityElement(self, nums): hash[i] += 1 # Selects the integer which occurs > [n / k] times. - ret = [] + result = [] for i in hash.keys(): if hash[i] > n / k: - ret.append(i) + result.append(i) - return ret + resulturn result From 6efd6b73a04cde4fa404480960ca85f8496ef740 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Jun 2016 17:00:11 +0800 Subject: [PATCH 2420/4971] Update majority-element-ii.py --- Python/majority-element-ii.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Python/majority-element-ii.py b/Python/majority-element-ii.py index f3d1e072d..aedc61807 100644 --- a/Python/majority-element-ii.py +++ b/Python/majority-element-ii.py @@ -20,9 +20,10 @@ def majorityElement(self, nums): # 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] + for j in hash.keys(): + hash[j] -= 1 + if hash[j] == 0: + del hash[j] # Resets hash for the following counting. for i in hash.keys(): @@ -39,4 +40,4 @@ def majorityElement(self, nums): if hash[i] > n / k: result.append(i) - resulturn result + return result From 511b15959b2373ccb08bdeaf8b5ca0a9c5bf5461 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Jun 2016 17:02:38 +0800 Subject: [PATCH 2421/4971] Update majority-element-ii.py --- Python/majority-element-ii.py | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/Python/majority-element-ii.py b/Python/majority-element-ii.py index aedc61807..4efbe7e76 100644 --- a/Python/majority-element-ii.py +++ b/Python/majority-element-ii.py @@ -11,33 +11,33 @@ def majorityElement(self, nums): :type nums: List[int] :rtype: List[int] """ - k, n, hash = 3, len(nums), collections.defaultdict(int) + k, n, cnts = 3, len(nums), collections.defaultdict(int) for i in nums: - hash[i] += 1 - # Detecting k items in hash, at least one of them must have exactly + cnts[i] += 1 + # Detecting k items in cnts, 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 j in hash.keys(): - hash[j] -= 1 - if hash[j] == 0: - del hash[j] + if len(cnts) == k: + for j in cnts.keys(): + cnts[j] -= 1 + if cnts[j] == 0: + del cnts[j] - # Resets hash for the following counting. - for i in hash.keys(): - hash[i] = 0 + # Resets cnts for the following counting. + for i in cnts.keys(): + cnts[i] = 0 # Counts the occurrence of each candidate integer. for i in nums: - if i in hash: - hash[i] += 1 + if i in cnts: + cnts[i] += 1 # Selects the integer which occurs > [n / k] times. result = [] - for i in hash.keys(): - if hash[i] > n / k: + for i in cnts.keys(): + if cnts[i] > n / k: result.append(i) return result From 9d0964d355e039c6c69be709f42a24853d5aaece Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jun 2016 13:55:42 +0800 Subject: [PATCH 2422/4971] Create logger-rate-limiter.cpp --- C++/logger-rate-limiter.cpp | 57 +++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 C++/logger-rate-limiter.cpp diff --git a/C++/logger-rate-limiter.cpp b/C++/logger-rate-limiter.cpp new file mode 100644 index 000000000..2b5b93e53 --- /dev/null +++ b/C++/logger-rate-limiter.cpp @@ -0,0 +1,57 @@ +// Time: O(1), amortized +// Space: O(k), k is the max number of messages in last 10 seconds + +class Logger { +public: + /** Initialize your data structure here. */ + Logger() { + + } + + /** Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity. */ + bool shouldPrintMessage(int timestamp, string message) { + while (!dq_.empty() && dq_.front().first <= timestamp - 10) { + printed_.erase(dq_.front().second); + dq_.pop_front(); + } + if (printed_.count(message)) { + return false; + } + dq_.emplace_back(timestamp, message); + printed_.emplace(message); + return true; + } + +private: + deque> dq_; + unordered_set printed_; +}; + +// Time: O(1) +// Space: O(n) +class Logger2 { +public: + /** Initialize your data structure here. */ + Logger() { + + } + + /** Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity. */ + bool shouldPrintMessage(int timestamp, string message) { + if (message_time_.count(message) && + timestamp < message_time_[message] + 10) { + return false; + } + message_time_[message] = timestamp; + return true; + } + +private: + unordered_map message_time_; +}; + +/** + * Your Logger object will be instantiated and called as such: + * Logger obj = new Logger(); + * bool param_1 = obj.shouldPrintMessage(timestamp,message); + */ From d44129c5a7d9c81f6f92da70f699cadb3f7ca288 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jun 2016 14:04:34 +0800 Subject: [PATCH 2423/4971] Create logger-rate-limiter.py --- Python/logger-rate-limiter.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/logger-rate-limiter.py diff --git a/Python/logger-rate-limiter.py b/Python/logger-rate-limiter.py new file mode 100644 index 000000000..7c8be3e49 --- /dev/null +++ b/Python/logger-rate-limiter.py @@ -0,0 +1,31 @@ +# Time: O(1), amortized +# Space: O(k), k is the max number of messages in last 10 seconds + +class Logger(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.__dq = collections.deque() + self.__printed = set() + + def shouldPrintMessage(self, timestamp, message): + """ + Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity. + :type timestamp: int + :type message: str + :rtype: bool + """ + while self.__dq and self.__dq[0][0] <= timestamp - 10: + self.__printed.remove(self.__dq.popleft()[1]) + if message in self.__printed: + return False + self.__dq.append((timestamp, message)) + self.__printed.add(message) + return True + + +# Your Logger object will be instantiated and called as such: +# obj = Logger() +# param_1 = obj.shouldPrintMessage(timestamp,message) From 7a6d713080dbfe6f0884344d461970147ba9451d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jun 2016 14:07:36 +0800 Subject: [PATCH 2424/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e3c918d43..c904651fc 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-358%20%2F%20358-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-359%20%2F%20359-ff69b4.svg) -Up to date (2016-06-14), there are `341` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-16), there are `342` 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 `358` questions. +Here is the classification of all `359` 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. ) @@ -471,6 +471,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_| _O(n^2)_| Medium |📖|| 353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(s)_| _O(s)_| Medium |📖| Deque | 355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_| _O(t + f)_| Hard | LintCode | Heap | +359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | [C++](./C++/logger-rate-limiter.cpp) [Python](./Python/logger-rate-limiter.py) | _O(1), amortized_ | _O(k)_| Easy |📖| Deque | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From fd457a67bcc8db317c52cb838dbea53a1aaad743 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jun 2016 14:10:00 +0800 Subject: [PATCH 2425/4971] Update logger-rate-limiter.cpp --- C++/logger-rate-limiter.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/logger-rate-limiter.cpp b/C++/logger-rate-limiter.cpp index 2b5b93e53..8872e6bad 100644 --- a/C++/logger-rate-limiter.cpp +++ b/C++/logger-rate-limiter.cpp @@ -1,5 +1,5 @@ // Time: O(1), amortized -// Space: O(k), k is the max number of messages in last 10 seconds +// Space: O(k), k is the max number of printed messages in last 10 seconds class Logger { public: @@ -28,7 +28,7 @@ class Logger { }; // Time: O(1) -// Space: O(n) +// Space: O(n), n is the number of total unique messages class Logger2 { public: /** Initialize your data structure here. */ From b1a516dd4681e888320f1221fecd4dede8036e66 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jun 2016 14:11:12 +0800 Subject: [PATCH 2426/4971] Update logger-rate-limiter.py --- Python/logger-rate-limiter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/logger-rate-limiter.py b/Python/logger-rate-limiter.py index 7c8be3e49..0e4006813 100644 --- a/Python/logger-rate-limiter.py +++ b/Python/logger-rate-limiter.py @@ -1,5 +1,5 @@ # Time: O(1), amortized -# Space: O(k), k is the max number of messages in last 10 seconds +# Space: O(k), k is the max number of printed messages in last 10 seconds class Logger(object): From 8054ca521919ada7b5653973ca7a437a22428fd8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Jun 2016 20:36:14 +0800 Subject: [PATCH 2427/4971] Update gray-code.py --- Python/gray-code.py | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/Python/gray-code.py b/Python/gray-code.py index 2bad42513..e6f298734 100644 --- a/Python/gray-code.py +++ b/Python/gray-code.py @@ -1,6 +1,6 @@ # Time: O(2^n) # Space: O(1) -# + # The gray code is a binary numeral system where two successive values differ in only one bit. # # Given a non-negative integer n representing the total number of bits in the code, @@ -15,26 +15,36 @@ # Note: # For a given n, a gray code sequence is not uniquely defined. # -# For example, [0,2,3,1] is also a valid gray code sequence according to the above definition. +# For example, [0,2,3,1] is also a valid gray code sequence according +# to the above definition. # -# For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. +# For now, the judge is able to judge based on one instance of gray code +# sequence. Sorry about that. -class Solution: - # @return a list of integers +class Solution(object): def grayCode(self, n): + """ + :type n: int + :rtype: List[int] + """ result = [0] - for i in xrange(0, n): + for i in xrange(n): for n in reversed(result): result.append(1 << i | n) return result -# proof of closed form formula could be found here: + +# Proof of closed form formula could be found here: # http://math.stackexchange.com/questions/425894/proof-of-closed-form-formula-to-convert-a-binary-number-to-its-gray-code -class Solution2: - # @return a list of integers - def grayCode(self, n): +class Solution(object): + def grayCode2(self, n): + """ + :type n: int + :rtype: List[int] + """ return [i >> 1 ^ i for i in xrange(1 << n)] + if __name__ == "__main__": print Solution().grayCode(0) print Solution().grayCode(2) From c9f78effbf2ed1f58b1cb7961299df1979bcdeb8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Jun 2016 17:04:47 +0800 Subject: [PATCH 2428/4971] Create sort-transformed-array.cpp --- C++/sort-transformed-array.cpp | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C++/sort-transformed-array.cpp diff --git a/C++/sort-transformed-array.cpp b/C++/sort-transformed-array.cpp new file mode 100644 index 000000000..818a08edf --- /dev/null +++ b/C++/sort-transformed-array.cpp @@ -0,0 +1,36 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector sortTransformedArray(vector& nums, int a, int b, int c) { + vector result; + const auto f = [](int x, int a, int b, int c) { + return a * x * x + b * x + c; + }; + + if (nums.empty()) { + return result; + } + int left = 0, right = nums.size() - 1; + if (a > 0) { + while (left <= right) { + if (f(nums[left], a, b, c) > f(nums[right], a, b, c)) { + result.emplace_back(f(nums[left++], a, b, c)); + } else { + result.emplace_back(f(nums[right--], a, b, c)); + } + } + reverse(result.begin(), result.end()); + } else { + while (left <= right) { + if (f(nums[left], a, b, c) < f(nums[right], a, b, c)) { + result.emplace_back(f(nums[left++], a, b, c)); + } else { + result.emplace_back(f(nums[right--], a, b, c)); + } + } + } + return result; + } +}; From 5300e73e4390f0c11635e99b1c628188fdd77933 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Jun 2016 17:12:10 +0800 Subject: [PATCH 2429/4971] Create sort-transformed-array.py --- Python/sort-transformed-array.py | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/sort-transformed-array.py diff --git a/Python/sort-transformed-array.py b/Python/sort-transformed-array.py new file mode 100644 index 000000000..aefa19543 --- /dev/null +++ b/Python/sort-transformed-array.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def sortTransformedArray(self, nums, a, b, c): + """ + :type nums: List[int] + :type a: int + :type b: int + :type c: int + :rtype: List[int] + """ + f = lambda x, a, b, c : a * x * x + b * x + c + + result = [] + if not nums: + return result + + left, right = 0, len(nums) - 1 + if a > 0: + while left <= right: + if f(nums[left], a, b, c) > f(nums[right], a, b, c): + result.append(f(nums[left], a, b, c)) + left += 1 + else: + result.append(f(nums[right], a, b, c)) + right -= 1 + else: + while left <= right: + if f(nums[left], a, b, c) < f(nums[right], a, b, c): + result.append(f(nums[left], a, b, c)) + left += 1 + else: + result.append(f(nums[right], a, b, c)) + right -= 1 + + return result if a <= 0 else result[::-1] From 1b699b2a65ee446084d66aaa7a4fa6c63f2c1859 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Jun 2016 17:13:07 +0800 Subject: [PATCH 2430/4971] Update sort-transformed-array.cpp --- C++/sort-transformed-array.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/C++/sort-transformed-array.cpp b/C++/sort-transformed-array.cpp index 818a08edf..4f96abb64 100644 --- a/C++/sort-transformed-array.cpp +++ b/C++/sort-transformed-array.cpp @@ -4,14 +4,15 @@ class Solution { public: vector sortTransformedArray(vector& nums, int a, int b, int c) { - vector result; const auto f = [](int x, int a, int b, int c) { return a * x * x + b * x + c; }; + vector result; if (nums.empty()) { return result; } + int left = 0, right = nums.size() - 1; if (a > 0) { while (left <= right) { @@ -31,6 +32,7 @@ class Solution { } } } + return result; } }; From 202b5bb2447a8f717ced35f424a35372ccc937ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Jun 2016 17:15:43 +0800 Subject: [PATCH 2431/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c904651fc..e6139dce8 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-359%20%2F%20359-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-360%20%2F%20360-ff69b4.svg) -Up to date (2016-06-16), there are `342` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-17), there are `343` 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 `359` questions. +Here is the classification of all `360` 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 345| [Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./C++/reverse-vowels-of-a-string.cpp) [Python](./Python/reverse-vowels-of-a-string.py) | _O(n)_ | _O(1)_ | Easy | | 349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI | Hash, Binary Search 350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash, Binary Search +360| [Sort Transformed Array](https://leetcode.com/problems/sort-transformed-array/) | [C++](./C++/sort-transformed-array.cpp) [Python](./Python/sort-transformed-array.py) | _O(n)_ | _O(1)_ | Medium |📖| ## Recursion # | Title | Solution | Time | Space | Difficulty | Tag | Note From ab15f0c8ca623c550415efcb3eb411c7da0008d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Jun 2016 17:27:31 +0800 Subject: [PATCH 2432/4971] Update sort-transformed-array.cpp --- C++/sort-transformed-array.cpp | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/C++/sort-transformed-array.cpp b/C++/sort-transformed-array.cpp index 4f96abb64..71f6e5541 100644 --- a/C++/sort-transformed-array.cpp +++ b/C++/sort-transformed-array.cpp @@ -14,23 +14,16 @@ class Solution { } int left = 0, right = nums.size() - 1; - if (a > 0) { - while (left <= right) { - if (f(nums[left], a, b, c) > f(nums[right], a, b, c)) { - result.emplace_back(f(nums[left++], a, b, c)); - } else { - result.emplace_back(f(nums[right--], a, b, c)); - } + int d = a > 0 ? -1 : 1; + while (left <= right) { + if (d * f(nums[left], a, b, c) < d * f(nums[right], a, b, c)) { + result.emplace_back(f(nums[left++], a, b, c)); + } else { + result.emplace_back(f(nums[right--], a, b, c)); } + } + if (d == -1) { reverse(result.begin(), result.end()); - } else { - while (left <= right) { - if (f(nums[left], a, b, c) < f(nums[right], a, b, c)) { - result.emplace_back(f(nums[left++], a, b, c)); - } else { - result.emplace_back(f(nums[right--], a, b, c)); - } - } } return result; From c156a086c0ffa987b87a7907e5895a26fbc639c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Jun 2016 17:29:42 +0800 Subject: [PATCH 2433/4971] Update sort-transformed-array.py --- Python/sort-transformed-array.py | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/Python/sort-transformed-array.py b/Python/sort-transformed-array.py index aefa19543..01eb27de1 100644 --- a/Python/sort-transformed-array.py +++ b/Python/sort-transformed-array.py @@ -17,21 +17,13 @@ def sortTransformedArray(self, nums, a, b, c): return result left, right = 0, len(nums) - 1 - if a > 0: - while left <= right: - if f(nums[left], a, b, c) > f(nums[right], a, b, c): - result.append(f(nums[left], a, b, c)) - left += 1 - else: - result.append(f(nums[right], a, b, c)) - right -= 1 - else: - while left <= right: - if f(nums[left], a, b, c) < f(nums[right], a, b, c): - result.append(f(nums[left], a, b, c)) - left += 1 - else: - result.append(f(nums[right], a, b, c)) - right -= 1 + d = -1 if a > 0 else 1 + while left <= right: + if d * f(nums[left], a, b, c) < d * f(nums[right], a, b, c): + result.append(f(nums[left], a, b, c)) + left += 1 + else: + result.append(f(nums[right], a, b, c)) + right -= 1 - return result if a <= 0 else result[::-1] + return result[::d] From 7dd813384e3014ece13c847a48f6e435688fed73 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jun 2016 13:40:51 +0800 Subject: [PATCH 2434/4971] 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 bb20c20d7..2d852315f 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -10,7 +10,7 @@ class Solution { uglies[0] = 1; for (int i = 0; i < primes.size(); ++i) { - heap.push({primes[i], i}); + heap.emplace(primes[i], i); } for (int i = 1; i < n; ++i) { int k; @@ -18,7 +18,7 @@ class Solution { heap.pop(); ugly_by_last_prime[i] = k; while (ugly_by_last_prime[++idx[k]] > k); // worst time: O(k) - heap.push({uglies[idx[k]] * primes[k], k}); + heap.emplace(uglies[idx[k]] * primes[k], k); } return uglies[n - 1]; } @@ -92,7 +92,7 @@ class Solution4 { uglies[0] = 1; for (int k = 0; k < primes.size(); ++k) { - heap.push({primes[k], k}); + heap.emplace(primes[k], k); ugly_set.emplace(primes[k]); } @@ -103,7 +103,7 @@ class Solution4 { while (ugly_set.count(primes[k] * uglies[idx[k]])) { ++idx[k]; } - heap.push({primes[k] * uglies[idx[k]], k}); + heap.emplace(primes[k] * uglies[idx[k]], k); ugly_set.emplace(primes[k] * uglies[idx[k]]); } @@ -122,7 +122,7 @@ class Solution5 { uglies[0] = 1; for (int k = 0; k < primes.size(); ++k) { - heap.push({primes[k], k}); + heap.emplace(primes[k], k); } for (int i = 1; i < n; ++i) { @@ -132,7 +132,7 @@ class Solution5 { 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}); + heap.emplace(primes[k] * uglies[++idx[k]], k); } } From 71e2255f32ee2e4386c7b875652a26daea3bc432 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jun 2016 13:42:36 +0800 Subject: [PATCH 2435/4971] 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 2d852315f..3e786e2b0 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -98,7 +98,7 @@ class Solution4 { for (int i = 1; i < n; ++i) { int k; - tie(uglies[i]) = heap.top(); + tie(uglies[i], k) = heap.top(); heap.pop(); while (ugly_set.count(primes[k] * uglies[idx[k]])) { ++idx[k]; From e9215038bafdeba6570f6e5d271d2003a205a7f8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jun 2016 15:13:36 +0800 Subject: [PATCH 2436/4971] Create bomb-enemy.cpp --- C++/bomb-enemy.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 C++/bomb-enemy.cpp diff --git a/C++/bomb-enemy.cpp b/C++/bomb-enemy.cpp new file mode 100644 index 000000000..e160e307f --- /dev/null +++ b/C++/bomb-enemy.cpp @@ -0,0 +1,47 @@ +// Time: O(m * n) +// Space: O(m * n) + +class Solution { +public: + int maxKilledEnemies(vector>& grid) { + if (grid.empty() || grid[0].empty()) { + return 0; + } + + vector> right{grid.size(), vector(grid[0].size())}; + vector> down{grid.size(), vector(grid[0].size())}; + for (int i = grid.size() - 1; i >= 0; --i) { + for (int j = grid[0].size() - 1; j >= 0; --j) { + if (grid[i][j] != 'Y') { + if (i + 1 < grid.size()) { + right[i][j] = right[i + 1][j]; + } + if (j + 1 < grid[0].size()) { + down[i][j] = down[i][j + 1]; + } + if (grid[i][j] == 'X') { + ++right[i][j]; + ++down[i][j]; + } + } + } + } + vector up(grid[0].size()); + int result = 0; + for (int i = 0; i < grid.size(); ++i) { + int left = 0; + for (int j = 0; j < grid[0].size(); ++j) { + if (grid[i][j] == 'Y') { + up[j] = 0; + left = 0; + } else if (grid[i][j] == 'X') { + ++left; + ++up[j]; + } else { + result = max(result, left + up[j] + right[i][j] + down[i][j]); + } + } + } + return result; + } +}; From 01a1ccb74f3cff7e0d0c2d394e8acfb8c80e3684 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jun 2016 15:20:44 +0800 Subject: [PATCH 2437/4971] Update bomb-enemy.cpp --- C++/bomb-enemy.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/bomb-enemy.cpp b/C++/bomb-enemy.cpp index e160e307f..95db62ff1 100644 --- a/C++/bomb-enemy.cpp +++ b/C++/bomb-enemy.cpp @@ -14,14 +14,14 @@ class Solution { for (int j = grid[0].size() - 1; j >= 0; --j) { if (grid[i][j] != 'Y') { if (i + 1 < grid.size()) { - right[i][j] = right[i + 1][j]; + down[i][j] = down[i + 1][j]; } if (j + 1 < grid[0].size()) { - down[i][j] = down[i][j + 1]; + right[i][j] = right[i][j + 1]; } if (grid[i][j] == 'X') { - ++right[i][j]; ++down[i][j]; + ++right[i][j]; } } } @@ -35,8 +35,8 @@ class Solution { up[j] = 0; left = 0; } else if (grid[i][j] == 'X') { - ++left; ++up[j]; + ++left; } else { result = max(result, left + up[j] + right[i][j] + down[i][j]); } From 0f77210a64d2e5234ac770ef652812764889f3e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jun 2016 15:26:38 +0800 Subject: [PATCH 2438/4971] Update bomb-enemy.cpp --- C++/bomb-enemy.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/C++/bomb-enemy.cpp b/C++/bomb-enemy.cpp index 95db62ff1..8b58889f7 100644 --- a/C++/bomb-enemy.cpp +++ b/C++/bomb-enemy.cpp @@ -4,12 +4,13 @@ class Solution { public: int maxKilledEnemies(vector>& grid) { + int result = 0; if (grid.empty() || grid[0].empty()) { - return 0; + return result; } - vector> right{grid.size(), vector(grid[0].size())}; vector> down{grid.size(), vector(grid[0].size())}; + vector> right{grid.size(), vector(grid[0].size())}; for (int i = grid.size() - 1; i >= 0; --i) { for (int j = grid[0].size() - 1; j >= 0; --j) { if (grid[i][j] != 'Y') { @@ -26,10 +27,11 @@ class Solution { } } } + + int left = 0; vector up(grid[0].size()); - int result = 0; for (int i = 0; i < grid.size(); ++i) { - int left = 0; + left = 0; for (int j = 0; j < grid[0].size(); ++j) { if (grid[i][j] == 'Y') { up[j] = 0; @@ -42,6 +44,7 @@ class Solution { } } } + return result; } }; From 7a0f37859bc6d3d304b0d904138ebd577160d5b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jun 2016 15:30:46 +0800 Subject: [PATCH 2439/4971] Create bomb-enemy.py --- Python/bomb-enemy.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/bomb-enemy.py diff --git a/Python/bomb-enemy.py b/Python/bomb-enemy.py new file mode 100644 index 000000000..b540793cf --- /dev/null +++ b/Python/bomb-enemy.py @@ -0,0 +1,39 @@ +# Time: O(m * n) +# Space: O(m * n) + +class Solution(object): + def maxKilledEnemies(self, grid): + """ + :type grid: List[List[str]] + :rtype: int + """ + result = 0 + if not grid or not grid[0]: + return result + + down = [[0 for _ in xrange(len(grid[0]))] for _ in xrange(len(grid))] + right = [[0 for _ in xrange(len(grid[0]))] for _ in xrange(len(grid))] + for i in reversed(xrange(len(grid))): + for j in reversed(xrange(len(grid[0]))): + if grid[i][j] != 'Y': + if i + 1 < len(grid): + down[i][j] = down[i + 1][j] + if j + 1 < len(grid[0]): + right[i][j] = right[i][j + 1] + if grid[i][j] == 'X': + down[i][j] += 1 + right[i][j] += 1 + + up = [0 for _ in xrange(len(grid[0]))] + for i in xrange(len(grid)): + left = 0 + for j in xrange(len(grid[0])): + if grid[i][j] == 'Y': + up[j], left = 0, 0 + elif grid[i][j] == 'X': + up[j] += 1 + left += 1 + else: + result = max(result, left + up[j] + right[i][j] + down[i][j]) + + return result From b561ca589596d89ce4f376671a7d8d14a3e51f65 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Jun 2016 15:46:48 +0800 Subject: [PATCH 2440/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e6139dce8..b44458af4 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-360%20%2F%20360-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-361%20%2F%20361-ff69b4.svg) -Up to date (2016-06-17), there are `343` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-18), there are `344` 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 `360` questions. +Here is the classification of all `361` 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. ) @@ -448,6 +448,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 || 351| [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) | [C++](./C++/android-unlock-patterns.cpp) [Python](./Python/android-unlock-patterns.py) | _O(9^2 * 2^9)_ | _O(9 * 2^9)_ | Medium | 📖 | Backtracking | 357| [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | [C++](./C++/count-numbers-with-unique-digits.cpp) [Python](./Python/count-numbers-with-unique-digits.py) | _O(n)_ | _O(1)_ | Medium || Backtracking, Math | +361| [Bomb Enemy](https://leetcode.com/problems/bomb-enemy/) | [C++](./C++/bomb-enemy.cpp) [Python](./Python/bomb-enemy.py) | _O(m * n)_ | _O(m * n)_ | Medium | 📖 | | ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From d8fc3e4e4f7fa8a435f8e78362ff2ea7ec8f3a44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Jun 2016 13:30:49 +0800 Subject: [PATCH 2441/4971] Create design-hit-counter.py --- Python/design-hit-counter.py | 45 ++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/design-hit-counter.py diff --git a/Python/design-hit-counter.py b/Python/design-hit-counter.py new file mode 100644 index 000000000..f113f4014 --- /dev/null +++ b/Python/design-hit-counter.py @@ -0,0 +1,45 @@ +# Time: O(1) +# Space: O(k), k is the count of seconds. + +from collections import deque + +class HitCounter(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.__k = 300 + self.__dq = deque() + self.__count = 0 + + def hit(self, timestamp): + """ + Record a hit. + @param timestamp - The current timestamp (in seconds granularity). + :type timestamp: int + :rtype: void + """ + self.getHits(timestamp) + if self.__dq and self.__dq[-1][0] == timestamp: + self.__dq[-1][1] += 1 + else: + self.__dq.append([timestamp, 1]) + self.__count += 1 + + def getHits(self, timestamp): + """ + Return the number of hits in the past 5 minutes. + @param timestamp - The current timestamp (in seconds granularity). + :type timestamp: int + :rtype: int + """ + while self.__dq and self.__dq[0][0] <= timestamp - self.__k: + self.__count -= self.__dq[0][1] + self.__dq.popleft() + return self.__count + +# Your HitCounter object will be instantiated and called as such: +# obj = HitCounter() +# obj.hit(timestamp) +# param_2 = obj.getHits(timestamp) From 79a0b15ee70d30e79aa35b9c55cda972ba5fea6c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Jun 2016 13:33:52 +0800 Subject: [PATCH 2442/4971] Create design-hit-counter.cpp --- C++/design-hit-counter.cpp | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 C++/design-hit-counter.cpp diff --git a/C++/design-hit-counter.cpp b/C++/design-hit-counter.cpp new file mode 100644 index 000000000..22038d828 --- /dev/null +++ b/C++/design-hit-counter.cpp @@ -0,0 +1,45 @@ +// Time: O(1), amortized +// Space: O(k), k is the count of seconds. + +class HitCounter { +public: + /** Initialize your data structure here. */ + HitCounter() : count_(0) { + + } + + /** Record a hit. + @param timestamp - The current timestamp (in seconds granularity). */ + void hit(int timestamp) { + getHits(timestamp); + if (!dq_.empty() && dq_.back().first == timestamp) { + ++dq_.back().second; + } else { + dq_.emplace_back(timestamp, 1); + } + ++count_; + } + + /** Return the number of hits in the past 5 minutes. + @param timestamp - The current timestamp (in seconds granularity). */ + int getHits(int timestamp) { + while (!dq_.empty() && dq_.front().first <= timestamp - k_) { + count_ -= dq_.front().second; + dq_.pop_front(); + } + return count_; + } + +private: + const int k_ = 300; + int count_; + deque> dq_; +}; + +/** + * Your HitCounter object will be instantiated and called as such: + * HitCounter obj = new HitCounter(); + * obj.hit(timestamp); + * int param_2 = obj.getHits(timestamp); + */ + From db983ef0e1ac85e0bed29c23ff3b9eb758b0546e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Jun 2016 13:34:18 +0800 Subject: [PATCH 2443/4971] Update design-hit-counter.py --- Python/design-hit-counter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/design-hit-counter.py b/Python/design-hit-counter.py index f113f4014..c6162aa6e 100644 --- a/Python/design-hit-counter.py +++ b/Python/design-hit-counter.py @@ -1,4 +1,4 @@ -# Time: O(1) +# Time: O(1), amortized # Space: O(k), k is the count of seconds. from collections import deque From f4de3bad795460177cfcdaf01c701b0cca23c9b4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Jun 2016 13:35:51 +0800 Subject: [PATCH 2444/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b44458af4..56de701d5 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-361%20%2F%20361-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-362%20%2F%20362-ff69b4.svg) -Up to date (2016-06-18), there are `344` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-21), there are `345` 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 `361` questions. +Here is the classification of all `362` 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. ) @@ -474,6 +474,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(s)_| _O(s)_| Medium |📖| Deque | 355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_| _O(t + f)_| Hard | LintCode | Heap | 359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | [C++](./C++/logger-rate-limiter.cpp) [Python](./Python/logger-rate-limiter.py) | _O(1), amortized_ | _O(k)_| Easy |📖| Deque | +362| [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [C++](./C++/design-hit-counter.cpp) [Python](./Python/design-hit-counter.py) | _O(1), amortized_ | _O(k)_| Medium |📖| Deque | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From 8f10ecf9dc640b2bab62646a26d0e7e087582fcb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Jun 2016 20:22:46 +0800 Subject: [PATCH 2445/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 56de701d5..b9864909b 100644 --- a/README.md +++ b/README.md @@ -461,7 +461,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/)| [C++](./C++/candy.cpp) [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 | +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 || Ascending 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 || From d6e703457c30ed9cc4891a32b820c410a688deac Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Jun 2016 20:59:09 +0800 Subject: [PATCH 2446/4971] Update design-hit-counter.py --- Python/design-hit-counter.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/design-hit-counter.py b/Python/design-hit-counter.py index c6162aa6e..f5ad39b18 100644 --- a/Python/design-hit-counter.py +++ b/Python/design-hit-counter.py @@ -35,8 +35,7 @@ def getHits(self, timestamp): :rtype: int """ while self.__dq and self.__dq[0][0] <= timestamp - self.__k: - self.__count -= self.__dq[0][1] - self.__dq.popleft() + self.__count -= self.__dq.popleft()[1] return self.__count # Your HitCounter object will be instantiated and called as such: From e73ddda651a742dce12781bc347f0603f0e8b553 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 22 Jun 2016 13:40:06 +0800 Subject: [PATCH 2447/4971] Create max-sum-of-sub-matrix-no-larger-than-k.cpp --- ...max-sum-of-sub-matrix-no-larger-than-k.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/max-sum-of-sub-matrix-no-larger-than-k.cpp diff --git a/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp b/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp new file mode 100644 index 000000000..aa54bfe10 --- /dev/null +++ b/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp @@ -0,0 +1,40 @@ +// Time: O(min(m, n)^2 * max(m, n) * log(max(m, n))) +// Space: O(max(m, n)) + +class Solution { +public: + int maxSumSubmatrix(vector>& matrix, int k) { + if (matrix.empty()) { + return 0; + } + + const int m = min(matrix.size(), matrix[0].size()); + const int n = max(matrix.size(), matrix[0].size()); + int result = numeric_limits::min(); + + for (int i = 0; i < m; ++i) { + vector sums(n, 0); + for (int j = i; j < m; ++j) { + for (int k = 0; k < n; ++k) { + sums[k] += (n == matrix.size()) ? matrix[k][j] : matrix[j][k]; + } + + // Find the max subarray no more than K. + set accu_sum_set; + accu_sum_set.emplace(0); + int accu_sum = 0, curr_max = numeric_limits::min(); + for (int sum : sums) { + accu_sum += sum; + auto it = accu_sum_set.lower_bound(accu_sum - k); + if (it != accu_sum_set.end()) { + curr_max = max(curr_max, accu_sum - *it); + } + accu_sum_set.emplace(accu_sum); + } + result = max(result, curr_max); + } + } + + return result; + } +}; From 3dd9ddf106e5a8a94ba42f0f57c52e17da19d74e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 22 Jun 2016 13:58:34 +0800 Subject: [PATCH 2448/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b9864909b..aa9d19b55 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-362%20%2F%20362-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-363%20%2F%20363-ff69b4.svg) -Up to date (2016-06-21), there are `345` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-22), there are `346` 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 `362` questions. +Here is the classification of all `363` 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. ) @@ -338,6 +338,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | 📖 | 354| [Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes/) | [C++](./C++/russian-doll-envelopes.cpp) [Python](./Python/russian-doll-envelopes.py) | _O(nlogn)_ | _O(1)_ | Hard ||| +363| [Max Sum of Rectangle No Larger Than K](https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/) | [C++](./C++/max-sum-of-sub-matrix-no-larger-than-k.cpp) [Python](./Python/max-sum-of-sub-matrix-no-larger-than-k.py) | _O(min(m, n)^2 * max(m, n) * logn(max(m, n)))_ | _O(max(m, n))_ | Medium ||| ## Binary Search Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note From 81f84af79a895c4ef505533b0c46b3c69221c0d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 22 Jun 2016 14:09:58 +0800 Subject: [PATCH 2449/4971] Update max-sum-of-sub-matrix-no-larger-than-k.cpp --- C++/max-sum-of-sub-matrix-no-larger-than-k.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp b/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp index aa54bfe10..c517a346e 100644 --- a/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp +++ b/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp @@ -22,16 +22,15 @@ class Solution { // Find the max subarray no more than K. set accu_sum_set; accu_sum_set.emplace(0); - int accu_sum = 0, curr_max = numeric_limits::min(); + int accu_sum = 0; for (int sum : sums) { accu_sum += sum; auto it = accu_sum_set.lower_bound(accu_sum - k); if (it != accu_sum_set.end()) { - curr_max = max(curr_max, accu_sum - *it); + result = max(result, accu_sum - *it); } accu_sum_set.emplace(accu_sum); } - result = max(result, curr_max); } } From bb7ebfa14e65c270101f0d43f54a3b787f8d1f0a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 22 Jun 2016 14:16:18 +0800 Subject: [PATCH 2450/4971] Update max-sum-of-sub-matrix-no-larger-than-k.cpp --- C++/max-sum-of-sub-matrix-no-larger-than-k.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp b/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp index c517a346e..1dba6f09b 100644 --- a/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp +++ b/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp @@ -15,8 +15,8 @@ class Solution { for (int i = 0; i < m; ++i) { vector sums(n, 0); for (int j = i; j < m; ++j) { - for (int k = 0; k < n; ++k) { - sums[k] += (n == matrix.size()) ? matrix[k][j] : matrix[j][k]; + for (int l = 0; l < n; ++l) { + sums[l] += (n == matrix.size()) ? matrix[l][j] : matrix[j][l]; } // Find the max subarray no more than K. From 588d5a69f7b6cf168d0c1a0c4dd62b7fcf22c9b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 22 Jun 2016 14:37:13 +0800 Subject: [PATCH 2451/4971] Update max-sum-of-sub-matrix-no-larger-than-k.cpp --- C++/max-sum-of-sub-matrix-no-larger-than-k.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp b/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp index 1dba6f09b..1fd294eca 100644 --- a/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp +++ b/C++/max-sum-of-sub-matrix-no-larger-than-k.cpp @@ -16,7 +16,7 @@ class Solution { vector sums(n, 0); for (int j = i; j < m; ++j) { for (int l = 0; l < n; ++l) { - sums[l] += (n == matrix.size()) ? matrix[l][j] : matrix[j][l]; + sums[l] += (m == matrix.size()) ? matrix[j][l] : matrix[l][j]; } // Find the max subarray no more than K. From 9ab96f0e60e54bf8ed4c8c3c0a1ff5d0d4bbec2b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 22 Jun 2016 17:48:01 +0800 Subject: [PATCH 2452/4971] Create max-sum-of-sub-matrix-no-larger-than-k.py --- .../max-sum-of-sub-matrix-no-larger-than-k.py | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Python/max-sum-of-sub-matrix-no-larger-than-k.py diff --git a/Python/max-sum-of-sub-matrix-no-larger-than-k.py b/Python/max-sum-of-sub-matrix-no-larger-than-k.py new file mode 100644 index 000000000..606c42717 --- /dev/null +++ b/Python/max-sum-of-sub-matrix-no-larger-than-k.py @@ -0,0 +1,82 @@ +# Time: O(min(m, n)^2 * max(m, n) * log(max(m, n))) +# Space: O(max(m, n)) + +# Given a non-empty 2D matrix matrix and an integer k, +# find the max sum of a rectangle in the matrix such that its sum is no larger than k. +# +# Example: +# Given matrix = [ +# [1, 0, 1], +# [0, -2, 3] +# ] +# k = 2 +# The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] +# is 2 and 2 is the max number no larger than k (k = 2). +# +# Note: +# The rectangle inside the matrix must have an area > 0. +# What if the number of rows is much larger than the number of columns? + +class BST(object): + def __init__(self, val): + """Create a new leaf with key t.""" + self.val = val + self.left = None + self.right = None + + def insert(self, val): + prev, curr = self, self + while curr: + if curr.val >= val: + if curr.left: + prev, curr = curr, curr.left + else: + curr.left = BST(val) + return + else: + if curr.right: + prev, curr = curr, curr.right + else: + curr.right = BST(val) + return + + def lower_bound(self, val): + result, curr = None, self + while curr: + if curr.val >= val: + result, curr = curr, curr.left + else: + curr = curr.right + return result + + +class Solution_TLE(object): + def maxSumSubmatrix(self, matrix, k): + """ + :type matrix: List[List[int]] + :type k: int + :rtype: int + """ + if not matrix: + return 0 + + result = float("-inf") + m = min(len(matrix), len(matrix[0])) + n = max(len(matrix), len(matrix[0])) + for i in xrange(m): + sums = [0] * n + for j in xrange(i, m): + for l in xrange(n): + sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j] + + # Find the max subarray no more than K. + accu_sum_set = BST(0) + accu_sum = 0 + for sum in sums: + accu_sum += sum + node = accu_sum_set.lower_bound(accu_sum - k); + if node: + result = max(result, accu_sum - node.val) + accu_sum_set.insert(accu_sum) + + return result From 27f0c6af282cce5e47ce7cb657fd5e16e4cff9d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 22 Jun 2016 17:50:31 +0800 Subject: [PATCH 2453/4971] Update max-sum-of-sub-matrix-no-larger-than-k.py --- Python/max-sum-of-sub-matrix-no-larger-than-k.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/max-sum-of-sub-matrix-no-larger-than-k.py b/Python/max-sum-of-sub-matrix-no-larger-than-k.py index 606c42717..eb7c6cdad 100644 --- a/Python/max-sum-of-sub-matrix-no-larger-than-k.py +++ b/Python/max-sum-of-sub-matrix-no-larger-than-k.py @@ -19,7 +19,6 @@ class BST(object): def __init__(self, val): - """Create a new leaf with key t.""" self.val = val self.left = None self.right = None @@ -60,9 +59,10 @@ def maxSumSubmatrix(self, matrix, k): if not matrix: return 0 - result = float("-inf") m = min(len(matrix), len(matrix[0])) n = max(len(matrix), len(matrix[0])) + result = float("-inf") + for i in xrange(m): sums = [0] * n for j in xrange(i, m): From b87bd75e1bd2a9992d90663c5c8bd4f44ebeb4fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 22 Jun 2016 17:54:37 +0800 Subject: [PATCH 2454/4971] Update max-sum-of-sub-matrix-no-larger-than-k.py --- Python/max-sum-of-sub-matrix-no-larger-than-k.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/max-sum-of-sub-matrix-no-larger-than-k.py b/Python/max-sum-of-sub-matrix-no-larger-than-k.py index eb7c6cdad..b90f056dc 100644 --- a/Python/max-sum-of-sub-matrix-no-larger-than-k.py +++ b/Python/max-sum-of-sub-matrix-no-larger-than-k.py @@ -24,17 +24,17 @@ def __init__(self, val): self.right = None def insert(self, val): - prev, curr = self, self + curr = self while curr: if curr.val >= val: if curr.left: - prev, curr = curr, curr.left + curr = curr.left else: curr.left = BST(val) return else: if curr.right: - prev, curr = curr, curr.right + curr = curr.right else: curr.right = BST(val) return From 2e732b538cba46f832034289e2a80cbc6bf96557 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jun 2016 00:45:22 +0800 Subject: [PATCH 2455/4971] Update max-sum-of-sub-matrix-no-larger-than-k.py --- .../max-sum-of-sub-matrix-no-larger-than-k.py | 111 +++++++++++++----- 1 file changed, 84 insertions(+), 27 deletions(-) diff --git a/Python/max-sum-of-sub-matrix-no-larger-than-k.py b/Python/max-sum-of-sub-matrix-no-larger-than-k.py index b90f056dc..3117b0c4a 100644 --- a/Python/max-sum-of-sub-matrix-no-larger-than-k.py +++ b/Python/max-sum-of-sub-matrix-no-larger-than-k.py @@ -17,38 +17,63 @@ # The rectangle inside the matrix must have an area > 0. # What if the number of rows is much larger than the number of columns? -class BST(object): - def __init__(self, val): - self.val = val - self.left = None - self.right = None +# Time: O(min(m, n)^2 * max(m, n)^2) +# Space: O(max(m, n)) - def insert(self, val): - curr = self - while curr: - if curr.val >= val: - if curr.left: - curr = curr.left - else: - curr.left = BST(val) - return - else: - if curr.right: - curr = curr.right - else: - curr.right = BST(val) - return +# Given a non-empty 2D matrix matrix and an integer k, +# find the max sum of a rectangle in the matrix such that its sum is no larger than k. +# +# Example: +# Given matrix = [ +# [1, 0, 1], +# [0, -2, 3] +# ] +# k = 2 +# The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] +# is 2 and 2 is the max number no larger than k (k = 2). +# +# Note: +# The rectangle inside the matrix must have an area > 0. +# What if the number of rows is much larger than the number of columns? + +# Time: O(min(m, n)^2 * max(m, n)^2) +# Space: O(max(m, n)) +from bisect import bisect_left, insort + +class Solution(object): + def maxSumSubmatrix(self, matrix, k): + """ + :type matrix: List[List[int]] + :type k: int + :rtype: int + """ + if not matrix: + return 0 + + m = min(len(matrix), len(matrix[0])) + n = max(len(matrix), len(matrix[0])) + result = float("-inf") + + for i in xrange(m): + sums = [0] * n + for j in xrange(i, m): + for l in xrange(n): + sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j] + + # Find the max subarray no more than K. + accu_sum_set, accu_sum = [0], 0 + for sum in sums: + accu_sum += sum + it = bisect_left(accu_sum_set, accu_sum - k) + if it != len(accu_sum_set): + result = max(result, accu_sum - accu_sum_set[it]) + insort(accu_sum_set, accu_sum) # Time: O(n) - def lower_bound(self, val): - result, curr = None, self - while curr: - if curr.val >= val: - result, curr = curr, curr.left - else: - curr = curr.right return result +# Time: O(min(m, n)^2 * max(m, n) * log(max(m, n))) +# Space: O(max(m, n)) class Solution_TLE(object): def maxSumSubmatrix(self, matrix, k): """ @@ -56,6 +81,38 @@ def maxSumSubmatrix(self, matrix, k): :type k: int :rtype: int """ + class BST(object): + def __init__(self, val): + self.val = val + self.left = None + self.right = None + + def insert(self, val): + curr = self + while curr: + if curr.val >= val: + if curr.left: + curr = curr.left + else: + curr.left = BST(val) + return + else: + if curr.right: + curr = curr.right + else: + curr.right = BST(val) + return + + def lower_bound(self, val): + result, curr = None, self + while curr: + if curr.val >= val: + result, curr = curr, curr.left + else: + curr = curr.right + return result + + if not matrix: return 0 From 78bbb4fe46ea06418e4349881c89ae8ba439ec2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jun 2016 00:46:13 +0800 Subject: [PATCH 2456/4971] Update max-sum-of-sub-matrix-no-larger-than-k.py --- Python/max-sum-of-sub-matrix-no-larger-than-k.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/max-sum-of-sub-matrix-no-larger-than-k.py b/Python/max-sum-of-sub-matrix-no-larger-than-k.py index 3117b0c4a..e9916eb18 100644 --- a/Python/max-sum-of-sub-matrix-no-larger-than-k.py +++ b/Python/max-sum-of-sub-matrix-no-larger-than-k.py @@ -64,7 +64,7 @@ def maxSumSubmatrix(self, matrix, k): accu_sum_set, accu_sum = [0], 0 for sum in sums: accu_sum += sum - it = bisect_left(accu_sum_set, accu_sum - k) + it = bisect_left(accu_sum_set, accu_sum - k) # Time: O(logn) if it != len(accu_sum_set): result = max(result, accu_sum - accu_sum_set[it]) insort(accu_sum_set, accu_sum) # Time: O(n) From f1629dfe1b9e53717090ab2807040f37153488ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jun 2016 00:46:36 +0800 Subject: [PATCH 2457/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index aa9d19b55..139144d9a 100644 --- a/README.md +++ b/README.md @@ -338,7 +338,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | 📖 | 354| [Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes/) | [C++](./C++/russian-doll-envelopes.cpp) [Python](./Python/russian-doll-envelopes.py) | _O(nlogn)_ | _O(1)_ | Hard ||| -363| [Max Sum of Rectangle No Larger Than K](https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/) | [C++](./C++/max-sum-of-sub-matrix-no-larger-than-k.cpp) [Python](./Python/max-sum-of-sub-matrix-no-larger-than-k.py) | _O(min(m, n)^2 * max(m, n) * logn(max(m, n)))_ | _O(max(m, n))_ | Medium ||| +363| [Max Sum of Rectangle No Larger Than K](https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/) | [C++](./C++/max-sum-of-sub-matrix-no-larger-than-k.cpp) [Python](./Python/max-sum-of-sub-matrix-no-larger-than-k.py) | _O(min(m, n)^2 * max(m, n) * logn(max(m, n)))_ | _O(max(m, n))_ | Hard ||| ## Binary Search Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note From 1972cefc1b2e30a97f59d5b0cb20735d4f4f7004 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jun 2016 01:03:03 +0800 Subject: [PATCH 2458/4971] Update max-sum-of-sub-matrix-no-larger-than-k.py --- Python/max-sum-of-sub-matrix-no-larger-than-k.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/max-sum-of-sub-matrix-no-larger-than-k.py b/Python/max-sum-of-sub-matrix-no-larger-than-k.py index e9916eb18..51406f39f 100644 --- a/Python/max-sum-of-sub-matrix-no-larger-than-k.py +++ b/Python/max-sum-of-sub-matrix-no-larger-than-k.py @@ -58,7 +58,7 @@ def maxSumSubmatrix(self, matrix, k): sums = [0] * n for j in xrange(i, m): for l in xrange(n): - sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j] + sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j] # Find the max subarray no more than K. accu_sum_set, accu_sum = [0], 0 @@ -124,7 +124,7 @@ def lower_bound(self, val): sums = [0] * n for j in xrange(i, m): for l in xrange(n): - sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j] + sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j] # Find the max subarray no more than K. accu_sum_set = BST(0) From 81a760d8dcc46a4d8ad84f2f5ac4ca3deb1d180a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jun 2016 01:06:06 +0800 Subject: [PATCH 2459/4971] Update max-sum-of-sub-matrix-no-larger-than-k.py --- Python/max-sum-of-sub-matrix-no-larger-than-k.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/max-sum-of-sub-matrix-no-larger-than-k.py b/Python/max-sum-of-sub-matrix-no-larger-than-k.py index 51406f39f..d21b3fe78 100644 --- a/Python/max-sum-of-sub-matrix-no-larger-than-k.py +++ b/Python/max-sum-of-sub-matrix-no-larger-than-k.py @@ -72,7 +72,7 @@ def maxSumSubmatrix(self, matrix, k): return result -# Time: O(min(m, n)^2 * max(m, n) * log(max(m, n))) +# Time: O(min(m, n)^2 * max(m, n) * log(max(m, n))) ~ O(min(m, n)^2 * max(m, n)^2) # Space: O(max(m, n)) class Solution_TLE(object): def maxSumSubmatrix(self, matrix, k): @@ -81,13 +81,13 @@ def maxSumSubmatrix(self, matrix, k): :type k: int :rtype: int """ - class BST(object): + class BST(object): # not avl, rbtree def __init__(self, val): self.val = val self.left = None self.right = None - def insert(self, val): + def insert(self, val): # Time: O(h) = O(logn) ~ O(n) curr = self while curr: if curr.val >= val: @@ -103,7 +103,7 @@ def insert(self, val): curr.right = BST(val) return - def lower_bound(self, val): + def lower_bound(self, val): # Time: O(h) = O(logn) ~ O(n) result, curr = None, self while curr: if curr.val >= val: From e4f6df2006cc7f16fa4ace11b17aac283aae3168 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jun 2016 12:09:17 +0800 Subject: [PATCH 2460/4971] Create nested-list-weight-sum-ii.cpp --- C++/nested-list-weight-sum-ii.cpp | 49 +++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 C++/nested-list-weight-sum-ii.cpp diff --git a/C++/nested-list-weight-sum-ii.cpp b/C++/nested-list-weight-sum-ii.cpp new file mode 100644 index 000000000..3fafc248e --- /dev/null +++ b/C++/nested-list-weight-sum-ii.cpp @@ -0,0 +1,49 @@ +// Time: O(n) +// Space: O(h) + +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ +class Solution { +public: + int depthSumInverse(vector& nestedList) { + vector result; + for(auto list : nestedList) { + depthSumInverseHelper(list, 0, &result); + } + + int sum = 0; + for (int i = result.size() - 1; i >= 0; --i) { + sum += result[i] * (result.size() - i); + } + return sum; + } + +private: + void depthSumInverseHelper(const NestedInteger &list, int depth, vector *result) { + if (result->size() < depth + 1) { + result->emplace_back(0); + } + if (list.isInteger()) { + (*result)[depth] += list.getInteger(); + } else { + for(auto l : list.getList()) { + depthSumInverseHelper(l, depth + 1, result); + } + } + } +}; From 61c99ec5fba2f491ae33132ddb82778086418dd2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jun 2016 12:12:47 +0800 Subject: [PATCH 2461/4971] Create nested-list-weight-sum-ii.py --- Python/nested-list-weight-sum-ii.py | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/nested-list-weight-sum-ii.py diff --git a/Python/nested-list-weight-sum-ii.py b/Python/nested-list-weight-sum-ii.py new file mode 100644 index 000000000..0594d091c --- /dev/null +++ b/Python/nested-list-weight-sum-ii.py @@ -0,0 +1,51 @@ +# Time: O(n) +# Space: O(h) + +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger(object): +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ + +class Solution(object): + def depthSumInverse(self, nestedList): + """ + :type nestedList: List[NestedInteger] + :rtype: int + """ + def depthSumInverseHelper(list, depth, result): + if len(result) < depth + 1: + result.append(0) + if list.isInteger(): + result[depth] += list.getInteger() + else: + for l in list.getList(): + depthSumInverseHelper(l, depth + 1, result) + + result = [] + for list in nestedList: + depthSumInverseHelper(list, 0, result) + + sum = 0 + for i in reversed(xrange(len(result))): + sum += result[i] * (len(result) - i) + return sum From 8bc7189790e113009d6a558fe0af5c901d73b05b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jun 2016 12:14:54 +0800 Subject: [PATCH 2462/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 139144d9a..81172cbeb 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-363%20%2F%20363-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-364%20%2F%20364-ff69b4.svg) -Up to date (2016-06-22), there are `346` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-23), there are `347` 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 `363` questions. +Here is the classification of all `364` 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. ) @@ -384,6 +384,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 ||| 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 ||| 339| [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) | [C++](./C++/nested-list-weight-sum.cpp) [Python](./Python/nested-list-weight-sum.py) | _O(n)_ | _O(h)_ | Easy |📖|| +364| [Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii/) | [C++](./C++/nested-list-weight-sum-ii.cpp) [Python](./Python/nested-list-weight-sum-ii.py) | _O(n)_ | _O(h)_ | Medium |📖|| ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note From efb6dcbaf72b94d591f2646e51cd92cc648f20d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jun 2016 12:16:08 +0800 Subject: [PATCH 2463/4971] Update nested-list-weight-sum-ii.cpp --- C++/nested-list-weight-sum-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/nested-list-weight-sum-ii.cpp b/C++/nested-list-weight-sum-ii.cpp index 3fafc248e..960ec46e6 100644 --- a/C++/nested-list-weight-sum-ii.cpp +++ b/C++/nested-list-weight-sum-ii.cpp @@ -22,7 +22,7 @@ class Solution { public: int depthSumInverse(vector& nestedList) { vector result; - for(auto list : nestedList) { + for (const auto& list : nestedList) { depthSumInverseHelper(list, 0, &result); } @@ -41,7 +41,7 @@ class Solution { if (list.isInteger()) { (*result)[depth] += list.getInteger(); } else { - for(auto l : list.getList()) { + for(const auto& l : list.getList()) { depthSumInverseHelper(l, depth + 1, result); } } From 7f36ee72cf70301f607bd481df8862e34cea7517 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Jun 2016 12:16:20 +0800 Subject: [PATCH 2464/4971] Update nested-list-weight-sum-ii.cpp --- C++/nested-list-weight-sum-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/nested-list-weight-sum-ii.cpp b/C++/nested-list-weight-sum-ii.cpp index 960ec46e6..61be50f94 100644 --- a/C++/nested-list-weight-sum-ii.cpp +++ b/C++/nested-list-weight-sum-ii.cpp @@ -41,7 +41,7 @@ class Solution { if (list.isInteger()) { (*result)[depth] += list.getInteger(); } else { - for(const auto& l : list.getList()) { + for (const auto& l : list.getList()) { depthSumInverseHelper(l, depth + 1, result); } } From 4e8aba753faa805450bdf1eb9693e708ebd39387 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Jun 2016 11:03:58 +0800 Subject: [PATCH 2465/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index 18dee3946..32e3cd758 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -33,7 +33,7 @@ class SummaryRanges { } vector getIntervals() { - return vector(intervals_.begin(), intervals_.end()); + return {intervals_.begin(), intervals_.end()}; } private: From bd6032e0321786d8bd117f590e5c3e1373acf1a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Jun 2016 11:06:18 +0800 Subject: [PATCH 2466/4971] Update data-stream-as-disjoint-intervals.cpp --- C++/data-stream-as-disjoint-intervals.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/data-stream-as-disjoint-intervals.cpp b/C++/data-stream-as-disjoint-intervals.cpp index 32e3cd758..4561488a1 100644 --- a/C++/data-stream-as-disjoint-intervals.cpp +++ b/C++/data-stream-as-disjoint-intervals.cpp @@ -33,7 +33,7 @@ class SummaryRanges { } vector getIntervals() { - return {intervals_.begin(), intervals_.end()}; + return {intervals_.cbegin(), intervals_.cend()}; } private: From 3e4bf0ef8d6ca46cfa252efeb6d6647ea63bc7f6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Jun 2016 15:17:49 +0800 Subject: [PATCH 2467/4971] Create water-and-jug-problem.py --- Python/water-and-jug-problem.py | 38 +++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/water-and-jug-problem.py diff --git a/Python/water-and-jug-problem.py b/Python/water-and-jug-problem.py new file mode 100644 index 000000000..3e0a464a8 --- /dev/null +++ b/Python/water-and-jug-problem.py @@ -0,0 +1,38 @@ +# Time: O(logn) +# Space: O(1) + +# You are given two jugs with capacities x and y litres. +# There is an infinite amount of water supply available. +# You need to determine whether it is possible to +# measure exactly z litres using these two jugs. +# +# Operations allowed: +# +# Fill any of the jugs completely. +# Empty any of the jugs. +# Pour water from one jug into another till +# the other jug is completely full or +# the first jug itself is empty. +# Example 1: +# +# Input: x = 2, y = 6, z = 4 +# Output: True +# Example 2: +# +# Input: x = 2, y = 6, z = 5 +# Output: False + +from fractions import gcd + +class Solution(object): + def canMeasureWater(self, x, y, z): + """ + :type x: int + :type y: int + :type z: int + :rtype: bool + """ + # The problem is to solve: + # - check z <= max(x, y) + # - check if there is any (a, b) integers s.t. ax + by = z + return z <= max(x, y) and z % gcd(x, y) == 0 From 47392f0497f97cd1d7c824c9223f7c1eb2e230ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Jun 2016 15:29:40 +0800 Subject: [PATCH 2468/4971] Create water-and-jug-problem.cpp --- C++/water-and-jug-problem.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/water-and-jug-problem.cpp diff --git a/C++/water-and-jug-problem.cpp b/C++/water-and-jug-problem.cpp new file mode 100644 index 000000000..49fa1e54a --- /dev/null +++ b/C++/water-and-jug-problem.cpp @@ -0,0 +1,19 @@ +// Time: O(logn), n is the max of (x, y) +// Space: O(1) + +class Solution { +public: + bool canMeasureWater(int x, int y, int z) { + return z <= max(x, y) && z % gcd(x, y) == 0; + } + +private: + int gcd(int a, int b) { + while (b != 0) { + int tmp = b; + b = a % b; + a = tmp; + } + return b; + } +}; From d6d0507b53d35acd59820c8df05229a8c73a2184 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Jun 2016 15:32:39 +0800 Subject: [PATCH 2469/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 81172cbeb..d3476582e 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-364%20%2F%20364-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-365%20%2F%20365-ff69b4.svg) -Up to date (2016-06-23), there are `347` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-24), there are `348` 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 `364` questions. +Here is the classification of all `365` 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. ) @@ -257,6 +257,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 ||| 343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(1)_ | Medium || Tricky, DP | +365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || Euclidean Algorithm | ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From 16b3557266c97f290a81ebabf9be346c525c4515 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Jun 2016 15:33:12 +0800 Subject: [PATCH 2470/4971] Update water-and-jug-problem.py --- Python/water-and-jug-problem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/water-and-jug-problem.py b/Python/water-and-jug-problem.py index 3e0a464a8..beb3af951 100644 --- a/Python/water-and-jug-problem.py +++ b/Python/water-and-jug-problem.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(logn), n is the max of (x, y) # Space: O(1) # You are given two jugs with capacities x and y litres. From ea1fcbfa01d184569c4cf56c8f1876ed40db15da Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Jun 2016 15:35:08 +0800 Subject: [PATCH 2471/4971] Update water-and-jug-problem.cpp --- C++/water-and-jug-problem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/water-and-jug-problem.cpp b/C++/water-and-jug-problem.cpp index 49fa1e54a..f8b1b053c 100644 --- a/C++/water-and-jug-problem.cpp +++ b/C++/water-and-jug-problem.cpp @@ -14,6 +14,6 @@ class Solution { b = a % b; a = tmp; } - return b; + return a; } }; From 08f09985be82190a9c73cdb399d9007820d83791 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 25 Jun 2016 11:16:17 +0800 Subject: [PATCH 2472/4971] Create find-leaves-of-binary-tree.cpp --- C++/find-leaves-of-binary-tree.cpp | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/find-leaves-of-binary-tree.cpp diff --git a/C++/find-leaves-of-binary-tree.cpp b/C++/find-leaves-of-binary-tree.cpp new file mode 100644 index 000000000..2d3e41ed6 --- /dev/null +++ b/C++/find-leaves-of-binary-tree.cpp @@ -0,0 +1,34 @@ +// 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: + vector> findLeaves(TreeNode* root) { + vector> result; + findLeavesHelper(root, &result); + return result; + } + +private: + int findLeavesHelper(TreeNode *node, vector> *result) { + if (node == nullptr) { + return -1; + } + const int level = 1 + max(findLeavesHelper(node->left, result), + findLeavesHelper(node->right, result)); + if (result->size() < level + 1){ + result->emplace_back(); + } + (*result)[level].emplace_back(node->val); + return level; + } +}; From ff358a79c502e1e37901773a125d580fd7179b4a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 25 Jun 2016 11:20:43 +0800 Subject: [PATCH 2473/4971] Create find-leaves-of-binary-tree.py --- Python/find-leaves-of-binary-tree.py | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python/find-leaves-of-binary-tree.py diff --git a/Python/find-leaves-of-binary-tree.py b/Python/find-leaves-of-binary-tree.py new file mode 100644 index 000000000..0560ed748 --- /dev/null +++ b/Python/find-leaves-of-binary-tree.py @@ -0,0 +1,29 @@ +# 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 findLeaves(self, root): + """ + :type root: TreeNode + :rtype: List[List[int]] + """ + def findLeavesHelper(node, result): + if not node: + return -1 + level = 1 + max(findLeavesHelper(node.left, result), \ + findLeavesHelper(node.right, result)) + if len(result) < level + 1: + result.append([]) + result[level].append(node.val) + return level + + result = [] + findLeavesHelper(root, result) + return result From e120516a0d6849655ea08fc3252ca2f60c776fb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 25 Jun 2016 11:22:36 +0800 Subject: [PATCH 2474/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d3476582e..14960fd49 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-365%20%2F%20365-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-366%20%2F%20366-ff69b4.svg) -Up to date (2016-06-24), there are `348` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-25), there are `349` 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 `365` questions. +Here is the classification of all `366` 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 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 ||| 339| [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) | [C++](./C++/nested-list-weight-sum.cpp) [Python](./Python/nested-list-weight-sum.py) | _O(n)_ | _O(h)_ | Easy |📖|| 364| [Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii/) | [C++](./C++/nested-list-weight-sum-ii.cpp) [Python](./Python/nested-list-weight-sum-ii.py) | _O(n)_ | _O(h)_ | Medium |📖|| +366| [Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/) | [C++](./C++/find-leaves-of-binary-tree.cpp) [Python](./Python/find-leaves-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium |📖|| ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note From c9babbfea01fa6fc13c9ee031dbaa8ae22ecebed Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Jun 2016 16:02:14 +0800 Subject: [PATCH 2475/4971] Create valid-perfect-square.cpp --- C++/valid-perfect-square.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/valid-perfect-square.cpp diff --git a/C++/valid-perfect-square.cpp b/C++/valid-perfect-square.cpp new file mode 100644 index 000000000..91c301ee5 --- /dev/null +++ b/C++/valid-perfect-square.cpp @@ -0,0 +1,18 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + bool isPerfectSquare(int num) { + int left = 1, right = num; + while (left <= right) { + const int mid = left + (right - left) / 2; + if (mid >= num / mid) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left == num / left && num % left == 0; + } +}; From bafc1bf47ef052f3d526f2e2ec77c711fe94d8ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Jun 2016 16:05:28 +0800 Subject: [PATCH 2476/4971] Create valid-perfect-square.py --- Python/valid-perfect-square.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/valid-perfect-square.py diff --git a/Python/valid-perfect-square.py b/Python/valid-perfect-square.py new file mode 100644 index 000000000..1b77255fa --- /dev/null +++ b/Python/valid-perfect-square.py @@ -0,0 +1,31 @@ +# Time: O(logn) +# Space: O(1) + +# Given a positive integer num, write a function +# which returns True if num is a perfect square else False. +# +# Note: Do not use any built-in library function such as sqrt. +# +# Example 1: +# +# Input: 16 +# Returns: True +# Example 2: +# +# Input: 14 +# Returns: False + +class Solution(object): + def isPerfectSquare(self, num): + """ + :type num: int + :rtype: bool + """ + left, right = 1, num + while left <= right: + mid = left + (right - left) / 2 + if mid >= num / mid: + right = mid - 1 + else: + left = mid + 1 + return left == num / left and num % left == 0 From 391fa98380ba87c71618055ad0d6b27970444834 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Jun 2016 16:07:21 +0800 Subject: [PATCH 2477/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 14960fd49..56e484283 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-366%20%2F%20366-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-367%20%2F%20367-ff69b4.svg) -Up to date (2016-06-25), there are `349` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-26), there are `350` 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 `366` questions. +Here is the classification of all `367` 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 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 | 📖 | 354| [Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes/) | [C++](./C++/russian-doll-envelopes.cpp) [Python](./Python/russian-doll-envelopes.py) | _O(nlogn)_ | _O(1)_ | Hard ||| 363| [Max Sum of Rectangle No Larger Than K](https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/) | [C++](./C++/max-sum-of-sub-matrix-no-larger-than-k.cpp) [Python](./Python/max-sum-of-sub-matrix-no-larger-than-k.py) | _O(min(m, n)^2 * max(m, n) * logn(max(m, n)))_ | _O(max(m, n))_ | Hard ||| +367| [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/)| [C++](./C++/valid-perfect-square.cpp) [Python](./Python/valid-perfect-square.py) | _O(logn)_ | _O(1)_ | Medium | | ## Binary Search Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note From 6dff023ae35b6cfab3f55c62f5b35ca297176438 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 14:32:03 +0800 Subject: [PATCH 2478/4971] Create largest-divisible-subset.py --- Python/largest-divisible-subset.py | 47 ++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/largest-divisible-subset.py diff --git a/Python/largest-divisible-subset.py b/Python/largest-divisible-subset.py new file mode 100644 index 000000000..32ddb03dd --- /dev/null +++ b/Python/largest-divisible-subset.py @@ -0,0 +1,47 @@ +# Time: O(n^2) +# Space: O(n) + +# Given a set of distinct positive integers, +# find the largest subset such that every pair (Si, Sj) of +# elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. +# +# If there are multiple solutions, return any subset is fine. +# +# Example 1: +# +# nums: [1,2,3] +# +# Result: [1,2] (of course, [1,3] will also be ok) +# Example 2: +# +# nums: [1,2,4,8] +# +# Result: [1,2,4,8] + +class Solution(object): + def largestDivisibleSubset(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + if not nums: + return [] + + nums.sort() + dp = [1] * (len(nums) + 1) + prev = [-1] * len(nums) + largest_idx = 1 + for i in xrange(1, len(nums)+1): + for j in xrange(1, i): + if nums[i-1] % nums[j-1] == 0: + if dp[i] < dp[j] + 1: + dp[i] = dp[j] + 1 + prev[i-1] = j-1 + if dp[largest_idx] < dp[i]: + largest_idx = i + result = [] + i = largest_idx - 1 + while i != -1: + result.append(nums[i]) + i = prev[i] + return result[::-1] From f696f20d256b522776c025ce274606b06988a34c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 14:35:59 +0800 Subject: [PATCH 2479/4971] Create largest-divisible-subset.cpp --- C++/largest-divisible-subset.cpp | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/largest-divisible-subset.cpp diff --git a/C++/largest-divisible-subset.cpp b/C++/largest-divisible-subset.cpp new file mode 100644 index 000000000..4092fda03 --- /dev/null +++ b/C++/largest-divisible-subset.cpp @@ -0,0 +1,37 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + vector largestDivisibleSubset(vector& nums) { + if (nums.empty()) { + return {}; + } + + sort(nums.begin(), nums.end()); + // dp[i]: the size of the largest distinct subset of + // the first i numbers including nums[i-1] + vector dp(nums.size() + 1, 1); + vector prev(nums.size(), -1); + int largest_idx = 1; + for (int i = 1; i <= nums.size(); ++i) { + for (int j = 1; j < i; ++j) { + if (nums[i - 1] % nums[j - 1] == 0) { + if (dp[i] < dp[j] + 1) { + dp[i] = dp[j] + 1; + prev[i - 1] = j - 1; + } + if (dp[largest_idx] < dp[i]) { + largest_idx = i; + } + } + } + } + vector result; + for (int i = largest_idx - 1; i != -1; i = prev[i]) { + result.emplace_back(nums[i]); + } + reverse(result.begin(), result.end()); + return result; + } +}; From 1201e2d5e82a44b0b0cdd56e4690b295165b377f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 14:37:37 +0800 Subject: [PATCH 2480/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 56e484283..fac017ec6 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-367%20%2F%20367-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-368%20%2F%20368-ff69b4.svg) -Up to date (2016-06-26), there are `350` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-27), there are `351` 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 `367` questions. +Here is the classification of all `368` 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. ) @@ -454,6 +454,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 351| [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) | [C++](./C++/android-unlock-patterns.cpp) [Python](./Python/android-unlock-patterns.py) | _O(9^2 * 2^9)_ | _O(9 * 2^9)_ | Medium | 📖 | Backtracking | 357| [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | [C++](./C++/count-numbers-with-unique-digits.cpp) [Python](./Python/count-numbers-with-unique-digits.py) | _O(n)_ | _O(1)_ | Medium || Backtracking, Math | 361| [Bomb Enemy](https://leetcode.com/problems/bomb-enemy/) | [C++](./C++/bomb-enemy.cpp) [Python](./Python/bomb-enemy.py) | _O(m * n)_ | _O(m * n)_ | Medium | 📖 | | +367| [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [C++](./C++/largest-divisible-subset.cpp) [Python](./Python/largest-divisible-subset.py) | _O(n^2)_ | _O(n)_ | Medium | | | ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 705622c53403b4cde55e63526e3115d5548e64db Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 14:38:08 +0800 Subject: [PATCH 2481/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fac017ec6..f693d1a0d 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 351| [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) | [C++](./C++/android-unlock-patterns.cpp) [Python](./Python/android-unlock-patterns.py) | _O(9^2 * 2^9)_ | _O(9 * 2^9)_ | Medium | 📖 | Backtracking | 357| [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | [C++](./C++/count-numbers-with-unique-digits.cpp) [Python](./Python/count-numbers-with-unique-digits.py) | _O(n)_ | _O(1)_ | Medium || Backtracking, Math | 361| [Bomb Enemy](https://leetcode.com/problems/bomb-enemy/) | [C++](./C++/bomb-enemy.cpp) [Python](./Python/bomb-enemy.py) | _O(m * n)_ | _O(m * n)_ | Medium | 📖 | | -367| [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [C++](./C++/largest-divisible-subset.cpp) [Python](./Python/largest-divisible-subset.py) | _O(n^2)_ | _O(n)_ | Medium | | | +368| [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [C++](./C++/largest-divisible-subset.cpp) [Python](./Python/largest-divisible-subset.py) | _O(n^2)_ | _O(n)_ | Medium | | | ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 29c909b81d50552f61498d5014e5ea02b7ef0fc4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 14:41:36 +0800 Subject: [PATCH 2482/4971] Update largest-divisible-subset.cpp --- C++/largest-divisible-subset.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/largest-divisible-subset.cpp b/C++/largest-divisible-subset.cpp index 4092fda03..f8b7af880 100644 --- a/C++/largest-divisible-subset.cpp +++ b/C++/largest-divisible-subset.cpp @@ -10,16 +10,16 @@ class Solution { sort(nums.begin(), nums.end()); // dp[i]: the size of the largest distinct subset of - // the first i numbers including nums[i-1] - vector dp(nums.size() + 1, 1); + // the first i+1 numbers including nums[i] + vector dp(nums.size() , 1); vector prev(nums.size(), -1); - int largest_idx = 1; - for (int i = 1; i <= nums.size(); ++i) { - for (int j = 1; j < i; ++j) { - if (nums[i - 1] % nums[j - 1] == 0) { + int largest_idx = 0; + for (int i = 0; i < nums.size(); ++i) { + for (int j = 0; j < i; ++j) { + if (nums[i] % nums[j] == 0) { if (dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1; - prev[i - 1] = j - 1; + prev[i] = j; } if (dp[largest_idx] < dp[i]) { largest_idx = i; @@ -28,7 +28,7 @@ class Solution { } } vector result; - for (int i = largest_idx - 1; i != -1; i = prev[i]) { + for (int i = largest_idx; i != -1; i = prev[i]) { result.emplace_back(nums[i]); } reverse(result.begin(), result.end()); From da4024168a48940966a135cbe0e74fe51ff80e68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 14:44:30 +0800 Subject: [PATCH 2483/4971] Update largest-divisible-subset.py --- Python/largest-divisible-subset.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Python/largest-divisible-subset.py b/Python/largest-divisible-subset.py index 32ddb03dd..daca2ffad 100644 --- a/Python/largest-divisible-subset.py +++ b/Python/largest-divisible-subset.py @@ -28,19 +28,19 @@ def largestDivisibleSubset(self, nums): return [] nums.sort() - dp = [1] * (len(nums) + 1) + dp = [1] * len(nums) prev = [-1] * len(nums) - largest_idx = 1 - for i in xrange(1, len(nums)+1): - for j in xrange(1, i): - if nums[i-1] % nums[j-1] == 0: + largest_idx = 0 + for i in xrange(len(nums)): + for j in xrange(i): + if nums[i] % nums[j] == 0: if dp[i] < dp[j] + 1: dp[i] = dp[j] + 1 - prev[i-1] = j-1 + prev[i] = j if dp[largest_idx] < dp[i]: largest_idx = i result = [] - i = largest_idx - 1 + i = largest_idx while i != -1: result.append(nums[i]) i = prev[i] From 767262eeb5eba26fff46164c76a0d147fcaa9db2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 14:48:13 +0800 Subject: [PATCH 2484/4971] Update largest-divisible-subset.py --- Python/largest-divisible-subset.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/largest-divisible-subset.py b/Python/largest-divisible-subset.py index daca2ffad..061024821 100644 --- a/Python/largest-divisible-subset.py +++ b/Python/largest-divisible-subset.py @@ -37,8 +37,8 @@ def largestDivisibleSubset(self, nums): if dp[i] < dp[j] + 1: dp[i] = dp[j] + 1 prev[i] = j - if dp[largest_idx] < dp[i]: - largest_idx = i + if dp[largest_idx] < dp[i]: + largest_idx = i result = [] i = largest_idx while i != -1: From 8e1de1d063708bd845d7d75e2098497223f76baf Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 21:46:48 +0800 Subject: [PATCH 2485/4971] Update largest-divisible-subset.cpp --- C++/largest-divisible-subset.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/largest-divisible-subset.cpp b/C++/largest-divisible-subset.cpp index f8b7af880..33cfb644f 100644 --- a/C++/largest-divisible-subset.cpp +++ b/C++/largest-divisible-subset.cpp @@ -21,11 +21,11 @@ class Solution { dp[i] = dp[j] + 1; prev[i] = j; } - if (dp[largest_idx] < dp[i]) { - largest_idx = i; - } } } + if (dp[largest_idx] < dp[i]) { + largest_idx = i; + } } vector result; for (int i = largest_idx; i != -1; i = prev[i]) { From 396758cf8fe27fb361357e8dde56f700a59d1d7b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 21:47:09 +0800 Subject: [PATCH 2486/4971] Update largest-divisible-subset.py --- Python/largest-divisible-subset.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/largest-divisible-subset.py b/Python/largest-divisible-subset.py index 061024821..c05ea7e9f 100644 --- a/Python/largest-divisible-subset.py +++ b/Python/largest-divisible-subset.py @@ -37,8 +37,8 @@ def largestDivisibleSubset(self, nums): if dp[i] < dp[j] + 1: dp[i] = dp[j] + 1 prev[i] = j - if dp[largest_idx] < dp[i]: - largest_idx = i + if dp[largest_idx] < dp[i]: + largest_idx = i result = [] i = largest_idx while i != -1: From fa0855c69759786bd180015f76a1f6b25fb0b669 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 21:51:22 +0800 Subject: [PATCH 2487/4971] Update largest-divisible-subset.py --- Python/largest-divisible-subset.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/largest-divisible-subset.py b/Python/largest-divisible-subset.py index c05ea7e9f..e908d1887 100644 --- a/Python/largest-divisible-subset.py +++ b/Python/largest-divisible-subset.py @@ -39,6 +39,7 @@ def largestDivisibleSubset(self, nums): prev[i] = j if dp[largest_idx] < dp[i]: largest_idx = i + result = [] i = largest_idx while i != -1: From 95a9ee604d6b9cffedba08d1d925c34dd6ef0e9a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Jun 2016 21:51:39 +0800 Subject: [PATCH 2488/4971] Update largest-divisible-subset.cpp --- C++/largest-divisible-subset.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/largest-divisible-subset.cpp b/C++/largest-divisible-subset.cpp index 33cfb644f..3a8ad35a2 100644 --- a/C++/largest-divisible-subset.cpp +++ b/C++/largest-divisible-subset.cpp @@ -27,6 +27,7 @@ class Solution { largest_idx = i; } } + vector result; for (int i = largest_idx; i != -1; i = prev[i]) { result.emplace_back(nums[i]); From 923e21132bd455997b72e96355b60455efb498ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jun 2016 13:53:47 +0800 Subject: [PATCH 2489/4971] Create plus-one-linked-list.py --- Python/plus-one-linked-list.py | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/plus-one-linked-list.py diff --git a/Python/plus-one-linked-list.py b/Python/plus-one-linked-list.py new file mode 100644 index 000000000..659ce7b3b --- /dev/null +++ b/Python/plus-one-linked-list.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(1) + +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def plusOne(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ + dummy = ListNode(0) + curr = head + while curr: + dummy.next, curr.next, curr = curr, dummy.next, curr.next + + curr, carry = dummy.next, 1 + while curr and carry: + curr.val += carry + carry = curr.val / 10 + curr.val %= 10 + if carry and curr.next is None: + curr.next = ListNode(0) + curr = curr.next + + curr = dummy.next + dummy.next = None + while curr: + dummy.next, curr.next, curr = curr, dummy.next, curr.next + + return dummy.next From 3ddb32a68d37c5930105c77b69ac044c4668dbcd Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jun 2016 14:10:16 +0800 Subject: [PATCH 2490/4971] Update plus-one-linked-list.py --- Python/plus-one-linked-list.py | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/Python/plus-one-linked-list.py b/Python/plus-one-linked-list.py index 659ce7b3b..9eba8016c 100644 --- a/Python/plus-one-linked-list.py +++ b/Python/plus-one-linked-list.py @@ -13,12 +13,15 @@ def plusOne(self, head): :type head: ListNode :rtype: ListNode """ - dummy = ListNode(0) - curr = head - while curr: - dummy.next, curr.next, curr = curr, dummy.next, curr.next + def reverseList(head): + dummy = ListNode(0) + curr = head + while curr: + dummy.next, curr.next, curr = curr, dummy.next, curr.next + return dummy.next - curr, carry = dummy.next, 1 + rev_head = reverseList(head) + curr, carry = rev_head, 1 while curr and carry: curr.val += carry carry = curr.val / 10 @@ -27,9 +30,4 @@ def plusOne(self, head): curr.next = ListNode(0) curr = curr.next - curr = dummy.next - dummy.next = None - while curr: - dummy.next, curr.next, curr = curr, dummy.next, curr.next - - return dummy.next + return reverseList(rev_head) From 44fb292f29dd07c602e60bcbd3e8ecc7e9747d8a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jun 2016 14:12:31 +0800 Subject: [PATCH 2491/4971] Create plus-one-linked-list.cpp --- C++/plus-one-linked-list.cpp | 46 ++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/plus-one-linked-list.cpp diff --git a/C++/plus-one-linked-list.cpp b/C++/plus-one-linked-list.cpp new file mode 100644 index 000000000..b83b9d2ea --- /dev/null +++ b/C++/plus-one-linked-list.cpp @@ -0,0 +1,46 @@ +// 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* plusOne(ListNode* head) { + auto rev_head = reverseList(head); + + auto curr = rev_head; + int carry = 1; + while (curr && carry) { + curr->val += carry; + carry = curr->val / 10; + curr->val %= 10; + if (carry && !curr->next) { + curr->next = new ListNode(0); + } + curr = curr->next; + } + + return reverseList(rev_head); + } + +private: + ListNode* reverseList(ListNode* head) { + auto dummy = ListNode{0}; + auto curr = head; + + while (curr) { + auto tmp = curr->next; + curr->next = dummy.next; + dummy.next = curr; + curr = tmp; + } + + return dummy.next; + } +}; From f959f10813a241cf74b2b14558b53d69869051d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jun 2016 14:15:42 +0800 Subject: [PATCH 2492/4971] Update README.md --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f693d1a0d..a6a8f6d74 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-368%20%2F%20368-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-369%20%2F%20369-ff69b4.svg) -Up to date (2016-06-27), there are `351` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-28), there are `352` 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 `368` questions. +Here is the classification of all `369` 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. ) @@ -112,7 +112,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/) | [C++](./C++/one-edit-distance.cpp) [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/) | [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/) |[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` @@ -140,6 +140,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 | 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 | | +369| [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [C++](./C++/plus-one-linked-list.cpp) [Python](./Python/plus-one-linked-list.py) | _O(n)_ | _O(1)_ | Medium | 📖 | ## Stack # | Title | Solution | Time | Space | Difficulty | Tag | Note From a2c89d242f313a7531ae7786f9540a8c41f0fac9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jun 2016 21:06:51 +0800 Subject: [PATCH 2493/4971] Update plus-one-linked-list.cpp --- C++/plus-one-linked-list.cpp | 44 +++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/C++/plus-one-linked-list.cpp b/C++/plus-one-linked-list.cpp index b83b9d2ea..597e8e5b8 100644 --- a/C++/plus-one-linked-list.cpp +++ b/C++/plus-one-linked-list.cpp @@ -9,7 +9,49 @@ * ListNode(int x) : val(x), next(NULL) {} * }; */ + // Two pointers solution. class Solution { +public: + ListNode* plusOne(ListNode* head) { + if (!head) { + return nullptr; + } + + auto dummy = new ListNode{0}; + dummy->next = head; + + auto left = dummy, right = dummy; + while (right->next) { + if (right->val != 9) { + left = right; + } + right = right->next; + } + + if (right->val != 9) { + ++right->val; + } else { + ++left->val; + right = left->next; + while (right) { + right->val = 0; + right = right->next; + } + } + + if (dummy->val == 0) { + head = dummy->next; + delete dummy; + return head; + } + + return dummy; + } +}; + +// Time: O(n) +// Space: O(1) +class Solution2 { public: ListNode* plusOne(ListNode* head) { auto rev_head = reverseList(head); @@ -31,7 +73,7 @@ class Solution { private: ListNode* reverseList(ListNode* head) { - auto dummy = ListNode{0}; + ListNode dummy{0}; auto curr = head; while (curr) { From 4979188f7f6c4f1948186b9ccd61cd1549454d07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jun 2016 21:11:57 +0800 Subject: [PATCH 2494/4971] Update plus-one-linked-list.py --- Python/plus-one-linked-list.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/Python/plus-one-linked-list.py b/Python/plus-one-linked-list.py index 9eba8016c..974c834a2 100644 --- a/Python/plus-one-linked-list.py +++ b/Python/plus-one-linked-list.py @@ -7,7 +7,40 @@ # self.val = x # self.next = None +# Two pointers solution. class Solution(object): + def plusOne(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ + if not head: + return None + + dummy = ListNode(0) + dummy.next = head + + left, right = dummy, dummy + while right.next: + if right.val != 9: + left = right + right = right.next + + if right.val != 9: + right.val += 1 + else: + left.val += 1 + right = left.next + while right: + right.val = 0 + right = right.next + + return dummy if dummy.val else dummy.next + + +# Time: O(n) +# Space: O(1) +class Solution2(object): def plusOne(self, head): """ :type head: ListNode From 8154b20a01402335eded080157cf348c079fdb56 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jun 2016 21:13:42 +0800 Subject: [PATCH 2495/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a6a8f6d74..d95d16251 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,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 | 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 | | -369| [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [C++](./C++/plus-one-linked-list.cpp) [Python](./Python/plus-one-linked-list.py) | _O(n)_ | _O(1)_ | Medium | 📖 | +369| [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [C++](./C++/plus-one-linked-list.cpp) [Python](./Python/plus-one-linked-list.py) | _O(n)_ | _O(1)_ | Medium | 📖 | Two Pointers | ## Stack # | Title | Solution | Time | Space | Difficulty | Tag | Note From f077f7c4f6c44cbff77dfe69c42b98aeb4568e07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jun 2016 21:17:40 +0800 Subject: [PATCH 2496/4971] Update plus-one-linked-list.cpp --- C++/plus-one-linked-list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/plus-one-linked-list.cpp b/C++/plus-one-linked-list.cpp index 597e8e5b8..f7e097520 100644 --- a/C++/plus-one-linked-list.cpp +++ b/C++/plus-one-linked-list.cpp @@ -20,7 +20,7 @@ class Solution { auto dummy = new ListNode{0}; dummy->next = head; - auto left = dummy, right = dummy; + auto left = dummy, right = head; while (right->next) { if (right->val != 9) { left = right; From 48ecc79dda81b4a4d0240f96ad0d543a0c917190 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jun 2016 21:17:50 +0800 Subject: [PATCH 2497/4971] Update plus-one-linked-list.py --- Python/plus-one-linked-list.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/plus-one-linked-list.py b/Python/plus-one-linked-list.py index 974c834a2..1d7e2c352 100644 --- a/Python/plus-one-linked-list.py +++ b/Python/plus-one-linked-list.py @@ -20,7 +20,7 @@ def plusOne(self, head): dummy = ListNode(0) dummy.next = head - left, right = dummy, dummy + left, right = dummy, head while right.next: if right.val != 9: left = right From 8bf237307114cef0b0bfcde0ab7a6358897da0fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Jun 2016 23:48:04 -0500 Subject: [PATCH 2498/4971] Create range-addition .py --- Python/range-addition .py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Python/range-addition .py diff --git a/Python/range-addition .py b/Python/range-addition .py new file mode 100644 index 000000000..bc9c6fcaf --- /dev/null +++ b/Python/range-addition .py @@ -0,0 +1,20 @@ +# Time: O(k + n) +# Space: O(1) + +class Solution(object): + def getModifiedArray(self, length, updates): + """ + :type length: int + :type updates: List[List[int]] + :rtype: List[int] + """ + result = [0] * length + for update in updates: + result[update[0]] += update[2] + if update[1]+1 < length: + result[update[1]+1] -= update[2] + + for i in xrange(1, length): + result[i] += result[i-1] + + return result From caaa4a67b25a9bfb6012774b893eb263df25e648 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 13:09:08 +0800 Subject: [PATCH 2499/4971] Create range-addition.cpp --- C++/range-addition.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/range-addition.cpp diff --git a/C++/range-addition.cpp b/C++/range-addition.cpp new file mode 100644 index 000000000..0664e622d --- /dev/null +++ b/C++/range-addition.cpp @@ -0,0 +1,22 @@ +// Time: O(k + n) +// Space: O(1) + +class Solution { +public: + vector getModifiedArray(int length, vector>& updates) { + vector result(length, 0); + + for (const auto& update: updates) { + result[update[0]] += update[2]; + if (update[1] + 1 < length) { + result[update[1] + 1] -= update[2]; + } + } + + for (int i = 1; i < length; ++i) { + result[i] += result[i - 1]; + } + + return result; + } +}; From c776660fefa2b26fd7fb9bc7599ddfee8c31ef9f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 13:11:10 +0800 Subject: [PATCH 2500/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d95d16251..37c6d29d2 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-369%20%2F%20369-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-370%20%2F%20370-ff69b4.svg) -Up to date (2016-06-28), there are `352` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-29), there are `353` 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 `369` questions. +Here is the classification of all `370` 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. ) @@ -96,6 +96,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 ||| +370| [Range Addition](https://leetcode.com/problems/range-addition/) | [C++](./C++/range-addition.cpp) [Python](./Python/range-addition.py) | _O(k + n)_ | _O(1)_ | Medium |📖|| ## String # | Title | Solution | Time | Space | Difficulty | Tag | Note From 487d97fe9c137ee0369c00a0fcf0b1ecf59077fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 21:44:43 +0800 Subject: [PATCH 2501/4971] Update range-sum-query-2d-mutable.py --- Python/range-sum-query-2d-mutable.py | 123 ++++++++++++++++++++++----- 1 file changed, 101 insertions(+), 22 deletions(-) diff --git a/Python/range-sum-query-2d-mutable.py b/Python/range-sum-query-2d-mutable.py index 74b2cf71c..3dc9626eb 100644 --- a/Python/range-sum-query-2d-mutable.py +++ b/Python/range-sum-query-2d-mutable.py @@ -1,10 +1,93 @@ -# Time: ctor: O(mlogm * nlogn) +# Time: ctor: O(m * n) # 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.__bit = [[0] * (len(self.__matrix[0]) + 1) \ + for _ in xrange(len(self.__matrix) + 1)] + + bit = [[0] * (len(self.__matrix[0]) + 1) \ + for _ in xrange(len(self.__matrix) + 1)] + for i in xrange(1, len(bit)): + for j in xrange(1, len(bit[0])): + bit[i][j] = matrix[i-1][j-1] + bit[i-1][j] + bit[i][j-1] - bit[i-1][j-1] + + self.__bit = [[0] * (len(self.__matrix[0]) + 1) \ + for _ in xrange(len(self.__matrix) + 1)] + for i in xrange(1, len(bit)): + for j in xrange(1, len(bit[0])): + last_i = i - (i & -i) + last_j = j - (j & -j) + self.__bit[i][j] = bit[i][j] - bit[i][last_j] - bit[last_i][j]+ bit[last_i][last_j] + + 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 + """ + return self.__sum(row2, col2) - self.__sum(row2, col1 - 1) - \ + self.__sum(row1 - 1, col2) + self.__sum(row1 - 1, col1 - 1) + + def __sum(self, row, col): + if row < 0 or col < 0: + return 0 + + 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 + + def __add(self, row, col, val): + row += 1 + col += 1 + i = row + while i <= len(self.__matrix): + j = col + while j <= len(self.__matrix[0]): + self.__bit[i][j] += val + j += (j & -j) + i += (i & -i) + + +# Time: ctor: O(mlogm * nlogn) +# update: O(logm * logn) +# query: O(logm * logn) +# Space: O(m * n) +# Binary Indexed Tree (BIT) solution. +class NumMatrix2(object): def __init__(self, matrix): """ initialize your data structure here. @@ -31,7 +114,6 @@ def update(self, row, col, val): 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. @@ -41,26 +123,23 @@ def sumRegion(self, row1, col1, row2, col2): :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 self.__sum(row2, col2) - self.__sum(row2, col1 - 1) - \ + self.__sum(row1 - 1, col2) + self.__sum(row1 - 1, col1 - 1) + + def __sum(self, row, col): + if row < 0 or col < 0: + return 0 + + 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 def __add(self, row, col, val): From 64954551afea9edb092c63eae4a1c687ce48f62d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 21:48:32 +0800 Subject: [PATCH 2502/4971] Update range-sum-query-2d-mutable.py --- Python/range-sum-query-2d-mutable.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/range-sum-query-2d-mutable.py b/Python/range-sum-query-2d-mutable.py index 3dc9626eb..d4cadea0e 100644 --- a/Python/range-sum-query-2d-mutable.py +++ b/Python/range-sum-query-2d-mutable.py @@ -26,8 +26,7 @@ def __init__(self, matrix): for _ in xrange(len(self.__matrix) + 1)] for i in xrange(1, len(bit)): for j in xrange(1, len(bit[0])): - last_i = i - (i & -i) - last_j = j - (j & -j) + last_i, last_j = i - (i & -i), j - (j & -j) self.__bit[i][j] = bit[i][j] - bit[i][last_j] - bit[last_i][j]+ bit[last_i][last_j] def update(self, row, col, val): From b0c4283860489a6bd8f49af754bdc4cef577ad06 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 21:57:32 +0800 Subject: [PATCH 2503/4971] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 64 ++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index dbd1b079e..577572485 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -103,12 +103,74 @@ class _SegmentTreeNode: def __init__(self, i, j, s): self.start, self.end, self.sum = i, j, s -# Time: ctor: O(nlogn), + +# Time: ctor: O(n), # 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 + bit = [0] * (len(self.__nums) + 1) + for i in xrange(1, len(bit)): + bit[i] = nums[i-1] + bit[i-1] + + self.__bit = [0] * (len(self.__nums) + 1) + for i in xrange(1, len(bit)): + last_i = i - (i & -i) + self.__bit[i] = bit[i] - bit[last_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 <= len(self.__nums): + self.__bit[i] += val + i += (i & -i) + + +# Time: ctor: O(nlogn), +# update: O(logn), +# query: O(logn) +# Space: O(n) +# Binary Indexed Tree (BIT) solution. +class NumArray3(object): def __init__(self, nums): """ initialize your data structure here. From e20a425019ac3b8774d2d463a6106cb43c2696ae Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:00:51 +0800 Subject: [PATCH 2504/4971] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index 577572485..c8e6aa7aa 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -115,18 +115,16 @@ def __init__(self, nums): initialize your data structure here. :type nums: List[int] """ - # Build segment tree. if not nums: return self.__nums = nums - bit = [0] * (len(self.__nums) + 1) - for i in xrange(1, len(bit)): - bit[i] = nums[i-1] + bit[i-1] - self.__bit = [0] * (len(self.__nums) + 1) - for i in xrange(1, len(bit)): + for i in xrange(1, len(self.__bit)): + self.__bit[i] = nums[i-1] + self.__bit[i-1] + + for i in reversed(xrange(1, len(self.__bit))): last_i = i - (i & -i) - self.__bit[i] = bit[i] - bit[last_i] + self.__bit[i] -= self.__bit[last_i] def update(self, i, val): """ @@ -176,7 +174,6 @@ def __init__(self, nums): initialize your data structure here. :type nums: List[int] """ - # Build segment tree. if not nums: return self.__nums = nums From 65b391df2f107529014adeaf3dcdb4f80dd29a8a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:03:28 +0800 Subject: [PATCH 2505/4971] Update range-sum-query-2d-mutable.py --- Python/range-sum-query-2d-mutable.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/Python/range-sum-query-2d-mutable.py b/Python/range-sum-query-2d-mutable.py index d4cadea0e..0cd7f936b 100644 --- a/Python/range-sum-query-2d-mutable.py +++ b/Python/range-sum-query-2d-mutable.py @@ -16,18 +16,17 @@ def __init__(self, matrix): self.__bit = [[0] * (len(self.__matrix[0]) + 1) \ for _ in xrange(len(self.__matrix) + 1)] - bit = [[0] * (len(self.__matrix[0]) + 1) \ - for _ in xrange(len(self.__matrix) + 1)] - for i in xrange(1, len(bit)): - for j in xrange(1, len(bit[0])): - bit[i][j] = matrix[i-1][j-1] + bit[i-1][j] + bit[i][j-1] - bit[i-1][j-1] - self.__bit = [[0] * (len(self.__matrix[0]) + 1) \ for _ in xrange(len(self.__matrix) + 1)] - for i in xrange(1, len(bit)): - for j in xrange(1, len(bit[0])): + for i in xrange(1, len(self.__bit)): + for j in xrange(1, len(self.__bit[0])): + self.__bit[i][j] = matrix[i-1][j-1] + self.__bit[i-1][j] + \ + self.__bit[i][j-1] - self.__bit[i-1][j-1] + for i in reversed(xrange(1, len(self.__bit))): + for j in reversed(xrange(1, len(self.__bit[0]))): last_i, last_j = i - (i & -i), j - (j & -j) - self.__bit[i][j] = bit[i][j] - bit[i][last_j] - bit[last_i][j]+ bit[last_i][last_j] + self.__bit[i][j] = self.__bit[i][j] - self.__bit[i][last_j] - \ + self.__bit[last_i][j] + self.__bit[last_i][last_j] def update(self, row, col, val): """ From 61c7be830e2be77f6ba666480becfcb83712d13e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:03:59 +0800 Subject: [PATCH 2506/4971] Update range-sum-query-2d-mutable.py --- Python/range-sum-query-2d-mutable.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/Python/range-sum-query-2d-mutable.py b/Python/range-sum-query-2d-mutable.py index 0cd7f936b..78b601fe0 100644 --- a/Python/range-sum-query-2d-mutable.py +++ b/Python/range-sum-query-2d-mutable.py @@ -13,9 +13,6 @@ def __init__(self, matrix): if not matrix: return self.__matrix = matrix - self.__bit = [[0] * (len(self.__matrix[0]) + 1) \ - for _ in xrange(len(self.__matrix) + 1)] - self.__bit = [[0] * (len(self.__matrix[0]) + 1) \ for _ in xrange(len(self.__matrix) + 1)] for i in xrange(1, len(self.__bit)): From feb40a10cca06a6ad94356da0b89d8e06fd556c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:25:26 +0800 Subject: [PATCH 2507/4971] Update range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 102 ++++++++++++++++++++++++----- 1 file changed, 84 insertions(+), 18 deletions(-) diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp index 17e9afefa..1fd3f5885 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -122,7 +122,7 @@ class NumMatrix { } }; -// Time: ctor: O(mlogm * nlogn) +// Time: ctor: O(m * n) // update: O(logm * logn) // query: O(logm * logn) // Space: O(m * n) @@ -130,14 +130,22 @@ class NumMatrix { class NumMatrix2 { public: 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]); - } + if (matrix_.empty()) { + return; + } + bit_ = vector>(matrix_.size() + 1, + vector(matrix_[0].size() + 1)); + for (int i = 1; i < bit_.size(); ++i) { + for (int j = 1; j < bit_[0].size(); ++j) { + bit_[i][j] = matrix[i - 1][j - 1] + bit_[i - 1][j] + + bit_[i][j - 1] - bit_[i - 1][j - 1]; + } + } + for (int i = bit_.size() - 1; i >= 0 ; --i) { + for (int j = bit_[0].size() - 1; j >= 0; --j) { + int last_i = i - (i & -i), last_j = j - (j & -j); + bit_[i][j] = bit_[i][j] - bit_[i][last_j] - + bit_[last_i][j] + bit_[last_i][last_j]; } } } @@ -150,24 +158,82 @@ class NumMatrix2 { } 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); + return sum(row2, col2) - sum(row2, col1 - 1) - + sum(row1 - 1, col2) + sum(row1 - 1, col1 - 1); + } + +private: + vector> &matrix_; + vector> bit_; + + int sum(int row, int col) { + if (row < 0 || col < 0) { + return 0; } - if (row1 > 0) { - sum -= sumRegion_bit(row1 - 1, col2); + ++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 <= matrix_.size(); i += lower_bit(i)) { + for (int j = col; j <= matrix_[0].size(); j += lower_bit(j)) { + bit_[i][j] += val; + } + } + } + + int lower_bit(int i) { + return i & -i; + } +}; + +// Time: ctor: O(mlogm * nlogn) +// update: O(logm * logn) +// query: O(logm * logn) +// Space: O(m * n) +// Binary Indexed Tree (BIT) solution. +class NumMatrix3 { +public: + NumMatrix(vector> &matrix) : matrix_(matrix) { + if (matrix_.empty()) { + return; + } + 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]); + } + } + } + + 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) { + return sum(row2, col2) - sum(row2, col1 - 1) - + sum(row1 - 1, col2) + sum(row1 - 1, col1 - 1); + } + private: vector> &matrix_; vector> bit_; - int sumRegion_bit(int row, int col) { + int sum(int row, int col) { + if (row < 0 || col < 0) { + return 0; + } ++row, ++col; int sum = 0; for (int i = row; i > 0; i -= lower_bit(i)) { From d29a4d9577006c5d7978547ae9d3747c35d51260 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:26:35 +0800 Subject: [PATCH 2508/4971] Update range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 64 ------------------------------ 1 file changed, 64 deletions(-) diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp index 1fd3f5885..057296daa 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -194,70 +194,6 @@ class NumMatrix2 { } }; -// Time: ctor: O(mlogm * nlogn) -// update: O(logm * logn) -// query: O(logm * logn) -// Space: O(m * n) -// Binary Indexed Tree (BIT) solution. -class NumMatrix3 { -public: - NumMatrix(vector> &matrix) : matrix_(matrix) { - if (matrix_.empty()) { - return; - } - 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]); - } - } - } - - 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) { - return sum(row2, col2) - sum(row2, col1 - 1) - - sum(row1 - 1, col2) + sum(row1 - 1, col1 - 1); - } - -private: - vector> &matrix_; - vector> bit_; - - int sum(int row, int col) { - if (row < 0 || col < 0) { - return 0; - } - ++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 <= matrix_.size(); i += lower_bit(i)) { - for (int j = col; j <= matrix_[0].size(); 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 972bd55346098c3b5934fbccda6566e203578755 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:27:10 +0800 Subject: [PATCH 2509/4971] Update range-sum-query-2d-mutable.py --- Python/range-sum-query-2d-mutable.py | 72 ---------------------------- 1 file changed, 72 deletions(-) diff --git a/Python/range-sum-query-2d-mutable.py b/Python/range-sum-query-2d-mutable.py index 78b601fe0..0c21a0721 100644 --- a/Python/range-sum-query-2d-mutable.py +++ b/Python/range-sum-query-2d-mutable.py @@ -77,78 +77,6 @@ def __add(self, row, col, val): i += (i & -i) -# Time: ctor: O(mlogm * nlogn) -# update: O(logm * logn) -# query: O(logm * logn) -# Space: O(m * n) -# Binary Indexed Tree (BIT) solution. -class NumMatrix2(object): - def __init__(self, matrix): - """ - initialize your data structure here. - :type matrix: List[List[int]] - """ - if not matrix: - return - self.__matrix = matrix - 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): - """ - 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 - """ - return self.__sum(row2, col2) - self.__sum(row2, col1 - 1) - \ - self.__sum(row1 - 1, col2) + self.__sum(row1 - 1, col1 - 1) - - def __sum(self, row, col): - if row < 0 or col < 0: - return 0 - - 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 - - def __add(self, row, col, val): - row += 1 - col += 1 - i = row - while i <= len(self.__matrix): - j = col - while j <= len(self.__matrix[0]): - self.__bit[i][j] += val - j += (j & -j) - i += (i & -i) - - # Your NumMatrix object will be instantiated and called as such: # numMatrix = NumMatrix(matrix) # numMatrix.sumRegion(0, 1, 2, 3) From b265d0830bd4285f04783023063ff4ca0b451f42 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:27:41 +0800 Subject: [PATCH 2510/4971] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 54 ------------------------------- 1 file changed, 54 deletions(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index c8e6aa7aa..8d9a72fc1 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -163,60 +163,6 @@ def __add(self, i, val): i += (i & -i) -# Time: ctor: O(nlogn), -# update: O(logn), -# query: O(logn) -# Space: O(n) -# Binary Indexed Tree (BIT) solution. -class NumArray3(object): - def __init__(self, nums): - """ - initialize your data structure here. - :type nums: List[int] - """ - if not nums: - return - self.__nums = nums - self.__bit = [0] * (len(self.__nums) + 1) - for i, num in enumerate(self.__nums): - self.__add(i, num) - - 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 <= len(self.__nums): - self.__bit[i] += val - i += (i & -i) - # Your NumArray object will be instantiated and called as such: # numArray = NumArray(nums) # numArray.sumRange(0, 1) From e7da71daabd6b0daba34d537478a10d264fdd2bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:31:16 +0800 Subject: [PATCH 2511/4971] 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 057296daa..55f121d1f 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -141,8 +141,8 @@ class NumMatrix2 { bit_[i][j - 1] - bit_[i - 1][j - 1]; } } - for (int i = bit_.size() - 1; i >= 0 ; --i) { - for (int j = bit_[0].size() - 1; j >= 0; --j) { + for (int i = bit_.size() - 1; i >= 1; --i) { + for (int j = bit_[0].size() - 1; j >= 1; --j) { int last_i = i - (i & -i), last_j = j - (j & -j); bit_[i][j] = bit_[i][j] - bit_[i][last_j] - bit_[last_i][j] + bit_[last_i][last_j]; From 8527a7651a34ced2c7699ac80cd41b92eeae029d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:33:13 +0800 Subject: [PATCH 2512/4971] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index e67971f04..632feb643 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -100,7 +100,7 @@ class NumArray { } }; -// Time: ctor: O(nlogn), +// Time: ctor: O(n), // update: O(logn), // query: O(logn) // Space: O(n) @@ -109,8 +109,12 @@ class NumArray2 { public: NumArray(vector &nums) : nums_(nums) { bit_ = vector(nums_.size() + 1); - for (int i = 0; i < nums_.size(); ++i) { - add(i, nums_[i]); + for (int i = 1; i < bit_.size(); ++i) { + bit_[i] = nums[i - 1] + bit_[i - 1]; + } + for (int i = bit_.size() - 1; i >= 1; --i) { + int last_i = i - (i & -i); + bit_[i] -= bit_[last_i]; } } From ebd028b1aa78452682a1126a51d9d783e8f9ea80 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:43:42 +0800 Subject: [PATCH 2513/4971] 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 55f121d1f..d4c67e048 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -143,7 +143,7 @@ class NumMatrix2 { } for (int i = bit_.size() - 1; i >= 1; --i) { for (int j = bit_[0].size() - 1; j >= 1; --j) { - int last_i = i - (i & -i), last_j = j - (j & -j); + int last_i = i - lower_bit(i), last_j = j - lower_bit(j); bit_[i][j] = bit_[i][j] - bit_[i][last_j] - bit_[last_i][j] + bit_[last_i][last_j]; } From c3464f93f91209180dd8deda25c3a5884a6a39ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 22:44:15 +0800 Subject: [PATCH 2514/4971] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index 632feb643..72745ca58 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -113,7 +113,7 @@ class NumArray2 { bit_[i] = nums[i - 1] + bit_[i - 1]; } for (int i = bit_.size() - 1; i >= 1; --i) { - int last_i = i - (i & -i); + int last_i = i - lower_bit(i); bit_[i] -= bit_[last_i]; } } From 0e7b8c7e1461cf0e1f13d90ab30bc46198a5692c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 23:12:14 +0800 Subject: [PATCH 2515/4971] Update range-sum-query-2d-mutable.cpp --- C++/range-sum-query-2d-mutable.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/C++/range-sum-query-2d-mutable.cpp b/C++/range-sum-query-2d-mutable.cpp index d4c67e048..7bd0a0eff 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -167,9 +167,6 @@ class NumMatrix2 { vector> bit_; int sum(int row, int col) { - if (row < 0 || col < 0) { - return 0; - } ++row, ++col; int sum = 0; for (int i = row; i > 0; i -= lower_bit(i)) { From a3e9804b1726590cae596d9be755b02702697777 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 23:14:24 +0800 Subject: [PATCH 2516/4971] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index 72745ca58..f0ed9f8e5 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -126,18 +126,14 @@ class NumArray2 { } int sumRange(int i, int j) { - int sum = sumRegion_bit(j); - if (i > 0) { - sum -= sumRegion_bit(i - 1); - } - return sum; + return sum(j) - sum(i - 1); } private: vector &nums_; vector bit_; - int sumRegion_bit(int i) { + int sum(int i) { ++i; int sum = 0; for (; i > 0; i -= lower_bit(i)) { From 1593fcaa7ceb8a4b0fba2d1f687c9d2194c1c867 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 23:16:56 +0800 Subject: [PATCH 2517/4971] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index 8d9a72fc1..515d5bc98 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -143,17 +143,14 @@ def sumRange(self, i, j): :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 self.__sum(j) - self.__sum(i-1) + + def __sum(self, i): + i += 1 + ret = 0 + while i > 0: + ret += self.__bit[i] + i -= (i & -i) return ret def __add(self, i, val): From 214478b77b843b25d8a0d2066fd1b56ec34cb851 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 23:17:38 +0800 Subject: [PATCH 2518/4971] Update range-sum-query-2d-mutable.py --- Python/range-sum-query-2d-mutable.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/Python/range-sum-query-2d-mutable.py b/Python/range-sum-query-2d-mutable.py index 0c21a0721..ac8963f41 100644 --- a/Python/range-sum-query-2d-mutable.py +++ b/Python/range-sum-query-2d-mutable.py @@ -50,9 +50,6 @@ def sumRegion(self, row1, col1, row2, col2): self.__sum(row1 - 1, col2) + self.__sum(row1 - 1, col1 - 1) def __sum(self, row, col): - if row < 0 or col < 0: - return 0 - row += 1 col += 1 ret = 0 From 84098cef2ae12678ba87cccffd0df36fe635efc6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 23:20:56 +0800 Subject: [PATCH 2519/4971] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index f0ed9f8e5..5a61a605b 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -149,7 +149,7 @@ class NumArray2 { } } - int lower_bit(int i) { + inline int lower_bit(int i) { return i & -i; } }; From a9893c777a925a61eb932c08a20d1c7d1ce9b68f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 23:21:13 +0800 Subject: [PATCH 2520/4971] 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 7bd0a0eff..391094098 100644 --- a/C++/range-sum-query-2d-mutable.cpp +++ b/C++/range-sum-query-2d-mutable.cpp @@ -186,7 +186,7 @@ class NumMatrix2 { } } - int lower_bit(int i) { + inline int lower_bit(int i) { return i & -i; } }; From 810e91028fe085021963225f8b43e732f83516d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 23:23:59 +0800 Subject: [PATCH 2521/4971] Update range-sum-query-mutable.cpp --- C++/range-sum-query-mutable.cpp | 111 ++++++++++++++++---------------- 1 file changed, 55 insertions(+), 56 deletions(-) diff --git a/C++/range-sum-query-mutable.cpp b/C++/range-sum-query-mutable.cpp index 5a61a605b..9119904ba 100644 --- a/C++/range-sum-query-mutable.cpp +++ b/C++/range-sum-query-mutable.cpp @@ -3,8 +3,62 @@ // query: O(logn) // Space: O(n) -// Segment Tree solution. +// Binary Indexed Tree (BIT) solution. class NumArray { +public: + NumArray(vector &nums) : nums_(nums) { + bit_ = vector(nums_.size() + 1); + for (int i = 1; i < bit_.size(); ++i) { + bit_[i] = nums[i - 1] + bit_[i - 1]; + } + for (int i = bit_.size() - 1; i >= 1; --i) { + int last_i = i - lower_bit(i); + bit_[i] -= bit_[last_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) { + return sum(j) - sum(i - 1); + } + +private: + vector &nums_; + vector bit_; + + int sum(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 <= nums_.size(); i += lower_bit(i)) { + bit_[i] += val; + } + } + + inline int lower_bit(int i) { + return i & -i; + } +}; + +// Time: ctor: O(n), +// update: O(logn), +// query: O(logn) +// Space: O(n) +// Segment Tree solution. +class NumArray2 { public: NumArray(vector &nums) : nums_(nums) { root_ = buildHelper(nums, 0, nums.size() - 1); @@ -100,61 +154,6 @@ class NumArray { } }; -// Time: ctor: O(n), -// update: O(logn), -// query: O(logn) -// Space: O(n) -// Binary Indexed Tree (BIT) solution. -class NumArray2 { -public: - NumArray(vector &nums) : nums_(nums) { - bit_ = vector(nums_.size() + 1); - for (int i = 1; i < bit_.size(); ++i) { - bit_[i] = nums[i - 1] + bit_[i - 1]; - } - for (int i = bit_.size() - 1; i >= 1; --i) { - int last_i = i - lower_bit(i); - bit_[i] -= bit_[last_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) { - return sum(j) - sum(i - 1); - } - -private: - vector &nums_; - vector bit_; - - int sum(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 <= nums_.size(); i += lower_bit(i)) { - bit_[i] += val; - } - } - - inline int lower_bit(int i) { - return i & -i; - } -}; - - // Your NumArray object will be instantiated and called as such: // NumArray numArray(nums); // numArray.sumRange(0, 1); From 5188d822a7bc8e0cad320cbad40bc8540bbb7834 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Jun 2016 23:25:59 +0800 Subject: [PATCH 2522/4971] Update range-sum-query-mutable.py --- Python/range-sum-query-mutable.py | 117 +++++++++++++++--------------- 1 file changed, 58 insertions(+), 59 deletions(-) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index 515d5bc98..d9b7db624 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -2,7 +2,7 @@ # update: O(logn), # query: O(logn) # Space: O(n) -# + # Given an integer array nums, find the sum of # the elements between indices i and j (i <= j), inclusive. # @@ -18,10 +18,65 @@ # The array is only modifiable by the update function. # You may assume the number of calls to update # and sumRange function is distributed evenly. -# -# Segment Tree solutoin. +# Binary Indexed Tree (BIT) solution. class NumArray(object): + def __init__(self, nums): + """ + initialize your data structure here. + :type nums: List[int] + """ + if not nums: + return + self.__nums = nums + self.__bit = [0] * (len(self.__nums) + 1) + for i in xrange(1, len(self.__bit)): + self.__bit[i] = nums[i-1] + self.__bit[i-1] + + for i in reversed(xrange(1, len(self.__bit))): + last_i = i - (i & -i) + self.__bit[i] -= self.__bit[last_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 + """ + return self.__sum(j) - self.__sum(i-1) + + def __sum(self, i): + i += 1 + ret = 0 + while i > 0: + ret += self.__bit[i] + i -= (i & -i) + return ret + + def __add(self, i, val): + i += 1 + while i <= len(self.__nums): + self.__bit[i] += val + i += (i & -i) + + +# Time: ctor: O(n), +# update: O(logn), +# query: O(logn) +# Space: O(n) +# Segment Tree solutoin. +class NumArray2(object): def __init__(self, nums): """ initialize your data structure here. @@ -104,62 +159,6 @@ def __init__(self, i, j, s): self.start, self.end, self.sum = i, j, s -# Time: ctor: O(n), -# 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] - """ - if not nums: - return - self.__nums = nums - self.__bit = [0] * (len(self.__nums) + 1) - for i in xrange(1, len(self.__bit)): - self.__bit[i] = nums[i-1] + self.__bit[i-1] - - for i in reversed(xrange(1, len(self.__bit))): - last_i = i - (i & -i) - self.__bit[i] -= self.__bit[last_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 - """ - return self.__sum(j) - self.__sum(i-1) - - def __sum(self, i): - i += 1 - ret = 0 - while i > 0: - ret += self.__bit[i] - i -= (i & -i) - return ret - - def __add(self, i, val): - i += 1 - while i <= len(self.__nums): - self.__bit[i] += val - i += (i & -i) - - # Your NumArray object will be instantiated and called as such: # numArray = NumArray(nums) # numArray.sumRange(0, 1) From 36a7ce2d69bd9309b087d7478d340d5c4083797f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 30 Jun 2016 19:13:32 +0800 Subject: [PATCH 2523/4971] Create sum-of-two-integers.py --- Python/sum-of-two-integers.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/sum-of-two-integers.py diff --git a/Python/sum-of-two-integers.py b/Python/sum-of-two-integers.py new file mode 100644 index 000000000..363f39a0c --- /dev/null +++ b/Python/sum-of-two-integers.py @@ -0,0 +1,21 @@ +# Time: O(1) +# Space: O(1) + +# Calculate the sum of two integers a and b, +# but you are not allowed to use the operator + and -. +# +# Example: +# Given a = 1 and b = 2, return 3. + +class Solution(object): + def getSum(self, a, b): + """ + :type a: int + :type b: int + :rtype: int + """ + while b and b != 1 << 32: + carry = a & b + a ^= b + b = carry << 1 + return a if b != 1 << 32 else a & 0xffffffff From 7ea7316f082e31b324086876c682d640798c953a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 30 Jun 2016 19:15:59 +0800 Subject: [PATCH 2524/4971] Create sum-of-two-integers.cpp --- C++/sum-of-two-integers.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/sum-of-two-integers.cpp diff --git a/C++/sum-of-two-integers.cpp b/C++/sum-of-two-integers.cpp new file mode 100644 index 000000000..50c66d19f --- /dev/null +++ b/C++/sum-of-two-integers.cpp @@ -0,0 +1,14 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int getSum(int a, int b) { + while (b) { + int carry = a & b; + a ^= b; + b = carry << 1; + } + return a; + } +}; From a22cf211eae4ee16e26b9e5be8fe08945f060f19 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 30 Jun 2016 19:17:41 +0800 Subject: [PATCH 2525/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 37c6d29d2..9a2fb00ec 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-370%20%2F%20370-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-371%20%2F%20371-ff69b4.svg) -Up to date (2016-06-29), there are `353` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-30), there are `354` 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 `370` questions. +Here is the classification of all `371` 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. ) @@ -55,6 +55,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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(n^2)_ | _O(n)_ | Medium || Bit Manipulation, Counting Sort, Pruning| 342 | [Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./C++/power-of-four.cpp) [Python](./Python/power-of-four.py) | _O(1)_ | _O(1)_ | Easy | | +371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | | ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note From 436d432b8c053e2469ebef79e55387394bdf8643 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 30 Jun 2016 19:18:08 +0800 Subject: [PATCH 2526/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9a2fb00ec..bde771851 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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(n^2)_ | _O(n)_ | Medium || Bit Manipulation, Counting Sort, Pruning| 342 | [Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./C++/power-of-four.cpp) [Python](./Python/power-of-four.py) | _O(1)_ | _O(1)_ | Easy | | -371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | | +371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | LintCode | ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note From 922fe1d74e332dd13b2e368bd4393a04e9b75c61 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jul 2016 00:33:23 +0800 Subject: [PATCH 2527/4971] Update sum-of-two-integers.py --- Python/sum-of-two-integers.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/Python/sum-of-two-integers.py b/Python/sum-of-two-integers.py index 363f39a0c..92a5b8366 100644 --- a/Python/sum-of-two-integers.py +++ b/Python/sum-of-two-integers.py @@ -14,8 +14,15 @@ def getSum(self, a, b): :type b: int :rtype: int """ - while b and b != 1 << 32: - carry = a & b - a ^= b - b = carry << 1 - return a if b != 1 << 32 else a & 0xffffffff + bit_length = 32 + neg_bit, mask = 1 << (bit_length-1), ~(~0 << bit_length) + + a = a | ~mask if a & neg_bit else a & mask + b = b | ~mask if b & neg_bit else b & mask + + while b: + carry = (a & b) & mask + a = (a ^ b) & mask + b = carry << 1 & mask + + return a | ~mask if a & neg_bit else a From 305d7a069b2611af716a3c85f0a2ea7211b17629 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jul 2016 00:34:50 +0800 Subject: [PATCH 2528/4971] Update sum-of-two-integers.py --- Python/sum-of-two-integers.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/sum-of-two-integers.py b/Python/sum-of-two-integers.py index 92a5b8366..84914b9cc 100644 --- a/Python/sum-of-two-integers.py +++ b/Python/sum-of-two-integers.py @@ -17,12 +17,12 @@ def getSum(self, a, b): bit_length = 32 neg_bit, mask = 1 << (bit_length-1), ~(~0 << bit_length) - a = a | ~mask if a & neg_bit else a & mask - b = b | ~mask if b & neg_bit else b & mask + a = (a | ~mask) if (a & neg_bit) else a & mask + b = (b | ~mask) if (b & neg_bit) else b & mask while b: carry = (a & b) & mask a = (a ^ b) & mask - b = carry << 1 & mask + b = (carry << 1) & mask - return a | ~mask if a & neg_bit else a + return (a | ~mask) if (a & neg_bit) else a From 18e5a11ceb2ff16189045576a3661e7fca70aa0d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jul 2016 00:38:55 +0800 Subject: [PATCH 2529/4971] Update sum-of-two-integers.py --- Python/sum-of-two-integers.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/sum-of-two-integers.py b/Python/sum-of-two-integers.py index 84914b9cc..29468f172 100644 --- a/Python/sum-of-two-integers.py +++ b/Python/sum-of-two-integers.py @@ -17,12 +17,13 @@ def getSum(self, a, b): bit_length = 32 neg_bit, mask = 1 << (bit_length-1), ~(~0 << bit_length) - a = (a | ~mask) if (a & neg_bit) else a & mask - b = (b | ~mask) if (b & neg_bit) else b & mask + a = (a | ~mask) if (a & neg_bit) else (a & mask) + b = (b | ~mask) if (b & neg_bit) else (b & mask) while b: carry = (a & b) & mask a = (a ^ b) & mask + a = (a | ~mask) if (a & neg_bit) else (a & mask) b = (carry << 1) & mask - return (a | ~mask) if (a & neg_bit) else a + return a From 086aa998357a6062cca9b4005957c7af8e978371 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jul 2016 00:45:07 +0800 Subject: [PATCH 2530/4971] Update sum-of-two-integers.py --- Python/sum-of-two-integers.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/sum-of-two-integers.py b/Python/sum-of-two-integers.py index 29468f172..cf175b0cc 100644 --- a/Python/sum-of-two-integers.py +++ b/Python/sum-of-two-integers.py @@ -21,9 +21,9 @@ def getSum(self, a, b): b = (b | ~mask) if (b & neg_bit) else (b & mask) while b: - carry = (a & b) & mask - a = (a ^ b) & mask - a = (a | ~mask) if (a & neg_bit) else (a & mask) - b = (carry << 1) & mask + carry = a & b + a ^= b + b = carry << 1 + b = (b | ~mask) if (b & neg_bit) else (b & mask) return a From 42ad6ec83c20c48c18ce505aec232ab6a493d1ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jul 2016 01:00:22 +0800 Subject: [PATCH 2531/4971] Update sum-of-two-integers.py --- Python/sum-of-two-integers.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/sum-of-two-integers.py b/Python/sum-of-two-integers.py index cf175b0cc..f1464d00b 100644 --- a/Python/sum-of-two-integers.py +++ b/Python/sum-of-two-integers.py @@ -23,6 +23,7 @@ def getSum(self, a, b): while b: carry = a & b a ^= b + a = (a | ~mask) if (a & neg_bit) else (a & mask) b = carry << 1 b = (b | ~mask) if (b & neg_bit) else (b & mask) From 98111033e474987b600a1013a1f7d46ccfdc53e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Jul 2016 01:23:41 +0800 Subject: [PATCH 2532/4971] Update sum-of-two-integers.py --- Python/sum-of-two-integers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/sum-of-two-integers.py b/Python/sum-of-two-integers.py index f1464d00b..8b1bc8153 100644 --- a/Python/sum-of-two-integers.py +++ b/Python/sum-of-two-integers.py @@ -15,7 +15,7 @@ def getSum(self, a, b): :rtype: int """ bit_length = 32 - neg_bit, mask = 1 << (bit_length-1), ~(~0 << bit_length) + neg_bit, mask = (1 << bit_length) >> 1, ~(~0 << bit_length) a = (a | ~mask) if (a & neg_bit) else (a & mask) b = (b | ~mask) if (b & neg_bit) else (b & mask) From 303052aad74856a3e27154f5a54db85cc46dda06 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 Jul 2016 10:45:52 -0500 Subject: [PATCH 2533/4971] Update rearrange-string-k-distance-apart.py --- Python/rearrange-string-k-distance-apart.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/rearrange-string-k-distance-apart.py b/Python/rearrange-string-k-distance-apart.py index a4ef4e541..ac2187fc3 100644 --- a/Python/rearrange-string-k-distance-apart.py +++ b/Python/rearrange-string-k-distance-apart.py @@ -21,7 +21,7 @@ def rearrangeString(self, str, k): heap = [] for c, cnt in cnts.iteritems(): heappush(heap, [-cnt, c]) - + result = [] while heap: used_cnt_chars = [] From 8124214236b2f657241247bafedf54a261b0eeb8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 00:48:19 +0800 Subject: [PATCH 2534/4971] Update rearrange-string-k-distance-apart.cpp --- C++/rearrange-string-k-distance-apart.cpp | 40 +++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/C++/rearrange-string-k-distance-apart.cpp b/C++/rearrange-string-k-distance-apart.cpp index bf51084f9..a5791668b 100644 --- a/C++/rearrange-string-k-distance-apart.cpp +++ b/C++/rearrange-string-k-distance-apart.cpp @@ -1,7 +1,43 @@ -// Time: O(nlogc), c is the count of unique characters. -// Space: O(c) +// Time: O(n), c is the count of unique characters. +// Space: O(n) class Solution { +public: + string rearrangeString(string str, int k) { + int cnts [26] = {0}; + for (int i = 0; i < str.length(); ++i) { + ++cnts[str[i] - 'a']; + } + multimap> bst; + for (int i = 0; i < 26; ++i) { + bst.emplace(cnts[i], i + 'a'); + } + + string blocks[bst.cbegin()->first]; + int i = 0; + for (auto it = bst.cbegin(); it != bst.cend(); ++it) { + for (int cnt = 0; cnt < it->first; ++cnt) { + blocks[i].push_back(it->second); + i = (i + 1) % max(it->first, bst.cbegin()->first - 1); + } + } + + string result; + for (int i = 0; i < bst.cbegin()->first - 1; ++i) { + if (blocks[i].size() < k) { + return ""; + } else { + result += blocks[i]; + } + } + result += blocks[bst.cbegin()->first - 1]; + return result; + } +}; + +// Time: O(nlogc), c is the count of unique characters. +// Space: O(c) +class Solution2 { public: string rearrangeString(string str, int k) { if (k == 0) { From f53b84668e9156cff51b24a828f7b463690cba99 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 00:53:49 +0800 Subject: [PATCH 2535/4971] Update rearrange-string-k-distance-apart.cpp --- C++/rearrange-string-k-distance-apart.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/C++/rearrange-string-k-distance-apart.cpp b/C++/rearrange-string-k-distance-apart.cpp index a5791668b..13eb7fa33 100644 --- a/C++/rearrange-string-k-distance-apart.cpp +++ b/C++/rearrange-string-k-distance-apart.cpp @@ -8,29 +8,30 @@ class Solution { for (int i = 0; i < str.length(); ++i) { ++cnts[str[i] - 'a']; } - multimap> bst; + vector> sorted_cnts; for (int i = 0; i < 26; ++i) { - bst.emplace(cnts[i], i + 'a'); + sorted_cnts.emplace_back(cnts[i], i + 'a'); } + sort(sorted_cnts.begin(), sorted_cnts.end(), greater>()); - string blocks[bst.cbegin()->first]; + string blocks[sorted_cnts.cbegin()->first]; int i = 0; - for (auto it = bst.cbegin(); it != bst.cend(); ++it) { + for (auto it = sorted_cnts.cbegin(); it != sorted_cnts.cend(); ++it) { for (int cnt = 0; cnt < it->first; ++cnt) { blocks[i].push_back(it->second); - i = (i + 1) % max(it->first, bst.cbegin()->first - 1); + i = (i + 1) % max(it->first, sorted_cnts.cbegin()->first - 1); } } string result; - for (int i = 0; i < bst.cbegin()->first - 1; ++i) { + for (int i = 0; i < sorted_cnts.cbegin()->first - 1; ++i) { if (blocks[i].size() < k) { return ""; } else { result += blocks[i]; } } - result += blocks[bst.cbegin()->first - 1]; + result += blocks[sorted_cnts.cbegin()->first - 1]; return result; } }; From 7c8b40ad53bda65b5263490514f20b1c6bb4c456 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 00:54:38 +0800 Subject: [PATCH 2536/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bde771851..88efc7a85 100644 --- a/README.md +++ b/README.md @@ -177,7 +177,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | -358| [Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/)| [C++](./C++/rearrange-string-k-distance-apart.cpp) [Python](./Python/rearrange-string-k-distance-apart.py) | _O(nlogc)_ | _O(c)_ | Hard |📖| Greedy, Heap | +358| [Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/)| [C++](./C++/rearrange-string-k-distance-apart.cpp) [Python](./Python/rearrange-string-k-distance-apart.py) | _O(n)_ | _O(n)_ | Hard |📖| Greedy, Heap | ## Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note From 608524758083470ed21cfa1ae906c289a51f5245 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 00:55:14 +0800 Subject: [PATCH 2537/4971] Update rearrange-string-k-distance-apart.cpp --- C++/rearrange-string-k-distance-apart.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/rearrange-string-k-distance-apart.cpp b/C++/rearrange-string-k-distance-apart.cpp index 13eb7fa33..560ef025a 100644 --- a/C++/rearrange-string-k-distance-apart.cpp +++ b/C++/rearrange-string-k-distance-apart.cpp @@ -1,4 +1,4 @@ -// Time: O(n), c is the count of unique characters. +// Time: O(n) // Space: O(n) class Solution { From 0f05c1d20d053662dabb98eb6e0da2b9d7cfcc38 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 01:05:35 +0800 Subject: [PATCH 2538/4971] Update rearrange-string-k-distance-apart.cpp --- C++/rearrange-string-k-distance-apart.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/rearrange-string-k-distance-apart.cpp b/C++/rearrange-string-k-distance-apart.cpp index 560ef025a..826095c3e 100644 --- a/C++/rearrange-string-k-distance-apart.cpp +++ b/C++/rearrange-string-k-distance-apart.cpp @@ -16,22 +16,22 @@ class Solution { string blocks[sorted_cnts.cbegin()->first]; int i = 0; - for (auto it = sorted_cnts.cbegin(); it != sorted_cnts.cend(); ++it) { - for (int cnt = 0; cnt < it->first; ++cnt) { - blocks[i].push_back(it->second); - i = (i + 1) % max(it->first, sorted_cnts.cbegin()->first - 1); + for (const auto& cnt : sorted_cnts) { + for (int j = 0; j < cnt.first; ++j) { + blocks[i].push_back(cnt.second); + i = (i + 1) % max(cnt.first, sorted_cnts[0].first - 1); } } string result; - for (int i = 0; i < sorted_cnts.cbegin()->first - 1; ++i) { + for (int i = 0; i < sorted_cnts[0].first - 1; ++i) { if (blocks[i].size() < k) { return ""; } else { result += blocks[i]; } } - result += blocks[sorted_cnts.cbegin()->first - 1]; + result += blocks[sorted_cnts[0].first - 1]; return result; } }; From 4a6b49e14b6314dd3b59b3c52d574d0c4d7614b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 01:08:16 +0800 Subject: [PATCH 2539/4971] Update rearrange-string-k-distance-apart.cpp --- C++/rearrange-string-k-distance-apart.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/C++/rearrange-string-k-distance-apart.cpp b/C++/rearrange-string-k-distance-apart.cpp index 826095c3e..c19221a65 100644 --- a/C++/rearrange-string-k-distance-apart.cpp +++ b/C++/rearrange-string-k-distance-apart.cpp @@ -8,30 +8,32 @@ class Solution { for (int i = 0; i < str.length(); ++i) { ++cnts[str[i] - 'a']; } + vector> sorted_cnts; for (int i = 0; i < 26; ++i) { sorted_cnts.emplace_back(cnts[i], i + 'a'); } sort(sorted_cnts.begin(), sorted_cnts.end(), greater>()); - string blocks[sorted_cnts.cbegin()->first]; + const auto max_cnt = sorted_cnts[0].first; + string blocks[max_cnt]; int i = 0; for (const auto& cnt : sorted_cnts) { for (int j = 0; j < cnt.first; ++j) { blocks[i].push_back(cnt.second); - i = (i + 1) % max(cnt.first, sorted_cnts[0].first - 1); + i = (i + 1) % max(cnt.first, max_cnt - 1); } } string result; - for (int i = 0; i < sorted_cnts[0].first - 1; ++i) { - if (blocks[i].size() < k) { + for (int i = 0; i < max_cnt - 1; ++i) { + if (blocks[i].length() < k) { return ""; } else { result += blocks[i]; } } - result += blocks[sorted_cnts[0].first - 1]; + result += blocks[max_cnt - 1]; return result; } }; From ec2aaf86f2002b060f6e5b4d040961a37f89d06a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 01:19:19 +0800 Subject: [PATCH 2540/4971] Update rearrange-string-k-distance-apart.py --- Python/rearrange-string-k-distance-apart.py | 38 +++++++++++++++++++-- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/Python/rearrange-string-k-distance-apart.py b/Python/rearrange-string-k-distance-apart.py index ac2187fc3..98610862c 100644 --- a/Python/rearrange-string-k-distance-apart.py +++ b/Python/rearrange-string-k-distance-apart.py @@ -1,10 +1,42 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def rearrangeString(self, str, k): + """ + :type str: str + :type k: int + :rtype: str + """ + cnts = [0] * 26; + for c in str: + cnts[ord(c) - ord('a')] += 1 + + sorted_cnts = [] + for i in xrange(26): + sorted_cnts.append((cnts[i], chr(i + ord('a')))) + sorted_cnts.sort(reverse=True) + + max_cnt = sorted_cnts[0][0] + blocks = [[] for _ in xrange(max_cnt)] + i = 0 + for cnt in sorted_cnts: + for _ in xrange(cnt[0]): + blocks[i].append(cnt[1]) + i = (i + 1) % max(cnt[0], max_cnt - 1) + + for i in xrange(max_cnt-1): + if len(blocks[i]) < k: + return "" + + return "".join(map(lambda x : "".join(x), blocks)) + + # Time: O(nlogc), c is the count of unique characters. # Space: O(c) - from collections import defaultdict from heapq import heappush, heappop - -class Solution(object): +class Solution2(object): def rearrangeString(self, str, k): """ :type str: str From e4567184f5d69a31f392de53b1ce171745fde9e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 12:48:34 +0800 Subject: [PATCH 2541/4971] Update word-break-ii.py --- Python/word-break-ii.py | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/Python/word-break-ii.py b/Python/word-break-ii.py index f0908b2d0..0efabf2e5 100644 --- a/Python/word-break-ii.py +++ b/Python/word-break-ii.py @@ -1,4 +1,4 @@ -# Time: O(2^n) +# Time: O(n * l^2 + n * r), r is the number of the results. # Space: O(n) # # Given a string s and a dictionary of words dict, @@ -13,24 +13,30 @@ # A solution is ["cats and dog", "cat sand dog"]. # -class Solution: - # @param s, a string - # @param dict, a set of string - # @return a list of strings - def wordBreak(self, s, dict): +class Solution(object): + def wordBreak(self, s, wordDict): + """ + :type s: str + :type wordDict: Set[str] + :rtype: List[str] + """ n = len(s) - possible = [False for _ in xrange(n)] + + max_len = 0 + for string in wordDict: + max_len = max(max_len, len(string)) + + can_break = [False for _ in xrange(n + 1)] valid = [[False] * n for _ in xrange(n)] - for i in xrange(n): - if s[:i+1] in dict: - possible[i] = True - valid[0][i] = True - for j in xrange(i): - if possible[j] and s[j+1:i+1] in dict: - valid[j+1][i] = True - possible[i] = True + can_break[0] = True + for i in xrange(1, n + 1): + for l in xrange(1, min(i, max_len) + 1): + if can_break[i-l] and s[i-l:i] in wordDict: + valid[i-l][i-1] = True + can_break[i] = True + result = [] - if possible[n-1]: + if can_break[-1]: self.genPath(s, valid, 0, [], result) return result @@ -44,5 +50,6 @@ def genPath(self, s, valid, start, path, result): self.genPath(s, valid, i + 1, path, result) path.pop() + if __name__ == "__main__": - print Solution().wordBreak("catsanddog", ["cat", "cats", "and", "sand", "dog"]) \ No newline at end of file + print Solution().wordBreak("catsanddog", ["cat", "cats", "and", "sand", "dog"]) From a8940e2ba28871e14a2bf688beb5b5cce7f378ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 12:58:43 +0800 Subject: [PATCH 2542/4971] Update word-break-ii.py --- Python/word-break-ii.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/word-break-ii.py b/Python/word-break-ii.py index 0efabf2e5..b8e0ef46a 100644 --- a/Python/word-break-ii.py +++ b/Python/word-break-ii.py @@ -1,4 +1,5 @@ -# Time: O(n * l^2 + n * r), r is the number of the results. +# Time: O(n * l^2 + n * r), l is the max length of the words, +# r is the number of the results. # Space: O(n) # # Given a string s and a dictionary of words dict, From 2234dad682918135a504e8bb76d7b9799d35f0ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 12:59:44 +0800 Subject: [PATCH 2543/4971] Update word-break-ii.py --- Python/word-break-ii.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/word-break-ii.py b/Python/word-break-ii.py index b8e0ef46a..64e77614c 100644 --- a/Python/word-break-ii.py +++ b/Python/word-break-ii.py @@ -38,17 +38,17 @@ def wordBreak(self, s, wordDict): result = [] if can_break[-1]: - self.genPath(s, valid, 0, [], result) + self.wordBreakHelper(s, valid, 0, [], result) return result - def genPath(self, s, valid, start, path, result): + def wordBreakHelper(self, s, valid, start, path, result): if start == len(s): result.append(" ".join(path)) return for i in xrange(start, len(s)): if valid[start][i]: path += [s[start:i+1]] - self.genPath(s, valid, i + 1, path, result) + self.wordBreakHelper(s, valid, i + 1, path, result) path.pop() From 8cbf10be0af9de2d80e24e418bb7f40765687422 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 13:14:47 +0800 Subject: [PATCH 2544/4971] Create word-break-ii.cpp --- C++/word-break-ii.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 C++/word-break-ii.cpp diff --git a/C++/word-break-ii.cpp b/C++/word-break-ii.cpp new file mode 100644 index 000000000..eb1fa1086 --- /dev/null +++ b/C++/word-break-ii.cpp @@ -0,0 +1,55 @@ +// Time: O(n * l^2 + n * r), l is the max length of the words, +// r is the number of the results. +// Space: O(n) + +class Solution { +public: + vector wordBreak(string s, unordered_set& wordDict) { + const int n = s.length(); + + size_t max_len = 0; + for (const auto& str: wordDict) { + max_len = max(max_len, str.length()); + } + + vector canBreak(n + 1, false); + vector> valid(n, vector(n, false)); + canBreak[0] = true; + for (int i = 1; i <= n; ++i) { + for (int l = 1; l <= max_len && i - l >= 0; ++l) { + if (canBreak[i - l] && wordDict.count(s.substr(i - l, l))) { + valid[i - l][i - 1] = true; + canBreak[i] = true; + } + } + } + + vector result, path; + if (canBreak[n]) { + wordBreakHelper(s, valid, 0, &path, &result); + } + return result; + } + + + void wordBreakHelper(const string& s, const vector>& valid, + int start, vector *path, vector *result) { + if (start == s.length()) { + string tmp; + for (const auto& str : *path) { + tmp += str; + tmp += " "; + } + tmp.pop_back(); + result->emplace_back(move(tmp)); + return; + } + for(int i = start; i < s.length(); ++i) { + if (valid[start][i]) { + path->emplace_back(s.substr(start, i + 1 - start)); + wordBreakHelper(s, valid, i + 1, path, result); + path->pop_back(); + } + } + } +}; From 2cd5d4f6f684a81f184f5e06b3e957fea6937cbc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 13:15:52 +0800 Subject: [PATCH 2545/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88efc7a85..cf22fa023 100644 --- a/README.md +++ b/README.md @@ -411,7 +411,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [C++](./C++/subsets-ii.cpp) [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 || +140| [Word Break II](https://leetcode.com/problems/word-break-ii/) | [C++](./Python/word-break-ii.cpp) [Python](./Python/word-break-ii.py) | _O(n * l^2 + n * r)_ | _O(n^2)_ | 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 |📖|| From ed6431cc6096512757ac9d67e4c9014a201f23d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 13:16:12 +0800 Subject: [PATCH 2546/4971] Update word-break-ii.py --- Python/word-break-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/word-break-ii.py b/Python/word-break-ii.py index 64e77614c..7dcb65c6d 100644 --- a/Python/word-break-ii.py +++ b/Python/word-break-ii.py @@ -1,6 +1,6 @@ # Time: O(n * l^2 + n * r), l is the max length of the words, # r is the number of the results. -# Space: O(n) +# Space: O(n^2) # # Given a string s and a dictionary of words dict, # add spaces in s to construct a sentence where each word is a valid dictionary word. From 372d515cdf4baddf24f3738d0c3213557d243f14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 13:16:45 +0800 Subject: [PATCH 2547/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cf22fa023..7a21e2cf9 100644 --- a/README.md +++ b/README.md @@ -411,7 +411,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [C++](./C++/subsets-ii.cpp) [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/) | [C++](./Python/word-break-ii.cpp) [Python](./Python/word-break-ii.py) | _O(n * l^2 + n * r)_ | _O(n^2)_ | Hard || +140| [Word Break II](https://leetcode.com/problems/word-break-ii/) | [C++](./C++/word-break-ii.cpp) [Python](./Python/word-break-ii.py) | _O(n * l^2 + n * r)_ | _O(n^2)_ | 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 |📖|| From 1b1a5b3a601ab4c8341fe283cb954e786de55644 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 13:17:05 +0800 Subject: [PATCH 2548/4971] Update word-break-ii.cpp --- C++/word-break-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/word-break-ii.cpp b/C++/word-break-ii.cpp index eb1fa1086..36801ce79 100644 --- a/C++/word-break-ii.cpp +++ b/C++/word-break-ii.cpp @@ -1,6 +1,6 @@ // Time: O(n * l^2 + n * r), l is the max length of the words, // r is the number of the results. -// Space: O(n) +// Space: O(n^2) class Solution { public: From ba9a4f9febc765a54a2903831694b7faeb7125d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jul 2016 13:17:47 +0800 Subject: [PATCH 2549/4971] Update word-break-ii.cpp --- C++/word-break-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/word-break-ii.cpp b/C++/word-break-ii.cpp index 36801ce79..3e2b92667 100644 --- a/C++/word-break-ii.cpp +++ b/C++/word-break-ii.cpp @@ -44,7 +44,7 @@ class Solution { result->emplace_back(move(tmp)); return; } - for(int i = start; i < s.length(); ++i) { + for (int i = start; i < s.length(); ++i) { if (valid[start][i]) { path->emplace_back(s.substr(start, i + 1 - start)); wordBreakHelper(s, valid, i + 1, path, result); From 388dd6071a204069179a069e4747d72269f230cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jul 2016 21:23:15 +0800 Subject: [PATCH 2550/4971] Create reverse-integer.cpp --- C++/reverse-integer.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/reverse-integer.cpp diff --git a/C++/reverse-integer.cpp b/C++/reverse-integer.cpp new file mode 100644 index 000000000..a59a85254 --- /dev/null +++ b/C++/reverse-integer.cpp @@ -0,0 +1,20 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int reverse(int x) { + int result = 0; + while (x) { + auto prev = result; + result *= 10; + result += x % 10; + if (result / 10 != prev) { + result = 0; + break; + } + x /= 10; + } + return result; + } +}; From b1d21212447d312b21f0f89b6fbb4da09170b594 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jul 2016 21:23:56 +0800 Subject: [PATCH 2551/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7a21e2cf9..bf8e23055 100644 --- a/README.md +++ b/README.md @@ -236,7 +236,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Math # | 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 || +7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [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 || From 5f8fd8f326adbd638c73a7abb3bdbb07ca63d1ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jul 2016 21:42:32 +0800 Subject: [PATCH 2552/4971] Update reverse-integer.py --- Python/reverse-integer.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py index 154445314..d20f21f6f 100644 --- a/Python/reverse-integer.py +++ b/Python/reverse-integer.py @@ -20,18 +20,22 @@ # You would then have to re-design the function (ie, add an extra parameter). # -class Solution: - # @return an integer +class Solution(object): def reverse(self, x): - ans = 0 + """ + :type x: int + :rtype: int + """ + result = 0 if x >= 0: while x: - ans = ans * 10 + x % 10 + result = result * 10 + x % 10 x /= 10 - return ans if ans <= 2147483647 else 0 # Handle overflow. + return result if result <= 0x7fffffff else 0 # Handle overflow. else: return -self.reverse(-x) - + + if __name__ == "__main__": print Solution().reverse(123) print Solution().reverse(-321) From 279ec17c120d313b71fc14e33719584086f4dc30 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jul 2016 21:46:44 +0800 Subject: [PATCH 2553/4971] Update reverse-integer.py --- Python/reverse-integer.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py index d20f21f6f..2abc168cf 100644 --- a/Python/reverse-integer.py +++ b/Python/reverse-integer.py @@ -26,15 +26,15 @@ def reverse(self, x): :type x: int :rtype: int """ - result = 0 - if x >= 0: - while x: - result = result * 10 + x % 10 - x /= 10 - return result if result <= 0x7fffffff else 0 # Handle overflow. - else: + if x < 0: return -self.reverse(-x) + result = 0 + while x: + result = result * 10 + x % 10 + x /= 10 + return result if result <= 0x7fffffff else 0 # Handle overflow. + if __name__ == "__main__": print Solution().reverse(123) From 0271f9b4c8ebcaef9bce87c0606e8e4683da668b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jul 2016 21:50:51 +0800 Subject: [PATCH 2554/4971] Update reverse-integer.py --- Python/reverse-integer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py index 2abc168cf..ad5085137 100644 --- a/Python/reverse-integer.py +++ b/Python/reverse-integer.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(logn) # Space: O(1) # # Reverse digits of an integer. From a0ad4f0d4b32f102d6a97a2d117950b109fdbd52 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Jul 2016 23:25:27 +0800 Subject: [PATCH 2555/4971] Update powx-n.cpp --- C++/powx-n.cpp | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/C++/powx-n.cpp b/C++/powx-n.cpp index 79df9e460..0378e9812 100644 --- a/C++/powx-n.cpp +++ b/C++/powx-n.cpp @@ -1,5 +1,5 @@ -// Time: O(logn) -// Space: O(1) +// Time: O(logn * nlogx * logx) = O(1) +// Space: O(nlogx) = O(1) class Solution { public: @@ -16,3 +16,24 @@ class Solution { return n < 0 ? 1 / res : res; } }; + +// Time: O(logn * nlogx * logx) = O(1) +// Space: O(nlogx) = O(1) +// Recursive solution. +class Solution2 { +public: + double myPow(double x, int n) { + if (n < 0 && n != -n) { + return 1.0 / myPow(x, -n); + } + if (n == 0) { + return 1; + } + double v = myPow(x, n / 2); + if (n % 2 == 0) { + return v * v; + } else { + return v * v * x; + } + } +}; From ca0cb68bf7763f8e2f7a4f90655b4b51e4a0fc1f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Jul 2016 23:28:52 +0800 Subject: [PATCH 2556/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bf8e23055..eee7f0946 100644 --- a/README.md +++ b/README.md @@ -241,7 +241,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || -50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(logn)_ | _O(1)_ | Medium || +50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(1)_ | _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 || From fc8739767c208f392cc7097ff919a4c2d7402a5d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Jul 2016 23:33:26 +0800 Subject: [PATCH 2557/4971] Update powx-n.py --- Python/powx-n.py | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/Python/powx-n.py b/Python/powx-n.py index 44fdae013..b929a6fb5 100644 --- a/Python/powx-n.py +++ b/Python/powx-n.py @@ -1,5 +1,5 @@ -# Time: O(logn) -# Space: O(1) +# Time: O(logn * nlogx * logx) = O(1) +# Space: O(nlogx) = O(1) # Implement pow(x, n). @@ -10,15 +10,35 @@ def myPow(self, x, n): :type n: int :rtype: float """ - res = 1 + result = 1 abs_n = abs(n) while abs_n: if abs_n & 1: - res *= x + result *= x abs_n >>= 1 x *= x - return 1 / res if n < 0 else res + return 1 / result if n < 0 else result + + +# Time: O(logn * nlogx * logx) = O(1) +# Space: O(nlogx) = O(1) +class Solution2(object): + def myPow(self, x, n): + """ + :type x: float + :type n: int + :rtype: float + """ + if n < 0 and n != -n: + return 1.0 / self.myPow(x, -n) + if n == 0: + return 1 + v = self.myPow(x, n / 2) + if n % 2 == 0: + return v * v + else: + return v * v * x if __name__ == "__main__": From ee043a56ee8ce02223e6fc0622f65a9a7b4d5e0c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Jul 2016 23:35:25 +0800 Subject: [PATCH 2558/4971] Update powx-n.cpp --- C++/powx-n.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/powx-n.cpp b/C++/powx-n.cpp index 0378e9812..3b10002f0 100644 --- a/C++/powx-n.cpp +++ b/C++/powx-n.cpp @@ -4,16 +4,16 @@ class Solution { public: double myPow(double x, int n) { - double res = 1; - long abs_n = abs(static_cast(n)); + double result = 1; + long long abs_n = abs(static_cast(n)); while (abs_n > 0) { if (abs_n & 1) { - res *= x; + result *= x; } abs_n >>= 1; x *= x; } - return n < 0 ? 1 / res : res; + return n < 0 ? 1 / result : result; } }; From 481855cc288ff20ffe0dd6a4e537ff8ba1c9e2b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 00:16:53 +0800 Subject: [PATCH 2559/4971] Update powx-n.py --- Python/powx-n.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Python/powx-n.py b/Python/powx-n.py index b929a6fb5..d18711831 100644 --- a/Python/powx-n.py +++ b/Python/powx-n.py @@ -3,6 +3,7 @@ # Implement pow(x, n). +# Iterative solution. class Solution(object): def myPow(self, x, n): """ @@ -23,6 +24,7 @@ def myPow(self, x, n): # Time: O(logn * nlogx * logx) = O(1) # Space: O(nlogx) = O(1) +# Recursive solution. class Solution2(object): def myPow(self, x, n): """ From 713839647be5b9c34a8eafd402be29f35b2850fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 02:10:28 +0800 Subject: [PATCH 2560/4971] Update powx-n.cpp --- C++/powx-n.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/powx-n.cpp b/C++/powx-n.cpp index 3b10002f0..89bbcd6ff 100644 --- a/C++/powx-n.cpp +++ b/C++/powx-n.cpp @@ -1,5 +1,5 @@ -// Time: O(logn * nlogx * logx) = O(1) -// Space: O(nlogx) = O(1) +// Time: O(logn) +// Space: O(1) class Solution { public: @@ -17,8 +17,8 @@ class Solution { } }; -// Time: O(logn * nlogx * logx) = O(1) -// Space: O(nlogx) = O(1) +// Time: O(logn) +// Space: O(logn) // Recursive solution. class Solution2 { public: From e668451b36b8c045df6d7737f941b6041b5b0a10 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 02:11:08 +0800 Subject: [PATCH 2561/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eee7f0946..bf8e23055 100644 --- a/README.md +++ b/README.md @@ -241,7 +241,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || -50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(1)_ | _O(1)_ | Medium || +50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.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 || From d9706dce33e824ca6fa4d930e7c4ebb6c5938741 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 02:11:40 +0800 Subject: [PATCH 2562/4971] Update powx-n.py --- Python/powx-n.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/powx-n.py b/Python/powx-n.py index d18711831..94539502e 100644 --- a/Python/powx-n.py +++ b/Python/powx-n.py @@ -1,5 +1,5 @@ -# Time: O(logn * nlogx * logx) = O(1) -# Space: O(nlogx) = O(1) +# Time: O(logn) +# Space: O(1) # Implement pow(x, n). @@ -22,8 +22,8 @@ def myPow(self, x, n): return 1 / result if n < 0 else result -# Time: O(logn * nlogx * logx) = O(1) -# Space: O(nlogx) = O(1) +# Time: O(logn) +# Space: O(logn) # Recursive solution. class Solution2(object): def myPow(self, x, n): From 6a67a7079ec289e9566427772df74a6d7ad99c30 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Jul 2016 19:46:07 -0500 Subject: [PATCH 2563/4971] Update powx-n.cpp --- C++/powx-n.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/powx-n.cpp b/C++/powx-n.cpp index 89bbcd6ff..c26568db4 100644 --- a/C++/powx-n.cpp +++ b/C++/powx-n.cpp @@ -1,6 +1,7 @@ // Time: O(logn) // Space: O(1) +// Iterative solution. class Solution { public: double myPow(double x, int n) { From 31c61b0f7c871f8d214a4c8339a0ae62dd361938 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 22:00:10 +0800 Subject: [PATCH 2564/4971] Create super-pow.py --- Python/super-pow.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/super-pow.py diff --git a/Python/super-pow.py b/Python/super-pow.py new file mode 100644 index 000000000..f55972807 --- /dev/null +++ b/Python/super-pow.py @@ -0,0 +1,40 @@ +# Time: O(n), n is the size of b. +# Space: O(1) + +# Your task is to calculate ab mod 1337 where a is a positive integer +# and b is an extremely large positive integer given in the form of an array. +# +# Example1: +# +# a = 2 +# b = [3] +# +# Result: 8 +# Example2: +# +# a = 2 +# b = [1,0] +# +# Result: 1024 + +class Solution(object): + def superPow(self, a, b): + """ + :type a: int + :type b: List[int] + :rtype: int + """ + def myPow(a, n, b): + result = 1 + x = a % b + while n: + if n & 1: + result = result * x % b + n >>= 1 + x = x * x % b + return result % b + + result = 1 + for digit in b: + result = myPow(result, 10, 1337) * myPow(a, digit, 1337) % 1337 + return result From 3b4768cc30301897839bbdf71b9ce5993bcf2ef5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 22:09:30 +0800 Subject: [PATCH 2565/4971] Update super-pow.py --- Python/super-pow.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/super-pow.py b/Python/super-pow.py index f55972807..70caf17c8 100644 --- a/Python/super-pow.py +++ b/Python/super-pow.py @@ -1,7 +1,7 @@ # Time: O(n), n is the size of b. # Space: O(1) -# Your task is to calculate ab mod 1337 where a is a positive integer +# Your task is to calculate a^b mod 1337 where a is a positive integer # and b is an extremely large positive integer given in the form of an array. # # Example1: From 35fc0ed5320cb040971a6cf22181bfc412e9dae0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 23:21:13 +0800 Subject: [PATCH 2566/4971] Create find-k-pairs-with-smallest-sums.cpp --- C++/find-k-pairs-with-smallest-sums.cpp | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/find-k-pairs-with-smallest-sums.cpp diff --git a/C++/find-k-pairs-with-smallest-sums.cpp b/C++/find-k-pairs-with-smallest-sums.cpp new file mode 100644 index 000000000..89d0cac00 --- /dev/null +++ b/C++/find-k-pairs-with-smallest-sums.cpp @@ -0,0 +1,37 @@ +// Time: O(k * log(min(n, m, k))), where n is the size of num1, and m is the size of num2. +// Space: O(min(n, m, k)) + +class Solution { +public: + vector> kSmallestPairs(vector& nums1, vector& nums2, int k) { + vector> pairs; + if (nums1.size() > nums2.size()) { + vector> tmp = kSmallestPairs(nums2, nums1, k); + for (const auto& pair : tmp) { + pairs.emplace_back(pair.second, pair.first); + } + return pairs; + } + + using P = pair>; + priority_queue, greater

> q; + auto push = [&nums1, &nums2, &q](int i, int j) { + if (i < nums1.size() && j < nums2.size()) { + q.emplace(nums1[i] + nums2[j], make_pair(i, j)); + } + }; + + push(0, 0); + while (k-- && !q.empty()) { + auto tmp = q.top(); q.pop(); + int i, j; + tie(i, j) = tmp.second; + pairs.emplace_back(nums1[i], nums2[j]); + push(i, j + 1); + if (j == 0) { + push(i + 1, 0); // at most queue min(m, n) space. + } + } + return pairs; + } +}; From 9fad7caf960839af6316cc539690dc6f21b60358 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 23:24:14 +0800 Subject: [PATCH 2567/4971] Create find-k-pairs-with-smallest-sums.py --- Python/find-k-pairs-with-smallest-sums.py | 63 +++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Python/find-k-pairs-with-smallest-sums.py diff --git a/Python/find-k-pairs-with-smallest-sums.py b/Python/find-k-pairs-with-smallest-sums.py new file mode 100644 index 000000000..272a4ccff --- /dev/null +++ b/Python/find-k-pairs-with-smallest-sums.py @@ -0,0 +1,63 @@ +# Time: O(k * log(min(n, m, k))), where n is the size of num1, and m is the size of num2. +# Space: O(min(n, m, k)) + +# You are given two integer arrays nums1 +# and nums2 sorted in ascending order and an integer k. +# +# Define a pair (u,v) which consists of one element +# from the first array and one element from the second array. +# +# Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums. +# +# Example 1: +# Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3 +# +# Return: [1,2],[1,4],[1,6] +# +# The first 3 pairs are returned from the sequence: +# [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] +# Example 2: +# Given nums1 = [1,1,2], nums2 = [1,2,3], k = 2 +# +# Return: [1,1],[1,1] +# +# The first 2 pairs are returned from the sequence: +# [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] +# Example 3: +# Given nums1 = [1,2], nums2 = [3], k = 3 +# +# Return: [1,3],[2,3] +# +# All possible pairs are returned from the sequence: +# [1,3],[2,3] + +from heapq import heappush, heappop + +class Solution(object): + def kSmallestPairs(self, nums1, nums2, k): + """ + :type nums1: List[int] + :type nums2: List[int] + :type k: int + :rtype: List[List[int]] + """ + pairs = [] + if len(nums1) > len(nums2): + tmp = self.kSmallestPairs(nums2, nums1, k) + for pair in tmp: + pairs.append([pair[1], pair[0]]) + return pairs + + min_heap = [] + def push(i, j): + if i < len(nums1) and j < len(nums2): + heappush(min_heap, [nums1[i] + nums2[j], i, j]) + + push(0, 0) + while min_heap and len(pairs) < k: + _, i, j = heappop(min_heap) + pairs.append([nums1[i], nums2[j]]) + push(i, j + 1) + if j == 0: + push(i + 1, 0) # at most queue min(n, m) space + return pairs From c9683bb139f1ae7746f3b22ac6e84ff9f8845aa3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 23:27:38 +0800 Subject: [PATCH 2568/4971] Create super-pow.cpp --- C++/super-pow.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/super-pow.cpp diff --git a/C++/super-pow.cpp b/C++/super-pow.cpp new file mode 100644 index 000000000..fe3393d87 --- /dev/null +++ b/C++/super-pow.cpp @@ -0,0 +1,27 @@ +// Time: O(n), n is the size of b. +// Space: O(1) + +class Solution { +public: + int superPow(int a, vector& b) { + int result = 1; + for (const auto& digit : b) { + result = myPow(result, 10, 1337) * myPow(a, digit, 1337) % 1337; + } + return result; + } + +private: + int myPow(int a, int n, int b) { + int result = 1; + int x = a % b; + while (n) { + if (n & 1) { + result = result * x % b; + } + n >>= 1; + x = x * x % b; + } + return result % b; + } +}; From 4c161c70502167d6f60e9c17bdc4c0a2747e1830 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 23:31:37 +0800 Subject: [PATCH 2569/4971] Update README.md --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index bf8e23055..d95eca219 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-371%20%2F%20371-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-373%20%2F%20373-ff69b4.svg) -Up to date (2016-06-30), there are `354` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-06-30), there are `356` 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 `371` questions. +Here is the classification of all `373` 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. ) @@ -178,6 +178,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | 358| [Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/)| [C++](./C++/rearrange-string-k-distance-apart.cpp) [Python](./Python/rearrange-string-k-distance-apart.py) | _O(n)_ | _O(n)_ | Hard |📖| Greedy, Heap | +373 | [Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/) | [C++](./C++/find-k-pairs-with-smallest-sums.cpp) [Python](./Python/find-k-pairs-with-smallest-sums.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium ||| ## Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -261,6 +262,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./C++/counting-bits.cpp) [Python](./Python/counting-bits.py) | _O(n)_ | _O(n)_ | Medium ||| 343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(1)_ | Medium || Tricky, DP | 365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || Euclidean Algorithm | +372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From e2967f999cf8a5fbd37ab5449668f05446a848fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 23:33:06 +0800 Subject: [PATCH 2570/4971] Update find-k-pairs-with-smallest-sums.cpp --- C++/find-k-pairs-with-smallest-sums.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/find-k-pairs-with-smallest-sums.cpp b/C++/find-k-pairs-with-smallest-sums.cpp index 89d0cac00..dbde1b312 100644 --- a/C++/find-k-pairs-with-smallest-sums.cpp +++ b/C++/find-k-pairs-with-smallest-sums.cpp @@ -22,7 +22,7 @@ class Solution { }; push(0, 0); - while (k-- && !q.empty()) { + while (!q.empty() && pairs.size() < k) { auto tmp = q.top(); q.pop(); int i, j; tie(i, j) = tmp.second; From c4a6d69db8059da80d1e9bb415a5e5c297f9e367 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Jul 2016 23:36:48 +0800 Subject: [PATCH 2571/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d95eca219..7558699a3 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-373%20%2F%20373-ff69b4.svg) -Up to date (2016-06-30), there are `356` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-07-07), there are `356` 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 `373` questions. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 411056bacafe972477d89806b6277e01ee5e9384 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Jul 2016 21:05:16 +0800 Subject: [PATCH 2572/4971] Update and rename isPalindrome.cpp to palindrome-number.cpp --- C++/isPalindrome.cpp | 22 -------------------- C++/palindrome-number.cpp | 44 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 22 deletions(-) delete mode 100644 C++/isPalindrome.cpp create mode 100644 C++/palindrome-number.cpp diff --git a/C++/isPalindrome.cpp b/C++/isPalindrome.cpp deleted file mode 100644 index b2506097f..000000000 --- a/C++/isPalindrome.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - bool isPalindrome(int x) { - if(x < 0) - return false; - - int d = 1; - for(; x / d >= 10 ; d *= 10); - - for(; x > 0; x = (x % d) / 10, d /= 100) { - int q = x / d; - int r = x % 10; - if(q != r) - return false; - } - - return true; - } -}; diff --git a/C++/palindrome-number.cpp b/C++/palindrome-number.cpp new file mode 100644 index 000000000..c338757a1 --- /dev/null +++ b/C++/palindrome-number.cpp @@ -0,0 +1,44 @@ +// Time: O(logx) = O(1) +// Space: O(1) + +class Solution { +public: + bool isPalindrome(int x) { + if(x < 0) { + return false; + } + + int divisor = 1; + while (x / divisor >= 10) { + divisor *= 10; + } + + for (; x > 0; x = (x % divisor) / 10, divisor /= 100) { + int left = x / divisor; + int right = x % 10; + if (left != right) { + return false; + } + } + + return true; + } +}; + +// Time: O(logx) = O(1) +// Space: O(1) +class Solution2 { +public: + bool isPalindrome(int x) { + if (x < 0) { + return false; + } + int temp = x; + int reversed = 0; + while (temp != 0) { + reversed = reversed * 10 + temp % 10; + temp = temp / 10; + } + return reversed == x; + } +}; From 72b05b57e7cda38bffd21c3881d42151e4d22d4e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Jul 2016 21:11:51 +0800 Subject: [PATCH 2573/4971] Update palindrome-number.cpp --- C++/palindrome-number.cpp | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/C++/palindrome-number.cpp b/C++/palindrome-number.cpp index c338757a1..6c32423e2 100644 --- a/C++/palindrome-number.cpp +++ b/C++/palindrome-number.cpp @@ -2,6 +2,24 @@ // Space: O(1) class Solution { +public: + bool isPalindrome(int x) { + if (x < 0) { + return false; + } + int temp = x; + int reversed = 0; + while (temp != 0) { + reversed = reversed * 10 + temp % 10; + temp = temp / 10; + } + return reversed == x; + } +}; + +// Time: O(logx) = O(1) +// Space: O(1) +class Solution2 { public: bool isPalindrome(int x) { if(x < 0) { @@ -24,21 +42,3 @@ class Solution { return true; } }; - -// Time: O(logx) = O(1) -// Space: O(1) -class Solution2 { -public: - bool isPalindrome(int x) { - if (x < 0) { - return false; - } - int temp = x; - int reversed = 0; - while (temp != 0) { - reversed = reversed * 10 + temp % 10; - temp = temp / 10; - } - return reversed == x; - } -}; From 530f2c4d03b5efe7cf58618b3a1953e1c6a5bf96 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Jul 2016 21:12:41 +0800 Subject: [PATCH 2574/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7558699a3..df2cb5d35 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 # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [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 || +9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C++](./C++/palindrome-number.cpp) [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 || From da31e84fc75a60fd2b1606e229afc72d369adb4c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Jul 2016 22:46:21 +0800 Subject: [PATCH 2575/4971] Create integer-to-roman.cpp --- C++/integer-to-roman.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/integer-to-roman.cpp diff --git a/C++/integer-to-roman.cpp b/C++/integer-to-roman.cpp new file mode 100644 index 000000000..4b4d4fc9c --- /dev/null +++ b/C++/integer-to-roman.cpp @@ -0,0 +1,24 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string intToRoman(int num) { + const vector nums{1000, 900, 500, 400, 100, 90, + 50, 40, 10, 9, 5, 4, 1}; + const vector romans{"M", "CM", "D", "CD", "C", "XC", "L", + "XL", "X", "IX", "V", "IV", "I"}; + + string result; + int i = 0; + while (num > 0) { + int times = num / nums[i]; + while (times--) { + num -= nums[i]; + result.append(romans[i]); + } + ++i; + } + return result; + } +}; From ed8d91213cdd901424c2ff108269f6ae02a0872d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Jul 2016 22:47:05 +0800 Subject: [PATCH 2576/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index df2cb5d35..18b68b6d3 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || 9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C++](./C++/palindrome-number.cpp) [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 || +12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [C++](./C++/integer-to-roman.cpp) [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 || 50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(logn)_ | _O(1)_ | Medium || From 95db85426fde47fa30982dca6cb00d231036f785 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jul 2016 16:34:04 +0800 Subject: [PATCH 2577/4971] Create roman-to-integer.cpp --- C++/roman-to-integer.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/roman-to-integer.cpp diff --git a/C++/roman-to-integer.cpp b/C++/roman-to-integer.cpp new file mode 100644 index 000000000..13553fdea --- /dev/null +++ b/C++/roman-to-integer.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int romanToInt(string s) { + unordered_map numeral_map = {{'I', 1}, {'V', 5}, {'X', 10}, + {'L', 50}, {'C', 100}, {'D', 500}, + {'M', 1000}}; + int decimal = 0; + for (int i = 0; i < s.length(); ++i) { + if (i > 0 && numeral_map[s[i]] > numeral_map[s[i - 1]]) { + decimal += numeral_map[s[i]] - 2 * numeral_map[s[i - 1]]; + } else { + decimal += numeral_map[s[i]]; + } + } + return decimal; + } +}; From 39e77b2e0e030046b937ea5af46823997a599b05 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jul 2016 16:34:42 +0800 Subject: [PATCH 2578/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 18b68b6d3..6a70c5105 100644 --- a/README.md +++ b/README.md @@ -240,7 +240,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || 9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C++](./C++/palindrome-number.cpp) [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || 12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [C++](./C++/integer-to-roman.cpp) [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 || +13| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [C++](./C++/roman-to-integer.cpp) [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 || 50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.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` From a2aa8097e1ecf94debba20bd975b1d28f2381b01 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:04:34 +0800 Subject: [PATCH 2579/4971] Update divide.cpp --- C++/divide.cpp | 89 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 72 insertions(+), 17 deletions(-) diff --git a/C++/divide.cpp b/C++/divide.cpp index 988507e84..79baca979 100644 --- a/C++/divide.cpp +++ b/C++/divide.cpp @@ -1,23 +1,78 @@ -// Time Complexity: O(logn) -// Space Complexity: O(1) +// Time: O(logn) = O(1) +// Space: O(1) +// Only using integer type. class Solution { - public: - int divide(int dividend, int divisor) { - long long a = dividend >= 0 ? dividend : -(long long)dividend; - long long b = divisor >= 0 ? divisor : -(long long)divisor; - - long long result = 0; - while(a >= b) { - long long c = b; - int i = 0; - for(; a >= c; c <<= 1, ++i); - if(i > 0) { - a -= c >> 1; - result += 1 << (i - 1); - } +public: + int divide(int dividend, int divisor) { + // Handle corner case. + if (dividend == numeric_limits::min() && divisor == -1) { + return numeric_limits::max(); + } + + int a = dividend > 0 ? -dividend : dividend; + int b = divisor > 0 ? -divisor : divisor; + + int shift = 0; + while (b << shift < 0 && shift < 32) { + ++shift; + } + shift -= 1; + + int result = 0; + while (shift >= 0) { + if (a <= b << shift) { + a -= b << shift; + result += 1 << shift; } + --shift; + } + + result = (dividend ^ divisor) >> 31 ? -result : result; + return result; + } +}; + +// Time: O(logn) = O(1) +// Space: O(1) +// Using long long type. +class Solution2 { +public: + int divide(int dividend, int divisor) { + long long result = 0; + long long a = llabs(dividend); + long long b = llabs(divisor); - return ((dividend ^ divisor) >> 31)? -result : result; + int shift = 31; + while (shift >= 0) { + if (a >= b << shift) { + a -= b << shift; + result += 1LL << shift; + } + --shift; + } + + result = ((dividend ^ divisor) >> 31) ? -result : result; + return min(result, static_cast(numeric_limits::max())); + } +}; + +// Time: O(logn) = O(1) +// Space: O(1) +// a / b = exp^(ln(a) - ln(b)) +class Solution3 { +public: + int divide(int dividend, int divisor) { + if (dividend == 0) { + return 0; + } + if (divisor == 0) { + return numeric_limits::max(); } + + long long result = exp(log(fabs(dividend)) - log(fabs(divisor))); + + result = ((dividend ^ divisor) >> 31) ? -result : result; + return min(result, static_cast(numeric_limits::max())); + } }; From 0a75d480fb2a14c24148237433db1b9c93c8e2df Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:06:13 +0800 Subject: [PATCH 2580/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6a70c5105..d5851f550 100644 --- a/README.md +++ b/README.md @@ -241,7 +241,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C++](./C++/palindrome-number.cpp) [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || 12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [C++](./C++/integer-to-roman.cpp) [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || 13| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [C++](./C++/roman-to-integer.cpp) [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 || +29| [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C++](./C++/divide-two-integers.cpp) [Python](./Python/divide-two-integers.py) | _O(1)_ | _O(1)_ | Medium || 50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.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` From e678b519ca45bbf21d86b813c8c0ef5dbcd1cc9c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:06:47 +0800 Subject: [PATCH 2581/4971] Rename divide.cpp to divide-two-integers.cpp --- C++/{divide.cpp => divide-two-integers.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{divide.cpp => divide-two-integers.cpp} (100%) diff --git a/C++/divide.cpp b/C++/divide-two-integers.cpp similarity index 100% rename from C++/divide.cpp rename to C++/divide-two-integers.cpp From 505f74a7fa62396988175072ab8df9df22c3ed58 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:17:27 +0800 Subject: [PATCH 2582/4971] Update powx-n.cpp --- C++/powx-n.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/powx-n.cpp b/C++/powx-n.cpp index c26568db4..652600ee8 100644 --- a/C++/powx-n.cpp +++ b/C++/powx-n.cpp @@ -1,4 +1,4 @@ -// Time: O(logn) +// Time: O(logn) = O(1) // Space: O(1) // Iterative solution. @@ -18,8 +18,8 @@ class Solution { } }; -// Time: O(logn) -// Space: O(logn) +// Time: O(logn) = O(1) +// Space: O(logn) = O(1) // Recursive solution. class Solution2 { public: From 3b9d429f057aeb1c83236b04b363738389fa978f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:18:38 +0800 Subject: [PATCH 2583/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d5851f550..f5f705155 100644 --- a/README.md +++ b/README.md @@ -242,7 +242,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [C++](./C++/integer-to-roman.cpp) [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || 13| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [C++](./C++/roman-to-integer.cpp) [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || 29| [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C++](./C++/divide-two-integers.cpp) [Python](./Python/divide-two-integers.py) | _O(1)_ | _O(1)_ | Medium || -50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(logn)_ | _O(1)_ | Medium || +50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(1)_ | _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 || From e75d9ed1e55a693c3d320a1bcb23281e33939f18 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:20:18 +0800 Subject: [PATCH 2584/4971] Update divide-two-integers.py --- Python/divide-two-integers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/divide-two-integers.py b/Python/divide-two-integers.py index ff8bd757e..258184bcd 100644 --- a/Python/divide-two-integers.py +++ b/Python/divide-two-integers.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(logn) = O(1) # Space: O(1) # # Divide two integers without using multiplication, division and mod operator. @@ -25,4 +25,4 @@ def divide(self, dividend, divisor): print Solution().divide(123, 12) print Solution().divide(123, -12) print Solution().divide(-123, 12) - print Solution().divide(-123, -12) \ No newline at end of file + print Solution().divide(-123, -12) From 28439942f60c4c20d3b3b29bbbe5aa5b7a0b9a51 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:20:34 +0800 Subject: [PATCH 2585/4971] Update powx-n.py --- Python/powx-n.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/powx-n.py b/Python/powx-n.py index 94539502e..a787cfd82 100644 --- a/Python/powx-n.py +++ b/Python/powx-n.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(logn) = O(1) # Space: O(1) # Implement pow(x, n). From dbe2df73a22ce9d0f3467b23b2cab5ec360cfcf0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:22:04 +0800 Subject: [PATCH 2586/4971] Update factorial-trailing-zeroes.py --- Python/factorial-trailing-zeroes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/factorial-trailing-zeroes.py b/Python/factorial-trailing-zeroes.py index d649a86ff..106b59beb 100644 --- a/Python/factorial-trailing-zeroes.py +++ b/Python/factorial-trailing-zeroes.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(logn) = O(1) # Space: O(1) # # Given an integer n, return the number of trailing zeroes in n!. @@ -16,4 +16,4 @@ def trailingZeroes(self, n): return result if __name__ == "__main__": - print Solution().trailingZeroes(100) \ No newline at end of file + print Solution().trailingZeroes(100) From 3ff32bb03080fc61faf9a2c676e334ddea037835 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:23:34 +0800 Subject: [PATCH 2587/4971] Update number-of-digit-one.cpp --- C++/number-of-digit-one.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/number-of-digit-one.cpp b/C++/number-of-digit-one.cpp index c13ebbefc..3b6f3f35d 100644 --- a/C++/number-of-digit-one.cpp +++ b/C++/number-of-digit-one.cpp @@ -1,4 +1,4 @@ -// Time: O(logn) +// Time: O(logn) = O(1) // Space: O(1) class Solution { From bb8dc30c3182e97a129a912c09b31e5efdbe9b76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:27:48 +0800 Subject: [PATCH 2588/4971] Update reverse-integer.cpp --- C++/reverse-integer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/reverse-integer.cpp b/C++/reverse-integer.cpp index a59a85254..5e00c210e 100644 --- a/C++/reverse-integer.cpp +++ b/C++/reverse-integer.cpp @@ -1,4 +1,4 @@ -// Time: O(logn) +// Time: O(logn) = O(1) // Space: O(1) class Solution { From 777249cc75e1061415dfb49036d3d865c37378ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:28:25 +0800 Subject: [PATCH 2589/4971] Update reverse-integer.py --- Python/reverse-integer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py index ad5085137..8ec6f985a 100644 --- a/Python/reverse-integer.py +++ b/Python/reverse-integer.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(logn) = O(1) # Space: O(1) # # Reverse digits of an integer. From 36b12144d10bd0c454917ad13eb5cb383af755a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:29:11 +0800 Subject: [PATCH 2590/4971] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f5f705155..c055c994e 100644 --- a/README.md +++ b/README.md @@ -237,7 +237,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Math # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [Python](./Python/reverse-integer.py) | _O(logn)_ | _O(1)_ | Easy || +7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [Python](./Python/reverse-integer.py) | _O(1)_ | _O(1)_ | Easy || 9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C++](./C++/palindrome-number.cpp) [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || 12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [C++](./C++/integer-to-roman.cpp) [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || 13| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [C++](./C++/roman-to-integer.cpp) [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || @@ -249,9 +249,9 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || +172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [Python](./Python/factorial-trailing-zeroes.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 || -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| +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(1)_ | _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 38ab72637f7dc65b503d28ea894d43fe056fc9e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:29:59 +0800 Subject: [PATCH 2591/4971] Update ugly-number.cpp --- C++/ugly-number.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/ugly-number.cpp b/C++/ugly-number.cpp index b804fc34d..3f357bc5c 100644 --- a/C++/ugly-number.cpp +++ b/C++/ugly-number.cpp @@ -1,4 +1,4 @@ -// Time: O(logn) +// Time: O(logn) = O(1) // Space: O(1) class Solution { From 572da2372bcf7a0b2886abe6e41b50d1ceb55d3b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:30:15 +0800 Subject: [PATCH 2592/4971] Update ugly-number.py --- Python/ugly-number.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/ugly-number.py b/Python/ugly-number.py index 003756ec7..c4185bda9 100644 --- a/Python/ugly-number.py +++ b/Python/ugly-number.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(logn) = O(1) # Space: O(1) # # Write a program to check whether a given number is an ugly number. From 8a378c4036ddeb284cbdebe2d79a64fa9331e1de Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Jul 2016 22:30:53 +0800 Subject: [PATCH 2593/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c055c994e..612a06e1f 100644 --- a/README.md +++ b/README.md @@ -254,7 +254,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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(1)_ | _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 ||| +263| [Ugly Number](https://leetcode.com/problems/ugly-number/) | [C++](./C++/ugly-number.cpp) [Python](./Python/ugly-number.py) | _O(1)_ | _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 ||| From bff9129f36d21a147ba7bd6990ffe83cac81c7fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Jul 2016 20:16:34 +0800 Subject: [PATCH 2594/4971] Update remove-duplicates-from-sorted-list-ii.py --- Python/remove-duplicates-from-sorted-list-ii.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/remove-duplicates-from-sorted-list-ii.py b/Python/remove-duplicates-from-sorted-list-ii.py index e1b71703c..0f21f2171 100644 --- a/Python/remove-duplicates-from-sorted-list-ii.py +++ b/Python/remove-duplicates-from-sorted-list-ii.py @@ -28,7 +28,6 @@ def deleteDuplicates(self, head): :rtype: ListNode """ dummy = ListNode(0) - dummy.next = head pre, cur = dummy, head while cur: if cur.next and cur.next.val == cur.val: From 2bb18bb069421208cd1974eae7585f2f25a7022c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Jul 2016 21:17:09 +0800 Subject: [PATCH 2595/4971] Create guess-number-higher-or-lower.py --- Python/guess-number-higher-or-lower.py | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/guess-number-higher-or-lower.py diff --git a/Python/guess-number-higher-or-lower.py b/Python/guess-number-higher-or-lower.py new file mode 100644 index 000000000..14f6bb46a --- /dev/null +++ b/Python/guess-number-higher-or-lower.py @@ -0,0 +1,32 @@ +# Time: O(logn) +# 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 number +# 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, O(1) extra space. +# Your runtime complexity should be less than O(n2). +# There is only one duplicate number in the array, but it could be repeated more than once. + +# The guess API is already defined for you. +# @param num, your guess +# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 +# def guess(num): + +class Solution(object): + def guessNumber(self, n): + """ + :type n: int + :rtype: int + """ + left, right = 1, n + while left <= right: + mid = left + (right - left) / 2 + if guess(mid) <= 0: + right = mid - 1 + else: + left = mid + 1 + return left From 56abfa8d8ca7dd1c1142d0f5ca2044589f50be18 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Jul 2016 21:20:31 +0800 Subject: [PATCH 2596/4971] Create guess-number-higher-or-lower.cpp --- C++/guess-number-higher-or-lower.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/guess-number-higher-or-lower.cpp diff --git a/C++/guess-number-higher-or-lower.cpp b/C++/guess-number-higher-or-lower.cpp new file mode 100644 index 000000000..8e41a9ba7 --- /dev/null +++ b/C++/guess-number-higher-or-lower.cpp @@ -0,0 +1,23 @@ +// Time: O(logn) +// Space: O(1) + +// Forward declaration of guess API. +// @param num, your guess +// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 +int guess(int num); + +class Solution { +public: + int guessNumber(int n) { + int left = 1, right = n; + while (left <= right) { + const auto mid = left + (right - left) / 2; + if (guess(mid) <= 0) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } +}; From 5f94c0aaf45f71eb6888a8f0c87e2963eb020deb Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Jul 2016 21:22:44 +0800 Subject: [PATCH 2597/4971] Update README.md --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 612a06e1f..220b519e3 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-373%20%2F%20373-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-374%20%2F%20374-ff69b4.svg) -Up to date (2016-07-07), there are `356` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-07-13), there are `357` 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 `373` questions. +Here is the classification of all `374` 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. ) +(Notes: "📖" means you need to subscribe to [LeetCode premium membership](https://leetcode.com/subscribe/) for the access to premium questions.) ## Algorithms @@ -346,6 +346,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 354| [Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes/) | [C++](./C++/russian-doll-envelopes.cpp) [Python](./Python/russian-doll-envelopes.py) | _O(nlogn)_ | _O(1)_ | Hard ||| 363| [Max Sum of Rectangle No Larger Than K](https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/) | [C++](./C++/max-sum-of-sub-matrix-no-larger-than-k.cpp) [Python](./Python/max-sum-of-sub-matrix-no-larger-than-k.py) | _O(min(m, n)^2 * max(m, n) * logn(max(m, n)))_ | _O(max(m, n))_ | Hard ||| 367| [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/)| [C++](./C++/valid-perfect-square.cpp) [Python](./Python/valid-perfect-square.py) | _O(logn)_ | _O(1)_ | Medium | | +374| [Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/)| [C++](./C++/guess-number-higher-or-lower.cpp) [Python](./Python/guess-number-higher-or-lower.py) | _O(logn)_ | _O(1)_ | Easy | | ## Binary Search Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note From da3b501d81e73dee99864db4bb4911e70c950913 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Jul 2016 21:14:52 +0800 Subject: [PATCH 2598/4971] Update and rename getPermutation.cpp to permutation-sequence.cpp --- C++/getPermutation.cpp | 44 ------------------------------------ C++/permutation-sequence.cpp | 33 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 44 deletions(-) delete mode 100644 C++/getPermutation.cpp create mode 100644 C++/permutation-sequence.cpp diff --git a/C++/getPermutation.cpp b/C++/getPermutation.cpp deleted file mode 100644 index 66f6b30f0..000000000 --- a/C++/getPermutation.cpp +++ /dev/null @@ -1,44 +0,0 @@ -// Time Complexity: O(n^2) -// Space Complexity: O(n) - -class Solution { - public: - string getPermutation(int n, int k) { - string s(n, '0'); - - for(int i = 0; i < n; ++i) { - s[i] += i + 1; - } - - return kth_permutation(s, k); - } - - private: - int factorial(int n) { - int sum = 1; - for(int i = n; i >= 1; --i) { - sum *= i; - } - return sum; - } - - // Cantor Encoding - template - Sequence kth_permutation(const Sequence &seq, int k) { - const int n = seq.size(); - Sequence ans; - Sequence S(seq); - int base = factorial(n - 1); - --k; - - for(int i = n - 1; i > 0; k %= base, base /= i, --i) { - auto a = next(S.begin(), k / base); - ans.push_back(*a); - S.erase(a); - } - - ans.push_back(S[0]); - - return ans; - } -}; diff --git a/C++/permutation-sequence.cpp b/C++/permutation-sequence.cpp new file mode 100644 index 000000000..c3a4e3c98 --- /dev/null +++ b/C++/permutation-sequence.cpp @@ -0,0 +1,33 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + string getPermutation(int n, int k) { + vector nums; + int total = 1; + for (int i = 1; i <= n; ++i) { + nums.emplace_back(i); + total *= i; + } + + // Cantor Ordering: + // Construct the k-th permutation with a list of n numbers + // Idea: group all permutations according to their first number (so n groups, each of + // (n - 1)! numbers), find the group where the k-th permutation belongs, remove the common + // first number from the list and append it to the resulting string, and iteratively + // construct the (((k - 1) % (n - 1)!) + 1)-th permutation with the remaining n-1 numbers + int group = total; + stringstream permutation; + while (n > 0) { + group /= n; + int idx = (k - 1) / group; + permutation << nums[idx]; + nums.erase(nums.begin() + idx); + k = (k - 1) % group + 1; + --n; + } + + return permutation.str(); + } +}; From 59c8833cd8e06b1c3392090f3be91bbaa1cb6c7f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Jul 2016 21:15:38 +0800 Subject: [PATCH 2599/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 220b519e3..89bc336b7 100644 --- a/README.md +++ b/README.md @@ -243,7 +243,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 13| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [C++](./C++/roman-to-integer.cpp) [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || 29| [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C++](./C++/divide-two-integers.cpp) [Python](./Python/divide-two-integers.py) | _O(1)_ | _O(1)_ | Medium || 50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(1)_ | _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` +60| [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | [C++](./C++/permutation-sequence.cpp) [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 || From 1f8432f363f89dfc323ac6747a3dd4b4c0704429 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Jul 2016 21:11:03 +0800 Subject: [PATCH 2600/4971] Create valid-number.cpp --- C++/valid-number.cpp | 64 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 C++/valid-number.cpp diff --git a/C++/valid-number.cpp b/C++/valid-number.cpp new file mode 100644 index 000000000..7e18513ac --- /dev/null +++ b/C++/valid-number.cpp @@ -0,0 +1,64 @@ +// Time: O(n) +// Space: O(1) + +// automata: http://images.cnitblog.com/i/627993/201405/012016243309923.png +class Solution { +public: + bool isNumber(string s) { + enum InputType { + INVALID, // 0 + SPACE, // 1 + SIGN, // 2 + DIGIT, // 3 + DOT, // 4 + EXPONENT, // 5 + NUM_INPUTS // 6 + }; + int transitionTable[][NUM_INPUTS] = { + -1, 0, 3, 1, 2, -1, // next states for state 0 + -1, 8, -1, 1, 4, 5, // next states for state 1 + -1, -1, -1, 4, -1, -1, // next states for state 2 + -1, -1, -1, 1, 2, -1, // next states for state 3 + -1, 8, -1, 4, -1, 5, // next states for state 4 + -1, -1, 6, 7, -1, -1, // next states for state 5 + -1, -1, -1, 7, -1, -1, // next states for state 6 + -1, 8, -1, 7, -1, -1, // next states for state 7 + -1, 8, -1, -1, -1, -1, // next states for state 8 + }; + + int state = 0; + for (const auto& c: s) { + InputType inputType = INVALID; + if (isspace(c)) { + inputType = SPACE; + } else if (c == '+' || c == '-') { + inputType = SIGN; + } else if (isdigit(c)) { + inputType = DIGIT; + } else if (c == '.') { + inputType = DOT; + } else if (c == 'e' || c == 'E') { + inputType = EXPONENT; + } + // Get next state from current state and input symbol + state = transitionTable[state][inputType]; + + // Invalid input + if (state == -1) { + return false; + } + } + // If the current state belongs to one of the accepting (final) states, + // then the number is valid + return state == 1 || state == 4 || state == 7 || state == 8; + } +}; + +#include +class Solution_TLE { +public: + bool isNumber(string s) { + regex e("^\\s*[\\+-]?((\\d+(\\.\\d*)?)|\\.\\d+)([eE][\\+-]?\\d+)?\\s*$"); + return regex_match(s, e); + } +}; From 644bb4d77bb768561fb2c7930fa190709c7ee6e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Jul 2016 21:11:44 +0800 Subject: [PATCH 2601/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 89bc336b7..dc87c795e 100644 --- a/README.md +++ b/README.md @@ -244,7 +244,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 29| [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C++](./C++/divide-two-integers.cpp) [Python](./Python/divide-two-integers.py) | _O(1)_ | _O(1)_ | Medium || 50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(1)_ | _O(1)_ | Medium || 60| [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | [C++](./C++/permutation-sequence.cpp) [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` +65| [Valid Number](https://leetcode.com/problems/valid-number/) | [C++](./C++/valid-number.cpp) [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 || From f9b9cef949a64a07ac6b75ec96ffd6ec322383c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Jul 2016 21:13:31 +0800 Subject: [PATCH 2602/4971] Update valid-number.py --- Python/valid-number.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/Python/valid-number.py b/Python/valid-number.py index 8a5c744e7..75773c0df 100644 --- a/Python/valid-number.py +++ b/Python/valid-number.py @@ -21,12 +21,15 @@ class InputType: DOT = 4 EXPONENT = 5 + # 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 - # @return a boolean +class Solution(object): def isNumber(self, s): + """ + :type s: str + :rtype: bool + """ transition_table = [[-1, 0, 3, 1, 2, -1], # next states for state 0 [-1, 8, -1, 1, 4, 5], # next states for state 1 [-1, -1, -1, 4, -1, -1], # next states for state 2 @@ -58,13 +61,17 @@ def isNumber(self, s): return state == 1 or state == 4 or state == 7 or state == 8 -class Solution2: - # @param s, a string - # @return a boolean + +class Solution2(object): def isNumber(self, s): + """ + :type s: str + :rtype: bool + """ import re return bool(re.match("^\s*[\+-]?((\d+(\.\d*)?)|\.\d+)([eE][\+-]?\d+)?\s*$", s)) - + + if __name__ == "__main__": print Solution().isNumber(" 0.1 ") print Solution().isNumber("abc") From a8516a7c32c50c6d1d3fe23b2728a6e5e7ec094f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Jul 2016 21:15:57 +0800 Subject: [PATCH 2603/4971] Update permutation-sequence.py --- Python/permutation-sequence.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Python/permutation-sequence.py b/Python/permutation-sequence.py index a3b5e1158..a672cce9f 100644 --- a/Python/permutation-sequence.py +++ b/Python/permutation-sequence.py @@ -20,9 +20,13 @@ import math # Cantor ordering solution -class Solution: - # @return a string +class Solution(object): def getPermutation(self, n, k): + """ + :type n: int + :type k: int + :rtype: str + """ seq, k, fact = "", k - 1, math.factorial(n - 1) perm = [i for i in xrange(1, n + 1)] for i in reversed(xrange(n)): @@ -33,6 +37,7 @@ def getPermutation(self, n, k): k %= fact fact /= i return seq + if __name__ == "__main__": print Solution().getPermutation(3, 2) From 9de5e74d6009debbb1d76ccd4186cb8f9efd2e00 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Jul 2016 21:16:14 +0800 Subject: [PATCH 2604/4971] Update permutation-sequence.py --- Python/permutation-sequence.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/permutation-sequence.py b/Python/permutation-sequence.py index a672cce9f..cc8b59603 100644 --- a/Python/permutation-sequence.py +++ b/Python/permutation-sequence.py @@ -1,6 +1,6 @@ # Time: O(n^2) # Space: O(n) -# + # The set [1,2,3,...,n] contains a total of n! unique permutations. # # By listing and labeling all of the permutations in order, @@ -15,7 +15,6 @@ # Given n and k, return the kth permutation sequence. # # Note: Given n will be between 1 and 9 inclusive. -# import math From d95bb716b979237b45442788abe542b0a952cacf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Jul 2016 13:31:05 +0800 Subject: [PATCH 2605/4971] Create guess-number-higher-or-lower-ii.py --- Python/guess-number-higher-or-lower-ii.py | 49 +++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/guess-number-higher-or-lower-ii.py diff --git a/Python/guess-number-higher-or-lower-ii.py b/Python/guess-number-higher-or-lower-ii.py new file mode 100644 index 000000000..48e7139a8 --- /dev/null +++ b/Python/guess-number-higher-or-lower-ii.py @@ -0,0 +1,49 @@ +# Time: O(n^2) +# Space: O(n^2) + +# We are playing the Guess Game. The game is as follows: +# +# I pick a number from 1 to n. You have to guess which number I picked. +# +# Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. +# +# However, when you guess a particular number x, and you guess wrong, +# you pay $x. You win the game when you guess the number I picked. +# +# Example: +# +# n = 10, I pick 8. +# +# First round: You guess 5, I tell you that it's higher. You pay $5. +# Second round: You guess 7, I tell you that it's higher. You pay $7. +# Third round: You guess 9, I tell you that it's lower. You pay $9. +# +# Game over. 8 is the number I picked. +# +# You end up paying $5 + $7 + $9 = $21. +# Given a particular n >= 1, find out how much money you need to have to guarantee a win. +# +# Hint: +# +# The best strategy to play the game is to minimize the maximum loss +# you could possibly face. Another strategy is to minimize the expected loss. +# Here, we are interested in the first scenario. +# Take a small example (n = 3). What do you end up paying in the worst case? +# Check out this article if you're still stuck. +# The purely recursive implementation of minimax would be worthless +# for even a small n. You MUST use dynamic programming. +# As a follow-up, how would you modify your code to solve the problem of +# minimizing the expected loss, instead of the worst-case loss? + +class Solution(object): + def getMoneyAmount(self, n): + """ + :type n: int + :rtype: int + """ + pay = [[0] * n for _ in xrange(n+1)] + for i in reversed(xrange(n)): + for j in xrange(i+1, n): + pay[i][j] = min(k+1 + max(pay[i][k-1], pay[k+1][j]) \ + for k in xrange(i, j+1)) + return pay[0][n-1] From 2771051310ef8e126a5ac6eb66b99bbc72b8f38f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Jul 2016 13:41:55 +0800 Subject: [PATCH 2606/4971] Create guess-number-higher-or-lower-ii.cpp --- C++/guess-number-higher-or-lower-ii.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/guess-number-higher-or-lower-ii.cpp diff --git a/C++/guess-number-higher-or-lower-ii.cpp b/C++/guess-number-higher-or-lower-ii.cpp new file mode 100644 index 000000000..972e05964 --- /dev/null +++ b/C++/guess-number-higher-or-lower-ii.cpp @@ -0,0 +1,18 @@ +// Time: O(n^2) +// Space: O(n^2) + +class Solution { +public: + int getMoneyAmount(int n) { + vector> pay(n + 1, vector(n)); + for (int i = n - 1; i >= 0; --i) { + for (int j = i + 1; j < n; ++j) { + pay[i][j] = numeric_limits::max(); + for (int k = i; k <= j; ++k) { + pay[i][j] = min(pay[i][j], k + 1 + max(pay[i][k - 1], pay[k + 1][j])); + } + } + } + return pay[0][n - 1]; + } +}; From 34bb0a19e1d7cd1bc3eb457122f09dba1852ce27 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Jul 2016 13:45:07 +0800 Subject: [PATCH 2607/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index dc87c795e..dd413caa5 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-374%20%2F%20374-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-375%20%2F%20375-ff69b4.svg) -Up to date (2016-07-13), there are `357` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-07-16), there are `358` 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 `374` questions. +Here is the classification of all `375` 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.) @@ -461,6 +461,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 357| [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | [C++](./C++/count-numbers-with-unique-digits.cpp) [Python](./Python/count-numbers-with-unique-digits.py) | _O(n)_ | _O(1)_ | Medium || Backtracking, Math | 361| [Bomb Enemy](https://leetcode.com/problems/bomb-enemy/) | [C++](./C++/bomb-enemy.cpp) [Python](./Python/bomb-enemy.py) | _O(m * n)_ | _O(m * n)_ | Medium | 📖 | | 368| [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [C++](./C++/largest-divisible-subset.cpp) [Python](./Python/largest-divisible-subset.py) | _O(n^2)_ | _O(n)_ | Medium | | | +375| [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)| [C++](./C++/guess-number-higher-or-lower-ii.cpp) [Python](./Python/guess-number-higher-or-lower-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium | | ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 20bb9844210a9ee89f75eb5122080d0dae2205ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Jul 2016 22:03:03 +0800 Subject: [PATCH 2608/4971] Update gray-code.py --- Python/gray-code.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/gray-code.py b/Python/gray-code.py index e6f298734..415e0f752 100644 --- a/Python/gray-code.py +++ b/Python/gray-code.py @@ -36,8 +36,8 @@ def grayCode(self, n): # Proof of closed form formula could be found here: # http://math.stackexchange.com/questions/425894/proof-of-closed-form-formula-to-convert-a-binary-number-to-its-gray-code -class Solution(object): - def grayCode2(self, n): +class Solution2(object): + def grayCode(self, n): """ :type n: int :rtype: List[int] From 7fdb22ed7e77afecb3f1b1d2f4310e3198445e61 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Jul 2016 22:05:07 +0800 Subject: [PATCH 2609/4971] Create gray-code.cpp --- C++/gray-code.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/gray-code.cpp diff --git a/C++/gray-code.cpp b/C++/gray-code.cpp new file mode 100644 index 000000000..e88269a02 --- /dev/null +++ b/C++/gray-code.cpp @@ -0,0 +1,30 @@ +// Time: (2^n) +// Space: O(1) + +class Solution { +public: + vector grayCode(int n) { + vector result = {0}; + for (int i = 0; i < n; ++i) { + for (int j = result.size() - 1; j >= 0; --j) { + result.emplace_back(1 << i | result[j]); + } + } + return result; + } +}; + +// Time: (2^n) +// Space: O(1) +// Proof of closed form formula could be found here: +// http://math.stackexchange.com/questions/425894/proof-of-closed-form-formula-to-convert-a-binary-number-to-its-gray-code +class Solution2 { +public: + vector grayCode(int n) { + vector result; + for (int i = 0; i < 1 << n; ++i) { + result.emplace_back(i >> 1 ^ i); + } + return result; + } +}; From 429c21b0fa44315449388e459827faa98023ac73 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Jul 2016 22:05:58 +0800 Subject: [PATCH 2610/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dd413caa5..d407220a0 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 50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(1)_ | _O(1)_ | Medium || 60| [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | [C++](./C++/permutation-sequence.cpp) [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` 65| [Valid Number](https://leetcode.com/problems/valid-number/) | [C++](./C++/valid-number.cpp) [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 || +89| [Gray Code](https://leetcode.com/problems/gray-code/) | [C++](./C++/gray-code.cpp) [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 || From 63be1e107ef662407a723307b6098023db3d08e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jul 2016 21:31:58 +0800 Subject: [PATCH 2611/4971] Create fraction-to-recurring-decimal.cpp --- C++/fraction-to-recurring-decimal.cpp | 37 +++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/fraction-to-recurring-decimal.cpp diff --git a/C++/fraction-to-recurring-decimal.cpp b/C++/fraction-to-recurring-decimal.cpp new file mode 100644 index 000000000..5338a4cb7 --- /dev/null +++ b/C++/fraction-to-recurring-decimal.cpp @@ -0,0 +1,37 @@ +// Time: O(logn), where logn is the length of result strings +// Space: O(1) + +class Solution { +public: + string fractionToDecimal(int numerator, int denominator) { + string result; + if ((numerator ^ denominator) >> 31 && numerator != 0) { + result = "-"; + } + + auto dvd = llabs(numerator); + auto dvs = llabs(denominator); + result += to_string(dvd / dvs); + dvd %= dvs; + if (dvd > 0) { + result += "."; + } + + unordered_map lookup; + while (dvd) { + if (lookup.count(dvd)) { + result.insert(lookup[dvd], "("); + result.push_back(')'); + break; + } + + lookup[dvd] = result.length(); + + dvd *= 10; + result += to_string(dvd / dvs); + dvd %= dvs; + } + + return result; + } +}; From b141c08af30d1dd0d8875e4e862bf20b56553b90 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jul 2016 21:39:25 +0800 Subject: [PATCH 2612/4971] Update fraction-to-recurring-decimal.py --- Python/fraction-to-recurring-decimal.py | 56 ++++++++++++------------- 1 file changed, 26 insertions(+), 30 deletions(-) diff --git a/Python/fraction-to-recurring-decimal.py b/Python/fraction-to-recurring-decimal.py index 13aa5a9e4..38a53d7c3 100644 --- a/Python/fraction-to-recurring-decimal.py +++ b/Python/fraction-to-recurring-decimal.py @@ -1,7 +1,8 @@ # Time: O(logn), where logn is the length of result strings # Space: O(1) -# -# Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. + +# Given two integers representing the numerator and denominator of a fraction, +# return the fraction in string format. # # If the fractional part is repeating, enclose the repeating part in parentheses. # @@ -10,43 +11,38 @@ # Given numerator = 1, denominator = 2, return "0.5". # Given numerator = 2, denominator = 1, return "2". # Given numerator = 2, denominator = 3, return "0.(6)". -# -class Solution: - # @return a string +class Solution(object): def fractionToDecimal(self, numerator, denominator): + """ + :type numerator: int + :type denominator: int + :rtype: str + """ dvd, dvs = abs(numerator), abs(denominator) - integer, decimal, dict = "", "", {} - - if dvd > dvs: - integer = str(dvd / dvs) - dvd %= dvs - else: - integer = "0" - + result, lookup = "", {} + if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0): + result = "-" + result += str(dvd / dvs) + dvd %= dvs + if dvd > 0: - integer += "." + result += "." - idx = 0 - while dvd: - if dvd in dict: - decimal = decimal[:dict[dvd]] + "(" + decimal[dict[dvd]:] + ")" - break - - dict[dvd] = idx - idx += 1 - + while dvd and dvd not in lookup: + lookup[dvd] = len(result) dvd *= 10 - decimal += str(dvd / dvs) + result += str(dvd / dvs) dvd %= dvs - - if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0): - return "-" + integer + decimal - else: - return integer + decimal + + if dvd in lookup: + result = result[:lookup[dvd]] + "(" + result[lookup[dvd]:] + ")" + + return result + if __name__ == "__main__": print Solution().fractionToDecimal(1, 9) print Solution().fractionToDecimal(-50, 8) print Solution().fractionToDecimal(22, 2) - print Solution().fractionToDecimal(-22, -2) \ No newline at end of file + print Solution().fractionToDecimal(-22, -2) From 9f5952a662e6452c69a3c4410e68b200292fafc6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jul 2016 21:40:27 +0800 Subject: [PATCH 2613/4971] Update fraction-to-recurring-decimal.cpp --- C++/fraction-to-recurring-decimal.cpp | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/C++/fraction-to-recurring-decimal.cpp b/C++/fraction-to-recurring-decimal.cpp index 5338a4cb7..f4f2f6171 100644 --- a/C++/fraction-to-recurring-decimal.cpp +++ b/C++/fraction-to-recurring-decimal.cpp @@ -18,20 +18,17 @@ class Solution { } unordered_map lookup; - while (dvd) { - if (lookup.count(dvd)) { - result.insert(lookup[dvd], "("); - result.push_back(')'); - break; - } - + while (dvd && !lookup.count(dvd)) { lookup[dvd] = result.length(); - dvd *= 10; result += to_string(dvd / dvs); dvd %= dvs; } - + + if (lookup.count(dvd)) { + result.insert(lookup[dvd], "("); + result.push_back(')'); + } return result; } }; From 4138ee2dbf89a90be88ffc333b6e814c1ad39a7e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jul 2016 21:42:14 +0800 Subject: [PATCH 2614/4971] Update fraction-to-recurring-decimal.py --- Python/fraction-to-recurring-decimal.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Python/fraction-to-recurring-decimal.py b/Python/fraction-to-recurring-decimal.py index 38a53d7c3..98dff2202 100644 --- a/Python/fraction-to-recurring-decimal.py +++ b/Python/fraction-to-recurring-decimal.py @@ -19,16 +19,18 @@ def fractionToDecimal(self, numerator, denominator): :type denominator: int :rtype: str """ - dvd, dvs = abs(numerator), abs(denominator) - result, lookup = "", {} + result = "" if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0): result = "-" + + dvd, dvs = abs(numerator), abs(denominator) result += str(dvd / dvs) dvd %= dvs if dvd > 0: result += "." - + + lookup = {} while dvd and dvd not in lookup: lookup[dvd] = len(result) dvd *= 10 From 5c7503a31d814ed89d38723b75c28b9473bd2776 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jul 2016 21:42:46 +0800 Subject: [PATCH 2615/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d407220a0..aaa134b2f 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 60| [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | [C++](./C++/permutation-sequence.cpp) [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` 65| [Valid Number](https://leetcode.com/problems/valid-number/) | [C++](./C++/valid-number.cpp) [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` 89| [Gray Code](https://leetcode.com/problems/gray-code/) | [C++](./C++/gray-code.cpp) [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 || +166| [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [C++](./C++/fraction-to-recurring-decimal.cpp) [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(1)_ | _O(1)_ | Easy || From d7a34e310e24be920bd9248d967190f77a8b1e8b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Jul 2016 23:04:48 +0800 Subject: [PATCH 2616/4971] Update excel-sheet-column-title.py --- Python/excel-sheet-column-title.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/Python/excel-sheet-column-title.py b/Python/excel-sheet-column-title.py index fe8cb669b..7fd6ef869 100644 --- a/Python/excel-sheet-column-title.py +++ b/Python/excel-sheet-column-title.py @@ -1,6 +1,6 @@ # Time: O(logn) # Space: O(1) -# + # Given a positive integer, return its corresponding column title as appear in an Excel sheet. # # For example: @@ -12,11 +12,13 @@ # 26 -> Z # 27 -> AA # 28 -> AB -# -class Solution: - # @return a string - def convertToTitle(self, num): +class Solution(object): + def convertToTitle(self, n): + """ + :type n: int + :rtype: str + """ result, dvd = "", num while dvd: @@ -24,7 +26,8 @@ def convertToTitle(self, num): dvd = (dvd - 1) / 26 return result[::-1] - + + if __name__ == "__main__": for i in xrange(1, 29): - print Solution().convertToTitle(i) \ No newline at end of file + print Solution().convertToTitle(i) From 7cd153e76340d78084d9efb1b90a1b9c0bf18bd6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Jul 2016 23:06:53 +0800 Subject: [PATCH 2617/4971] Create excel-sheet-column-title.cpp --- C++/excel-sheet-column-title.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/excel-sheet-column-title.cpp diff --git a/C++/excel-sheet-column-title.cpp b/C++/excel-sheet-column-title.cpp new file mode 100644 index 000000000..a3342a427 --- /dev/null +++ b/C++/excel-sheet-column-title.cpp @@ -0,0 +1,32 @@ +// Time: O(logn) +// Space: O(1) + +// Iterative solution. +class Solution { +public: + string convertToTitle(int n) { + string result; + int dvd{n}; + + while (dvd) { + result.push_back((dvd - 1) % 26 + 'A'); + dvd = (dvd - 1) / 26; + } + reverse(result.begin(), result.end()); + + return result; + } +}; + +// Time: O((logn)^2) +// Space: O(logn) +// Recursive solution. +class Solution2 { +public: + string convertToTitle(int n) { + if (n == 0) { + return ""; + } + return convertToTitle((n - 1) / 26) + static_cast((n - 1) % 26 + 'A'); + } +}; From 3c72629aff36d043de5b758b5b0ab48ed4b2892b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Jul 2016 23:07:56 +0800 Subject: [PATCH 2618/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index aaa134b2f..299e0c217 100644 --- a/README.md +++ b/README.md @@ -247,7 +247,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 65| [Valid Number](https://leetcode.com/problems/valid-number/) | [C++](./C++/valid-number.cpp) [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` 89| [Gray Code](https://leetcode.com/problems/gray-code/) | [C++](./C++/gray-code.cpp) [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || 166| [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [C++](./C++/fraction-to-recurring-decimal.cpp) [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 || +168| [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | [C++](./C++/excel-sheet-column-title.cpp) [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(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 1eb09a370f1c8b49372557341a9410fe7b53809e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Jul 2016 20:32:59 +0800 Subject: [PATCH 2619/4971] Update two-sum-iii-data-structure-design.py --- Python/two-sum-iii-data-structure-design.py | 28 ++++++++++++++------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/Python/two-sum-iii-data-structure-design.py b/Python/two-sum-iii-data-structure-design.py index 828b5db15..808c80d91 100644 --- a/Python/two-sum-iii-data-structure-design.py +++ b/Python/two-sum-iii-data-structure-design.py @@ -1,6 +1,6 @@ # Time: O(n) # Space: O(n) -# + # Design and implement a TwoSum class. It should support the following operations: add and find. # # add - Add the number to an internal data structure. @@ -10,29 +10,40 @@ # add(1); add(3); add(5); # find(4) -> true # find(7) -> false -# -class TwoSum: +from collections import defaultdict + +class TwoSum(object): - # initialize your data structure here def __init__(self): - self.lookup = collections.defaultdict(int) + """ + initialize your data structure here + """ + self.lookup = defaultdict(int) - # @return nothing + def add(self, number): + """ + Add the number to an internal data structure. + :rtype: nothing + """ self.lookup[number] += 1 - # @param value, an integer - # @return a Boolean def find(self, value): + """ + Find if there exists any pair of numbers which sum is equal to the value. + :type value: int + :rtype: bool + """ for key in self.lookup: num = value - key if num in self.lookup and (num != key or self.lookup[key] > 1): return True return False + if __name__ == "__main__": Sol = TwoSum() @@ -42,4 +53,3 @@ def find(self, value): for i in (4, 7): print Sol.find(i) - From 22e0074dfafbed0a7be969a575dd50d78002061c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Jul 2016 20:49:46 +0800 Subject: [PATCH 2620/4971] Create two-sum-iii-data-structure-design.cpp --- C++/two-sum-iii-data-structure-design.cpp | 31 +++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/two-sum-iii-data-structure-design.cpp diff --git a/C++/two-sum-iii-data-structure-design.cpp b/C++/two-sum-iii-data-structure-design.cpp new file mode 100644 index 000000000..3a3b2e37f --- /dev/null +++ b/C++/two-sum-iii-data-structure-design.cpp @@ -0,0 +1,31 @@ +// Time: O(n) +// Space: O(n) + +class TwoSum { +public: + + // Add the number to an internal data structure. + void add(int number) { + ++lookup_[number]; + } + + // Find if there exists any pair of numbers which sum is equal to the value. + bool find(int value) { + for (const auto& kvp : lookup_) { + const auto num = value - kvp.first; + if (lookup_.count(num) && (num != kvp.first || kvp.second > 1)) { + return true; + } + } + return false; + } + +private: + unordered_map lookup_; +}; + + +// Your TwoSum object will be instantiated and called as such: +// TwoSum twoSum; +// twoSum.add(number); +// twoSum.find(value); From e8020b02bf7f83ace847980fa135a0a1532dc648 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Jul 2016 20:50:30 +0800 Subject: [PATCH 2621/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 299e0c217..5cfbde8ec 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [C++](./C++/minimum-window-substring.cpp) [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/) | [C++](./C++/max-points-on-a-line.cpp) [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/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _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 | 📖 | +170| [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) | [C++](./C++/two-sum-iii-data-structure-design.cpp) [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/) | [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 || From 0536787533d159ddf41fe87e1da89734d4f12328 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Jul 2016 20:53:44 +0800 Subject: [PATCH 2622/4971] Update two-sum-iii-data-structure-design.cpp --- C++/two-sum-iii-data-structure-design.cpp | 24 +++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/C++/two-sum-iii-data-structure-design.cpp b/C++/two-sum-iii-data-structure-design.cpp index 3a3b2e37f..d664aea3c 100644 --- a/C++/two-sum-iii-data-structure-design.cpp +++ b/C++/two-sum-iii-data-structure-design.cpp @@ -5,20 +5,20 @@ class TwoSum { public: // Add the number to an internal data structure. - void add(int number) { - ++lookup_[number]; - } + void add(int number) { + ++lookup_[number]; + } // Find if there exists any pair of numbers which sum is equal to the value. - bool find(int value) { - for (const auto& kvp : lookup_) { - const auto num = value - kvp.first; - if (lookup_.count(num) && (num != kvp.first || kvp.second > 1)) { - return true; - } - } - return false; - } + bool find(int value) { + for (const auto& kvp : lookup_) { + const auto num = value - kvp.first; + if (lookup_.count(num) && (num != kvp.first || kvp.second > 1)) { + return true; + } + } + return false; + } private: unordered_map lookup_; From b330cc12d65f17c4ccd4379f9b3db9621e3357c8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Jul 2016 14:07:17 +0800 Subject: [PATCH 2623/4971] Create wiggle-subsequence.py --- Python/wiggle-subsequence.py | 58 ++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Python/wiggle-subsequence.py diff --git a/Python/wiggle-subsequence.py b/Python/wiggle-subsequence.py new file mode 100644 index 000000000..3336a9338 --- /dev/null +++ b/Python/wiggle-subsequence.py @@ -0,0 +1,58 @@ +# Time: O(n) +# Space: O(1) + +# A sequence of numbers is called a wiggle sequence +# if the differences between successive numbers strictly +# alternate between positive and negative. +# The first difference (if one exists) may be either positive +# or negative. A sequence with fewer than two elements +# is trivially a wiggle sequence. +# +# For example, [1,7,4,9,2,5] is a wiggle sequence because +# the differences (6,-3,5,-7,3) are alternately positive +# and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are +# not wiggle sequences, the first because its first two differences +# are positive and the second because its last difference is zero. +# +# Given a sequence of integers, return the length of +# the longest subsequence that is a wiggle sequence. +# A subsequence is obtained by deleting some number of elements +# (eventually, also zero) from the original sequence, leaving +# the remaining elements in their original order. +# +# Examples: +# Input: [1,7,4,9,2,5] +# Output: 6 +# The entire sequence is a wiggle sequence. +# +# Input: [1,17,5,10,13,15,10,5,16,8] +# Output: 7 +# There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8]. +# +# Input: [1,2,3,4,5,6,7,8,9] +# Output: 2 +# +# Follow up: +# Can you do it in O(n) time? + + +class Solution(object): + def wiggleMaxLength(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if len(nums) < 2: + return len(nums) + + length, up = 1, None + + for i in xrange(1, len(nums)): + if nums[i - 1] < nums[i] and (up is None or up is False): + length += 1 + up = True + elif nums[i - 1] > nums[i] and (up is None or up is True): + length += 1 + up = False + + return length From 18e66eabcc48b8395a4aa1ade3f043ce07a7e38d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Jul 2016 14:11:45 +0800 Subject: [PATCH 2624/4971] Create wiggle-subsequence.cpp --- C++/wiggle-subsequence.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/wiggle-subsequence.cpp diff --git a/C++/wiggle-subsequence.cpp b/C++/wiggle-subsequence.cpp new file mode 100644 index 000000000..83830a720 --- /dev/null +++ b/C++/wiggle-subsequence.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int wiggleMaxLength(vector& nums) { + if (nums.size() < 2) { + return nums.size(); + } + + int length = 1, up = 0; + + for (int i = 1; i < nums.size(); ++i) { + if (nums[i - 1] < nums[i] && (up == 0 || up == 1)) { + ++length; + up = -1; + } else if (nums[i - 1] > nums[i] && (up == 0 || up == -1)) { + ++length; + up = 1; + } + } + + return length; + } +}; From e47a166ed111f525f4cda959760f97e5b8a5d31a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Jul 2016 14:15:17 +0800 Subject: [PATCH 2625/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5cfbde8ec..aa3a2b4a3 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-375%20%2F%20375-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-376%20%2F%20376-ff69b4.svg) -Up to date (2016-07-16), there are `358` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-07-21), there are `359` 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 `375` questions. +Here is the classification of all `376` 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.) @@ -477,6 +477,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || Ascending 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 || +376| [Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/)| [C++](./C++/wiggle-subsequence.cpp) [Python](./Python/wiggle-subsequence.py) | _O(n)_ | _O(1)_ | Medium || --- ## Design From 630a53ef8314923836d6f4679fd4c8f84d257bc7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Jul 2016 21:22:37 +0800 Subject: [PATCH 2626/4971] Update count-primes.py --- Python/count-primes.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Python/count-primes.py b/Python/count-primes.py index 8c3337efd..318fa8cf9 100644 --- a/Python/count-primes.py +++ b/Python/count-primes.py @@ -17,14 +17,14 @@ def countPrimes(self, n): return 0 is_prime = [True] * n - sqr = sqrt(n - 1) - - num = 0 - for i in xrange(2, n): + num = n / 2 + for i in xrange(3, n, 2): + if i * i >= n: + break + if is_prime[i]: - num += 1 - for j in xrange(i+i, n, i): - is_prime[j] = False - + for j in xrange(i*i, n, 2*i): + if is_prime[j]: + num -= 1 + is_prime[j] = False return num - From dc358cdf63d1b24f7c66644f882ddc077d3d1dbb Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Jul 2016 21:26:40 +0800 Subject: [PATCH 2627/4971] Update count-primes.py --- Python/count-primes.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Python/count-primes.py b/Python/count-primes.py index 318fa8cf9..1d4b18a89 100644 --- a/Python/count-primes.py +++ b/Python/count-primes.py @@ -18,10 +18,7 @@ def countPrimes(self, n): is_prime = [True] * n num = n / 2 - for i in xrange(3, n, 2): - if i * i >= n: - break - + for i in xrange(3, int(sqrt(n))+1, 2): if is_prime[i]: for j in xrange(i*i, n, 2*i): if is_prime[j]: From 55307cdd805915e9ebe1e4d5ce44a0d47130fe4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Jul 2016 21:28:40 +0800 Subject: [PATCH 2628/4971] Update count-primes.py --- Python/count-primes.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Python/count-primes.py b/Python/count-primes.py index 1d4b18a89..488e2d6d9 100644 --- a/Python/count-primes.py +++ b/Python/count-primes.py @@ -1,13 +1,11 @@ # 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 @@ -18,10 +16,14 @@ def countPrimes(self, n): is_prime = [True] * n num = n / 2 - for i in xrange(3, int(sqrt(n))+1, 2): + for i in xrange(3, n, 2): + if i * i >= n: + break + if is_prime[i]: for j in xrange(i*i, n, 2*i): if is_prime[j]: num -= 1 is_prime[j] = False + return num From 411e596b37c95c819c881a982a205daa86138be1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Jul 2016 21:41:57 +0800 Subject: [PATCH 2629/4971] Update count-primes.cpp --- C++/count-primes.cpp | 37 ++++++++++++++++--------------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/C++/count-primes.cpp b/C++/count-primes.cpp index dcafc14bf..0a6378427 100644 --- a/C++/count-primes.cpp +++ b/C++/count-primes.cpp @@ -1,36 +1,31 @@ // 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) { + if (n <= 2) { 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; + auto num = n / 2; + vector is_prime(n, true); + + for (int i = 3; i * i < n; i += 2) { + if (!is_prime[i]) { + continue; + } + + for (int j = i * i; j < n; j += 2 * i) { + if (!is_prime[j]) { + continue; } + + --num; + is_prime[j] = false; } } - delete[] primes; - - return sum; + return num; } }; From fa9eb942571128efe948a8e8416597fc8d761a80 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Jul 2016 21:42:43 +0800 Subject: [PATCH 2630/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index aa3a2b4a3..23c9a0ebe 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 170| [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) | [C++](./C++/two-sum-iii-data-structure-design.cpp) [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/) | [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 || +204| [Count Primes](https://leetcode.com/problems/count-primes/) | [C++](./C++/count-primes.cpp) [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 || From 18b9a0e75e36ff68055748bfca7cef4f11e4afe3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 22 Jul 2016 21:44:07 +0800 Subject: [PATCH 2631/4971] Update count-primes.py --- Python/count-primes.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Python/count-primes.py b/Python/count-primes.py index 488e2d6d9..525d960e1 100644 --- a/Python/count-primes.py +++ b/Python/count-primes.py @@ -20,10 +20,14 @@ def countPrimes(self, n): if i * i >= n: break - if is_prime[i]: - for j in xrange(i*i, n, 2*i): - if is_prime[j]: - num -= 1 - is_prime[j] = False + if not is_prime[i]: + continue + + for j in xrange(i*i, n, 2*i): + if not is_prime[j]: + continue + + num -= 1 + is_prime[j] = False return num From 526522fb7ff845254ee391515af4bdfd4423bf06 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Jul 2016 15:23:19 +0800 Subject: [PATCH 2632/4971] Update excel-sheet-column-number.py --- Python/excel-sheet-column-number.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Python/excel-sheet-column-number.py b/Python/excel-sheet-column-number.py index 7ea985aa3..667233c59 100644 --- a/Python/excel-sheet-column-number.py +++ b/Python/excel-sheet-column-number.py @@ -1,6 +1,6 @@ # Time: O(n) # Space: O(1) -# + # Related to question Excel Sheet Column Title # # Given a column title as appear in an Excel sheet, return its corresponding column number. @@ -14,17 +14,19 @@ # Z -> 26 # AA -> 27 # AB -> 28 -# -class Solution: - # @param s, a string - # @return an integer +class Solution(object): def titleToNumber(self, s): + """ + :type s: str + :rtype: int + """ result = 0 for i in xrange(len(s)): result *= 26 result += ord(s[i]) - ord('A') + 1 return result + if __name__ == "__main__": - print Solution().titleToNumber("AAAB") \ No newline at end of file + print Solution().titleToNumber("AAAB") From b5f4f83e5d43096c48ffefc6192365a7104378c8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Jul 2016 15:29:37 +0800 Subject: [PATCH 2633/4971] Create excel-sheet-column-number.cpp --- C++/excel-sheet-column-number.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/excel-sheet-column-number.cpp diff --git a/C++/excel-sheet-column-number.cpp b/C++/excel-sheet-column-number.cpp new file mode 100644 index 000000000..a3b84c8cf --- /dev/null +++ b/C++/excel-sheet-column-number.cpp @@ -0,0 +1,14 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int titleToNumber(string s) { + int number = 0; + for (const auto& c : s) { + number *= 26; + number += c - 'A' + 1; + } + return number; + } +}; From 581a02ec7fcee5c53d30fa33c59d12a48fbbd830 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Jul 2016 15:30:11 +0800 Subject: [PATCH 2634/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 23c9a0ebe..b6e3b2b31 100644 --- a/README.md +++ b/README.md @@ -248,7 +248,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 89| [Gray Code](https://leetcode.com/problems/gray-code/) | [C++](./C++/gray-code.cpp) [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || 166| [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [C++](./C++/fraction-to-recurring-decimal.cpp) [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/) | [C++](./C++/excel-sheet-column-title.cpp) [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 || +171| [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [C++](./C++/excel-sheet-column-number.cpp) [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(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 || 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(1)_ | _O(1)_ | Medium | CTCI, LintCode| From 81769222d4f12fd228d87e4768c5397bbfa9583c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jul 2016 20:32:41 +0800 Subject: [PATCH 2635/4971] Update isomorphic-strings.py --- Python/isomorphic-strings.py | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/Python/isomorphic-strings.py b/Python/isomorphic-strings.py index c66061412..e22243e67 100644 --- a/Python/isomorphic-strings.py +++ b/Python/isomorphic-strings.py @@ -1,6 +1,6 @@ # 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. @@ -18,12 +18,33 @@ # # Note: # You may assume both s and t have the same length. -# -class Solution: - # @param {string} s - # @param {string} t - # @return {boolean} +from itertools import izip # Generator version of zip. + +class Solution(object): + def isIsomorphic(self, s, t): + """ + :type s: str + :type t: str + :rtype: bool + """ + if len(s) != len(t): + return False + + s2t, t2s = {}, {} + for p, w in izip(s, t): + if w not in s2t and p not in t2s: + s2t[w] = p + t2s[p] = w + elif w not in s2t or s2t[w] != p: + # Contradict mapping. + return False + return True + + +# Time: O(n) +# Space: O(1) +class Solution2(object): def isIsomorphic(self, s, t): if len(s) != len(t): return False From 7ec235daa2cfd18e5bf4b9258aa160877de5475f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jul 2016 20:39:45 +0800 Subject: [PATCH 2636/4971] Update isomorphic-strings.cpp --- C++/isomorphic-strings.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/C++/isomorphic-strings.cpp b/C++/isomorphic-strings.cpp index de37015b8..a779f2fba 100644 --- a/C++/isomorphic-strings.cpp +++ b/C++/isomorphic-strings.cpp @@ -1,16 +1,21 @@ +// Time: O(n) +// Space: O(1) + class Solution { public: bool isIsomorphic(string s, string t) { if (s.length() != t.length()) { return false; } - 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; + vector s2t(256, 0), t2s(256, 0); + for (int i = 0; i < s.length(); ++i) { + if (s2t[s[i]] == 0 && t2s[t[i]] == 0) { + s2t[s[i]] = t[i]; + t2s[t[i]] = s[i]; + } else if (s2t[s[i]] == 0 || s2t[s[i]] != t[i]) { + // Contradict mapping. + return false; + } } return true; } From 262a223a82e1286006ab085a950d9fd77aa6c19e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jul 2016 20:41:18 +0800 Subject: [PATCH 2637/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b6e3b2b31..1406c49d8 100644 --- a/README.md +++ b/README.md @@ -210,7 +210,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/) | [C++](./C++/happy-number.cpp) [Python](./Python/happy-number.py) | _O(k)_ | _O(k)_ | Easy || 204| [Count Primes](https://leetcode.com/problems/count-primes/) | [C++](./C++/count-primes.cpp) [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 || +205| [Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) | [C++](./C++/isomorphic-strings.cpp) [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 |📖|| From f0d7202118de57338fbd884f6b0a54e658c66a90 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jul 2016 20:51:14 +0800 Subject: [PATCH 2638/4971] 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 a779f2fba..1a100d7cf 100644 --- a/C++/isomorphic-strings.cpp +++ b/C++/isomorphic-strings.cpp @@ -12,7 +12,7 @@ class Solution { if (s2t[s[i]] == 0 && t2s[t[i]] == 0) { s2t[s[i]] = t[i]; t2s[t[i]] = s[i]; - } else if (s2t[s[i]] == 0 || s2t[s[i]] != t[i]) { + } else if (s2t[s[i]] != t[i]) { // Contradict mapping. return false; } From 67d1f70d9848c283347cd803dfd3848ca23826d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Jul 2016 13:16:15 +0800 Subject: [PATCH 2639/4971] Create combination-sum-iv.cpp --- C++/combination-sum-iv.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/combination-sum-iv.cpp diff --git a/C++/combination-sum-iv.cpp b/C++/combination-sum-iv.cpp new file mode 100644 index 000000000..e7cc8b806 --- /dev/null +++ b/C++/combination-sum-iv.cpp @@ -0,0 +1,19 @@ +// Time: O(nlogn + n * t), t is the value of target. +// Space: O(t) + +class Solution { +public: + int combinationSum4(vector& nums, int target) { + vector dp(target + 1, 0); + dp[0] = 1; + sort(nums.begin(), nums.end()); + + for (int i = 1; i <= target; ++i) { + for (int j = 0; j < nums.size() && nums[j] <= i; ++j) { + dp[i] += dp[i - nums[j]]; + } + } + + return dp[target]; + } +}; From aecebf4d1680bd87c82458bd8301d0c16c84b807 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Jul 2016 13:20:26 +0800 Subject: [PATCH 2640/4971] Create combination-sum-iv.py --- Python/combination-sum-iv.py | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/combination-sum-iv.py diff --git a/Python/combination-sum-iv.py b/Python/combination-sum-iv.py new file mode 100644 index 000000000..1b24689b1 --- /dev/null +++ b/Python/combination-sum-iv.py @@ -0,0 +1,47 @@ +# Time: O(nlon + n * t), t is the value of target. +# Space: O(t) + +# Given an integer array with all positive numbers and no duplicates, +# find the number of possible combinations that add up to a positive integer target. +# +# Example: +# +# nums = [1, 2, 3] +# target = 4 +# +# The possible combination ways are: +# (1, 1, 1, 1) +# (1, 1, 2) +# (1, 2, 1) +# (1, 3) +# (2, 1, 1) +# (2, 2) +# (3, 1) +# +# Note that different sequences are counted as different combinations. +# +# Therefore the output is 7. +# Follow up: +# What if negative numbers are allowed in the given array? +# How does it change the problem? +# What limitation we need to add to the question to allow negative numbers? + +class Solution(object): + def combinationSum4(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + dp = [0] * (target+1) + dp[0] = 1 + nums.sort() + + for i in xrange(1, target+1): + for j in xrange(len(nums)): + if nums[j] <= i: + dp[i] += dp[i - nums[j]] + else: + break + + return dp[target] From 1c640fc62c209c5f6df92280653a3b417e32d9d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Jul 2016 13:22:52 +0800 Subject: [PATCH 2641/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1406c49d8..02f25bd32 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-376%20%2F%20376-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-377%20%2F%20377-ff69b4.svg) -Up to date (2016-07-21), there are `359` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-07-25), there are `360` 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 `376` questions. +Here is the classification of all `377` 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.) @@ -462,6 +462,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 361| [Bomb Enemy](https://leetcode.com/problems/bomb-enemy/) | [C++](./C++/bomb-enemy.cpp) [Python](./Python/bomb-enemy.py) | _O(m * n)_ | _O(m * n)_ | Medium | 📖 | | 368| [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [C++](./C++/largest-divisible-subset.cpp) [Python](./Python/largest-divisible-subset.py) | _O(n^2)_ | _O(n)_ | Medium | | | 375| [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)| [C++](./C++/guess-number-higher-or-lower-ii.cpp) [Python](./Python/guess-number-higher-or-lower-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium | | +377| [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/)| [C++](./C++/combination-sum-iv.cpp) [Python](./Python/combination-sum-iv.py) | _O(nlogn + n * t)_ | _O(t)_ | Medium | | ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 1f509ef6b548744b849ea751e195a8601a257bd9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Jul 2016 20:59:23 +0800 Subject: [PATCH 2642/4971] Create factorial-trailing-zeroes.cpp --- C++/factorial-trailing-zeroes.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/factorial-trailing-zeroes.cpp diff --git a/C++/factorial-trailing-zeroes.cpp b/C++/factorial-trailing-zeroes.cpp new file mode 100644 index 000000000..a9ea04b70 --- /dev/null +++ b/C++/factorial-trailing-zeroes.cpp @@ -0,0 +1,14 @@ +// Time: O(logn) = O(1) +// Space: O(1) + +class Solution { +public: + int trailingZeroes(int n) { + int number = 0; + while (n > 0) { + number += n / 5; + n /= 5; + } + return number; + } +}; From 6758ae8124479f0cac873e25e1eae89ad7cc6b4f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Jul 2016 21:00:00 +0800 Subject: [PATCH 2643/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 02f25bd32..46d3ce7a4 100644 --- a/README.md +++ b/README.md @@ -249,7 +249,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 166| [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [C++](./C++/fraction-to-recurring-decimal.cpp) [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/) | [C++](./C++/excel-sheet-column-title.cpp) [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/) | [C++](./C++/excel-sheet-column-number.cpp) [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(1)_ | _O(1)_ | Easy || +172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [C++](./C++/factorial-trailing-zeroes.cpp) [Python](./Python/factorial-trailing-zeroes.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 || 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(1)_ | _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 |📖|| From 3f5828ef2022534af13f10347d76c38370d1db11 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 Jul 2016 22:34:37 +0800 Subject: [PATCH 2644/4971] Update and rename merge.cpp to merge-intervals.cpp --- C++/merge-intervals.cpp | 37 +++++++++++++++++++++++++++++++++ C++/merge.cpp | 45 ----------------------------------------- 2 files changed, 37 insertions(+), 45 deletions(-) create mode 100644 C++/merge-intervals.cpp delete mode 100644 C++/merge.cpp diff --git a/C++/merge-intervals.cpp b/C++/merge-intervals.cpp new file mode 100644 index 000000000..036ced02f --- /dev/null +++ b/C++/merge-intervals.cpp @@ -0,0 +1,37 @@ +// Time: O(nlogn) +// Space: O(1) + +/** + * 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: + vector merge(vector& intervals) { + if (intervals.empty()) { + return intervals; + } + + sort(intervals.begin(), intervals.end(), + [](const Interval& a, const Interval& b) { + return a.start < b.start; + }); + + vector result{intervals[0]}; + for (int i = 1; i < intervals.size(); ++i) { + Interval& prev = result.back(); + if (intervals[i].start <= prev.end) { + prev.end = max(prev.end, intervals[i].end); + } else { + result.emplace_back(intervals[i]); + } + } + + return result; + } +}; diff --git a/C++/merge.cpp b/C++/merge.cpp deleted file mode 100644 index b161ee7ac..000000000 --- a/C++/merge.cpp +++ /dev/null @@ -1,45 +0,0 @@ -// Time Complexity: O(n^2) -// Space Complexity: O(1) - -/** - * 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: - vector merge(vector &intervals) { - vector ans; - for(auto i : intervals) { - ans = insert(ans, i); - } - return ans; - } - private: - vector insert(vector &intervals, Interval newInterval) { - vector ans; - auto n = intervals.size(); - for(int i = 0; i < n; ++i) { - if (newInterval.end < intervals[i].start) { // not overlapped - ans.push_back(newInterval); - for(; i < n; ++i) - ans.push_back(intervals[i]); - return ans; - } - else if (newInterval.start > intervals[i].end) { // not overlapped - ans.push_back(intervals[i]); - } - else { // merge - newInterval.start = min(newInterval.start, intervals[i].start); - newInterval.end = max(newInterval.end, intervals[i].end); - } - } - - ans.push_back(newInterval); - return ans; - } -}; From 1e329fd0d57b6ac62bb588af6dab54bf45ac217f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 Jul 2016 22:37:15 +0800 Subject: [PATCH 2645/4971] Update merge-intervals.cpp --- C++/merge-intervals.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/merge-intervals.cpp b/C++/merge-intervals.cpp index 036ced02f..f99e5bd26 100644 --- a/C++/merge-intervals.cpp +++ b/C++/merge-intervals.cpp @@ -24,9 +24,8 @@ class Solution { vector result{intervals[0]}; for (int i = 1; i < intervals.size(); ++i) { - Interval& prev = result.back(); - if (intervals[i].start <= prev.end) { - prev.end = max(prev.end, intervals[i].end); + if (intervals[i].start <= result.back().end) { + result.back().end = max(result.back().end, intervals[i].end); } else { result.emplace_back(intervals[i]); } From e65f2be79e853599256485acc62ffa0a4c014295 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 Jul 2016 22:38:00 +0800 Subject: [PATCH 2646/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 46d3ce7a4..85d7d55fb 100644 --- a/README.md +++ b/README.md @@ -267,7 +267,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || +56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [C++](./C++/merge-intervals.cpp) [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/) | [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 || From 69da6ff790ff68d228714568b5fb324a373c0a70 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 Jul 2016 22:44:13 +0800 Subject: [PATCH 2647/4971] Update merge-intervals.cpp --- C++/merge-intervals.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/merge-intervals.cpp b/C++/merge-intervals.cpp index f99e5bd26..09b707d65 100644 --- a/C++/merge-intervals.cpp +++ b/C++/merge-intervals.cpp @@ -18,9 +18,9 @@ class Solution { } sort(intervals.begin(), intervals.end(), - [](const Interval& a, const Interval& b) { - return a.start < b.start; - }); + [](const Interval& a, const Interval& b) { + return a.start < b.start; + }); vector result{intervals[0]}; for (int i = 1; i < intervals.size(); ++i) { From 775abcddebf0ca032355cd9252999ef94164f9a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 Jul 2016 22:16:34 +0800 Subject: [PATCH 2648/4971] Create insert-interval.cpp --- C++/insert-interval.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/insert-interval.cpp diff --git a/C++/insert-interval.cpp b/C++/insert-interval.cpp new file mode 100644 index 000000000..8a5bc9120 --- /dev/null +++ b/C++/insert-interval.cpp @@ -0,0 +1,35 @@ +// Time: O(n) +// Space: O(1) + +/** + * 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: + vector insert(vector& intervals, Interval newInterval) { + size_t i = 0; + vector result; + // Insert intervals appeared before newInterval. + while (i < intervals.size() && newInterval.start > intervals[i].end) { + result.emplace_back(intervals[i++]); + } + + // Merge intervals that overlap with newInterval. + while (i < intervals.size() && newInterval.end >= intervals[i].start) { + newInterval = {min(newInterval.start, intervals[i].start), + max(newInterval.end, intervals[i].end)}; + ++i; + } + result.emplace_back(newInterval); + + // Insert intervals appearing after newInterval. + result.insert(result.end(), intervals.cbegin() + i, intervals.cend()); + return result; + } +}; From ad80e710989fcd9c8919973720e6bb458b144095 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 Jul 2016 22:17:03 +0800 Subject: [PATCH 2649/4971] Delete insert.cpp --- C++/insert.cpp | 37 ------------------------------------- 1 file changed, 37 deletions(-) delete mode 100644 C++/insert.cpp diff --git a/C++/insert.cpp b/C++/insert.cpp deleted file mode 100644 index 12a2a6e10..000000000 --- a/C++/insert.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -/** - * 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: - vector insert(vector &intervals, Interval newInterval) { - vector ans; - auto n = intervals.size(); - for(int i = 0; i < n; ++i) { - if (newInterval.end < intervals[i].start) { // not overlapped - ans.push_back(newInterval); - for(; i < n; ++i) - ans.push_back(intervals[i]); - return ans; - } - else if (newInterval.start > intervals[i].end) { // not overlapped - ans.push_back(intervals[i]); - } - else { // merge - newInterval.start = min(newInterval.start, intervals[i].start); - newInterval.end = max(newInterval.end, intervals[i].end); - } - } - - ans.push_back(newInterval); - return ans; - } -}; From 4451c51c920561f981a539493402824186dbd824 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 Jul 2016 22:17:59 +0800 Subject: [PATCH 2650/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 85d7d55fb..e0ede24f5 100644 --- a/README.md +++ b/README.md @@ -268,7 +268,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [C++](./C++/merge-intervals.cpp) [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 || +57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [C++](./C++/insert-interval.cpp) [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || 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/)|[C++](./C++/insertion-sort-list.cpp) [Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || From 500083276ab9d3c883229613c91aef45c67a8f5a Mon Sep 17 00:00:00 2001 From: JinkeCao <956510645@qq.com> Date: Sat, 30 Jul 2016 15:47:31 +0800 Subject: [PATCH 2651/4971] modified: second-highest-salary.sql --- MySQL/second-highest-salary.sql | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/MySQL/second-highest-salary.sql b/MySQL/second-highest-salary.sql index 0a1a3e1c7..26d351666 100644 --- a/MySQL/second-highest-salary.sql +++ b/MySQL/second-highest-salary.sql @@ -13,5 +13,6 @@ # For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return null. # # Write your MySQL query statement below -SELECT MAX(Salary) FROM Employee -WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee) +select (SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)) SecondHighestSalary; +# or +SELECT (SELECT Salary FROM Employee GROUP BY Salary ORDER BY Salary DESC LIMIT 1,1) SecondHighestSalary; From 6ddbcdbb86008215576448c943fa698d8047345c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Jul 2016 23:12:51 +0800 Subject: [PATCH 2652/4971] Update second-highest-salary.sql --- MySQL/second-highest-salary.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/second-highest-salary.sql b/MySQL/second-highest-salary.sql index 26d351666..2565e2a61 100644 --- a/MySQL/second-highest-salary.sql +++ b/MySQL/second-highest-salary.sql @@ -13,6 +13,6 @@ # For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return null. # # Write your MySQL query statement below -select (SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)) SecondHighestSalary; +SELECT (SELECT MAX(Salary) FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)) SecondHighestSalary; # or SELECT (SELECT Salary FROM Employee GROUP BY Salary ORDER BY Salary DESC LIMIT 1,1) SecondHighestSalary; From d796c1e5520397ff440d54e73f559f09f57df36a Mon Sep 17 00:00:00 2001 From: JinkeCao Date: Sun, 31 Jul 2016 16:09:22 +0800 Subject: [PATCH 2653/4971] modified: MySQL/consecutive-numbers.sql --- MySQL/consecutive-numbers.sql | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/MySQL/consecutive-numbers.sql b/MySQL/consecutive-numbers.sql index 47026f66f..0dc357240 100644 --- a/MySQL/consecutive-numbers.sql +++ b/MySQL/consecutive-numbers.sql @@ -17,6 +17,7 @@ # For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times. # +# Solution 1 # Write your MySQL query statement below SELECT DISTINCT(Num) AS ConsecutiveNums FROM ( @@ -27,3 +28,8 @@ FROM ( FROM Logs y, (SELECT @counter:=1, @prev:=NULL) vars ) sq WHERE how_many_cnt_in_a_row >= 3 + +# Solution 1 +SELECT DISTINCT l1.Num as ConsecutiveNums +FROM Logs l1, Logs l2, Logs l3 +WHERE l1.Id + 1 = l2.Id AND l2.Id + 1 = l3.Id AND l1.Num = l2.Num AND l2.Num = l3.Num From e9c31a00a64b71abed524fdb3678aea7ff323dad Mon Sep 17 00:00:00 2001 From: JinkeCao Date: Sun, 31 Jul 2016 16:15:07 +0800 Subject: [PATCH 2654/4971] modified: MySQL/consecutive-numbers.sql --- MySQL/consecutive-numbers.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/consecutive-numbers.sql b/MySQL/consecutive-numbers.sql index 0dc357240..37e214118 100644 --- a/MySQL/consecutive-numbers.sql +++ b/MySQL/consecutive-numbers.sql @@ -29,7 +29,7 @@ FROM ( ) sq WHERE how_many_cnt_in_a_row >= 3 -# Solution 1 +# Solution 2 SELECT DISTINCT l1.Num as ConsecutiveNums FROM Logs l1, Logs l2, Logs l3 WHERE l1.Id + 1 = l2.Id AND l2.Id + 1 = l3.Id AND l1.Num = l2.Num AND l2.Num = l3.Num From a77b0078f30e943b6a6110e68d991c404e7dc3d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Jul 2016 17:04:38 +0800 Subject: [PATCH 2655/4971] Update consecutive-numbers.sql --- MySQL/consecutive-numbers.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/consecutive-numbers.sql b/MySQL/consecutive-numbers.sql index 37e214118..7d4cc2e27 100644 --- a/MySQL/consecutive-numbers.sql +++ b/MySQL/consecutive-numbers.sql @@ -19,7 +19,7 @@ # Solution 1 # Write your MySQL query statement below -SELECT DISTINCT(Num) AS ConsecutiveNums +SELECT DISTINCT(Num) AS ConsecutiveNums FROM ( SELECT Num, From 07fbe341bb251a4d4b901664ae8c543961679392 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Aug 2016 21:43:09 +0800 Subject: [PATCH 2656/4971] Create kth-smallest-element-in-a-sorted-matrix.cpp --- ...th-smallest-element-in-a-sorted-matrix.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/kth-smallest-element-in-a-sorted-matrix.cpp diff --git a/C++/kth-smallest-element-in-a-sorted-matrix.cpp b/C++/kth-smallest-element-in-a-sorted-matrix.cpp new file mode 100644 index 000000000..36122d4fe --- /dev/null +++ b/C++/kth-smallest-element-in-a-sorted-matrix.cpp @@ -0,0 +1,34 @@ +// Time: O(klogk) +// Space: O(k) + +class Solution { +public: + int kthSmallest(vector>& matrix, int k) { + int kth_smallest = 0; + + using P = pair; + const auto Compare = [&matrix](const P& a, const P& b) { + return matrix[a.first][a.second] > matrix[b.first][b.second]; + }; + + priority_queue, decltype(Compare)> min_heap(Compare); + min_heap.emplace(0, 0); + + for (int i = 0; i < k; ++i) { + const auto idx = min_heap.top(); + min_heap.pop(); + + if (idx.first == 0 && idx.second + 1 < matrix[0].size()) { + min_heap.emplace(0, idx.second + 1); + } + + if (idx.first + 1 < matrix.size()) { + min_heap.emplace(idx.first + 1, idx.second); + } + + kth_smallest = matrix[idx.first][idx.second]; + } + + return kth_smallest; + } +}; From 9ef1136bf93bdebca3564f149bca3ed3fcb8aed9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Aug 2016 22:30:02 +0800 Subject: [PATCH 2657/4971] Create kth-smallest-element-in-a-sorted-matrix.py --- ...kth-smallest-element-in-a-sorted-matrix.py | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/kth-smallest-element-in-a-sorted-matrix.py diff --git a/Python/kth-smallest-element-in-a-sorted-matrix.py b/Python/kth-smallest-element-in-a-sorted-matrix.py new file mode 100644 index 000000000..be66a8b8f --- /dev/null +++ b/Python/kth-smallest-element-in-a-sorted-matrix.py @@ -0,0 +1,52 @@ +# Time: O(k * log(min(n, m, k))), with n x m matrix +# Space: O(min(n, m, k)) + +# Given a n x n matrix where each of the rows and +# columns are sorted in ascending order, +# find the kth smallest element in the matrix. +# +# Note that it is the kth smallest element in the sorted order, +# not the kth distinct element. +# +# Example: +# +# matrix = [ +# [ 1, 5, 9], +# [10, 11, 13], +# [12, 13, 15] +# ], +# k = 8, +# +# return 13. +# Note: +# You may assume k is always valid, 1 <= k <= n^2. + +from heapq import heappush, heappop + +class Solution(object): + def kthSmallest(self, matrix, k): + """ + :type matrix: List[List[int]] + :type k: int + :rtype: int + """ + kth_smallest = 0 + min_heap = [] + + def push(i, j): + if len(matrix) > len(matrix[0]): + if i < len(matrix[0]) and j < len(matrix): + heappush(min_heap, [matrix[j][i], i, j]) + else: + if i < len(matrix) and j < len(matrix[0]): + heappush(min_heap, [matrix[i][j], i, j]) + + push(0, 0) + while min_heap and k > 0: + kth_smallest, i, j = heappop(min_heap) + push(i, j + 1) + if j == 0: + push(i + 1, 0) + k -= 1 + + return kth_smallest From 3cb7070d7cabc8971e30243d6eb47eaf322fffad Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Aug 2016 22:37:35 +0800 Subject: [PATCH 2658/4971] Update kth-smallest-element-in-a-sorted-matrix.cpp --- ...th-smallest-element-in-a-sorted-matrix.cpp | 46 ++++++++++--------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/C++/kth-smallest-element-in-a-sorted-matrix.cpp b/C++/kth-smallest-element-in-a-sorted-matrix.cpp index 36122d4fe..5135b7a13 100644 --- a/C++/kth-smallest-element-in-a-sorted-matrix.cpp +++ b/C++/kth-smallest-element-in-a-sorted-matrix.cpp @@ -1,34 +1,36 @@ -// Time: O(klogk) -// Space: O(k) +// Time: O(k * log(min(n, m, k))), with n x m matrix +// Space: O(min(n, m, k)) class Solution { public: int kthSmallest(vector>& matrix, int k) { int kth_smallest = 0; - using P = pair; - const auto Compare = [&matrix](const P& a, const P& b) { - return matrix[a.first][a.second] > matrix[b.first][b.second]; - }; - - priority_queue, decltype(Compare)> min_heap(Compare); - min_heap.emplace(0, 0); - - for (int i = 0; i < k; ++i) { - const auto idx = min_heap.top(); - min_heap.pop(); - - if (idx.first == 0 && idx.second + 1 < matrix[0].size()) { - min_heap.emplace(0, idx.second + 1); + using P = pair>; + priority_queue, greater

> q; + auto push = [&matrix, &q](int i, int j) { + if (matrix.size() > matrix[0].size()) { + if (i < matrix[0].size() && j < matrix.size()) { + q.emplace(matrix[j][i], make_pair(j, i)); + } + } else { + if (i < matrix.size() && j < matrix[0].size()) { + q.emplace(matrix[i][j], make_pair(i, j)); + } } + }; - if (idx.first + 1 < matrix.size()) { - min_heap.emplace(idx.first + 1, idx.second); + push(0, 0); + while (!q.empty() && k--) { + auto tmp = q.top(); q.pop(); + kth_smallest = tmp.first; + int i, j; + tie(i, j) = tmp.second; + push(i, j + 1); + if (j == 0) { + push(i + 1, 0); } - - kth_smallest = matrix[idx.first][idx.second]; } - - return kth_smallest; + return kth_smallest; } }; From 359ee65c3145dc1531d1805e13ffe7562e0b38cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Aug 2016 22:47:07 +0800 Subject: [PATCH 2659/4971] Update kth-smallest-element-in-a-sorted-matrix.cpp --- C++/kth-smallest-element-in-a-sorted-matrix.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/kth-smallest-element-in-a-sorted-matrix.cpp b/C++/kth-smallest-element-in-a-sorted-matrix.cpp index 5135b7a13..580af5978 100644 --- a/C++/kth-smallest-element-in-a-sorted-matrix.cpp +++ b/C++/kth-smallest-element-in-a-sorted-matrix.cpp @@ -11,7 +11,7 @@ class Solution { auto push = [&matrix, &q](int i, int j) { if (matrix.size() > matrix[0].size()) { if (i < matrix[0].size() && j < matrix.size()) { - q.emplace(matrix[j][i], make_pair(j, i)); + q.emplace(matrix[j][i], make_pair(i, j)); } } else { if (i < matrix.size() && j < matrix[0].size()) { From 195ca9b54288d6373a36437248392057651d2f1a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Aug 2016 22:50:28 +0800 Subject: [PATCH 2660/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e0ede24f5..c337bb356 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-377%20%2F%20377-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-378%20%2F%20378-ff69b4.svg) -Up to date (2016-07-25), there are `360` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-01), there are `361` 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 `377` questions. +Here is the classification of all `378` 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 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 | 358| [Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/)| [C++](./C++/rearrange-string-k-distance-apart.cpp) [Python](./Python/rearrange-string-k-distance-apart.py) | _O(n)_ | _O(n)_ | Hard |📖| Greedy, Heap | 373 | [Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/) | [C++](./C++/find-k-pairs-with-smallest-sums.cpp) [Python](./Python/find-k-pairs-with-smallest-sums.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium ||| +378 | [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/) | [C++](./C++/kth-smallest-element-in-a-sorted-matrix.cpp) [Python](./Python/kth-smallest-element-in-a-sorted-matrix.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium | LintCode || ## Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note From 7747dc2af22413034830d14a60a58af1d4ecfcc8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Aug 2016 21:26:09 +0800 Subject: [PATCH 2661/4971] Update binary-tree-preorder-traversal.py --- Python/binary-tree-preorder-traversal.py | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/Python/binary-tree-preorder-traversal.py b/Python/binary-tree-preorder-traversal.py index a49e4142b..2ba22d545 100644 --- a/Python/binary-tree-preorder-traversal.py +++ b/Python/binary-tree-preorder-traversal.py @@ -30,25 +30,23 @@ def preorderTraversal(self, root): :type root: TreeNode :rtype: List[int] """ - result, prev, cur = [], None, root - while cur: - if cur.left is None: - result.append(cur.val) - prev = cur - cur = cur.right + result, curr = [], root + while curr: + if curr.left is None: + result.append(curr.val) + curr = curr.right else: - node = cur.left - while node.right and node.right != cur: + node = curr.left + while node.right and node.right != curr: node = node.right if node.right is None: - result.append(cur.val) - node.right = cur - prev =cur - cur = cur.left + result.append(curr.val) + node.right = curr + curr = curr.left else: node.right = None - cur = cur.right + curr = curr.right return result From f76af249346bc61ce03821ddfeb37c6e41e849bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Aug 2016 21:27:20 +0800 Subject: [PATCH 2662/4971] Update binary-tree-inorder-traversal.py --- Python/binary-tree-inorder-traversal.py | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py index f277d51a6..11448e3fa 100644 --- a/Python/binary-tree-inorder-traversal.py +++ b/Python/binary-tree-inorder-traversal.py @@ -30,25 +30,23 @@ def inorderTraversal(self, root): :type root: TreeNode :rtype: List[int] """ - result, prev, cur = [], None, root - while cur: - if cur.left is None: - result.append(cur.val) - prev = cur - cur = cur.right + result, curr = [], root + while curr: + if curr.left is None: + result.append(curr.val) + curr = curr.right else: - node = cur.left - while node.right and node.right != cur: + node = curr.left + while node.right and node.right != curr: node = node.right if node.right is None: - node.right = cur - cur = cur.left + node.right = curr + curr = curr.left else: - result.append(cur.val) + result.append(curr.val) node.right = None - prev = cur - cur = cur.right + curr = curr.right return result From 36cfaf2ad24c7bce0864923a1df49e83310e079b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Aug 2016 21:29:22 +0800 Subject: [PATCH 2663/4971] Update binary-tree-inorder-traversal.cpp --- C++/binary-tree-inorder-traversal.cpp | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/C++/binary-tree-inorder-traversal.cpp b/C++/binary-tree-inorder-traversal.cpp index 911853025..28c341587 100644 --- a/C++/binary-tree-inorder-traversal.cpp +++ b/C++/binary-tree-inorder-traversal.cpp @@ -14,26 +14,23 @@ class Solution { public: vector inorderTraversal(TreeNode* root) { vector res; - TreeNode *prev = nullptr; - TreeNode *cur = root; - while (cur) { - if (!cur->left) { - res.emplace_back(cur->val); - prev = cur; - cur = cur->right; + TreeNode *curr = root; + while (curr) { + if (!curr->left) { + res.emplace_back(curr->val); + curr = curr->right; } else { - TreeNode *node = cur->left; - while (node->right && node->right != cur) { + TreeNode *node = curr->left; + while (node->right && node->right != curr) { node = node->right; } if (!node->right) { - node->right = cur; - cur = cur->left; + node->right = curr; + curr = curr->left; } else { - res.emplace_back(cur->val); - prev = cur; + res.emplace_back(curr->val); node->right = nullptr; - cur = cur->right; + curr = curr->right; } } } From 21cd6dcb7f4c4b835220a9abd2f16266bd12ead3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Aug 2016 21:30:44 +0800 Subject: [PATCH 2664/4971] Update binary-tree-preorder-traversal.cpp --- C++/binary-tree-preorder-traversal.cpp | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/C++/binary-tree-preorder-traversal.cpp b/C++/binary-tree-preorder-traversal.cpp index 6603df016..007fbab11 100644 --- a/C++/binary-tree-preorder-traversal.cpp +++ b/C++/binary-tree-preorder-traversal.cpp @@ -14,26 +14,23 @@ class Solution { public: vector preorderTraversal(TreeNode* root) { vector res; - TreeNode *prev = nullptr; - auto *cur = root; - while (cur) { - if (!cur->left) { - res.emplace_back(cur->val); - prev = cur; - cur = cur->right; + auto *curr = root; + while (curr) { + if (!curr->left) { + res.emplace_back(curr->val); + curr = curr->right; } else { - auto *node = cur->left; - while (node->right && node->right != cur) { + auto *node = curr->left; + while (node->right && node->right != curr) { node = node->right; } if (!node->right) { - res.emplace_back(cur->val); - prev = cur; - node->right = cur; - cur = cur->left; + res.emplace_back(curr->val); + node->right = curr; + curr = curr->left; } else { node->right = nullptr; - cur = cur->right; + curr = curr->right; } } } From 5609361cf1160fd0b1b0cc8d9e1c3de44d62f924 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Aug 2016 22:11:37 +0800 Subject: [PATCH 2665/4971] Create design-phone-directory.cpp --- C++/design-phone-directory.cpp | 56 ++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 C++/design-phone-directory.cpp diff --git a/C++/design-phone-directory.cpp b/C++/design-phone-directory.cpp new file mode 100644 index 000000000..67af5001e --- /dev/null +++ b/C++/design-phone-directory.cpp @@ -0,0 +1,56 @@ +// init: Time: O(n), Space: O(n) +// get: Time: O(1), Space: O(1) +// check: Time: O(1), Space: O(1) +// release: Time: O(1), Space: O(1) + +class PhoneDirectory { +public: + /** Initialize your data structure here + @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ + PhoneDirectory(int maxNumbers) : + curr_(0), numbers_(maxNumbers), used_(maxNumbers) { // Time: O(n), Space: O(n) + + iota(numbers_.begin(), numbers_.end(), 0); + } + + /** Provide a number which is not assigned to anyone. + @return - Return an available number. Return -1 if none is available. */ + int get() { // Time: O(1), Space: O(1) + if (curr_ == numbers_.size()) { + return -1; + } + const auto number = numbers_[curr_++]; + used_[number] = true; + return number; + } + + /** Check if a number is available or not. */ + bool check(int number) { // Time: O(1), Space: O(1) + if (number < 0 || number >= numbers_.size()) { + return false; + } + return !used_[number]; + } + + /** Recycle or release a number. */ + void release(int number) { // Time: O(1), Space: O(1) + if (number < 0 || number >= numbers_.size() || !used_[number]) { + return; + } + used_[number] = false; + numbers_[--curr_] = number ; + } + +private: + int curr_; + vector numbers_; + vector used_; +}; + +/** + * Your PhoneDirectory object will be instantiated and called as such: + * PhoneDirectory obj = new PhoneDirectory(maxNumbers); + * int param_1 = obj.get(); + * bool param_2 = obj.check(number); + * obj.release(number); + */ From eeaeb07a8c173e04f375a04f1bbc60f486929b17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Aug 2016 22:13:34 +0800 Subject: [PATCH 2666/4971] Update design-phone-directory.cpp --- C++/design-phone-directory.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/design-phone-directory.cpp b/C++/design-phone-directory.cpp index 67af5001e..16f79d06b 100644 --- a/C++/design-phone-directory.cpp +++ b/C++/design-phone-directory.cpp @@ -8,7 +8,7 @@ class PhoneDirectory { /** Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. */ PhoneDirectory(int maxNumbers) : - curr_(0), numbers_(maxNumbers), used_(maxNumbers) { // Time: O(n), Space: O(n) + curr_{0}, numbers_(maxNumbers), used_(maxNumbers) { // Time: O(n), Space: O(n) iota(numbers_.begin(), numbers_.end(), 0); } From 5808862d6192ec64abd5b9846f094badb22da379 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Aug 2016 22:14:07 +0800 Subject: [PATCH 2667/4971] Update design-phone-directory.cpp --- C++/design-phone-directory.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/design-phone-directory.cpp b/C++/design-phone-directory.cpp index 16f79d06b..19f77a75b 100644 --- a/C++/design-phone-directory.cpp +++ b/C++/design-phone-directory.cpp @@ -15,7 +15,7 @@ class PhoneDirectory { /** Provide a number which is not assigned to anyone. @return - Return an available number. Return -1 if none is available. */ - int get() { // Time: O(1), Space: O(1) + int get() { // Time: O(1), Space: O(1) if (curr_ == numbers_.size()) { return -1; } @@ -25,7 +25,7 @@ class PhoneDirectory { } /** Check if a number is available or not. */ - bool check(int number) { // Time: O(1), Space: O(1) + bool check(int number) { // Time: O(1), Space: O(1) if (number < 0 || number >= numbers_.size()) { return false; } @@ -33,7 +33,7 @@ class PhoneDirectory { } /** Recycle or release a number. */ - void release(int number) { // Time: O(1), Space: O(1) + void release(int number) { // Time: O(1), Space: O(1) if (number < 0 || number >= numbers_.size() || !used_[number]) { return; } From 460e31e3ece2e356b49f885f643afce4e11c7181 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Aug 2016 22:52:54 +0800 Subject: [PATCH 2668/4971] Create design-phone-directory.py --- Python/design-phone-directory.py | 61 ++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/design-phone-directory.py diff --git a/Python/design-phone-directory.py b/Python/design-phone-directory.py new file mode 100644 index 000000000..d0c2af2a1 --- /dev/null +++ b/Python/design-phone-directory.py @@ -0,0 +1,61 @@ +# init: Time: O(n), Space: O(n) +# get: Time: O(1), Space: O(1) +# check: Time: O(1), Space: O(1) +# release: Time: O(1), Space: O(1) + +class PhoneDirectory(object): + + def __init__(self, maxNumbers): + """ + Initialize your data structure here + @param maxNumbers - The maximum numbers that can be stored in the phone directory. + :type maxNumbers: int + """ + self.__curr = 0 + self.__numbers = range(maxNumbers) + self.__used = [False] * maxNumbers + + + def get(self): + """ + Provide a number which is not assigned to anyone. + @return - Return an available number. Return -1 if none is available. + :rtype: int + """ + if self.__curr == len(self.__numbers): + return -1 + number = self.__numbers[self.__curr] + self.__curr += 1 + self.__used[number] = True + return number + + + def check(self, number): + """ + Check if a number is available or not. + :type number: int + :rtype: bool + """ + return 0 <= number < len(self.__numbers) and \ + not self.__used[number] + + + def release(self, number): + """ + Recycle or release a number. + :type number: int + :rtype: void + """ + if not 0 <= number < len(self.__numbers) or \ + not self.__used[number]: + return + self.__used[number] = False + self.__curr -= 1 + self.__numbers[self.__curr] = number + + +# Your PhoneDirectory object will be instantiated and called as such: +# obj = PhoneDirectory(maxNumbers) +# param_1 = obj.get() +# param_2 = obj.check(number) +# obj.release(number) From c1f9fdb4c74fc74785459b2b067e2e283287ba66 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Aug 2016 22:56:08 +0800 Subject: [PATCH 2669/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c337bb356..4ce3ecc10 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-378%20%2F%20378-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-379%20%2F%20379-ff69b4.svg) -Up to date (2016-08-01), there are `361` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-03), there are `362` 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 `378` questions. +Here is the classification of all `379` 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.) @@ -491,6 +491,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_| _O(t + f)_| Hard | LintCode | Heap | 359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | [C++](./C++/logger-rate-limiter.cpp) [Python](./Python/logger-rate-limiter.py) | _O(1), amortized_ | _O(k)_| Easy |📖| Deque | 362| [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [C++](./C++/design-hit-counter.cpp) [Python](./Python/design-hit-counter.py) | _O(1), amortized_ | _O(k)_| Medium |📖| Deque | +379| [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) | [C++](./C++/design-phone-directory.cpp) [Python](./Python/design-phone-directory.py) | _O(1), amortized_ | _O(n)_| Medium |📖| | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From 81620cab35ae2be5c4927cfd3bfd1821a2901ef8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Aug 2016 22:57:06 +0800 Subject: [PATCH 2670/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4ce3ecc10..f744f624f 100644 --- a/README.md +++ b/README.md @@ -491,7 +491,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_| _O(t + f)_| Hard | LintCode | Heap | 359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | [C++](./C++/logger-rate-limiter.cpp) [Python](./Python/logger-rate-limiter.py) | _O(1), amortized_ | _O(k)_| Easy |📖| Deque | 362| [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [C++](./C++/design-hit-counter.cpp) [Python](./Python/design-hit-counter.py) | _O(1), amortized_ | _O(k)_| Medium |📖| Deque | -379| [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) | [C++](./C++/design-phone-directory.cpp) [Python](./Python/design-phone-directory.py) | _O(1), amortized_ | _O(n)_| Medium |📖| | +379| [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) | [C++](./C++/design-phone-directory.cpp) [Python](./Python/design-phone-directory.py) | _O(1)_ | _O(n)_| Medium |📖| | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From 5163e1503b7520b5afa88d05dde03e5c79aecf39 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Aug 2016 13:07:14 +0800 Subject: [PATCH 2671/4971] Create insert-delete-getrandom-o1.cpp --- C++/insert-delete-getrandom-o1.cpp | 55 ++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 C++/insert-delete-getrandom-o1.cpp diff --git a/C++/insert-delete-getrandom-o1.cpp b/C++/insert-delete-getrandom-o1.cpp new file mode 100644 index 000000000..cbc097811 --- /dev/null +++ b/C++/insert-delete-getrandom-o1.cpp @@ -0,0 +1,55 @@ +// Time: O(1) +// Space: O(n) + +class RandomizedSet { +public: + /** Initialize your data structure here. */ + RandomizedSet() { + + } + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + bool insert(int val) { + if (used_.count(val)) { + return false; + } + + set_.emplace_back(val); + used_[val] = set_.size() - 1; + + return true; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + bool remove(int val) { + if (!used_.count(val)) { + return false; + } + + used_[set_.back()] = used_[val]; + swap(set_[used_[val]], set_.back()); + + used_.erase(val); + set_.pop_back(); + + return true; + } + + /** Get a random element from the set. */ + int getRandom() { + return set_[rand() % set_.size()]; + } + +private: + vector set_; + unordered_map used_; +}; + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet obj = new RandomizedSet(); + * bool param_1 = obj.insert(val); + * bool param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); + */ + From 9622609b3e7c2abc04b3dd5377f372bdc77dace7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Aug 2016 13:18:20 +0800 Subject: [PATCH 2672/4971] Create insert-delete-getrandom-o1.py --- Python/insert-delete-getrandom-o1.py | 94 ++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Python/insert-delete-getrandom-o1.py diff --git a/Python/insert-delete-getrandom-o1.py b/Python/insert-delete-getrandom-o1.py new file mode 100644 index 000000000..fc72def7e --- /dev/null +++ b/Python/insert-delete-getrandom-o1.py @@ -0,0 +1,94 @@ +# Time: O(1) +# Space: O(1) + +# Design a data structure that supports all following operations in O(1) time. +# +# insert(val): Inserts an item val to the set if not already present. +# remove(val): Removes an item val from the set if present. +# getRandom: Returns a random element from current set of elements. +# Each element must have the same probability of being returned. +# +# Example: +# +# // Init an empty set. +# RandomizedSet randomSet = new RandomizedSet(); +# +# // Inserts 1 to the set. Returns true as 1 was inserted successfully. +# randomSet.insert(1); +# +# // Returns false as 2 does not exist in the set. +# randomSet.remove(2); +# +# // Inserts 2 to the set, returns true. Set now contains [1,2]. +# randomSet.insert(2); +# +# // getRandom should return either 1 or 2 randomly. +# randomSet.getRandom(); +# +# // Removes 1 from the set, returns true. Set now contains [2]. +# randomSet.remove(1); +# +# // 2 was already in the set, so return false. +# randomSet.insert(2); +# +# // Since 1 is the only number in the set, getRandom always return 1. +# randomSet.getRandom(); + + +from random import randint + +class RandomizedSet(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.__set = [] + self.__used = {} + + + def insert(self, val): + """ + Inserts a value to the set. Returns true if the set did not already contain the specified element. + :type val: int + :rtype: bool + """ + if val in self.__used: + return False + + self.__set += val, + self.__used[val] = len(self.__set)-1 + + return True + + + def remove(self, val): + """ + Removes a value from the set. Returns true if the set contained the specified element. + :type val: int + :rtype: bool + """ + if val not in self.__used: + return False + + self.__used[self.__set[-1]] = self.__used[val] + self.__set[self.__used[val]], self.__set[-1] = self.__set[-1], self.__set[self.__used[val]] + + self.__used.pop(val) + self.__set.pop() + + return True + + def getRandom(self): + """ + Get a random element from the set. + :rtype: int + """ + return self.__set[randint(0, len(self.__set)-1)] + + +# Your RandomizedSet object will be instantiated and called as such: +# obj = RandomizedSet() +# param_1 = obj.insert(val) +# param_2 = obj.remove(val) +# param_3 = obj.getRandom() From 4796fbc55daef96e4393116a15861cff6db665c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Aug 2016 13:21:55 +0800 Subject: [PATCH 2673/4971] Update insert-delete-getrandom-o1.py --- Python/insert-delete-getrandom-o1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/insert-delete-getrandom-o1.py b/Python/insert-delete-getrandom-o1.py index fc72def7e..136636091 100644 --- a/Python/insert-delete-getrandom-o1.py +++ b/Python/insert-delete-getrandom-o1.py @@ -1,5 +1,5 @@ # Time: O(1) -# Space: O(1) +# Space: O(n) # Design a data structure that supports all following operations in O(1) time. # From eb5b831f09b71c502c97b357077c749d906ffb26 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Aug 2016 13:22:08 +0800 Subject: [PATCH 2674/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f744f624f..4d58dab3e 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-379%20%2F%20379-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-380%20%2F%20380-ff69b4.svg) -Up to date (2016-08-03), there are `362` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-04), there are `363` 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 `379` questions. +Here is the classification of all `380` 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.) @@ -492,6 +492,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | [C++](./C++/logger-rate-limiter.cpp) [Python](./Python/logger-rate-limiter.py) | _O(1), amortized_ | _O(k)_| Easy |📖| Deque | 362| [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [C++](./C++/design-hit-counter.cpp) [Python](./Python/design-hit-counter.py) | _O(1), amortized_ | _O(k)_| Medium |📖| Deque | 379| [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) | [C++](./C++/design-phone-directory.cpp) [Python](./Python/design-phone-directory.py) | _O(1)_ | _O(n)_| Medium |📖| | +379| [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./C++/insert-delete-getrandom-o1.cpp) [Python](./Python/insert-delete-getrandom-o1.py) | _O(1)_ | _O(n)_| Medium || | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From e0dc62e57a46383b03925f941e15840b2dcf2c15 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Aug 2016 13:22:21 +0800 Subject: [PATCH 2675/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d58dab3e..42d01e410 100644 --- a/README.md +++ b/README.md @@ -492,7 +492,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | [C++](./C++/logger-rate-limiter.cpp) [Python](./Python/logger-rate-limiter.py) | _O(1), amortized_ | _O(k)_| Easy |📖| Deque | 362| [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [C++](./C++/design-hit-counter.cpp) [Python](./Python/design-hit-counter.py) | _O(1), amortized_ | _O(k)_| Medium |📖| Deque | 379| [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) | [C++](./C++/design-phone-directory.cpp) [Python](./Python/design-phone-directory.py) | _O(1)_ | _O(n)_| Medium |📖| | -379| [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./C++/insert-delete-getrandom-o1.cpp) [Python](./Python/insert-delete-getrandom-o1.py) | _O(1)_ | _O(n)_| Medium || | +380| [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./C++/insert-delete-getrandom-o1.cpp) [Python](./Python/insert-delete-getrandom-o1.py) | _O(1)_ | _O(n)_| Medium || | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From 5d2dc7b30d2737ca55fe702edd806e6ba5620809 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Aug 2016 22:57:58 +0800 Subject: [PATCH 2676/4971] Update bomb-enemy.cpp --- C++/bomb-enemy.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/bomb-enemy.cpp b/C++/bomb-enemy.cpp index 8b58889f7..d3b58e527 100644 --- a/C++/bomb-enemy.cpp +++ b/C++/bomb-enemy.cpp @@ -13,14 +13,14 @@ class Solution { vector> right{grid.size(), vector(grid[0].size())}; for (int i = grid.size() - 1; i >= 0; --i) { for (int j = grid[0].size() - 1; j >= 0; --j) { - if (grid[i][j] != 'Y') { + if (grid[i][j] != 'W') { if (i + 1 < grid.size()) { down[i][j] = down[i + 1][j]; } if (j + 1 < grid[0].size()) { right[i][j] = right[i][j + 1]; } - if (grid[i][j] == 'X') { + if (grid[i][j] == 'E') { ++down[i][j]; ++right[i][j]; } @@ -33,10 +33,10 @@ class Solution { for (int i = 0; i < grid.size(); ++i) { left = 0; for (int j = 0; j < grid[0].size(); ++j) { - if (grid[i][j] == 'Y') { + if (grid[i][j] == 'W') { up[j] = 0; left = 0; - } else if (grid[i][j] == 'X') { + } else if (grid[i][j] == 'E') { ++up[j]; ++left; } else { From 782fa525f899454514724a98434d40b83005cebe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Aug 2016 22:58:49 +0800 Subject: [PATCH 2677/4971] Update bomb-enemy.py --- Python/bomb-enemy.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/bomb-enemy.py b/Python/bomb-enemy.py index b540793cf..7da26b0b3 100644 --- a/Python/bomb-enemy.py +++ b/Python/bomb-enemy.py @@ -15,12 +15,12 @@ def maxKilledEnemies(self, grid): right = [[0 for _ in xrange(len(grid[0]))] for _ in xrange(len(grid))] for i in reversed(xrange(len(grid))): for j in reversed(xrange(len(grid[0]))): - if grid[i][j] != 'Y': + if grid[i][j] != 'W': if i + 1 < len(grid): down[i][j] = down[i + 1][j] if j + 1 < len(grid[0]): right[i][j] = right[i][j + 1] - if grid[i][j] == 'X': + if grid[i][j] == 'E': down[i][j] += 1 right[i][j] += 1 @@ -28,9 +28,9 @@ def maxKilledEnemies(self, grid): for i in xrange(len(grid)): left = 0 for j in xrange(len(grid[0])): - if grid[i][j] == 'Y': + if grid[i][j] == 'W': up[j], left = 0, 0 - elif grid[i][j] == 'X': + elif grid[i][j] == 'E': up[j] += 1 left += 1 else: From 2db92c8071822b0d93b8335017facd57ed52b528 Mon Sep 17 00:00:00 2001 From: Wenting Zhao Date: Fri, 5 Aug 2016 01:17:13 -0500 Subject: [PATCH 2678/4971] Added a quicker solution. --- Python/missing-number.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Python/missing-number.py b/Python/missing-number.py index 2abee7bb6..3db99ede1 100644 --- a/Python/missing-number.py +++ b/Python/missing-number.py @@ -20,3 +20,7 @@ def missingNumber(self, nums): """ return reduce(operator.xor, nums, \ reduce(operator.xor, xrange(len(nums) + 1))) + +class Solution2(object): + def missingNumber(self, nums): + return sum([i for i in xrange(len(nums)+1)])-sum(nums) From 69fbaf6c18f1414c8c6f0a5bb2b2e41513b902f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 5 Aug 2016 22:17:36 +0800 Subject: [PATCH 2679/4971] Update missing-number.py --- Python/missing-number.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/missing-number.py b/Python/missing-number.py index 3db99ede1..39aae053a 100644 --- a/Python/missing-number.py +++ b/Python/missing-number.py @@ -21,6 +21,7 @@ def missingNumber(self, nums): return reduce(operator.xor, nums, \ reduce(operator.xor, xrange(len(nums) + 1))) + class Solution2(object): def missingNumber(self, nums): - return sum([i for i in xrange(len(nums)+1)])-sum(nums) + return sum(xrange(len(nums)+1)) - sum(nums) From af8104194bdea71f8c442431ece2c474034d2c64 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Aug 2016 11:32:55 +0800 Subject: [PATCH 2680/4971] Create insert-delete-getrandom-o1-duplicates-allowed.py --- ...-delete-getrandom-o1-duplicates-allowed.py | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Python/insert-delete-getrandom-o1-duplicates-allowed.py diff --git a/Python/insert-delete-getrandom-o1-duplicates-allowed.py b/Python/insert-delete-getrandom-o1-duplicates-allowed.py new file mode 100644 index 000000000..570bc6b54 --- /dev/null +++ b/Python/insert-delete-getrandom-o1-duplicates-allowed.py @@ -0,0 +1,91 @@ +# Time: O(1) +# Space: O(n) + +# Design a data structure that supports all following operations in average O(1) time. +# +# Note: Duplicate elements are allowed. +# insert(val): Inserts an item val to the collection. +# remove(val): Removes an item val from the collection if present. +# getRandom: Returns a random element from current collection of elements. +# The probability of each element being returned is linearly related to +# the number of same value the collection contains. +# Example: +# +# // Init an empty collection. +# RandomizedCollection collection = new RandomizedCollection(); +# +# // Inserts 1 to the collection. Returns true as the collection did not contain 1. +# collection.insert(1); +# +# // Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1]. +# collection.insert(1); +# +# // Inserts 2 to the collection, returns true. Collection now contains [1,1,2]. +# collection.insert(2); +# +# // getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3. +# collection.getRandom(); +# +# // Removes 1 from the collection, returns true. Collection now contains [1,2]. +# collection.remove(1); +# +# // getRandom should return 1 and 2 both equally likely. +# collection.getRandom(); + +from random import randint +from collections import defaultdict + +class RandomizedCollection(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.__list = [] + self.__used = defaultdict(list) + + + def insert(self, val): + """ + Inserts a value to the collection. Returns true if the collection did not already contain the specified element. + :type val: int + :rtype: bool + """ + self.__list += val, + self.__used[val] += len(self.__list)-1, + + return True + + + def remove(self, val): + """ + Removes a value from the collection. Returns true if the collection contained the specified element. + :type val: int + :rtype: bool + """ + if val not in self.__used: + return False + + self.__used[self.__list[-1]][-1] = self.__used[val][-1] + self.__list[self.__used[val][-1]], self.__list[-1] = self.__list[-1], self.__list[self.__used[val][-1]] + + self.__used[val].pop() + if not self.__used[val]: + self.__used.pop(val) + self.__list.pop() + + return True + + def getRandom(self): + """ + Get a random element from the collection. + :rtype: int + """ + return self.__list[randint(0, len(self.__list)-1)] + + +# Your RandomizedCollection object will be instantiated and called as such: +# obj = RandomizedCollection() +# param_1 = obj.insert(val) +# param_2 = obj.remove(val) +# param_3 = obj.getRandom() From fd71b5049141ac3548fe56089e5618ccd5ca79fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Aug 2016 11:37:59 +0800 Subject: [PATCH 2681/4971] Create insert-delete-getrandom-o1-duplicates-allowed.cpp --- ...delete-getrandom-o1-duplicates-allowed.cpp | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 C++/insert-delete-getrandom-o1-duplicates-allowed.cpp diff --git a/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp b/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp new file mode 100644 index 000000000..067a2d046 --- /dev/null +++ b/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp @@ -0,0 +1,54 @@ +// Time: O(1) +// Space: O(n) + +class RandomizedCollection { +public: + /** Initialize your data structure here. */ + RandomizedCollection() { + + } + + /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ + bool insert(int val) { + list_.emplace_back(val); + used_[val].emplace_back(list_.size() - 1); + + return true; + } + + /** Removes a value from the collection. Returns true if the collection contained the specified element. */ + bool remove(int val) { + if (!used_.count(val)) { + return false; + } + + used_[list_.back()].back() = used_[val].back(); + swap(list_[used_[val].back()], list_.back()); + + used_[val].pop_back(); + if (used_[val].empty()) { + used_.erase(val); + } + list_.pop_back(); + + return true; + } + + /** Get a random element from the collection. */ + int getRandom() { + return list_[rand() % list_.size()]; + } + +private: + vector list_; + unordered_map> used_; +}; + +/** + * Your RandomizedCollection object will be instantiated and called as such: + * RandomizedCollection obj = new RandomizedCollection(); + * bool param_1 = obj.insert(val); + * bool param_2 = obj.remove(val); + * int param_3 = obj.getRandom(); + */ + From a57527ce6f4a78573958ec016b4bf820886dbc98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Aug 2016 11:39:29 +0800 Subject: [PATCH 2682/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 42d01e410..b8952124a 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-380%20%2F%20380-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-381%20%2F%20381-ff69b4.svg) -Up to date (2016-08-04), there are `363` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-09), there are `364` 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 `380` questions. +Here is the classification of all `381` 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.) @@ -493,6 +493,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 362| [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [C++](./C++/design-hit-counter.cpp) [Python](./Python/design-hit-counter.py) | _O(1), amortized_ | _O(k)_| Medium |📖| Deque | 379| [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) | [C++](./C++/design-phone-directory.cpp) [Python](./Python/design-phone-directory.py) | _O(1)_ | _O(n)_| Medium |📖| | 380| [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./C++/insert-delete-getrandom-o1.cpp) [Python](./Python/insert-delete-getrandom-o1.py) | _O(1)_ | _O(n)_| Medium || | +381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_| Medium || | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From a1a462f51a4c1ba3d378def43d978631d557ac7b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Aug 2016 11:55:53 +0800 Subject: [PATCH 2683/4971] Update insert-delete-getrandom-o1-duplicates-allowed.cpp --- ...delete-getrandom-o1-duplicates-allowed.cpp | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp b/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp index 067a2d046..4ae2a7665 100644 --- a/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp +++ b/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp @@ -44,6 +44,50 @@ class RandomizedCollection { unordered_map> used_; }; + +// Time: O(1) +// Space: O(n) +class RandomizedCollection2 { +public: + /** Initialize your data structure here. */ + RandomizedCollection() { + + } + + /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ + bool insert(int val) { + list_.emplace_back(val); + used_.emplace(val, list_.size() - 1); + + return true; + } + + /** Removes a value from the collection. Returns true if the collection contained the specified element. */ + bool remove(int val) { + if (!used_.count(val)) { + return false; + } + auto it_to_delete = used_.find(val); + auto it_to_back = used_.find(list_.back()); + it_to_back->second = it_to_delete->second; + swap(list_[it_to_delete->second], list_.back()); + + used_.erase(it_to_delete); + list_.pop_back(); + + return true; + } + + /** Get a random element from the collection. */ + int getRandom() { + return list_[rand() % list_.size()]; + } + +private: + vector list_; + unordered_multimap used_; +}; + /** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection obj = new RandomizedCollection(); From 4de3db9dc3b7cd88169f93495e0fb3ad3f3f81aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Aug 2016 11:56:35 +0800 Subject: [PATCH 2684/4971] Update insert-delete-getrandom-o1-duplicates-allowed.cpp --- C++/insert-delete-getrandom-o1-duplicates-allowed.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp b/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp index 4ae2a7665..1841ba503 100644 --- a/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp +++ b/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp @@ -67,6 +67,7 @@ class RandomizedCollection2 { if (!used_.count(val)) { return false; } + auto it_to_delete = used_.find(val); auto it_to_back = used_.find(list_.back()); it_to_back->second = it_to_delete->second; From aa10366f3559ad51a4b11beabebe4a86f5807593 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Aug 2016 12:07:48 +0800 Subject: [PATCH 2685/4971] Update insert-delete-getrandom-o1-duplicates-allowed.cpp --- C++/insert-delete-getrandom-o1-duplicates-allowed.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp b/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp index 1841ba503..7e27d4891 100644 --- a/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp +++ b/C++/insert-delete-getrandom-o1-duplicates-allowed.cpp @@ -10,10 +10,12 @@ class RandomizedCollection { /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ bool insert(int val) { + bool has = used_.count(val); + list_.emplace_back(val); used_[val].emplace_back(list_.size() - 1); - return true; + return !has; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ @@ -50,16 +52,18 @@ class RandomizedCollection { class RandomizedCollection2 { public: /** Initialize your data structure here. */ - RandomizedCollection() { + RandomizedCollection2() { } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ bool insert(int val) { + bool has = used_.count(val); + list_.emplace_back(val); used_.emplace(val, list_.size() - 1); - return true; + return !has; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ From 6cd69c00dfe2dc2bf3cd96c53409f98758a48c17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Aug 2016 12:09:09 +0800 Subject: [PATCH 2686/4971] Update insert-delete-getrandom-o1-duplicates-allowed.py --- Python/insert-delete-getrandom-o1-duplicates-allowed.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Python/insert-delete-getrandom-o1-duplicates-allowed.py b/Python/insert-delete-getrandom-o1-duplicates-allowed.py index 570bc6b54..3aa6ab1a7 100644 --- a/Python/insert-delete-getrandom-o1-duplicates-allowed.py +++ b/Python/insert-delete-getrandom-o1-duplicates-allowed.py @@ -51,10 +51,12 @@ def insert(self, val): :type val: int :rtype: bool """ + has = val in self.__used + self.__list += val, self.__used[val] += len(self.__list)-1, - return True + return not has def remove(self, val): From fd95958403132064a015c2f4e4d9e43dc66e5648 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Aug 2016 21:20:32 +0800 Subject: [PATCH 2687/4971] Create linked-list-random-node.py --- Python/linked-list-random-node.py | 53 +++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/linked-list-random-node.py diff --git a/Python/linked-list-random-node.py b/Python/linked-list-random-node.py new file mode 100644 index 000000000..c07627521 --- /dev/null +++ b/Python/linked-list-random-node.py @@ -0,0 +1,53 @@ +# Time: O(n) +# Space: O(1) + +# Given a singly linked list, return a random node's value from the linked list. +# Each node must have the same probability of being chosen. +# +# Follow up: +# What if the linked list is extremely large and its length is unknown to you? +# Could you solve this efficiently without using extra space? +# +# Example: +# +# // Init a singly linked list [1,2,3]. +# ListNode head = new ListNode(1); +# head.next = new ListNode(2); +# head.next.next = new ListNode(3); +# Solution solution = new Solution(head); +# +# // getRandom() should return either 1, 2, or 3 randomly. +# Each element should have equal probability of returning. +# solution.getRandom(); + + +from random import randint + +class Solution(object): + + def __init__(self, head): + """ + @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. + :type head: ListNode + """ + self.__head = head + + + # Proof of Reservoir Sampling: + # https://discuss.leetcode.com/topic/53753/brief-explanation-for-reservoir-sampling + def getRandom(self): + """ + Returns a random node's value. + :rtype: int + """ + reservoir = self.__head.val + curr, n = self.__head.next, 1 + while curr: + reservoir = curr.val if randint(1, n+1) == 1 else reservoir + curr, n = curr.next, n+1 + return reservoir + + +# Your Solution object will be instantiated and called as such: +# obj = Solution(head) +# param_1 = obj.getRandom() From f0d05eed8a0271ba773cbd7fae2b31007c3b6c48 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Aug 2016 21:28:54 +0800 Subject: [PATCH 2688/4971] Create linked-list-random-node.cpp --- C++/linked-list-random-node.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/linked-list-random-node.cpp diff --git a/C++/linked-list-random-node.cpp b/C++/linked-list-random-node.cpp new file mode 100644 index 000000000..3a6bec697 --- /dev/null +++ b/C++/linked-list-random-node.cpp @@ -0,0 +1,32 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + /** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */ + Solution(ListNode* head) : head_(head) { + + } + + /** Returns a random node's value. */ + int getRandom() { + auto reservoir = head_->val; + auto n = 1; + for (auto curr = head_->next; curr; curr = curr->next) { + if (rand() % ++n == 0) { + reservoir = curr->val; + } + } + return reservoir; + } + +private: + ListNode *head_; +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(head); + * int param_1 = obj.getRandom(); + */ + From 121947d377b27f8e6920a28e719c8ad0df82309b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Aug 2016 21:32:16 +0800 Subject: [PATCH 2689/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b8952124a..2ab9482cf 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-381%20%2F%20381-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-382%20%2F%20382-ff69b4.svg) -Up to date (2016-08-09), there are `364` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-10), there are `365` 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 `381` questions. +Here is the classification of all `382` 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.) @@ -264,6 +264,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(1)_ | Medium || Tricky, DP | 365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || Euclidean Algorithm | 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| +382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From ac17bf34398452ce54b3cd61103c0e48e831595f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Aug 2016 21:08:23 +0800 Subject: [PATCH 2690/4971] Create ransom-note.cpp --- C++/ransom-note.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/ransom-note.cpp diff --git a/C++/ransom-note.cpp b/C++/ransom-note.cpp new file mode 100644 index 000000000..550b4a3ae --- /dev/null +++ b/C++/ransom-note.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool canConstruct(string ransomNote, string magazine) { + vector counts(26); + int letters = 0; + for (const auto& c : ransomNote) { + if (counts[c - 'a']++ == 0) { + ++letters; + } + } + for (const auto& c : magazine) { + if (--counts[c - 'a'] == 0 && --letters == 0) { + // Break as soon as possible if letters have been enough. + break; + } + } + return letters == 0; + } +}; From 79d1629c1da683fb2d093426c12b6e8da4e6e2af Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Aug 2016 21:14:14 +0800 Subject: [PATCH 2691/4971] Create ransom-note.py --- Python/ransom-note.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/ransom-note.py diff --git a/Python/ransom-note.py b/Python/ransom-note.py new file mode 100644 index 000000000..755b2f316 --- /dev/null +++ b/Python/ransom-note.py @@ -0,0 +1,40 @@ +# Time: O(n) +# Space: O(1) + +# Given an arbitrary ransom note string and another string containing letters +# from all the magazines, write a function that will return true if +# the ransom note can be constructed from the magazines ; +# otherwise, it will return false. +# +# Each letter in the magazine string can only be used once in your ransom note. +# +# Note: +# You may assume that both strings contain only lowercase letters. +# +# canConstruct("a", "b") -> false +# canConstruct("aa", "ab") -> false +# canConstruct("aa", "aab") -> true + +class Solution(object): + def canConstruct(self, ransomNote, magazine): + """ + :type ransomNote: str + :type magazine: str + :rtype: bool + """ + counts = [0] * 26 + letters = 0 + + for c in ransomNote: + if counts[ord(c) - ord('a')] == 0: + letters += 1 + counts[ord(c) - ord('a')] += 1 + + for c in magazine: + counts[ord(c) - ord('a')] -= 1 + if counts[ord(c) - ord('a')] == 0: + letters -= 1 + if letters == 0: + break + + return letters == 0 From 0e58790e7a334a9150ecf30587bd98770fa370d3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Aug 2016 21:16:53 +0800 Subject: [PATCH 2692/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2ab9482cf..9dc092b7a 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-382%20%2F%20382-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-383%20%2F%20383-ff69b4.svg) -Up to date (2016-08-10), there are `365` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-11), there are `366` 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 `382` questions. +Here is the classification of all `383` 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.) @@ -122,6 +122,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | | +383| [Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./C++/ransom-note.cpp) [Python](./Python/ransom-note.py) | _O(n)_ | _O(1)_ | Easy | EPI | ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note From 4c83ed147daf8dbc894c86e9b3a57bc5e29f5040 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Aug 2016 21:20:33 +0800 Subject: [PATCH 2693/4971] Update ransom-note.py --- Python/ransom-note.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Python/ransom-note.py b/Python/ransom-note.py index 755b2f316..347cc0548 100644 --- a/Python/ransom-note.py +++ b/Python/ransom-note.py @@ -38,3 +38,16 @@ def canConstruct(self, ransomNote, magazine): break return letters == 0 + +# Time: O(n) +# Space: O(1) +from collections import Counter + +class Solution2(object): + def canConstruct(self, ransomNote, magazine): + """ + :type ransomNote: str + :type magazine: str + :rtype: bool + """ + return not Counter(ransomNote) - Counter(magazine) From d9426e3904929f014ea2192f2711f8c81c0212e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Aug 2016 13:26:15 +0800 Subject: [PATCH 2694/4971] Create shuffle-an-array.py --- Python/shuffle-an-array.py | 56 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/shuffle-an-array.py diff --git a/Python/shuffle-an-array.py b/Python/shuffle-an-array.py new file mode 100644 index 000000000..0d373852a --- /dev/null +++ b/Python/shuffle-an-array.py @@ -0,0 +1,56 @@ +# Time: O(n) +# Space: O(n) + +# Shuffle a set of numbers without duplicates. +# +# Example: +# +# // Init an array with set 1, 2, and 3. +# int[] nums = {1,2,3}; +# Solution solution = new Solution(nums); +# +# // Shuffle the array [1,2,3] and return its result. +# Any permutation of [1,2,3] must equally likely to be returned. +# solution.shuffle(); +# +# // Resets the array back to its original configuration [1,2,3]. +# solution.reset(); +# +# // Returns the random shuffling of array [1,2,3]. +# solution.shuffle(); + +class Solution(object): + + def __init__(self, nums): + """ + + :type nums: List[int] + :type size: int + """ + self.__nums = nums + + + def reset(self): + """ + Resets the array to its original configuration and return it. + :rtype: List[int] + """ + return self.__nums + + + def shuffle(self): + """ + Returns a random shuffling of the array. + :rtype: List[int] + """ + nums = list(self.__nums) + for i in xrange(len(nums)): + j = random.randint(i, len(nums)-1) + nums[i], nums[j] = nums[j], nums[i] + return nums + + +# Your Solution object will be instantiated and called as such: +# obj = Solution(nums) +# param_1 = obj.reset() +# param_2 = obj.shuffle() From 42c8192f7168d97a67b5421cbd8d8764fcfb4737 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Aug 2016 13:32:26 +0800 Subject: [PATCH 2695/4971] Create shuffle-an-array.cpp --- C++/shuffle-an-array.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C++/shuffle-an-array.cpp diff --git a/C++/shuffle-an-array.cpp b/C++/shuffle-an-array.cpp new file mode 100644 index 000000000..2d60b923f --- /dev/null +++ b/C++/shuffle-an-array.cpp @@ -0,0 +1,36 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + Solution(vector nums) : nums_(nums) { + + } + + /** Resets the array to its original configuration and return it. */ + vector reset() { + return nums_; + } + + /** Returns a random shuffling of the array. */ + vector shuffle() { + vector nums{nums_}; + default_random_engine seed((random_device())()); + for (int i = 0; i < nums.size(); ++i) { + swap(nums[i], nums[uniform_int_distribution{ + i, static_cast(nums.size()) - 1}(seed)]); + } + return nums; + } + +private: + const vector nums_; +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(nums); + * vector param_1 = obj.reset(); + * vector param_2 = obj.shuffle(); + */ + From 22c10fee0f46e388529040198e625c8bc27770c6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Aug 2016 13:34:08 +0800 Subject: [PATCH 2696/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9dc092b7a..3404f2cb2 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-383%20%2F%20383-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-384%20%2F%20384-ff69b4.svg) -Up to date (2016-08-11), there are `366` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-12), there are `367` 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 `383` questions. +Here is the classification of all `384` 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.) @@ -98,6 +98,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 |📖|| 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 ||| 370| [Range Addition](https://leetcode.com/problems/range-addition/) | [C++](./C++/range-addition.cpp) [Python](./Python/range-addition.py) | _O(k + n)_ | _O(1)_ | Medium |📖|| +384| [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [C++](./C++/shuffle-an-array.cpp) [Python](./Python/shuffle-an-array.py) | _O(n)_ | _O(n)_ | Medium | EPI || ## String # | Title | Solution | Time | Space | Difficulty | Tag | Note From edc9bf3711f35f2adf8dad4a263a270c6ed04930 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Aug 2016 23:18:59 +0800 Subject: [PATCH 2697/4971] Update and rename partition.cpp to partition-list.cpp --- C++/partition-list.cpp | 35 +++++++++++++++++++++++++++++++++++ C++/partition.cpp | 35 ----------------------------------- 2 files changed, 35 insertions(+), 35 deletions(-) create mode 100644 C++/partition-list.cpp delete mode 100644 C++/partition.cpp diff --git a/C++/partition-list.cpp b/C++/partition-list.cpp new file mode 100644 index 000000000..b3a38a912 --- /dev/null +++ b/C++/partition-list.cpp @@ -0,0 +1,35 @@ +// 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 *partition(ListNode *head, int x) { + ListNode dummy_smaller{0}; + ListNode dummy_larger{0}; + auto smaller = &dummy_smaller; + auto larger = &dummy_larger; + + while (head) { + if (head->val < x) { + smaller->next = head; + smaller = smaller->next; + } else { + larger->next = head; + larger = larger->next; + } + head = head->next; + } + smaller->next = dummy_larger.next; + larger->next = nullptr; + + return dummy_smaller.next; + } +}; diff --git a/C++/partition.cpp b/C++/partition.cpp deleted file mode 100644 index 70e9b8da0..000000000 --- a/C++/partition.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 *partition(ListNode *head, int x) { - ListNode left_dummy(-1); - ListNode right_dummy(-1); - auto left_cur = &left_dummy; - auto right_cur = &right_dummy; - - for(auto cur = head; cur; cur = cur->next) { - if(cur->val < x) { - left_cur->next = cur; - left_cur = cur; - } - else { - right_cur->next = cur; - right_cur = cur; - } - } - - left_cur->next = right_dummy.next; - right_cur->next = nullptr; - return left_dummy.next; - } -}; From 8d141e2c12232b9cfc067e7f3708b31a2ece2a4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Aug 2016 23:19:41 +0800 Subject: [PATCH 2698/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3404f2cb2..6b2b953a8 100644 --- a/README.md +++ b/README.md @@ -291,7 +291,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | 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 || +86| [Partition List](https://leetcode.com/problems/partition-list/)| [C++](./C++/partition-list.cpp) [Python](./Python/partition-list.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/)| [C++](./C++/reorder-list.cpp) [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || From 8eddaeb6f0bcb04f4b4148484424960728fea611 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Aug 2016 23:19:23 +0800 Subject: [PATCH 2699/4971] Create mini-parser.cpp --- C++/mini-parser.cpp | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 C++/mini-parser.cpp diff --git a/C++/mini-parser.cpp b/C++/mini-parser.cpp new file mode 100644 index 000000000..2542f8bb9 --- /dev/null +++ b/C++/mini-parser.cpp @@ -0,0 +1,68 @@ +// Time: O(n) +// Space: O(h) + +/** + * // This is the interface that allows for creating nested lists. + * // You should not implement it, or speculate about its implementation + * class NestedInteger { + * public: + * // Constructor initializes an empty nested list. + * NestedInteger(); + * + * // Constructor initializes a single integer. + * NestedInteger(int value); + * + * // Return true if this NestedInteger holds a single integer, rather than a nested list. + * bool isInteger() const; + * + * // Return the single integer that this NestedInteger holds, if it holds a single integer + * // The result is undefined if this NestedInteger holds a nested list + * int getInteger() const; + * + * // Set this NestedInteger to hold a single integer. + * void setInteger(int value); + * + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. + * void add(const NestedInteger &ni); + * + * // Return the nested list that this NestedInteger holds, if it holds a nested list + * // The result is undefined if this NestedInteger holds a single integer + * const vector &getList() const; + * }; + */ +class Solution { +public: + NestedInteger deserialize(string s) { + int i = 0; + return deserializeHelper(s, &i); + } + +private: + NestedInteger deserializeHelper(const string& s, int *i) { + NestedInteger result; + if (s[*i] != '[') { + int num = 0; + int sign = 1; + if (*i < s.length() && s[*i] == '-') { + sign = -1; + ++(*i); + } + while (*i < s.length() && isdigit(s[*i])) { + num *= 10; + num += s[*i] - '0'; + ++(*i); + } + result.setInteger(sign * num); + } else { + ++(*i); + while (*i < s.length() && s[*i] != ']') { + result.add(deserializeHelper(s, i)); + if (*i < s.length() && s[*i] == ',') { + ++(*i); + } + } + ++(*i); + } + return result; + } +}; From d4d1704ceb26bd9f3b68168483c4007bc87d6c1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Aug 2016 23:28:08 +0800 Subject: [PATCH 2700/4971] Update mini-parser.cpp --- C++/mini-parser.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/C++/mini-parser.cpp b/C++/mini-parser.cpp index 2542f8bb9..d1c6f8040 100644 --- a/C++/mini-parser.cpp +++ b/C++/mini-parser.cpp @@ -66,3 +66,32 @@ class Solution { return result; } }; + +// Time: O(n) +// Space: O(n) +class Solution2 { +public: + NestedInteger deserialize(string s) { + istringstream in(s); // copy string: extra O(n) space + return deserializeHelper(in); + } +private: + NestedInteger deserializeHelper(istringstream &in) { + NestedInteger result; + int num = 0; + if (in >> num) { + result.setInteger(num); + } else { + in.clear(); + in.get(); + while (in.peek() != ']') { + result.add(deserializeHelper(in)); + if (in.peek() == ',') { + in.get(); + } + } + in.get(); + } + return result; + } +}; From 90cdd5a44fe16bd72cb6eec89d3cfdc2ab9ecc3f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Aug 2016 23:28:52 +0800 Subject: [PATCH 2701/4971] Update mini-parser.cpp --- C++/mini-parser.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/mini-parser.cpp b/C++/mini-parser.cpp index d1c6f8040..3b6a66b59 100644 --- a/C++/mini-parser.cpp +++ b/C++/mini-parser.cpp @@ -75,6 +75,7 @@ class Solution2 { istringstream in(s); // copy string: extra O(n) space return deserializeHelper(in); } + private: NestedInteger deserializeHelper(istringstream &in) { NestedInteger result; From b775d99f403aed410159a9083a2900c7d8673796 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Aug 2016 23:36:32 +0800 Subject: [PATCH 2702/4971] Update mini-parser.cpp --- C++/mini-parser.cpp | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/C++/mini-parser.cpp b/C++/mini-parser.cpp index 3b6a66b59..a05ddf3e9 100644 --- a/C++/mini-parser.cpp +++ b/C++/mini-parser.cpp @@ -41,18 +41,12 @@ class Solution { NestedInteger deserializeHelper(const string& s, int *i) { NestedInteger result; if (s[*i] != '[') { - int num = 0; - int sign = 1; - if (*i < s.length() && s[*i] == '-') { - sign = -1; - ++(*i); + int j = *i; + while (j < s.length() && (s[j] == '-' || isdigit(s[j]))) { + ++j; } - while (*i < s.length() && isdigit(s[*i])) { - num *= 10; - num += s[*i] - '0'; - ++(*i); - } - result.setInteger(sign * num); + result.setInteger(stoi(s.substr(*i, j - *i + 1))); + *i = j; } else { ++(*i); while (*i < s.length() && s[*i] != ']') { From 6318f91423ff60b52be81484a64b6eb0bb201894 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Aug 2016 00:16:47 +0800 Subject: [PATCH 2703/4971] Update mini-parser.cpp --- C++/mini-parser.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/C++/mini-parser.cpp b/C++/mini-parser.cpp index a05ddf3e9..76b3db410 100644 --- a/C++/mini-parser.cpp +++ b/C++/mini-parser.cpp @@ -30,9 +30,50 @@ * const vector &getList() const; * }; */ + + +// Iterative solution. class Solution { public: NestedInteger deserialize(string s) { + if (s.empty()) { + return NestedInteger(); + } + + if (s[0] != '[') { + return NestedInteger(stoi(s)); + } + + stack stk; + for (int i = 0, j = 0; j < s.length(); ++j) { + if (s[j] == '[') { + stk.emplace(NestedInteger()); + i = j + 1; + } else if (s[j] == ',' ||s[j] == ']'){ + if (isdigit(s[j - 1])) { + stk.top().add(NestedInteger(stoi(s.substr(i,j - i)))); + } + if (s[j] == ']' && stk.size() > 1) { + NestedInteger cur = stk.top(); + stk.pop(); + stk.top().add(cur); + } + i = j + 1; + } + } + return stk.top(); + } +}; + +// Time: O(n) +// Space: O(h) +// Recursive solution. +class Solution2 { +public: + NestedInteger deserialize(string s) { + if (s.empty()) { + return NestedInteger(); + } int i = 0; return deserializeHelper(s, &i); } @@ -63,9 +104,13 @@ class Solution { // Time: O(n) // Space: O(n) -class Solution2 { +// Recursive solution. +class Solution3 { public: NestedInteger deserialize(string s) { + if (s.empty()) { + return NestedInteger(); + } istringstream in(s); // copy string: extra O(n) space return deserializeHelper(in); } From 6d02db2af8f42d8294c71dfded795148eddb1c1b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Aug 2016 00:17:04 +0800 Subject: [PATCH 2704/4971] Update mini-parser.cpp --- C++/mini-parser.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/mini-parser.cpp b/C++/mini-parser.cpp index 76b3db410..65e9dd628 100644 --- a/C++/mini-parser.cpp +++ b/C++/mini-parser.cpp @@ -31,7 +31,6 @@ * }; */ - // Iterative solution. class Solution { public: From 84faba9ae38231887e39aecfabfdd92ad5d4fb05 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Aug 2016 00:20:03 +0800 Subject: [PATCH 2705/4971] Update mini-parser.cpp --- C++/mini-parser.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/mini-parser.cpp b/C++/mini-parser.cpp index 65e9dd628..e21011dd7 100644 --- a/C++/mini-parser.cpp +++ b/C++/mini-parser.cpp @@ -48,9 +48,9 @@ class Solution { if (s[j] == '[') { stk.emplace(NestedInteger()); i = j + 1; - } else if (s[j] == ',' ||s[j] == ']'){ + } else if (s[j] == ',' || s[j] == ']'){ if (isdigit(s[j - 1])) { - stk.top().add(NestedInteger(stoi(s.substr(i,j - i)))); + stk.top().add(NestedInteger(stoi(s.substr(i, j - i)))); } if (s[j] == ']' && stk.size() > 1) { NestedInteger cur = stk.top(); From 4b016b5043fd2d31c4617ea83e4f1f2e19c0a602 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Aug 2016 00:32:17 +0800 Subject: [PATCH 2706/4971] Create mini-parser.py --- Python/mini-parser.py | 98 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Python/mini-parser.py diff --git a/Python/mini-parser.py b/Python/mini-parser.py new file mode 100644 index 000000000..fadf39f66 --- /dev/null +++ b/Python/mini-parser.py @@ -0,0 +1,98 @@ +# Time: O(n) +# Space: O(h) + +# Given a nested list of integers represented as a string, implement a parser to deserialize it. +# +# Each element is either an integer, or a list -- whose elements may also be integers or other lists. +# +# Note: You may assume that the string is well-formed: +# +# String is non-empty. +# String does not contain white spaces. +# String contains only digits 0-9, [, - ,, ]. +# Example 1: +# +# Given s = "324", +# +# You should return a NestedInteger object which contains a single integer 324. +# Example 2: +# +# Given s = "[123,[456,[789]]]", +# +# Return a NestedInteger object containing a nested list with 2 elements: +# +# 1. An integer containing value 123. +# 2. A nested list containing two elements: +# i. An integer containing value 456. +# ii. A nested list with one element: +# a. An integer containing value 789. +# +# """ +# This is the interface that allows for creating nested lists. +# You should not implement it, or speculate about its implementation +# """ +#class NestedInteger(object): +# def __init__(self, value=None): +# """ +# If value is not specified, initializes an empty list. +# Otherwise initializes a single integer equal to value. +# """ +# +# def isInteger(self): +# """ +# @return True if this NestedInteger holds a single integer, rather than a nested list. +# :rtype bool +# """ +# +# def add(self, elem): +# """ +# Set this NestedInteger to hold a nested list and adds a nested integer elem to it. +# :rtype void +# """ +# +# def setInteger(self, value): +# """ +# Set this NestedInteger to hold a single integer equal to value. +# :rtype void +# """ +# +# def getInteger(self): +# """ +# @return the single integer that this NestedInteger holds, if it holds a single integer +# Return None if this NestedInteger holds a nested list +# :rtype int +# """ +# +# def getList(self): +# """ +# @return the nested list that this NestedInteger holds, if it holds a nested list +# Return None if this NestedInteger holds a single integer +# :rtype List[NestedInteger] +# """ + + +class Solution(object): + def deserialize(self, s): + if not s: + return NestedInteger() + + if s[0] != '[': + return NestedInteger(int(s)) + + stk = [] + + i = 0 + for j in xrange(len(s)): + if s[j] == '[': + stk += NestedInteger(), + i = j+1 + elif s[j] in ',]': + if s[j-1].isdigit(): + stk[-1].add(NestedInteger(int(s[i:j]))) + if s[j] == ']' and len(stk) > 1: + cur = stk[-1] + stk.pop(); + stk[-1].add(cur) + i = j+1 + + return stk[-1] From 40b32ceb9a90da1f4244837ba8634e60a125e892 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Aug 2016 00:34:32 +0800 Subject: [PATCH 2707/4971] Update README.md --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6b2b953a8..b65402cec 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-384%20%2F%20384-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-385%20%2F%20384-ff69b4.svg) -Up to date (2016-08-12), there are `367` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-14), there are `368` 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 `384` questions. +Here is the classification of all `385` 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.) @@ -165,6 +165,8 @@ 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 |📖|| 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 ||| 341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(h)_ | Medium |📖| Iterator | +385| [Mini Parser](https://leetcode.com/problems/mini-parser/)| [C++](./C++/mini-parser.cpp) [Python](./Python/mini-parser.py) | _O(n)_ | _O(h)_ | Medium ||| + ## Queue # | Title | Solution | Time | Space | Difficulty | Tag | Note From 1af87fa8be2b361057659a9241dc1c4d49d8c50e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Aug 2016 00:35:23 +0800 Subject: [PATCH 2708/4971] Update mini-parser.cpp --- C++/mini-parser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/mini-parser.cpp b/C++/mini-parser.cpp index e21011dd7..7c7cd6229 100644 --- a/C++/mini-parser.cpp +++ b/C++/mini-parser.cpp @@ -48,7 +48,7 @@ class Solution { if (s[j] == '[') { stk.emplace(NestedInteger()); i = j + 1; - } else if (s[j] == ',' || s[j] == ']'){ + } else if (s[j] == ',' || s[j] == ']') { if (isdigit(s[j - 1])) { stk.top().add(NestedInteger(stoi(s.substr(i, j - i)))); } From 17c4f2cd6cf0c6cd5685c99f197ed8da90e249ef Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Aug 2016 14:01:16 +0800 Subject: [PATCH 2709/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b65402cec..f73b47bb4 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%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-385%20%2F%20384-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-385%20%2F%20385-ff69b4.svg) Up to date (2016-08-14), there are `368` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. From 6f857f7948b30d102fa27cf8f04504e34435d14e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Aug 2016 21:40:35 +0800 Subject: [PATCH 2710/4971] Update and rename removeNthFromEnd.cpp to remove-nth-node-from-end-of-list.cpp --- C++/remove-nth-node-from-end-of-list.cpp | 38 +++++++++++++++++++++++ C++/removeNthFromEnd.cpp | 39 ------------------------ 2 files changed, 38 insertions(+), 39 deletions(-) create mode 100644 C++/remove-nth-node-from-end-of-list.cpp delete mode 100644 C++/removeNthFromEnd.cpp diff --git a/C++/remove-nth-node-from-end-of-list.cpp b/C++/remove-nth-node-from-end-of-list.cpp new file mode 100644 index 000000000..81568c340 --- /dev/null +++ b/C++/remove-nth-node-from-end-of-list.cpp @@ -0,0 +1,38 @@ +// 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 *removeNthFromEnd(ListNode *head, int n) { + ListNode dummy{0}; + dummy.next = head; + auto slow = &dummy; + auto fast = &dummy; + + // fast is n-step ahead. + while (n > 0) { + fast = fast->next; + --n; + } + + // When fast reaches the end, slow must be nth to last node. + while (fast->next != nullptr) { + slow = slow->next; + fast = fast->next; + } + + auto node_to_delete = slow->next; + slow->next = slow->next->next; + delete node_to_delete; + + return dummy.next; + } +}; diff --git a/C++/removeNthFromEnd.cpp b/C++/removeNthFromEnd.cpp deleted file mode 100644 index f2f71848d..000000000 --- a/C++/removeNthFromEnd.cpp +++ /dev/null @@ -1,39 +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 *removeNthFromEnd(ListNode *head, int n) { - ListNode *slow = head, *fast = head, *pre = NULL; - - while(n > 0) { - fast = fast->next; - --n; - } - - while(fast) { - pre = slow; - slow = slow->next; - fast = fast->next; - } - - if(!pre && !slow->next) - return NULL; - - if(!pre && slow->next) - return slow->next; - - pre->next = slow->next; - delete slow; - - return head; - } -}; From e0f1bb6e1a5a247202b103080c0fe21d04065e18 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Aug 2016 21:41:09 +0800 Subject: [PATCH 2711/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f73b47bb4..8890986f9 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 ## Two Pointers # | 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 || +19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [C++](./C++/remove-nth-node-from-end-of-list.cpp) [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || 86| [Partition List](https://leetcode.com/problems/partition-list/)| [C++](./C++/partition-list.cpp) [Python](./Python/partition-list.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 || From 5feeaeb832941eabf1e1fcac7f373bee343d9891 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 17 Aug 2016 22:17:55 +0800 Subject: [PATCH 2712/4971] Create merge-sorted-array.cpp --- C++/merge-sorted-array.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/merge-sorted-array.cpp diff --git a/C++/merge-sorted-array.cpp b/C++/merge-sorted-array.cpp new file mode 100644 index 000000000..a5f688ddb --- /dev/null +++ b/C++/merge-sorted-array.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + int i = m + n; + while (m > 0 && n > 0) { + if (nums1[m - 1] > nums2[n - 1]) { + nums1[i - 1] = nums1[m - 1]; + --m; + } else { + nums1[i - 1] = nums2[n - 1]; + --n; + } + --i; + } + + while (n > 0) { + nums1[i - 1] = nums2[n - 1]; + --n; + --i; + } + } +}; From d850f672551d6b1a244a32dbe61c0a4e0d0f9574 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 17 Aug 2016 22:19:49 +0800 Subject: [PATCH 2713/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8890986f9..229e61d72 100644 --- a/README.md +++ b/README.md @@ -276,7 +276,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [C++](./C++/merge-intervals.cpp) [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || 57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [C++](./C++/insert-interval.cpp) [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || 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 || +88| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [C++](./C++/merge-sorted-array.cpp) [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[C++](./C++/insertion-sort-list.cpp) [Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || 148| [Sort List](https://leetcode.com/problems/sort-list/) | [C++](./C++/sort-list.cpp) [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 From cb8491b90fd682c83177c139d2988bb19cc72c25 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 18 Aug 2016 21:02:26 +0800 Subject: [PATCH 2714/4971] Create two-sum-ii-input-array-is-sorted.cpp --- C++/two-sum-ii-input-array-is-sorted.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/two-sum-ii-input-array-is-sorted.cpp diff --git a/C++/two-sum-ii-input-array-is-sorted.cpp b/C++/two-sum-ii-input-array-is-sorted.cpp new file mode 100644 index 000000000..d7baf13f8 --- /dev/null +++ b/C++/two-sum-ii-input-array-is-sorted.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector twoSum(vector& numbers, int target) { + int left = 0, right = numbers.size() - 1; + + while (left != right) { + const auto sum = numbers[left] + numbers[right]; + if (sum > target) { + --right; + } else if (sum < target) { + ++left; + } else { + return {left + 1, right + 1}; + } + } + + return {0, 0}; + } +}; From de17a916bc232063c1b56c6707f99d423825fd14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 18 Aug 2016 21:03:03 +0800 Subject: [PATCH 2715/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 229e61d72..77d31c6a1 100644 --- a/README.md +++ b/README.md @@ -297,7 +297,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/)| [C++](./C++/reorder-list.cpp) [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 | 📖 | +167| [Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [C++](./C++/two-sum-ii-input-array-is-sorted.cpp) [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 Zeroes](https://leetcode.com/problems/move-zeroes/) | [C++](./C++/move-zeroes.cpp) [Python](./Python/move-zeroes.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 | From 931c1ce435b428ec8c0217928055648adb252d1c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Aug 2016 23:07:29 +0800 Subject: [PATCH 2716/4971] Create maximum-gap.cpp --- C++/maximum-gap.cpp | 92 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 C++/maximum-gap.cpp diff --git a/C++/maximum-gap.cpp b/C++/maximum-gap.cpp new file mode 100644 index 000000000..07d005c73 --- /dev/null +++ b/C++/maximum-gap.cpp @@ -0,0 +1,92 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + struct Bucket { + int max = numeric_limits::min(); + int min = numeric_limits::max(); + }; + + int maximumGap(vector& nums) { + if (nums.size() < 2) { + return 0; + } + + // Init bucket. + int max_val = *max_element(nums.cbegin(), nums.cend()); + int min_val = *min_element(nums.cbegin(), nums.cend()); + int gap = max(1, static_cast((max_val - min_val) / + (nums.size() - 1))); + vector buckets((max_val - min_val) / gap + 1); + + // Find the bucket where the n should be put. + for (const auto& n : nums) { + // min_val / max_val is in the first / last bucket. + if (n == max_val || n == min_val) { + continue; + } + int i = (n - min_val) / gap; + buckets[i].min = min(buckets[i].min, n); + buckets[i].max = max(buckets[i].max, n); + } + + // Maximum gap should not be smaller than any gap inside the bucket. + // i.e. max_gap >= (max_val - min_val) / (count - 1) + // Thus, only count each bucket gap between the first and the last bucket. + int max_gap = 0, pre_bucket_max = min_val; + for (const auto& bucket : buckets) { + if (bucket.min != numeric_limits::max()) { + max_gap = max(max_gap, bucket.min - pre_bucket_max); + pre_bucket_max = bucket.max; + } + } + // Count the last bucket. + max_gap = max(max_gap, max_val - pre_bucket_max); + + return max_gap; + } +}; + +// Time: O(nlogn) +// Space: O(n) +class Solution2 { +public: + int maximumGap(vector& nums) { + if (nums.size() < 2) { + return 0; + } + + // Init bucket. + int max_val = *max_element(nums.cbegin(), nums.cend()); + int min_val = *min_element(nums.cbegin(), nums.cend()); + int gap = max(1, static_cast((max_val - min_val) / + (nums.size() - 1))); + map> bucket; + using ValueType = enum {MIN, MAX}; + + // Find the bucket where the n should be put. + for (const auto& n : nums) { + // min_val / max_val is in the first / last bucket. + if (n == max_val || n == min_val) { + continue ; + } + int i = (n - min_val) / gap; + bucket[i][MIN] = min(!bucket[i][MIN] ? numeric_limits::max() : + bucket[i][MIN], n); + bucket[i][MAX] = max(!bucket[i][MAX] ? numeric_limits::min() : + bucket[i][MAX], n); + } + + // Count each bucket gap between the first and the last bucket. + int max_gap = 0, pre_bucket_max = min_val; + for (auto& kvp : bucket) { + max_gap = max(max_gap, kvp.second[MIN] - pre_bucket_max); + pre_bucket_max = (kvp.second)[MAX]; + } + // Count the last bucket. + max_gap = max(max_gap, max_val - pre_bucket_max); + + return max_gap; + } +}; From 11ced0870ef288efe45b69b353e2b18c08072fe1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Aug 2016 23:08:54 +0800 Subject: [PATCH 2717/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 77d31c6a1..52a89d8e1 100644 --- a/README.md +++ b/README.md @@ -279,7 +279,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 88| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [C++](./C++/merge-sorted-array.cpp) [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[C++](./C++/insertion-sort-list.cpp) [Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || 148| [Sort List](https://leetcode.com/problems/sort-list/) | [C++](./C++/sort-list.cpp) [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 +164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [C++](./C++/maximum-gap.cpp) [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| 252| [Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) | [C++](./C++/meeting-rooms.cpp) [Python](./Python/meeting-rooms.py) | _O(nlogn)_ | _O(n)_ | Easy |📖| | From 43834079739c3fa8983c359d0188b866048f8083 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Aug 2016 23:11:44 +0800 Subject: [PATCH 2718/4971] Update maximum-gap.py --- Python/maximum-gap.py | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/Python/maximum-gap.py b/Python/maximum-gap.py index fd574a9ac..87ae6e01e 100644 --- a/Python/maximum-gap.py +++ b/Python/maximum-gap.py @@ -17,11 +17,12 @@ # bucket sort # Time: O(n) # Space: O(n) - -class Solution: - # @param numss: a list of integers - # @return: the maximum difference +class Solution(object): def maximumGap(self, nums): + """ + :type nums: List[int] + :rtype: int + """ if len(nums) < 2: return 0 @@ -56,24 +57,27 @@ def maximumGap(self, nums): return max_gap - # Time: O(nlogn) # Space: O(n) -class Solution2: - # @param num, a list of integer - # @return an integer - def maximumGap(self, num): - if len(num) < 2: +class Solution2(object): + def maximumGap(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + + if len(nums) < 2: return 0 - num.sort() - pre = num[0] + nums.sort() + pre = nums[0] max_gap = float("-inf") - for i in num: + for i in nums: max_gap = max(max_gap, i - pre) pre = i return max_gap - + + if __name__ == "__main__": print Solution().maximumGap([3, 1, 1, 1, 5, 5, 5, 5]) From 60f8259cb572e477e28d0e14d8077dd71889ff96 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Aug 2016 23:12:08 +0800 Subject: [PATCH 2719/4971] Update maximum-gap.py --- Python/maximum-gap.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/maximum-gap.py b/Python/maximum-gap.py index 87ae6e01e..2003ab711 100644 --- a/Python/maximum-gap.py +++ b/Python/maximum-gap.py @@ -1,6 +1,6 @@ # Time: O(n) # Space: O(n) -# + # Given an unsorted array, find the maximum difference between # # the successive elements in its sorted form. @@ -12,7 +12,6 @@ # You may assume all elements in the array are non-negative integers # # and fit in the 32-bit signed integer range. -# # bucket sort # Time: O(n) From b82aadd9649e4d428eea37cddd65736a2cd50013 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Aug 2016 22:20:46 +0800 Subject: [PATCH 2720/4971] Update and rename searchRange.cpp to search-for-a-range.cpp --- C++/search-for-a-range.cpp | 59 ++++++++++++++++++++++++++++++++++++++ C++/searchRange.cpp | 42 --------------------------- 2 files changed, 59 insertions(+), 42 deletions(-) create mode 100644 C++/search-for-a-range.cpp delete mode 100644 C++/searchRange.cpp diff --git a/C++/search-for-a-range.cpp b/C++/search-for-a-range.cpp new file mode 100644 index 000000000..cd775bc3f --- /dev/null +++ b/C++/search-for-a-range.cpp @@ -0,0 +1,59 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + vector searchRange(vector& nums, int target) { + const auto start = lower_bound(nums.cbegin(), nums.cend(), target); + const auto end = upper_bound(nums.cbegin(), nums.cend(), target); + if (start != nums.cend() && *start == target) { + return {start - nums.cbegin(), end - nums.cbegin() - 1}; + } + return {-1, -1}; + } +}; + +class Solution2 { +public: + vector searchRange(vector &nums, int target) { + const int begin = lower_bound(nums, target); + const int end = upper_bound(nums, target); + + if (begin < nums.size() && nums[begin] == target) { + return {begin, end - 1}; + } + + return {-1, -1}; + } + +private: + int lower_bound(vector &nums, int target) { + int left = 0; + int right = nums.size(); + // Find min left s.t. A[left] >= target. + while (left < right) { + const auto mid = left + (right - left) / 2; + if (nums[mid] >= target) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + int upper_bound(vector &nums, int target) { + int left = 0; + int right = nums.size(); + // Find min left s.t. A[left] > target. + while (left < right) { + const auto mid = left + (right - left) / 2; + if (nums[mid] > target) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; diff --git a/C++/searchRange.cpp b/C++/searchRange.cpp deleted file mode 100644 index abcf490e0..000000000 --- a/C++/searchRange.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// Time Complexity: O(logn) -// Space Complexity: O(1) - -class Solution { - public: - vector searchRange(int A[], int n, int target) { - int begin = lower_bound(A, n, target); - int end = upper_bound(A, n, target); - - if(begin < n && A[begin] == target) - return {begin, end - 1}; - - return {-1, -1}; - } - - private: - int lower_bound(int A[], int n, int target) { - int begin = 0; - int end = n; - while(begin < end) { - int mid = (begin + end) / 2; - if(A[mid] < target) - begin = mid + 1; - else - end = mid; - } - return begin; - } - - int upper_bound(int A[], int n, int target) { - int begin = 0; - int end = n; - while(begin < end) { - int mid = (begin + end) / 2; - if(A[mid] <= target) - begin = mid + 1; - else - end = mid; - } - return begin; - } -}; From c89dbe1b9629d00ec4d288da0ad54098c0ea94b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 20 Aug 2016 22:21:26 +0800 Subject: [PATCH 2721/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 52a89d8e1..3b3eea377 100644 --- a/README.md +++ b/README.md @@ -336,7 +336,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 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/) | [C++](./C++/search-in-rotated-sorted-array.cpp) [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 || +34| [Search for a Range](https://leetcode.com/problems/search-for-a-range/) | [C++](./C++/search-for-a-range.cpp) [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 || 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 || From 99f179d0e1297ea00f00451bf3b17187f2d088b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Aug 2016 19:59:33 +0800 Subject: [PATCH 2722/4971] Create largest-number.cpp --- C++/largest-number.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/largest-number.cpp diff --git a/C++/largest-number.cpp b/C++/largest-number.cpp new file mode 100644 index 000000000..44ded1bb0 --- /dev/null +++ b/C++/largest-number.cpp @@ -0,0 +1,25 @@ +// Time: O(nlogn) +// Space: O(1) + +class Solution { +public: + string largestNumber(vector& nums) { + // sort numbers + sort(nums.begin(), nums.end(), [](const int &i, const int &j) { + return to_string(i) + to_string(j) > to_string(j) + to_string(i); + }); + + // combine the numbers + string max_num; + for (const auto& i : nums) { + max_num.append(to_string(i)); + } + + // special case: start with zero (e.g. [0, 0]) + if (!max_num.empty() && max_num[0] == '0') { + return "0"; + } + + return max_num; + } +}; From 19de6cf0816439b08df4ee2e5fec9d239d6c5a1a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Aug 2016 20:00:23 +0800 Subject: [PATCH 2723/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3b3eea377..c88ff46b8 100644 --- a/README.md +++ b/README.md @@ -280,7 +280,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[C++](./C++/insertion-sort-list.cpp) [Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || 148| [Sort List](https://leetcode.com/problems/sort-list/) | [C++](./C++/sort-list.cpp) [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [C++](./C++/maximum-gap.cpp) [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 || +179| [Largest Number](https://leetcode.com/problems/largest-number/) | [C++](./C++/largest-number.cpp) [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| 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 4fda34d2947a4c2c97776dfea5590ad57b8c297e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Aug 2016 22:03:26 +0800 Subject: [PATCH 2724/4971] Create lexicographical-numbers.py --- Python/lexicographical-numbers.py | 37 +++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/lexicographical-numbers.py diff --git a/Python/lexicographical-numbers.py b/Python/lexicographical-numbers.py new file mode 100644 index 000000000..789aa4d51 --- /dev/null +++ b/Python/lexicographical-numbers.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(1) + +# Given an integer n, return 1 - n in lexicographical order. +# +# For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9]. +# +# Please optimize your algorithm to use less time and space. +# The input size may be as large as 5,000,000. + +class Solution(object): + def lexicalOrder(self, n): + result = [] + + i = 1 + while len(result) < n: + k = 0 + while i * 10**k <= n: + result.append(i * 10**k) + k += 1 + + num = result[-1] + 1 + while num <= n and num % 10: + result.append(num) + num += 1 + + if not num % 10: + num -= 1 + else: + num /= 10 + + while num % 10 == 9: + num /= 10 + + i = num+1 + + return result From 94ceabd43e22f342017d0810320fedaf5c658ba4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Aug 2016 22:52:42 +0800 Subject: [PATCH 2725/4971] Create longest-absolute-file-path.py --- Python/longest-absolute-file-path.py | 68 ++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Python/longest-absolute-file-path.py diff --git a/Python/longest-absolute-file-path.py b/Python/longest-absolute-file-path.py new file mode 100644 index 000000000..bc29abb10 --- /dev/null +++ b/Python/longest-absolute-file-path.py @@ -0,0 +1,68 @@ +# Time: O(n) +# Space: O(d), d is the max depth of the paths + +# Suppose we abstract our file system by a string in the following manner: +# +# The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: +# +# dir +# subdir1 +# subdir2 +# file.ext +# The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. +# +# The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents: +# +# dir +# subdir1 +# file1.ext +# subsubdir1 +# subdir2 +# subsubdir2 +# file2.ext +# The directory dir contains two sub-directories subdir1 and subdir2. +# subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. +# subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext. +# +# We are interested in finding the longest (number of characters) absolute path to a file within our file system. +# For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", +# and its length is 32 (not including the double quotes). +# +# Given a string representing the file system in the above format, +# return the length of the longest absolute path to file in the abstracted file system. +# If there is no file in the system, return 0. +# +# Note: +# The name of a file contains at least a . and an extension. +# The name of a directory or sub-directory will not contain a .. +# Time complexity required: O(n) where n is the size of the input string. +# +# Notice that a/aa/aaa/file1.txt is not the longest file path, if there is +# another path aaaaaaaaaaaaaaaaaaaaa/sth.png. + + +class Solution(object): + def lengthLongestPath(self, input): + """ + :type input: str + :rtype: int + """ + 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:] + + + max_len = 0 + path_len = {0: 0} + for line in split_iter(input, '\n'): + name = line.lstrip('\t') + depth = len(line) - len(name) + if '.' in name: + max_len = max(max_len, path_len[depth] + len(name)) + else: + path_len[depth + 1] = path_len[depth] + len(name) + 1 + return max_len From c87b1efa7ca5a5c1b9337b63abb536e74f09fd1b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Aug 2016 23:11:25 +0800 Subject: [PATCH 2726/4971] Create first-unique-character-in-a-string.py --- Python/first-unique-character-in-a-string.py | 34 ++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/first-unique-character-in-a-string.py diff --git a/Python/first-unique-character-in-a-string.py b/Python/first-unique-character-in-a-string.py new file mode 100644 index 000000000..15c759774 --- /dev/null +++ b/Python/first-unique-character-in-a-string.py @@ -0,0 +1,34 @@ +# Time: O(n) +# Space: O(n) + +# Given a string, find the first non-repeating character in it and +# return it's index. If it doesn't exist, return -1. +# +# Examples: +# +# s = "leetcode" +# return 0. +# +# s = "loveleetcode", +# return 2. +# Note: You may assume the string contain only lowercase letters. + + +from collections import defaultdict + +class Solution(object): + def firstUniqChar(self, s): + """ + :type s: str + :rtype: int + """ + lookup = defaultdict(int) + candidtates = set() + for i, c in enumerate(s): + if lookup[c]: + candidtates.discard(lookup[c]) + else: + lookup[c] = i+1 + candidtates.add(i+1) + + return min(candidtates) - 1 if candidtates else -1 From 5f67fb047126ac359de07b325b4ef07ccfeae8bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Aug 2016 23:13:30 +0800 Subject: [PATCH 2727/4971] Update first-unique-character-in-a-string.py --- Python/first-unique-character-in-a-string.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/first-unique-character-in-a-string.py b/Python/first-unique-character-in-a-string.py index 15c759774..9dbbff04e 100644 --- a/Python/first-unique-character-in-a-string.py +++ b/Python/first-unique-character-in-a-string.py @@ -31,4 +31,4 @@ def firstUniqChar(self, s): lookup[c] = i+1 candidtates.add(i+1) - return min(candidtates) - 1 if candidtates else -1 + return min(candidtates)-1 if candidtates else -1 From e417845958634efb66018de8dea75f7b039d7d7b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Aug 2016 23:21:29 +0800 Subject: [PATCH 2728/4971] Create first-unique-character-in-a-string.cpp --- C++/first-unique-character-in-a-string.cpp | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/first-unique-character-in-a-string.cpp diff --git a/C++/first-unique-character-in-a-string.cpp b/C++/first-unique-character-in-a-string.cpp new file mode 100644 index 000000000..1a3b279aa --- /dev/null +++ b/C++/first-unique-character-in-a-string.cpp @@ -0,0 +1,24 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int firstUniqChar(string s) { + using IT = list::iterator; + + list candidates; + unordered_map lookup; + for (int i = 0; i < s.size(); ++i) { + const auto& c = s[i]; + if (lookup.count(c)) { + if (lookup[c] != candidates.end()) { + candidates.erase(lookup[c]); + } + lookup[c] = candidates.end(); + } else { + lookup[c] = candidates.emplace(candidates.end(), i); + } + } + return candidates.empty() ? -1 : candidates.front(); + } +}; From 292686ebe661cb602d511b7ae514bb93990b4b25 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Aug 2016 00:18:51 +0800 Subject: [PATCH 2729/4971] Create longest-absolute-file-path.cpp --- C++/longest-absolute-file-path.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/longest-absolute-file-path.cpp diff --git a/C++/longest-absolute-file-path.cpp b/C++/longest-absolute-file-path.cpp new file mode 100644 index 000000000..aca011c53 --- /dev/null +++ b/C++/longest-absolute-file-path.cpp @@ -0,0 +1,29 @@ +// Time: O(n) +// Space: O(d), d is the max depth of the paths + +class Solution { +public: + int lengthLongestPath(string input) { + input.push_back('\n'); + + size_t max_len = 0; + unordered_map path_len; + path_len[0] = 0; + + for (auto i = input.find("\n"), prev_i = 0ul; + i != string::npos; + prev_i = i + 1, i = input.find("\n", i + 1)) { + + const auto line = input.substr(prev_i, i - prev_i); + const auto name = line.substr(line.find_first_not_of("\t")); + const auto depth = line.length() - name.length(); + + if (name.find('.') != string::npos) { + max_len = max(max_len, path_len[depth] + name.length()); + } else { + path_len[depth + 1] = path_len[depth] + name.length() + 1; + } + } + return max_len; + } +}; From 4b21d2e56765c1dea7f0dd48107458548f595c49 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Aug 2016 00:34:58 +0800 Subject: [PATCH 2730/4971] Create lexicographical-numbers.cpp --- C++/lexicographical-numbers.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/lexicographical-numbers.cpp diff --git a/C++/lexicographical-numbers.cpp b/C++/lexicographical-numbers.cpp new file mode 100644 index 000000000..8edaf8dcd --- /dev/null +++ b/C++/lexicographical-numbers.cpp @@ -0,0 +1,31 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector lexicalOrder(int n) { + vector result; + + for (int i = 1, num = 1; result.size() < n; i = num + 1) { + for (int k = 0; i * pow(10, k) <= n; ++k) { + result.emplace_back(i * pow(10, k)); + } + + for (num = result.back() + 1; num <= n && num % 10; ++num) { + result.emplace_back(num); + } + + if (num % 10 == 0) { + --num; + } else { + num /= 10; + } + + while (num % 10 == 9) { + num /= 10; + } + } + + return result; + } +}; From de7d0e8542ac4864d039e7732fec237ea80fd037 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Aug 2016 00:39:42 +0800 Subject: [PATCH 2731/4971] Update README.md --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c88ff46b8..d5347e2b5 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-385%20%2F%20385-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-388%20%2F%20388-ff69b4.svg) -Up to date (2016-08-14), there are `368` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-22), there are `371` 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 `385` questions. +Here is the classification of all `388` 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.) @@ -232,6 +232,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | | | 340| [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-k-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| 356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(n)_| _O(n)_| Medium |📖| Hash, Two Pointers | +387| [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/first-unique-character-in-a-string.cpp) [Python](./Python/first-unique-character-in-a-string.py) | _O(n)_| _O(n)_| Easy ||| +388| [Longest Absolute File Path](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/longest-absolute-file-path.cpp) [Python](./Python/longest-absolute-file-path.py) | _O(n)_| _O(d)_| Medium || Stack | ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -269,6 +271,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || Euclidean Algorithm | 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | +386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/llexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From 2975061b2f07560c3f9c102efa73b4a2d443fe65 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Aug 2016 00:40:47 +0800 Subject: [PATCH 2732/4971] Update first-unique-character-in-a-string.cpp --- C++/first-unique-character-in-a-string.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/first-unique-character-in-a-string.cpp b/C++/first-unique-character-in-a-string.cpp index 1a3b279aa..053c65574 100644 --- a/C++/first-unique-character-in-a-string.cpp +++ b/C++/first-unique-character-in-a-string.cpp @@ -9,7 +9,7 @@ class Solution { list candidates; unordered_map lookup; for (int i = 0; i < s.size(); ++i) { - const auto& c = s[i]; + const auto c = s[i]; if (lookup.count(c)) { if (lookup[c] != candidates.end()) { candidates.erase(lookup[c]); From d19d6329ea96d18390c10eb670a4e1c006f8eeb4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Aug 2016 00:41:00 +0800 Subject: [PATCH 2733/4971] Update first-unique-character-in-a-string.cpp --- C++/first-unique-character-in-a-string.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/first-unique-character-in-a-string.cpp b/C++/first-unique-character-in-a-string.cpp index 053c65574..c7013b8ab 100644 --- a/C++/first-unique-character-in-a-string.cpp +++ b/C++/first-unique-character-in-a-string.cpp @@ -8,7 +8,7 @@ class Solution { list candidates; unordered_map lookup; - for (int i = 0; i < s.size(); ++i) { + for (int i = 0; i < s.length(); ++i) { const auto c = s[i]; if (lookup.count(c)) { if (lookup[c] != candidates.end()) { From 5ba3893acc888486494c17e32bb6d8be385da173 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Aug 2016 00:41:49 +0800 Subject: [PATCH 2734/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d5347e2b5..cc852ccf3 100644 --- a/README.md +++ b/README.md @@ -271,7 +271,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || Euclidean Algorithm | 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | -386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/llexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| +386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From 8efc5a76da34bf05d956b84a9d9dec071e0a144d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Aug 2016 00:42:36 +0800 Subject: [PATCH 2735/4971] Update first-unique-character-in-a-string.cpp --- C++/first-unique-character-in-a-string.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/first-unique-character-in-a-string.cpp b/C++/first-unique-character-in-a-string.cpp index c7013b8ab..7e06b6a11 100644 --- a/C++/first-unique-character-in-a-string.cpp +++ b/C++/first-unique-character-in-a-string.cpp @@ -1,6 +1,7 @@ // Time: O(n) // Space: O(n) +// One-pass solution. class Solution { public: int firstUniqChar(string s) { From aaa6fb2bf3089cd372a99c0158a2768aa31955ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 27 Aug 2016 00:01:06 +0800 Subject: [PATCH 2736/4971] Create search-insert-position.cpp --- C++/search-insert-position.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/search-insert-position.cpp diff --git a/C++/search-insert-position.cpp b/C++/search-insert-position.cpp new file mode 100644 index 000000000..b348cd62e --- /dev/null +++ b/C++/search-insert-position.cpp @@ -0,0 +1,21 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int searchInsert(vector& nums, int target) { + int left = 0; + int right = nums.size() - 1; + + while (left <= right) { + const auto mid = left + (right -left) / 2; + if (nums[mid] >= target) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + return left; + } +}; From 76f8d2fe1fd91a2eb7aefca4cf409ff6a42db759 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 27 Aug 2016 00:02:37 +0800 Subject: [PATCH 2737/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cc852ccf3..3c8c25def 100644 --- a/README.md +++ b/README.md @@ -340,7 +340,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/) | [C++](./C++/search-in-rotated-sorted-array.cpp) [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/) | [C++](./C++/search-for-a-range.cpp) [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 || +35| [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [C++](./C++/search-insert-position.cpp) [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | 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/) | [C++](./C++/search-in-rotated-sorted-array-ii.cpp) [Python](./Python/search-in-rotated-sorted-array-ii.py) | _O(logn)_ | _O(1)_ | Medium || From a1a806f16a8282059290ec595d2e203999c08142 Mon Sep 17 00:00:00 2001 From: Peng Xiao Date: Sun, 28 Aug 2016 19:37:33 +0800 Subject: [PATCH 2738/4971] add golang solution Signed-off-by: Peng Xiao --- Golang/add-two-numbers.go | 62 +++++++++++++++++++ ...-substring-without-repeating-characters.go | 34 ++++++++++ Golang/two-sum.go | 37 +++++++++++ Golang/two-sum_test.go | 13 ++++ 4 files changed, 146 insertions(+) create mode 100644 Golang/add-two-numbers.go create mode 100644 Golang/longest-substring-without-repeating-characters.go create mode 100644 Golang/two-sum.go create mode 100644 Golang/two-sum_test.go diff --git a/Golang/add-two-numbers.go b/Golang/add-two-numbers.go new file mode 100644 index 000000000..a344cc633 --- /dev/null +++ b/Golang/add-two-numbers.go @@ -0,0 +1,62 @@ +package leetcode + +// ListNode represents a non-negative number. +// You are given two linked lists representing two non-negative numbers. +// The digits are stored in reverse order and each of their nodes contain a single digit. +// Add the two numbers and return it as a linked list. +// +// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) +// Output: 7 -> 0 -> 8 +type ListNode struct { + Val int + Next *ListNode +} + +func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { + results := &ListNode{} + node := results + node1 := l1 + node2 := l2 + + overten := false + + for node1 != nil || node2 != nil { + + tmp := 0 + + if node1 != nil { + tmp = tmp + node1.Val + node1 = node1.Next + } + + if node2 != nil { + tmp = tmp + node2.Val + node2 = node2.Next + } + if overten { + tmp++ + } + + if tmp >= 10 { + overten = true + tmp -= 10 + } else { + overten = false + } + + node.Val = tmp + + if node1 != nil || node2 != nil { + node.Next = &ListNode{} + node = node.Next + } + } + + if overten { + node.Next = &ListNode{} + node = node.Next + node.Val = 1 + } + + return results +} diff --git a/Golang/longest-substring-without-repeating-characters.go b/Golang/longest-substring-without-repeating-characters.go new file mode 100644 index 000000000..11dd57570 --- /dev/null +++ b/Golang/longest-substring-without-repeating-characters.go @@ -0,0 +1,34 @@ +package leetcode + +// Given a string, find the length of the longest substring without repeating characters. +// +// Examples: +// Given "abcabcbb", the answer is "abc", which the length is 3. +// Given "bbbbb", the answer is "b", with the length of 1. +// Given "pwwkew", the answer is "wke", with the length of 3. +// Note that the answer must be a substring, "pwke" is a subsequence and not a substring. +// +func lengthOfLongestSubstring(s string) int { + hashmap := map[byte]int{} + max := 0 + for i := range s { + _, ok := hashmap[s[i]] + if !ok { + hashmap[s[i]] = i + if len(hashmap) > max { + max = len(hashmap) + } + } else { + // remove repeated + oldI := hashmap[s[i]] + hashmap[s[i]] = i + + for key, value := range hashmap { + if value < oldI { + delete(hashmap, key) + } + } + } + } + return max +} diff --git a/Golang/two-sum.go b/Golang/two-sum.go new file mode 100644 index 000000000..bdf987986 --- /dev/null +++ b/Golang/two-sum.go @@ -0,0 +1,37 @@ +package leetcode + +import "sort" + +// Given an array of integers, return indices of the two numbers +// such that they add up to a specific target. +// You may assume that each input would have exactly one solution. +// +// Example: +// Given nums = [2, 7, 11, 15], target = 9, +// Because nums[0] + nums[1] = 2 + 7 = 9, +// return [0, 1]. +func TwoSum(nums []int, target int) []int { + + indexs := make([]int, 2) + hash := map[int]int{} + + for i := range nums { + hash[target-nums[i]] = i + } + + for i := range nums { + index, ok := hash[nums[i]] + if ok { + if i == index { + continue + } + indexs[0] = index + indexs[1] = i + sort.Ints(indexs) + break + } + continue + } + + return indexs +} diff --git a/Golang/two-sum_test.go b/Golang/two-sum_test.go new file mode 100644 index 000000000..e6e6c414b --- /dev/null +++ b/Golang/two-sum_test.go @@ -0,0 +1,13 @@ +package leetcode + +import "testing" + +func Test_two_sum(t *testing.T) { + + if result := TwoSum([]int{1, 3, 5}, 4); result[0] != 0 && result[1] != 1 { + t.Errorf("Error") + } + if result := TwoSum([]int{3, 1, 5}, 6); result[0] != 1 && result[1] != 2 { + t.Errorf("Error") + } +} From de42e8fa820a7fed8f731fb370a7f9383768d4bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Aug 2016 23:12:52 +0800 Subject: [PATCH 2739/4971] Create find-the-difference.cpp --- C++/find-the-difference.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 C++/find-the-difference.cpp diff --git a/C++/find-the-difference.cpp b/C++/find-the-difference.cpp new file mode 100644 index 000000000..bfa3a01ca --- /dev/null +++ b/C++/find-the-difference.cpp @@ -0,0 +1,10 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + char findTheDifference(string s, string t) { + return accumulate(s.cbegin(), s.cend(), 0, std::bit_xor()) ^ + accumulate(t.cbegin(), t.cend(), 0, std::bit_xor()); + } +}; From a324862e961b48c5175706acf647ac7dc140f5d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Aug 2016 23:16:50 +0800 Subject: [PATCH 2740/4971] Create find-the-difference.py --- Python/find-the-difference.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/find-the-difference.py diff --git a/Python/find-the-difference.py b/Python/find-the-difference.py new file mode 100644 index 000000000..73948c1ac --- /dev/null +++ b/Python/find-the-difference.py @@ -0,0 +1,32 @@ +# Time: O(n) +# Space: O(1) + +# Given two strings s and t which consist of only lowercase letters. +# +# String t is generated by random shuffling string s +# and then add one more letter at a random position. +# +# Find the letter that was added in t. +# +# Example: +# +# Input: +# s = "abcd" +# t = "abcde" +# +# Output: +# e +# +# Explanation: +# 'e' is the letter that was added. + +from operator import xor + +class Solution(object): + def findTheDifference(self, s, t): + """ + :type s: str + :type t: str + :rtype: str + """ + return chr(reduce(xor, map(ord, s), 0) ^ reduce(xor, map(ord, t), 0)) From 46b30ebbca6e548f258342063be002619fbd2513 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Aug 2016 22:34:30 +0800 Subject: [PATCH 2741/4971] Create perfect-rectangle.cpp --- C++/perfect-rectangle.cpp | 49 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 C++/perfect-rectangle.cpp diff --git a/C++/perfect-rectangle.cpp b/C++/perfect-rectangle.cpp new file mode 100644 index 000000000..dfbfd3be3 --- /dev/null +++ b/C++/perfect-rectangle.cpp @@ -0,0 +1,49 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + bool isRectangleCover(vector>& rectangles) { + enum DIR {L = 0, B = 1, R = 2, T = 3}; + int left = numeric_limits::max(), bottom = numeric_limits::max(), + right = numeric_limits::min(), top = numeric_limits::min(); + for (const auto& rect : rectangles) { + left = min(left, rect[L]); + bottom = min(bottom, rect[B]); + right = max(right, rect[R]); + top = max(top, rect[T]); + } + + using P = pair, int>; + enum CORNER {LB = 1, RB = 2, LT = 4, RT = 8}; + unordered_map> corner_count; + vector

corners{{{L, B}, LB}, {{R, B}, RB}, {{L, T}, LT}, {{R, T}, RT}}; + for (const auto& rect : rectangles) { + for (const auto& corner : corners) { + const auto x = rect[corner.first.first]; + const auto y = rect[corner.first.second]; + if (corner_count[x][y] & corner.second) { + return false; + } + corner_count[x][y] |= corner.second; + } + } + + bool is_valid[16] = {false}; + is_valid[LB | RB] = is_valid[LB | LT] = is_valid[RB | RT] = is_valid[LT | RT] = is_valid[LB | RB | LT | RT] = true; + for (auto itx = corner_count.begin(); itx != corner_count.end(); ++itx) { + const auto x = itx->first; + for (auto ity = itx->second.begin(); ity != itx->second.end(); ++ity) { + int y = ity->first; + int mask = ity->second; + if ((left < x && x < right) || (bottom < y && y < top)) { + if (!is_valid[mask]) { + return false; + } + } + } + } + + return true; + } +}; From 9c22af3abcfce1e920a3461cc95a127c63026df6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Aug 2016 22:36:36 +0800 Subject: [PATCH 2742/4971] Update perfect-rectangle.cpp --- C++/perfect-rectangle.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/perfect-rectangle.cpp b/C++/perfect-rectangle.cpp index dfbfd3be3..2e11e5ece 100644 --- a/C++/perfect-rectangle.cpp +++ b/C++/perfect-rectangle.cpp @@ -34,8 +34,8 @@ class Solution { for (auto itx = corner_count.begin(); itx != corner_count.end(); ++itx) { const auto x = itx->first; for (auto ity = itx->second.begin(); ity != itx->second.end(); ++ity) { - int y = ity->first; - int mask = ity->second; + const auto y = ity->first; + const auto mask = ity->second; if ((left < x && x < right) || (bottom < y && y < top)) { if (!is_valid[mask]) { return false; From f34a3c3bf6929eacdd159a1f9cbbe8c5fb8e30e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Aug 2016 22:37:26 +0800 Subject: [PATCH 2743/4971] Update perfect-rectangle.cpp --- C++/perfect-rectangle.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/perfect-rectangle.cpp b/C++/perfect-rectangle.cpp index 2e11e5ece..0da1ba018 100644 --- a/C++/perfect-rectangle.cpp +++ b/C++/perfect-rectangle.cpp @@ -31,9 +31,9 @@ class Solution { bool is_valid[16] = {false}; is_valid[LB | RB] = is_valid[LB | LT] = is_valid[RB | RT] = is_valid[LT | RT] = is_valid[LB | RB | LT | RT] = true; - for (auto itx = corner_count.begin(); itx != corner_count.end(); ++itx) { + for (auto itx = corner_count.cbegin(); itx != corner_count.cend(); ++itx) { const auto x = itx->first; - for (auto ity = itx->second.begin(); ity != itx->second.end(); ++ity) { + for (auto ity = itx->second.cbegin(); ity != itx->second.cend(); ++ity) { const auto y = ity->first; const auto mask = ity->second; if ((left < x && x < right) || (bottom < y && y < top)) { From d2d6380f99a006e5090724565f054c2638accd14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Aug 2016 22:40:26 +0800 Subject: [PATCH 2744/4971] Create perfect-rectangle.py --- Python/perfect-rectangle.py | 81 +++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Python/perfect-rectangle.py diff --git a/Python/perfect-rectangle.py b/Python/perfect-rectangle.py new file mode 100644 index 000000000..7a3822f41 --- /dev/null +++ b/Python/perfect-rectangle.py @@ -0,0 +1,81 @@ +# Time: O(n) +# Space: O(n) + +# Given N axis-aligned rectangles where N > 0, +# determine if they all together form an exact cover of a rectangular region. +# +# Each rectangle is represented as a bottom-left point and a top-right point. +# For example, a unit square is represented as [1,1,2,2]. +# (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)). +# +# Example 1: +# +# rectangles = [ +# [1,1,3,3], +# [3,1,4,2], +# [3,2,4,4], +# [1,3,2,4], +# [2,3,3,4] +# ] +# +# Return true. All 5 rectangles together form an exact cover of a rectangular region. +# +# Example 2: +# +# rectangles = [ +# [1,1,2,3], +# [1,3,2,4], +# [3,1,4,2], +# [3,2,4,4] +# ] +# +# Return false. Because there is a gap between the two rectangular regions. +# +# Example 3: +# +# rectangles = [ +# [1,1,3,3], +# [3,1,4,2], +# [1,3,2,4], +# [3,2,4,4] +# ] +# +# Return false. Because there is a gap in the top center. +# +# Example 4: +# +# rectangles = [ +# [1,1,3,3], +# [3,1,4,2], +# [1,3,2,4], +# [2,2,4,4] +# ] +# +# Return false. Because two of the rectangles overlap with each other. + +from collections import defaultdict + +class Solution(object): + def isRectangleCover(self, rectangles): + """ + :type rectangles: List[List[int]] + :rtype: bool + """ + left = min(rec[0] for rec in rectangles) + bottom = min(rec[1] for rec in rectangles) + right = max(rec[2] for rec in rectangles) + top = max(rec[3] for rec in rectangles) + + points = defaultdict(int) + for l, b, r, t in rectangles: + for p, q in zip(((l, b), (r, b), (l, t), (r, t)), (1, 2, 4, 8)): + if points[p] & q: + return False + points[p] |= q + + for px, py in points: + if left < px < right or bottom < py < top: + if points[(px, py)] not in (3, 5, 10, 12, 15): + return False + + return True From 6bca8db1b5cec06e4a51ca9c321d2d659931b7a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Aug 2016 22:45:00 +0800 Subject: [PATCH 2745/4971] Update README.md --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3c8c25def..3dc57274b 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-388%20%2F%20388-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-390%20%2F%20390-ff69b4.svg) -Up to date (2016-08-22), there are `371` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-28), there are `373` 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 `388` questions. +Here is the classification of all `390` 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.) @@ -56,6 +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| 342 | [Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./C++/power-of-four.cpp) [Python](./Python/power-of-four.py) | _O(1)_ | _O(1)_ | Easy | | 371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | LintCode | +389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./C++/find-the-difference.cpp) [Python](./Python/find-the-difference.py) | _O(n)_ | _O(1)_ | Easy | | ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -272,6 +273,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| +391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./C++/perfect-rectangle.cpp) [Python](./Python/perfect-rectangle.py) | _O(n)_ | _O(n)_ | Hard | | ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note From cd2aaee0186cfccab69ef012b41f4ffe501fc547 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Aug 2016 23:49:04 +0800 Subject: [PATCH 2746/4971] Update perfect-rectangle.cpp --- C++/perfect-rectangle.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/perfect-rectangle.cpp b/C++/perfect-rectangle.cpp index 0da1ba018..dba2fffb0 100644 --- a/C++/perfect-rectangle.cpp +++ b/C++/perfect-rectangle.cpp @@ -4,7 +4,7 @@ class Solution { public: bool isRectangleCover(vector>& rectangles) { - enum DIR {L = 0, B = 1, R = 2, T = 3}; + enum Location {L = 0, B = 1, R = 2, T = 3}; int left = numeric_limits::max(), bottom = numeric_limits::max(), right = numeric_limits::min(), top = numeric_limits::min(); for (const auto& rect : rectangles) { @@ -15,7 +15,7 @@ class Solution { } using P = pair, int>; - enum CORNER {LB = 1, RB = 2, LT = 4, RT = 8}; + enum Corner {LB = 1, RB = 2, LT = 4, RT = 8}; unordered_map> corner_count; vector

corners{{{L, B}, LB}, {{R, B}, RB}, {{L, T}, LT}, {{R, T}, RT}}; for (const auto& rect : rectangles) { From aecb8eb84baae0521ce68fda2f06d53d443618c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 30 Aug 2016 00:00:56 +0800 Subject: [PATCH 2747/4971] Update perfect-rectangle.cpp --- C++/perfect-rectangle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/perfect-rectangle.cpp b/C++/perfect-rectangle.cpp index dba2fffb0..96d72b5df 100644 --- a/C++/perfect-rectangle.cpp +++ b/C++/perfect-rectangle.cpp @@ -29,7 +29,7 @@ class Solution { } } - bool is_valid[16] = {false}; + bitset<16> is_valid; is_valid[LB | RB] = is_valid[LB | LT] = is_valid[RB | RT] = is_valid[LT | RT] = is_valid[LB | RB | LT | RT] = true; for (auto itx = corner_count.cbegin(); itx != corner_count.cend(); ++itx) { const auto x = itx->first; From ea31ed42912f2e366021e6b561757df37b75b310 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 30 Aug 2016 14:28:22 +0800 Subject: [PATCH 2748/4971] Create elimination-game.cpp --- C++/elimination-game.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/elimination-game.cpp diff --git a/C++/elimination-game.cpp b/C++/elimination-game.cpp new file mode 100644 index 000000000..072d60659 --- /dev/null +++ b/C++/elimination-game.cpp @@ -0,0 +1,17 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int lastRemaining(int n) { + int start = 1; + + for (int i = n, step = 2, direction = 1; i > 1; + i /= 2, step *= 2, direction *= -1) { + + start += direction * (step * (i / 2) - step / 2); + } + + return start; + } +}; From 22e581b726f8b81c003168d46640c2f9952c6d0a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 30 Aug 2016 14:33:56 +0800 Subject: [PATCH 2749/4971] Create elimination-game.py --- Python/elimination-game.py | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/elimination-game.py diff --git a/Python/elimination-game.py b/Python/elimination-game.py new file mode 100644 index 000000000..2d3b7059b --- /dev/null +++ b/Python/elimination-game.py @@ -0,0 +1,39 @@ +# Time: O(logn) +# Space: O(1) + +# There is a list of sorted integers from 1 to n. Starting from left to right, +# remove the first number and every other number afterward until you reach the end of the list. +# +# Repeat the previous step again, but this time from right to left, +# remove the right most number and every other number from the remaining numbers. +# +# We keep repeating the steps again, alternating left to right and right to left, +# until a single number remains. +# +# Find the last number that remains starting with a list of length n. +# +# Example: +# +# Input: +# n = 9, +# 1 2 3 4 5 6 7 8 9 +# 2 4 6 8 +# 2 6 +# 6 +# +# Output: +# 6 + +class Solution(object): + def lastRemaining(self, n): + """ + :type n: int + :rtype: int + """ + start, step, direction = 1, 2, 1 + while n > 1: + start += direction * (step * (n / 2) - step / 2) + n /= 2 + step *= 2 + direction *= -1 + return start From c445fb3185de01e3771a0eb3045496f3dd6bc373 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 30 Aug 2016 14:34:41 +0800 Subject: [PATCH 2750/4971] Update elimination-game.cpp --- C++/elimination-game.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/elimination-game.cpp b/C++/elimination-game.cpp index 072d60659..0541d375f 100644 --- a/C++/elimination-game.cpp +++ b/C++/elimination-game.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(logn) // Space: O(1) class Solution { @@ -6,10 +6,10 @@ class Solution { int lastRemaining(int n) { int start = 1; - for (int i = n, step = 2, direction = 1; i > 1; - i /= 2, step *= 2, direction *= -1) { + for (int step = 2, direction = 1; n > 1; + n /= 2, step *= 2, direction *= -1) { - start += direction * (step * (i / 2) - step / 2); + start += direction * (step * (n / 2) - step / 2); } return start; From 058f71c4cb317a22d31002e6059850025de926c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 30 Aug 2016 14:36:45 +0800 Subject: [PATCH 2751/4971] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3dc57274b..cc8c240a9 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-390%20%2F%20390-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-391%20%2F%20391-ff69b4.svg) -Up to date (2016-08-28), there are `373` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-08-28), there are `374` 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 `390` questions. +Here is the classification of all `391` 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.) @@ -273,6 +273,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| +390 | [Elimination Game](https://leetcode.com/contest/2/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium | | 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./C++/perfect-rectangle.cpp) [Python](./Python/perfect-rectangle.py) | _O(n)_ | _O(n)_ | Hard | | ## Sort From 6d8e714a8cb7348529388c3aa50c2f05bc37abf0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 31 Aug 2016 22:16:06 +0800 Subject: [PATCH 2752/4971] Update elimination-game.py --- Python/elimination-game.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/elimination-game.py b/Python/elimination-game.py index 2d3b7059b..0dd69f485 100644 --- a/Python/elimination-game.py +++ b/Python/elimination-game.py @@ -32,7 +32,7 @@ def lastRemaining(self, n): """ start, step, direction = 1, 2, 1 while n > 1: - start += direction * (step * (n / 2) - step / 2) + start += direction * (step * (n/2) - step/2) n /= 2 step *= 2 direction *= -1 From e261a0c3d9c697d78653d442b97f11bf4129bfb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 1 Sep 2016 23:54:54 +0800 Subject: [PATCH 2753/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cc8c240a9..c0698b605 100644 --- a/README.md +++ b/README.md @@ -273,7 +273,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| -390 | [Elimination Game](https://leetcode.com/contest/2/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium | | +390 | [Elimination Game](https://leetcode.com/contest/2/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium | 2nd Contest | 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./C++/perfect-rectangle.cpp) [Python](./Python/perfect-rectangle.py) | _O(n)_ | _O(n)_ | Hard | | ## Sort From a144285bb58c271eac3d280929c42c9a71fa9207 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Sep 2016 23:27:04 +0800 Subject: [PATCH 2754/4971] Update and rename sqrt.cpp to sqrtx.cpp --- C++/sqrt.cpp | 27 --------------------------- C++/sqrtx.cpp | 23 +++++++++++++++++++++++ 2 files changed, 23 insertions(+), 27 deletions(-) delete mode 100644 C++/sqrt.cpp create mode 100644 C++/sqrtx.cpp diff --git a/C++/sqrt.cpp b/C++/sqrt.cpp deleted file mode 100644 index df80bc622..000000000 --- a/C++/sqrt.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - int sqrt(int x) { - int left = 1; - int right = x; - int last_mid = 0; - - while(left <= right) { - int mid = left + (right - left) / 2; - - if(x / mid > mid) { - left = mid + 1; - last_mid = mid; - } - else if (x / mid < mid) { - right = mid - 1; - } - else - return mid; - } - - return last_mid; - } -}; diff --git a/C++/sqrtx.cpp b/C++/sqrtx.cpp new file mode 100644 index 000000000..2d4092aca --- /dev/null +++ b/C++/sqrtx.cpp @@ -0,0 +1,23 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int mySqrt(int x) { + if (x < 2) { + return x; + } + + int left = 1, right = x / 2; + while (left <= right) { + const auto mid = left + (right - left) / 2; + if (mid > x / mid) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + return left - 1; + } +}; From 5df34acd8c54bd7ca8c845358fdb1c1d7ca42c96 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Sep 2016 23:27:51 +0800 Subject: [PATCH 2755/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c0698b605..6ddd8bcf4 100644 --- a/README.md +++ b/README.md @@ -344,7 +344,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 33| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [C++](./C++/search-in-rotated-sorted-array.cpp) [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/) | [C++](./C++/search-for-a-range.cpp) [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || 35| [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [C++](./C++/search-insert-position.cpp) [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || -69| [Sqrt(x)](https://leetcode.com/problems/sqrtx/) | [Python](./Python/sqrtx.py) | _O(logn)_ | _O(1)_ | Medium || +69| [Sqrt(x)](https://leetcode.com/problems/sqrtx/) | [C++](./C++/sqrtx.cpp) [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/) | [C++](./C++/search-in-rotated-sorted-array-ii.cpp) [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/) | [C++](./C++/find-minimum-in-rotated-sorted-array.cpp) [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium || From 3451e4a9ae1820ebd0da223e4d03fe23e251b85f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Sep 2016 23:58:20 +0800 Subject: [PATCH 2756/4971] Update and rename searchMatrix.cpp to search-a-2d-matrix.cpp --- C++/search-a-2d-matrix.cpp | 34 ++++++++++++++++++++++++++++++++++ C++/searchMatrix.cpp | 27 --------------------------- 2 files changed, 34 insertions(+), 27 deletions(-) create mode 100644 C++/search-a-2d-matrix.cpp delete mode 100644 C++/searchMatrix.cpp diff --git a/C++/search-a-2d-matrix.cpp b/C++/search-a-2d-matrix.cpp new file mode 100644 index 000000000..a6fcfa723 --- /dev/null +++ b/C++/search-a-2d-matrix.cpp @@ -0,0 +1,34 @@ +// Time: O(logm + logn) +// Space: O(1) + +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + if (matrix.empty()) { + return false; + } + + // Treat matrix as 1D array. + const int m = matrix.size(); + const int n = matrix[0].size(); + int left = 0; + int right = m * n - 1; + + // Find min of left s.t. matrix[left / n][left % n] >= target + while (left <= right) { + int mid = left + (right - left) / 2; + if (matrix[mid / n][mid % n] >= target) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + // Check if matrix[left / n][left % n] equals to target. + if (left != m * n && matrix[left / n][left % n] == target) { + return true; + } + + return false; + } +}; diff --git a/C++/searchMatrix.cpp b/C++/searchMatrix.cpp deleted file mode 100644 index 6bc9a9a07..000000000 --- a/C++/searchMatrix.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// Time Complexity: O(m+n) (Akra-Bazzi theorem) -// Space Complexity: O(log(mn)) - -class Solution { - public: - bool partitionAndSearch(vector > &matrix, int target, int i, int j, int m, int n) { - if(m < 1 || n < 1) - return false; - int start, end; - for(start = 0, end = min(m, n); start < end;) { - int tmp = (start+end)/2; - if(target < matrix[i+tmp][j+tmp]) - end = tmp; - else if (target > matrix[i+tmp][j+tmp]) - start = tmp+1; - else - return true; - } - if(start < 1) - return false; - return partitionAndSearch(matrix, target, i, j+start, m, n - start) - || partitionAndSearch(matrix, target, i+start, j, m - start, n); - } - bool searchMatrix(vector > &matrix, int target) { - return partitionAndSearch(matrix, target, 0, 0, matrix.size(), matrix[0].size()); - } -}; From f93e356f83fe65fc9bf7ac57fb91d4e87e78d349 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Sep 2016 23:59:09 +0800 Subject: [PATCH 2757/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6ddd8bcf4..a31b61fcc 100644 --- a/README.md +++ b/README.md @@ -345,7 +345,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 34| [Search for a Range](https://leetcode.com/problems/search-for-a-range/) | [C++](./C++/search-for-a-range.cpp) [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || 35| [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [C++](./C++/search-insert-position.cpp) [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || 69| [Sqrt(x)](https://leetcode.com/problems/sqrtx/) | [C++](./C++/sqrtx.cpp) [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 || +74| [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | [C++](./C++/search-a-2d-matrix.cpp) [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/) | [C++](./C++/search-in-rotated-sorted-array-ii.cpp) [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/) | [C++](./C++/find-minimum-in-rotated-sorted-array.cpp) [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/) | [C++](./C++/find-minimum-in-rotated-sorted-array-ii.cpp) [Python](./Python/find-minimum-in-rotated-sorted-array-ii.py) | _O(logn)_ ~ _O(n)_ | _O(1)_ | Hard || From 75bd5c16bc886f2b4e87347d2744b621fb20b787 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Sep 2016 22:50:11 +0800 Subject: [PATCH 2758/4971] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a31b61fcc..7f762b2cf 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-391%20%2F%20391-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-391%20%2F%20395-ff69b4.svg) -Up to date (2016-08-28), there are `374` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-09-04), there are `378` 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 `391` questions. +Here is the classification of all `395` 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 48c2f2a0a7bd99c526c3457e631f2ad22c49d3e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 5 Sep 2016 23:56:56 +0800 Subject: [PATCH 2759/4971] Create is-subsequence.cpp --- C++/is-subsequence.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/is-subsequence.cpp diff --git a/C++/is-subsequence.cpp b/C++/is-subsequence.cpp new file mode 100644 index 000000000..8738914e7 --- /dev/null +++ b/C++/is-subsequence.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(1) + +// Greedy solution. +class Solution { +public: + bool isSubsequence(string s, string t) { + if (s.empty()) { + return true; + } + int i = 0; + for (const auto& c : t) { + if (c == s[i]) { + ++i; + } + if (i == s.length()) { + return true; + } + } + return false; + } +}; From a845b25c7995866754f9b0fe1e68932e924f7395 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 5 Sep 2016 23:58:06 +0800 Subject: [PATCH 2760/4971] Update is-subsequence.cpp --- C++/is-subsequence.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/is-subsequence.cpp b/C++/is-subsequence.cpp index 8738914e7..96c9526b2 100644 --- a/C++/is-subsequence.cpp +++ b/C++/is-subsequence.cpp @@ -14,9 +14,9 @@ class Solution { ++i; } if (i == s.length()) { - return true; + break; } } - return false; + return i == s.length(); } }; From 1de121870230f3d0c5d922fa97377018b73945f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Sep 2016 00:01:17 +0800 Subject: [PATCH 2761/4971] Create is-subsequence.py --- Python/is-subsequence.py | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/is-subsequence.py diff --git a/Python/is-subsequence.py b/Python/is-subsequence.py new file mode 100644 index 000000000..e92eceef0 --- /dev/null +++ b/Python/is-subsequence.py @@ -0,0 +1,41 @@ +# Time: O(n) +# Space: O(1) + +# Given a string s and a string t, check if s is subsequence of t. +# +# You may assume that there is only lower case English letters in both s and t. +# t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100). +# +# A subsequence of a string is a new string which is formed from +# the original string by deleting some (can be none) of the characters +# without disturbing the relative positions of the remaining characters. +# (ie, "ace" is a subsequence of "abcde" while "aec" is not). +# +# Example 1: +# s = "abc", t = "ahbgdc" +# +# Return true. +# +# Example 2: +# s = "axc", t = "ahbgdc" +# +# Return false. + +# Greedy solution. +class Solution(object): + def isSubsequence(self, s, t): + """ + :type s: str + :type t: str + :rtype: bool + """ + if not s: + return True + + i = 0 + for c in t: + if c == s[i]: + i += 1 + if i == len(s): + break + return i == len(s) From c9df5e8038a8ac3779a5d130f61c9d2a7b8ab84f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Sep 2016 00:05:49 +0800 Subject: [PATCH 2762/4971] Create utf-8-validation.cpp --- C++/utf-8-validation.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/utf-8-validation.cpp diff --git a/C++/utf-8-validation.cpp b/C++/utf-8-validation.cpp new file mode 100644 index 000000000..319f94569 --- /dev/null +++ b/C++/utf-8-validation.cpp @@ -0,0 +1,28 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool validUtf8(vector& data) { + int count = 0; + for (const auto& c : data) { + if (count == 0) { + if ((c >> 5) == 0b110) { + count = 1; + } else if ((c >> 4) == 0b1110) { + count = 2; + } else if ((c >> 3) == 0b11110) { + count = 3; + } else if ((c >> 7)) { + return false; + } + } else { + if ((c >> 6) != 0b10) { + return false; + } + --count; + } + } + return count == 0; + } +}; From 208a54ea63728e9ca224f38584c20d6f23b150d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Sep 2016 00:19:41 +0800 Subject: [PATCH 2763/4971] Create utf-8-validation.py --- Python/utf-8-validation.py | 61 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/utf-8-validation.py diff --git a/Python/utf-8-validation.py b/Python/utf-8-validation.py new file mode 100644 index 000000000..6a53dd5ac --- /dev/null +++ b/Python/utf-8-validation.py @@ -0,0 +1,61 @@ +# Time: O(n) +# Space: O(1) + +# A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: +# +# For 1-byte character, the first bit is a 0, followed by its unicode code. +# For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, +# followed by n-1 bytes with most significant 2 bits being 10. +# This is how the UTF-8 encoding would work: +# +# Char. number range | UTF-8 octet sequence +# (hexadecimal) | (binary) +# --------------------+--------------------------------------------- +# 0000 0000-0000 007F | 0xxxxxxx +# 0000 0080-0000 07FF | 110xxxxx 10xxxxxx +# 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx +# 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx +# Given an array of integers representing the data, return whether it is a valid utf-8 encoding. +# +# Note: +# The input is an array of integers. +# Only the least significant 8 bits of each integer is used to store the data. +# This means each integer represents only 1 byte of data. +# +# Example 1: +# +# data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001. +# +# Return true. +# It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. +# Example 2: +# +# data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100. +# +# Return false. +# The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. +# The next byte is a continuation byte which starts with 10 and that's correct. +# But the second continuation byte does not start with 10, so it is invalid. + +class Solution(object): + def validUtf8(self, data): + """ + :type data: List[int] + :rtype: bool + """ + count = 0 + for c in data: + if count == 0: + if (c >> 5) == 0b110: + count = 1 + elif (c >> 4) == 0b1110: + count = 2 + elif (c >> 3) == 0b11110: + count = 3 + elif (c >> 7): + return False + else: + if (c >> 6) != 0b10: + return False + count -= 1 + return count == 0 From 222ccb025eec6e392898363f909de491b70f88bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Sep 2016 00:49:39 +0800 Subject: [PATCH 2764/4971] Create decode-string.cpp --- C++/decode-string.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/decode-string.cpp diff --git a/C++/decode-string.cpp b/C++/decode-string.cpp new file mode 100644 index 000000000..18498c434 --- /dev/null +++ b/C++/decode-string.cpp @@ -0,0 +1,32 @@ +// Time: O(n) +// Space: O(h), h is the depth of the recursion + +class Solution { +public: + string decodeString(string s) { + string curr; + stack nums; + stack strs; + int n = 0; + for (int i = 0; i < s.length(); ++i) { + if (isdigit(s[i])) { + n = n * 10 + s[i] - '0'; + } else if (s[i] == '[') { + nums.emplace(n); + n = 0; + strs.emplace(curr); + curr.clear(); + } else if (s[i] == ']') { + for (; nums.top() > 0; --nums.top()) { + strs.top() += curr; + } + nums.pop(); + curr = strs.top(); + strs.pop(); + } else { + curr += s[i]; + } + } + return strs.empty() ? curr : strs.top(); + } +}; From bb3a36a2e355c86b2a6c2f747945edfa142e1556 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Sep 2016 00:52:37 +0800 Subject: [PATCH 2765/4971] Update decode-string.cpp --- C++/decode-string.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/decode-string.cpp b/C++/decode-string.cpp index 18498c434..07bee9973 100644 --- a/C++/decode-string.cpp +++ b/C++/decode-string.cpp @@ -8,15 +8,15 @@ class Solution { stack nums; stack strs; int n = 0; - for (int i = 0; i < s.length(); ++i) { - if (isdigit(s[i])) { - n = n * 10 + s[i] - '0'; - } else if (s[i] == '[') { + for (const auto& c: s) { + if (isdigit(c)) { + n = n * 10 + c - '0'; + } else if (c == '[') { nums.emplace(n); n = 0; strs.emplace(curr); curr.clear(); - } else if (s[i] == ']') { + } else if (c == ']') { for (; nums.top() > 0; --nums.top()) { strs.top() += curr; } @@ -24,7 +24,7 @@ class Solution { curr = strs.top(); strs.pop(); } else { - curr += s[i]; + curr += c; } } return strs.empty() ? curr : strs.top(); From 255ec157506f1b18afd7dc5a35960c17a3cc02f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Sep 2016 01:20:41 +0800 Subject: [PATCH 2766/4971] Create decode-string.py --- Python/decode-string.py | 47 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/decode-string.py diff --git a/Python/decode-string.py b/Python/decode-string.py new file mode 100644 index 000000000..ab0256f17 --- /dev/null +++ b/Python/decode-string.py @@ -0,0 +1,47 @@ +# Time: O(n) +# Space: O(h), h is the depth of the recursion + +# Given an encoded string, return it's decoded string. +# +# The encoding rule is: k[encoded_string], +# where the encoded_string inside the square brackets is +# being repeated exactly k times. Note that k is guaranteed +# to be a positive integer. +# +# You may assume that the input string is always valid; +# No extra white spaces, square brackets are well-formed, etc. +# +# Furthermore, you may assume that the original data does not +# contain any digits and that digits are only for those repeat numbers, k. +# For example, there won't be input like 3a or 2[4]. +# +# Examples: +# +# s = "3[a]2[bc]", return "aaabcbc". +# s = "3[a2[c]]", return "accaccacc". +# s = "2[abc]3[cd]ef", return "abcabccdcdcdef". + +class Solution(object): + def decodeString(self, s): + """ + :type s: str + :rtype: str + """ + curr, nums, strs = [], [], [] + n = 0 + + for c in s: + if c.isdigit(): + n = n * 10 + ord(c) - ord('0') + elif c == '[': + nums.append(n) + n = 0 + strs.append(curr) + curr = [] + elif c == ']': + strs[-1].extend(curr * nums.pop()) + curr = strs.pop() + else: + curr.append(c) + + return "".join(strs[-1]) if strs else "".join(curr) From 0e7ce3cc207813a7f53273bc0328993ea81efc1c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Sep 2016 11:37:58 +0800 Subject: [PATCH 2767/4971] Create longest-substring-with-at-least-k-repeating-characters.cpp --- ...g-with-at-least-k-repeating-characters.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/longest-substring-with-at-least-k-repeating-characters.cpp diff --git a/C++/longest-substring-with-at-least-k-repeating-characters.cpp b/C++/longest-substring-with-at-least-k-repeating-characters.cpp new file mode 100644 index 000000000..b2f107d16 --- /dev/null +++ b/C++/longest-substring-with-at-least-k-repeating-characters.cpp @@ -0,0 +1,40 @@ +// Time: O(26 * n) = O(n) +// Space: O(26) = O(1) + +// Recursive solution. +class Solution { +public: + int longestSubstring(string s, int k) { + return longestSubstringHelper(s, k, 0, s.size()); + } + +private: + int longestSubstringHelper(const string& s, int k, int start, int end) { + vector count(26); + for (int i = start; i < end; ++i) { + ++count[s[i] - 'a']; + } + + int max_len = 0; + for (int i = start; i < end;) { + while (i < end && count[s[i] - 'a'] < k) { + ++i; + } + if (i == end) { + break; + } + + int j = i; + while (j < end && count[s[j] - 'a'] >= k) { + ++j; + } + if (i == start && j == end) { + return end - start; + } + + max_len = max(max_len, longestSubstringHelper(s, k, i, j)); + i = j; + } + return max_len; + } +}; From 2fadf8025e88e7a3a6b4cb49c143b3f7c03746ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Sep 2016 11:45:33 +0800 Subject: [PATCH 2768/4971] Create longest-substring-with-at-least-k-repeating-characters.py --- ...ng-with-at-least-k-repeating-characters.py | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/longest-substring-with-at-least-k-repeating-characters.py diff --git a/Python/longest-substring-with-at-least-k-repeating-characters.py b/Python/longest-substring-with-at-least-k-repeating-characters.py new file mode 100644 index 000000000..d17bae4d2 --- /dev/null +++ b/Python/longest-substring-with-at-least-k-repeating-characters.py @@ -0,0 +1,55 @@ +# Time: O(26 * n) = O(n) +# Space: O(26) = O(1) + +# Find the length of the longest substring T of a given string +# (consists of lowercase letters only) such that every character in T +# appears no less than k times. +# +# Example 1: +# +# Input: +# s = "aaabb", k = 3 +# +# Output: +# 3 +# +# The longest substring is "aaa", as 'a' is repeated 3 times. +# Example 2: +# +# Input: +# s = "ababbc", k = 2 +# +# Output: +# 5 +# +# The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times. + +# Recursive solution. +class Solution(object): + def longestSubstring(self, s, k): + """ + :type s: str + :type k: int + :rtype: int + """ + def longestSubstringHelper(s, k, start, end): + count = [0] * 26 + for i in xrange(start, end): + count[ord(s[i]) - ord('a')] += 1 + max_len = 0 + i = start + while i < end: + while i < end and count[ord(s[i]) - ord('a')] < k: + i += 1 + j = i + while j < end and count[ord(s[j]) - ord('a')] >= k: + j += 1 + + if i == start and j == end: + return end - start + + max_len = max(max_len, longestSubstringHelper(s, k, i, j)) + i = j + return max_len + + return longestSubstringHelper(s, k, 0, len(s)) From 01fa8194acdec2d0642490b079f46c58a2bd2088 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Sep 2016 11:59:21 +0800 Subject: [PATCH 2769/4971] Update README.md --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f762b2cf..8eb2d57be 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%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-391%20%2F%20395-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-395%20%2F%20395-ff69b4.svg) Up to date (2016-09-04), there are `378` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. @@ -57,6 +57,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 342 | [Power of Four](https://leetcode.com/problems/power-of-four/) | [C++](./C++/power-of-four.cpp) [Python](./Python/power-of-four.py) | _O(1)_ | _O(1)_ | Easy | | 371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./C++/find-the-difference.cpp) [Python](./Python/find-the-difference.py) | _O(n)_ | _O(1)_ | Easy | | +393 | [UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./C++/utf-8-validation.cpp) [Python](./Python/utf-8-validation.py) | _O(n)_ | _O(1)_ | Medium | | ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -167,6 +168,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 ||| 341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(h)_ | Medium |📖| Iterator | 385| [Mini Parser](https://leetcode.com/problems/mini-parser/)| [C++](./C++/mini-parser.cpp) [Python](./Python/mini-parser.py) | _O(n)_ | _O(h)_ | Medium ||| +394| [Decode String](https://leetcode.com/problems/decode-string/)| [C++](./C++/decode-string.cpp) [Python](./Python/decode-string.py) | _O(n)_ | _O(h)_ | Medium ||| ## Queue @@ -336,6 +338,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 || 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 |📖| 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 || +395| [Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./C++/longest-substring-with-at-least-k-repeating-characters.cpp) [Python](./Python/longest-substring-with-at-least-k-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || ## Binary Search # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -491,6 +494,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || 376| [Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/)| [C++](./C++/wiggle-subsequence.cpp) [Python](./Python/wiggle-subsequence.py) | _O(n)_ | _O(1)_ | Medium || +392| [Is Subsequence](https://leetcode.com/problems/is-subsequence/)| [C++](./C++/is-subsequence.cpp) [Python](./Python/is-subsequence.py) | _O(n)_ | _O(1)_ | Medium || --- ## Design From d142de5497c30c3c8ba507faba441756720f88a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Sep 2016 12:00:42 +0800 Subject: [PATCH 2770/4971] Update is-subsequence.cpp --- C++/is-subsequence.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/is-subsequence.cpp b/C++/is-subsequence.cpp index 96c9526b2..9be890d17 100644 --- a/C++/is-subsequence.cpp +++ b/C++/is-subsequence.cpp @@ -8,6 +8,7 @@ class Solution { if (s.empty()) { return true; } + int i = 0; for (const auto& c : t) { if (c == s[i]) { From 23a2f51fcc007cc5f829e349615d6db3346b2e2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Sep 2016 23:56:08 +0800 Subject: [PATCH 2771/4971] Update and rename generateTrees.cpp to unique-binary-search-trees-ii.cpp --- C++/generateTrees.cpp | 41 ------------------- C++/unique-binary-search-trees-ii.cpp | 57 +++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 41 deletions(-) delete mode 100644 C++/generateTrees.cpp create mode 100644 C++/unique-binary-search-trees-ii.cpp diff --git a/C++/generateTrees.cpp b/C++/generateTrees.cpp deleted file mode 100644 index 00c304e8b..000000000 --- a/C++/generateTrees.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// Time Complexity: O( (2n, n) / n ) ~= O( 4^n / n^(3/2) ) -// Space Complexity: O( (2n, n) ) ~= O( 4^n / n^(1/2) ) - -/** - * Definition for binary tree - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - public: - vector generateTrees(int n) { - return generate(1, n); - } - private: - vector generate(int begin, int end) { - vector subTree; - if(begin > end) { - subTree.push_back(NULL); - } - - for(int k = begin; k <= end; ++k) { - vector leftSubTree = generate(begin, k - 1); - vector rightSubTree = generate(k + 1, end); - - for(auto i : leftSubTree) { - for(auto j : rightSubTree) { - TreeNode *node = new TreeNode(k); - node->left = i; - node->right = j; - subTree.push_back(node); - } - } - } - - return subTree; - } -}; diff --git a/C++/unique-binary-search-trees-ii.cpp b/C++/unique-binary-search-trees-ii.cpp new file mode 100644 index 000000000..a26e83c9f --- /dev/null +++ b/C++/unique-binary-search-trees-ii.cpp @@ -0,0 +1,57 @@ +// Time: O(n * 4^n / n^(3/2)) ~= Catalan numbers +// 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 generateTrees(int n) { + if (n == 0) { + return {}; + } + return generateTreesHelper(1, n); + } + +private: + vector generateTreesHelper(int start, int end) { + vector result; + if (start > end) { + result.emplace_back(nullptr); + return result; + } + + for (int i = start; i <= end; ++i) { + vector leftSubTrees = generateTreesHelper(start, i - 1); + vector rightSubTrees = generateTreesHelper(i + 1, end); + for (const auto& left : leftSubTrees) { + for (const auto& right : rightSubTrees) { + TreeNode *root = new TreeNode(i); + root->left = clone(left); + root->right = clone(right); + result.emplace_back(root); + } + } + + } + return result; + } + + TreeNode *clone(TreeNode *root) { + TreeNode *newRoot = nullptr; + + if (root) { + newRoot = new TreeNode(root->val); + newRoot->left = clone(root->left); + newRoot->right = clone(root->right); + } + + return newRoot; + } +}; From 438fd1979cf7cc214c565f3fc7ffd3018642eeea Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Sep 2016 23:56:40 +0800 Subject: [PATCH 2772/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8eb2d57be..241e1aea4 100644 --- a/README.md +++ b/README.md @@ -318,7 +318,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Recursion # | 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 || +95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [C++](./C++/unique-binary-search-trees-ii.cpp) [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 || From f2ff2107624337ae33511a290f7a6fd8339f8c66 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Sep 2016 23:19:16 +0800 Subject: [PATCH 2773/4971] Update and rename isValidBST.cpp to validate-binary-search-tree.cpp --- C++/isValidBST.cpp | 35 -------------------------- C++/validate-binary-search-tree.cpp | 39 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 35 deletions(-) delete mode 100644 C++/isValidBST.cpp create mode 100644 C++/validate-binary-search-tree.cpp diff --git a/C++/isValidBST.cpp b/C++/isValidBST.cpp deleted file mode 100644 index cb8359ba7..000000000 --- a/C++/isValidBST.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(logn) - -/** - * Definition for binary tree - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - public: - bool isValidBST(TreeNode *root) { - if(!root) - return true; - - if(!isValidBST(root->left)) - return false; - - if(last && last != root && last->val >= root->val) - return false; - - last = root; - - if(!isValidBST(root->right)) - return false; - - return true; - } - - private: - TreeNode *last; -}; diff --git a/C++/validate-binary-search-tree.cpp b/C++/validate-binary-search-tree.cpp new file mode 100644 index 000000000..0aa1d8904 --- /dev/null +++ b/C++/validate-binary-search-tree.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: + bool isValidBST(TreeNode* root) { + if (!root) { + return true; + } + + if (!isValidBST(root->left)) { + return false; + } + + if (last && last != root && last->val >= root->val) { + return false; + } + + last = root; + + if (!isValidBST(root->right)) { + return false; + } + + return true; + } + +private: + TreeNode *last = nullptr; +}; From b1c9a2851a1f05a998a118a3267c402fa2cbb232 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Sep 2016 23:20:45 +0800 Subject: [PATCH 2774/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 241e1aea4..6ebdd6734 100644 --- a/README.md +++ b/README.md @@ -319,7 +319,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [C++](./C++/unique-binary-search-trees-ii.cpp) [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 || +98| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[C++](./C++/validate-binary-search-tree.cpp) [Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(h)_ | 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 || From ab7cd594f601902f4dd9edafbb4379d4a3b9da6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Sep 2016 23:21:08 +0800 Subject: [PATCH 2775/4971] Update validate-binary-search-tree.py --- Python/validate-binary-search-tree.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Python/validate-binary-search-tree.py b/Python/validate-binary-search-tree.py index 7e329c4cf..8425ef443 100644 --- a/Python/validate-binary-search-tree.py +++ b/Python/validate-binary-search-tree.py @@ -45,9 +45,10 @@ def isValidBST(self, root): cur = cur.right return True - + + # Time: O(n) -# Space: O(logn) +# Space: O(h) class Solution2: # @param root, a tree node # @return a boolean @@ -61,6 +62,7 @@ def isValidBSTRecu(self, root, low, high): return low < root.val and root.val < high \ and self.isValidBSTRecu(root.left, low, root.val) \ and self.isValidBSTRecu(root.right, root.val, high) + if __name__ == "__main__": root = TreeNode(2) From 04e3f90265148355eb2683478fa18d916e72e882 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Sep 2016 23:54:37 +0800 Subject: [PATCH 2776/4971] Update validate-binary-search-tree.cpp --- C++/validate-binary-search-tree.cpp | 41 ++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/C++/validate-binary-search-tree.cpp b/C++/validate-binary-search-tree.cpp index 0aa1d8904..4ac6bab20 100644 --- a/C++/validate-binary-search-tree.cpp +++ b/C++/validate-binary-search-tree.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(h) +// Space: O(1) /** * Definition for a binary tree node. @@ -10,7 +10,46 @@ * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ + +// Morris Traversal class Solution { +public: + bool isValidBST(TreeNode* root) { + TreeNode *prev = nullptr; + TreeNode *curr = root; + while (curr) { + if (!curr->left) { + if (prev && prev->val >= curr->val) { + return false; + } + prev = curr; + curr = curr->right; + } else { + TreeNode *node = curr->left; + while (node->right && node->right != curr) { + node = node->right; + } + if (!node->right) { + node->right = curr; + curr = curr->left; + } else { + if (prev && prev->val >= curr->val) { + return false; + } + prev = curr; + node->right = nullptr; + curr = curr->right; + } + } + } + + return true; + } +}; + +// Time: O(n) +// Space: O(h) +class Solution2 { public: bool isValidBST(TreeNode* root) { if (!root) { From 997b0490555370799dd4c75a1aaae01b1456953b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Sep 2016 23:55:06 +0800 Subject: [PATCH 2777/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6ebdd6734..57d111d1e 100644 --- a/README.md +++ b/README.md @@ -319,7 +319,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [C++](./C++/unique-binary-search-trees-ii.cpp) [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/)|[C++](./C++/validate-binary-search-tree.cpp) [Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(h)_ | Medium || +98| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[C++](./C++/validate-binary-search-tree.cpp) [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 || From d5f9506f18f4a8a09bbb4e6064982d16b74222a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Sep 2016 23:50:02 +0800 Subject: [PATCH 2778/4971] Create same-tree.cpp --- C++/same-tree.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/same-tree.cpp diff --git a/C++/same-tree.cpp b/C++/same-tree.cpp new file mode 100644 index 000000000..6fa9f9dad --- /dev/null +++ b/C++/same-tree.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(h), h is height of binary tree + +/** + * 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: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (!p && !q) { + return true; + } + return p && q && p->val == q->val && + isSameTree(p->left, q->left) && + isSameTree(p->right, q->right); + } +}; From ba5cd71d6cff4b71a3eb9572cd1897e2ab1f3dc8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Sep 2016 23:51:05 +0800 Subject: [PATCH 2779/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 57d111d1e..74d9e5862 100644 --- a/README.md +++ b/README.md @@ -320,7 +320,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [C++](./C++/unique-binary-search-trees-ii.cpp) [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/)|[C++](./C++/validate-binary-search-tree.cpp) [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 || +100| [Same Tree](https://leetcode.com/problems/same-tree/) |[C+](./C++/same-tree.cpp) [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 || From 59d07f29e4facb5125bfb2955f81e694fc5030cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Sep 2016 22:31:50 +0800 Subject: [PATCH 2780/4971] Update and rename maxDepth.cpp to maximum-depth-of-binary-tree.cpp --- ...maxDepth.cpp => maximum-depth-of-binary-tree.cpp} | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) rename C++/{maxDepth.cpp => maximum-depth-of-binary-tree.cpp} (51%) diff --git a/C++/maxDepth.cpp b/C++/maximum-depth-of-binary-tree.cpp similarity index 51% rename from C++/maxDepth.cpp rename to C++/maximum-depth-of-binary-tree.cpp index df822474a..23c2cdc8d 100644 --- a/C++/maxDepth.cpp +++ b/C++/maximum-depth-of-binary-tree.cpp @@ -1,5 +1,8 @@ +// Time: O(n) +// Space: O(h) + /** - * Definition for binary tree + * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; @@ -9,9 +12,10 @@ */ class Solution { public: - int maxDepth(TreeNode *root) { - if(!root) + int maxDepth(TreeNode* root) { + if (!root) { return 0; - return max(maxDepth(root->left), maxDepth(root->right))+1; + } + return max(maxDepth(root->left), maxDepth(root->right)) + 1; } }; From 1362d65809bd451a6641cea377c4dfca45fc5a09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Sep 2016 22:32:27 +0800 Subject: [PATCH 2781/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 74d9e5862..de2804df8 100644 --- a/README.md +++ b/README.md @@ -321,7 +321,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [C++](./C++/unique-binary-search-trees-ii.cpp) [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/)|[C++](./C++/validate-binary-search-tree.cpp) [Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || 100| [Same Tree](https://leetcode.com/problems/same-tree/) |[C+](./C++/same-tree.cpp) [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 || +104| [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)| [C++](./C++/maximum-depth-of-binary-tree.cpp) [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 || From bcd05cd0e99657aac1ac0d3b0e6bb06acd4a5273 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Sep 2016 22:58:33 +0800 Subject: [PATCH 2782/4971] Create rotate-function.py --- Python/rotate-function.py | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/rotate-function.py diff --git a/Python/rotate-function.py b/Python/rotate-function.py new file mode 100644 index 000000000..654d6aa9d --- /dev/null +++ b/Python/rotate-function.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(1) + +# Given an array of integers A and let n to be its length. +# +# Assume Bk to be an array obtained by rotating the array A +# k positions clock-wise, we define a "rotation function" F on A as follow: +# +# F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]. +# +# Calculate the maximum value of F(0), F(1), ..., F(n-1). +# +# Note: +# n is guaranteed to be less than 105. +# +# Example: +# +# A = [4, 3, 2, 6] +# +# F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 +# F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 +# F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 +# F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 +# +# So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. + +class Solution(object): + def maxRotateFunction(self, A): + """ + :type A: List[int] + :rtype: int + """ + s = sum(A) + fi = 0 + for i in xrange(len(A)): + fi += i * A[i] + + result = fi + for i in xrange(1, len(A)+1): + fi += s - len(A) * A[-i] + result = max(result, fi) + return result From d2d03d38099786218ce0092182951a346525e9ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Sep 2016 23:03:33 +0800 Subject: [PATCH 2783/4971] Create rotate-function.cpp --- C++/rotate-function.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/rotate-function.cpp diff --git a/C++/rotate-function.cpp b/C++/rotate-function.cpp new file mode 100644 index 000000000..fb15b424d --- /dev/null +++ b/C++/rotate-function.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int maxRotateFunction(vector& A) { + int sum = accumulate(A.begin(), A.end(), 0); + int fi = 0; + for (int i = 0; i < A.size(); ++i) { + fi += i * A[i]; + } + + int result = fi; + for (int i = 1; i <= A.size(); ++i) { + fi += sum - A.size() * A[A.size() - i]; + result = max(result, fi); + } + return result; + } +}; From 261c1a68d9131d06835382b7f00792b39db6fce0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 00:12:07 +0800 Subject: [PATCH 2784/4971] Create integer-replacement.cpp --- C++/integer-replacement.cpp | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 C++/integer-replacement.cpp diff --git a/C++/integer-replacement.cpp b/C++/integer-replacement.cpp new file mode 100644 index 000000000..9539e1c8f --- /dev/null +++ b/C++/integer-replacement.cpp @@ -0,0 +1,55 @@ +// Time: O(logn) +// Space: O(1) + +// Iterative solution. +class Solution { +public: + int integerReplacement(int n) { + if (n == 2147483647) { + return 2 + integerReplacement(n / 2 + 1); + } + + int result = 0; + while (n != 1) { + const auto b = n & 3; + if (n == 3) { + --n; + } else if (b == 3) { + ++n; + } else if (b == 1) { + --n; + } else { + n /= 2; + } + ++result; + } + return result; + } +}; + +// Time: O(logn) +// Space: O(logn) +// Recursive solution +class Solution2 { +public: + int integerReplacement(int n) { + if (n == 2147483647) { + return 2 + integerReplacement(n / 2 + 1); + } + + if (n < 4) { + switch (n % 4) { + case 0: case 1: return 0; + case 2: return 1; + case 3: return 2; + } + } + + switch (n % 4) { + case 0: case 2: return integerReplacement(n / 2) + 1; + case 1: return integerReplacement((n - 1) / 4) + 3; + case 3: return integerReplacement((n + 1) / 4) + 3; + } + return 0; + } +}; From c2c5ed179e51ae8cab3ef31adcbf540204059ba5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 00:16:25 +0800 Subject: [PATCH 2785/4971] Create integer-replacement.py --- Python/integer-replacement.py | 73 +++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Python/integer-replacement.py diff --git a/Python/integer-replacement.py b/Python/integer-replacement.py new file mode 100644 index 000000000..8ec74bf04 --- /dev/null +++ b/Python/integer-replacement.py @@ -0,0 +1,73 @@ +# Time: O(logn) +# Space: O(1) + +# Given a positive integer n and you can do operations as follow: +# +# If n is even, replace n with n/2. +# If n is odd, you can replace n with either n + 1 or n - 1. +# What is the minimum number of replacements needed for n to become 1? +# +# Example 1: +# +# Input: +# 8 +# +# Output: +# 3 +# +# Explanation: +# 8 -> 4 -> 2 -> 1 +# Example 2: +# +# Input: +# 7 +# +# Output: +# 4 +# +# Explanation: +# 7 -> 8 -> 4 -> 2 -> 1 +# or +# 7 -> 6 -> 3 -> 2 -> 1 + +# Iterative solution. +class Solution(object): + def integerReplacement(self, n): + """ + :type n: int + :rtype: int + """ + result = 0 + while n != 1: + b = n & 3 + if n == 3: + n -= 1 + elif b == 3: + n += 1 + elif b == 1: + n -= 1 + else: + n /= 2 + result += 1 + + return result + + +# Time: O(logn) +# Space: O(logn) +# Recursive solution. +class Solution2(object): + def integerReplacement(self, n): + """ + :type n: int + :rtype: int + """ + if n < 4: + return [0, 0, 1, 2][n] + if n % 4 in (0, 2): + return self.integerReplacement(n / 2) + 1 + elif n % 4 == 1: + return self.integerReplacement((n - 1) / 4) + 3 + else: + return self.integerReplacement((n + 1) / 4) + 3 + From 09ac3a56139f9c525e71eef6e958c8e5b9f782a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 00:37:31 +0800 Subject: [PATCH 2786/4971] Create random-pick-index.cpp --- C++/random-pick-index.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/random-pick-index.cpp diff --git a/C++/random-pick-index.cpp b/C++/random-pick-index.cpp new file mode 100644 index 000000000..32ed28e72 --- /dev/null +++ b/C++/random-pick-index.cpp @@ -0,0 +1,32 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + Solution(vector nums) : nums_(nums) { + + } + + int pick(int target) { + auto reservoir = -1; + int n = 0; + for (int i = 0; i < nums_.size(); ++i) { + if (nums_[i] != target) { + continue; + } + if (++n == 1 || rand() % n == 0) { + reservoir = i; + } + } + return reservoir; + } + +private: + const vector nums_; +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(nums); + * int param_1 = obj.pick(target); + */ From 16d8a9b29add2e252198a5ca29f69a6ec0e489d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 00:48:15 +0800 Subject: [PATCH 2787/4971] Create random-pick-index.py --- Python/random-pick-index.py | 53 +++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/random-pick-index.py diff --git a/Python/random-pick-index.py b/Python/random-pick-index.py new file mode 100644 index 000000000..59fbaadf9 --- /dev/null +++ b/Python/random-pick-index.py @@ -0,0 +1,53 @@ +# Time: O(n) +# Space: O(1) + +# Given an array of integers with possible duplicates, +# randomly output the index of a given target number. +# You can assume that the given target number must exist in the array. +# +# Note: +# The array size can be very large. +# Solution that uses too much extra space will not pass the judge. +# +# Example: +# +# int[] nums = new int[] {1,2,3,3,3}; +# Solution solution = new Solution(nums); +# +# // pick(3) should return either index 2, 3, or 4 randomly. +# Each index should have equal probability of returning. +# solution.pick(3); +# +# // pick(1) should return 0. Since in the array only nums[0] is equal to 1. +# solution.pick(1); + +from random import randint + +class Solution(object): + + def __init__(self, nums): + """ + + :type nums: List[int] + :type numsSize: int + """ + self.__nums = nums + + def pick(self, target): + """ + :type target: int + :rtype: int + """ + reservoir = -1 + n = 0 + for i in xrange(len(self.__nums)): + if self.__nums[i] != target: + continue + reservoir = i if n == 0 or randint(1, n+1) == 1 else reservoir + n += 1 + return reservoir + + +# Your Solution object will be instantiated and called as such: +# obj = Solution(nums) +# param_1 = obj.pick(target) From e0ee644ee0ff3e63585b470d36a804a12e52ffbb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 01:11:00 +0800 Subject: [PATCH 2788/4971] Create evaluate-division.cpp --- C++/evaluate-division.cpp | 48 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 C++/evaluate-division.cpp diff --git a/C++/evaluate-division.cpp b/C++/evaluate-division.cpp new file mode 100644 index 000000000..ae4da0db8 --- /dev/null +++ b/C++/evaluate-division.cpp @@ -0,0 +1,48 @@ +// Time: O(e + q * e) +// Space: O(e) + +class Solution { +public: + vector calcEquation(vector> equations, + vector& values, vector> query) { + + unordered_map> lookup; + vector result; + for (int i = 0; i < values.size(); ++i) { + lookup[equations[i].first].emplace(equations[i].second, values[i]); + if (values[i] != 0) { + lookup[equations[i].second].emplace(equations[i].first, 1 / values[i]); + } + } + + for (const auto& i : query) { + unordered_set visited; + auto tmp = check(i.first, i.second, lookup, &visited); + if (tmp.first) { + result.emplace_back(tmp.second); + } else { + result.emplace_back(-1); + } + } + return result; + } + +private: + pair check(string up, string down, + unordered_map> &lookup, + unordered_set *visited) { + if (lookup[up].find(down) != lookup[up].end()) { + return {true, lookup[up][down]}; + } + for (const auto& i : lookup[up]) { + if (!visited->count(i.first)) { + visited->emplace(i.first); + const auto tmp = check(i.first, down, lookup, visited); + if (tmp.first) { + return {true, i.second * tmp.second}; + } + } + } + return {false, 0}; + } +}; From 171582a16400831bfb95cde7b063a63f79aaffe5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 01:14:14 +0800 Subject: [PATCH 2789/4971] Update evaluate-division.cpp --- C++/evaluate-division.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/evaluate-division.cpp b/C++/evaluate-division.cpp index ae4da0db8..5617e9b7e 100644 --- a/C++/evaluate-division.cpp +++ b/C++/evaluate-division.cpp @@ -7,7 +7,6 @@ class Solution { vector& values, vector> query) { unordered_map> lookup; - vector result; for (int i = 0; i < values.size(); ++i) { lookup[equations[i].first].emplace(equations[i].second, values[i]); if (values[i] != 0) { @@ -15,6 +14,7 @@ class Solution { } } + vector result; for (const auto& i : query) { unordered_set visited; auto tmp = check(i.first, i.second, lookup, &visited); @@ -34,12 +34,12 @@ class Solution { if (lookup[up].find(down) != lookup[up].end()) { return {true, lookup[up][down]}; } - for (const auto& i : lookup[up]) { - if (!visited->count(i.first)) { - visited->emplace(i.first); - const auto tmp = check(i.first, down, lookup, visited); + for (const auto& q : lookup[up]) { + if (!visited->count(q.first)) { + visited->emplace(q.first); + const auto tmp = check(q.first, down, lookup, visited); if (tmp.first) { - return {true, i.second * tmp.second}; + return {true, q.second * tmp.second}; } } } From 06c90ce11ea7ade88f3f8ff6e7abe3eeaed41b36 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 01:23:40 +0800 Subject: [PATCH 2790/4971] Update evaluate-division.cpp --- C++/evaluate-division.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/evaluate-division.cpp b/C++/evaluate-division.cpp index 5617e9b7e..983d5886d 100644 --- a/C++/evaluate-division.cpp +++ b/C++/evaluate-division.cpp @@ -6,7 +6,7 @@ class Solution { vector calcEquation(vector> equations, vector& values, vector> query) { - unordered_map> lookup; + unordered_map> lookup; for (int i = 0; i < values.size(); ++i) { lookup[equations[i].first].emplace(equations[i].second, values[i]); if (values[i] != 0) { @@ -29,7 +29,7 @@ class Solution { private: pair check(string up, string down, - unordered_map> &lookup, + unordered_map> &lookup, unordered_set *visited) { if (lookup[up].find(down) != lookup[up].end()) { return {true, lookup[up][down]}; From bdbb65f4dff5586b7cefee7b9f96c3c85653dfc9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 01:28:53 +0800 Subject: [PATCH 2791/4971] Create evaluate-division.py --- Python/evaluate-division.py | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/evaluate-division.py diff --git a/Python/evaluate-division.py b/Python/evaluate-division.py new file mode 100644 index 000000000..896b94b29 --- /dev/null +++ b/Python/evaluate-division.py @@ -0,0 +1,56 @@ +# Time: O(e + q * e) +# Space: O(e) + +# Equations are given in the format A / B = k, +# where A and B are variables represented as strings, +# and k is a real number (floating point number). +# Given some queries, return the answers. +# If the answer does not exist, return -1.0. +# +# Example: +# Given a / b = 2.0, b / c = 3.0. +# queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? . +# return [6.0, 0.5, -1.0, 1.0, -1.0 ]. +# +# The input is: +# vector> euqations, vector& values, vector> query . +# +# where equations.size() == values.size(),the values are positive. +# this represents the equations.return vector. . +# The example above: equations = [ ["a", "b"], ["b", "c"] ]. +# values = [2.0, 3.0]. queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. +# +# The input is always valid. You may assume that +# evaluating the queries will result in no division by zero and there is no contradiction. + +class Solution(object): + def calcEquation(self, equations, values, query): + """ + :type equations: List[List[str]] + :type values: List[float] + :type query: List[List[str]] + :rtype: List[float] + """ + def check(up, down, lookup, visited): + if up in lookup and down in lookup[up]: + return (True, lookup[up][down]) + for k, v in lookup[up].iteritems(): + if k not in visited: + visited.add(k) + tmp = check(k, down, lookup, visited) + if tmp[0]: + return (True, v * tmp[1]) + return (False, 0) + + lookup = collections.defaultdict(dict) + for i, e in enumerate(equations): + lookup[e[0]][e[1]] = values[i] + if values[i]: + lookup[e[1]][e[0]] = 1.0 / values[i] + + result = [] + for q in query: + visited = set() + tmp = check(q[0], q[1], lookup, visited) + result.append(tmp[1] if tmp[0] else -1) + return result From 5cfa682bf73002c11244d539b73d32ff4db3a0e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 01:38:52 +0800 Subject: [PATCH 2792/4971] Update README.md --- README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index de2804df8..d8960f3e3 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-395%20%2F%20395-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-399%20%2F%20399-ff69b4.svg) -Up to date (2016-09-04), there are `378` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-09-11), there are `382` 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 `395` questions. +Here is the classification of all `399` 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.) @@ -101,6 +101,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 ||| 370| [Range Addition](https://leetcode.com/problems/range-addition/) | [C++](./C++/range-addition.cpp) [Python](./Python/range-addition.py) | _O(k + n)_ | _O(1)_ | Medium |📖|| 384| [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [C++](./C++/shuffle-an-array.cpp) [Python](./Python/shuffle-an-array.py) | _O(n)_ | _O(n)_ | Medium | EPI || +396| [Rotate Function](https://leetcode.com/problems/rotate-function/) | [C++](./C++/rotate-function.cpp) [Python](./Python/rotate-function.py) | _O(n)_ | _O(1)_ | Easy ||| ## String # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -277,6 +278,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| 390 | [Elimination Game](https://leetcode.com/contest/2/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium | 2nd Contest | 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./C++/perfect-rectangle.cpp) [Python](./Python/perfect-rectangle.py) | _O(n)_ | _O(n)_ | Hard | | +398 | [Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./C++/random-pick-index.cpp) [Python](./Python/random-pick-index.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -409,6 +411,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 339| [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) | [C++](./C++/nested-list-weight-sum.cpp) [Python](./Python/nested-list-weight-sum.py) | _O(n)_ | _O(h)_ | Easy |📖|| 364| [Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii/) | [C++](./C++/nested-list-weight-sum-ii.cpp) [Python](./Python/nested-list-weight-sum-ii.py) | _O(n)_ | _O(h)_ | Medium |📖|| 366| [Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/) | [C++](./C++/find-leaves-of-binary-tree.cpp) [Python](./Python/find-leaves-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium |📖|| +399| [Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./C++/evaluate-division.cpp) [Python](./Python/evaluate-division.py) | _O(q * |V|!)_ | _O(e)_ | Medium ||| ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -495,6 +498,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || 376| [Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/)| [C++](./C++/wiggle-subsequence.cpp) [Python](./Python/wiggle-subsequence.py) | _O(n)_ | _O(1)_ | Medium || 392| [Is Subsequence](https://leetcode.com/problems/is-subsequence/)| [C++](./C++/is-subsequence.cpp) [Python](./Python/is-subsequence.py) | _O(n)_ | _O(1)_ | Medium || +397| [Integer Replacement](https://leetcode.com/problems/integer-replacement/)| [C++](./C++/integer-replacement.cpp) [Python](./Python/integer-replacement.py) | _O(n)_ | _O(1)_ | Easy || Math --- ## Design From dd82b9ba507cc4725d3e6eba5700c5cfc175ab98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 01:39:12 +0800 Subject: [PATCH 2793/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d8960f3e3..c2583953f 100644 --- a/README.md +++ b/README.md @@ -411,7 +411,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 339| [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) | [C++](./C++/nested-list-weight-sum.cpp) [Python](./Python/nested-list-weight-sum.py) | _O(n)_ | _O(h)_ | Easy |📖|| 364| [Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii/) | [C++](./C++/nested-list-weight-sum-ii.cpp) [Python](./Python/nested-list-weight-sum-ii.py) | _O(n)_ | _O(h)_ | Medium |📖|| 366| [Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/) | [C++](./C++/find-leaves-of-binary-tree.cpp) [Python](./Python/find-leaves-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium |📖|| -399| [Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./C++/evaluate-division.cpp) [Python](./Python/evaluate-division.py) | _O(q * |V|!)_ | _O(e)_ | Medium ||| +399| [Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./C++/evaluate-division.cpp) [Python](./Python/evaluate-division.py) | _O(q * \|V\|!)_ | _O(e)_ | Medium ||| ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note From d7b46494135f9baa19f751ab16027b054a32c213 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 01:39:49 +0800 Subject: [PATCH 2794/4971] Update evaluate-division.cpp --- C++/evaluate-division.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/evaluate-division.cpp b/C++/evaluate-division.cpp index 983d5886d..d030a551c 100644 --- a/C++/evaluate-division.cpp +++ b/C++/evaluate-division.cpp @@ -1,4 +1,4 @@ -// Time: O(e + q * e) +// Time: O(e + q * |V|), |V| is the number of variables // Space: O(e) class Solution { From 4c12a357e73d443a3c248b6a6fd0e784b0be15ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 01:41:03 +0800 Subject: [PATCH 2795/4971] Update evaluate-division.py --- Python/evaluate-division.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/evaluate-division.py b/Python/evaluate-division.py index 896b94b29..bf1399601 100644 --- a/Python/evaluate-division.py +++ b/Python/evaluate-division.py @@ -1,4 +1,4 @@ -# Time: O(e + q * e) +# Time: O(e + q * |V|!), |V| is the number of variables # Space: O(e) # Equations are given in the format A / B = k, From df530d2710d8175d6c5feac688cc4f83468da51a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 01:44:19 +0800 Subject: [PATCH 2796/4971] Update evaluate-division.cpp --- C++/evaluate-division.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/evaluate-division.cpp b/C++/evaluate-division.cpp index d030a551c..dae4b7185 100644 --- a/C++/evaluate-division.cpp +++ b/C++/evaluate-division.cpp @@ -17,7 +17,7 @@ class Solution { vector result; for (const auto& i : query) { unordered_set visited; - auto tmp = check(i.first, i.second, lookup, &visited); + const auto tmp = check(i.first, i.second, lookup, &visited); if (tmp.first) { result.emplace_back(tmp.second); } else { From edd3863ce2d03816c6bed6ab8c21e9164d8326d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 11:41:49 +0800 Subject: [PATCH 2797/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c2583953f..f3de3b5a3 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,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| [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 ||| +299| [Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/) | [C++](./C++/bulls-and-cows.cpp) [Python](./Python/bulls-and-cows.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 From f75ac75340e57003f02d4763d1e9c51c933f5141 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 11:42:34 +0800 Subject: [PATCH 2798/4971] Rename bulls-and-cow.py to bulls-and-cows.py --- Python/{bulls-and-cow.py => bulls-and-cows.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{bulls-and-cow.py => bulls-and-cows.py} (100%) diff --git a/Python/bulls-and-cow.py b/Python/bulls-and-cows.py similarity index 100% rename from Python/bulls-and-cow.py rename to Python/bulls-and-cows.py From 26794f9deadb9fd1405bb44a6a7dc3eefac59094 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Sep 2016 11:43:16 +0800 Subject: [PATCH 2799/4971] Rename bulls-and-cow.cpp to bulls-and-cows.cpp --- C++/{bulls-and-cow.cpp => bulls-and-cows.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{bulls-and-cow.cpp => bulls-and-cows.cpp} (100%) diff --git a/C++/bulls-and-cow.cpp b/C++/bulls-and-cows.cpp similarity index 100% rename from C++/bulls-and-cow.cpp rename to C++/bulls-and-cows.cpp From 99beaaf0f91d0eba37994aa020cc10ded87acf4d Mon Sep 17 00:00:00 2001 From: Vijay Mahantesh SM Date: Mon, 12 Sep 2016 09:44:49 -0700 Subject: [PATCH 2800/4971] Update water-and-jug-problem.py --- Python/water-and-jug-problem.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Python/water-and-jug-problem.py b/Python/water-and-jug-problem.py index beb3af951..20030b4ad 100644 --- a/Python/water-and-jug-problem.py +++ b/Python/water-and-jug-problem.py @@ -22,7 +22,11 @@ # Input: x = 2, y = 6, z = 5 # Output: False -from fractions import gcd + +def gcd(a, b): + while b: + a, b = b, a%b + return a class Solution(object): def canMeasureWater(self, x, y, z): @@ -32,7 +36,4 @@ def canMeasureWater(self, x, y, z): :type z: int :rtype: bool """ - # The problem is to solve: - # - check z <= max(x, y) - # - check if there is any (a, b) integers s.t. ax + by = z - return z <= max(x, y) and z % gcd(x, y) == 0 + return z == 0 or ((x + y >= z) and (z % gcd(x, y) == 0)) From fb8093aa5bc646a462aed2c29d963855b85b041c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Sep 2016 13:38:38 +0800 Subject: [PATCH 2801/4971] Update water-and-jug-problem.cpp --- C++/water-and-jug-problem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/water-and-jug-problem.cpp b/C++/water-and-jug-problem.cpp index f8b1b053c..21c402d2a 100644 --- a/C++/water-and-jug-problem.cpp +++ b/C++/water-and-jug-problem.cpp @@ -4,7 +4,7 @@ class Solution { public: bool canMeasureWater(int x, int y, int z) { - return z <= max(x, y) && z % gcd(x, y) == 0; + return z == 0 || (z <= x + y && z % gcd(x, y) == 0); } private: From 0cee535be055ad47b0e9545fb702b989e6a34073 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Sep 2016 21:26:40 +0800 Subject: [PATCH 2802/4971] Rename range-addition .py to range-addition.py --- Python/{range-addition .py => range-addition.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{range-addition .py => range-addition.py} (100%) diff --git a/Python/range-addition .py b/Python/range-addition.py similarity index 100% rename from Python/range-addition .py rename to Python/range-addition.py From fc05d8e217d0ae1bd460b45b1994bafeb10e18d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 14 Sep 2016 23:26:49 +0800 Subject: [PATCH 2803/4971] Update evaluate-division.cpp --- C++/evaluate-division.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/evaluate-division.cpp b/C++/evaluate-division.cpp index dae4b7185..7db86be31 100644 --- a/C++/evaluate-division.cpp +++ b/C++/evaluate-division.cpp @@ -1,4 +1,4 @@ -// Time: O(e + q * |V|), |V| is the number of variables +// Time: O(e + q * |V|!), |V| is the number of variables // Space: O(e) class Solution { From e2cd472eda96f200981f0fac37d168cf4014cf0a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Sep 2016 14:28:10 +0800 Subject: [PATCH 2804/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f3de3b5a3..5f68b3e31 100644 --- a/README.md +++ b/README.md @@ -207,7 +207,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Hash Table # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Medium || +1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Easy || 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [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/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || @@ -307,7 +307,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/)| [C++](./C++/reorder-list.cpp) [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/) | [C++](./C++/two-sum-ii-input-array-is-sorted.cpp) [Python](./Python/two-sum-ii-input-array-is-sorted.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/) | [C++](./C++/two-sum-ii-input-array-is-sorted.cpp) [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 Zeroes](https://leetcode.com/problems/move-zeroes/) | [C++](./C++/move-zeroes.cpp) [Python](./Python/move-zeroes.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 | From e74db9a3eaf2958dc7a70be317beb9e3b7d76792 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Sep 2016 17:13:08 +0800 Subject: [PATCH 2805/4971] Update and rename maxArea.cpp to container-with-most-water.cpp --- C++/container-with-most-water.cpp | 20 ++++++++++++++++++++ C++/maxArea.cpp | 21 --------------------- 2 files changed, 20 insertions(+), 21 deletions(-) create mode 100644 C++/container-with-most-water.cpp delete mode 100644 C++/maxArea.cpp diff --git a/C++/container-with-most-water.cpp b/C++/container-with-most-water.cpp new file mode 100644 index 000000000..acaa98efe --- /dev/null +++ b/C++/container-with-most-water.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int maxArea(vector& height) { + int i = 0, j = height.size() - 1, max_area = 0; + while (i < j) { + max_area = max(max_area, min(height[i], height[j]) * (j - i)); + if (height[i] > height[j]) { + --j; + } else if (height[i] < height[j]) { + ++i; + } else { // height[i] == height[j]. + ++i, --j; + } + } + return max_area; + } +}; diff --git a/C++/maxArea.cpp b/C++/maxArea.cpp deleted file mode 100644 index a6c8fb46a..000000000 --- a/C++/maxArea.cpp +++ /dev/null @@ -1,21 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - int maxArea(vector &height) { - int start = 0, end = height.size() - 1, ans = 0; - - while(start < end) { - if(height[start] <= height[end]) { - ans = max(ans, height[start] * (end - start)); - start++; - } - if(height[start] > height[end]) { - ans = max(ans, height[end] * (end - start)); - end--; - } - } - return ans; - } -}; From 6329a333cd471bdcdf9f4bca7f4aabafcaa0a02f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 14:37:36 +0800 Subject: [PATCH 2806/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5f68b3e31..eeb06fc81 100644 --- a/README.md +++ b/README.md @@ -276,7 +276,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| -390 | [Elimination Game](https://leetcode.com/contest/2/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium | 2nd Contest | +390 | [Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium | 2nd Contest | 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./C++/perfect-rectangle.cpp) [Python](./Python/perfect-rectangle.py) | _O(n)_ | _O(n)_ | Hard | | 398 | [Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./C++/random-pick-index.cpp) [Python](./Python/random-pick-index.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | From 636a634af3596bc2b6b5bb914f2eddc00633ef93 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 14:37:58 +0800 Subject: [PATCH 2807/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eeb06fc81..20cc96fe6 100644 --- a/README.md +++ b/README.md @@ -276,7 +276,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| -390 | [Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium | 2nd Contest | +390 | [Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium || 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./C++/perfect-rectangle.cpp) [Python](./Python/perfect-rectangle.py) | _O(n)_ | _O(n)_ | Hard | | 398 | [Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./C++/random-pick-index.cpp) [Python](./Python/random-pick-index.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | From 5409b865264e8678db764da3ad68922c35368b16 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 17:36:50 +0800 Subject: [PATCH 2808/4971] Create nth-digit.py --- Python/nth-digit.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/nth-digit.py diff --git a/Python/nth-digit.py b/Python/nth-digit.py new file mode 100644 index 000000000..e8a71b89a --- /dev/null +++ b/Python/nth-digit.py @@ -0,0 +1,45 @@ +# Time: O(logn) +# Space: O(1) + +# Find the nth digit of the infinite integer sequence +# 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... +# +# Note: +# n is positive and will fit within the range of a 32-bit signed integer (n < 231). +# +# Example 1: +# +# Input: +# 3 +# +# Output: +# 3 +# Example 2: +# +# Input: +# 11 +# +# Output: +# 0 +# +# Explanation: +# The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, +# ... is a 0, which is part of the number 10. + +class Solution(object): + def findNthDigit(self, n): + """ + :type n: int + :rtype: int + """ + digit_len = 1 + while n > digit_len * 9 * (10 ** (digit_len-1)): + n -= digit_len * 9 * (10 ** (digit_len-1)) + digit_len += 1 + + num = 10 ** (digit_len-1) + (n-1)/digit_len + + nth_digit = num / (10 ** (digit_len-1 - (n-1)%digit_len)) + nth_digit %= 10 + + return nth_digit From b2fe8aae00a47afdebc5c0692aa9f61bf78ca007 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 18:00:06 +0800 Subject: [PATCH 2809/4971] Create binary-watch.py --- Python/binary-watch.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/binary-watch.py diff --git a/Python/binary-watch.py b/Python/binary-watch.py new file mode 100644 index 000000000..5a048487c --- /dev/null +++ b/Python/binary-watch.py @@ -0,0 +1,38 @@ +# Time: O(1) +# Space: O(1) + +# A binary watch has 4 LEDs on the top which represent the hours (0-11), +# and the 6 LEDs on the bottom represent the minutes (0-59). +# +# Each LED represents a zero or one, with the least significant bit on the right. +# +# For example, the above binary watch reads "3:25". +# +# Given a non-negative integer n which represents the number of LEDs that are currently on, +# return all possible times the watch could represent. +# +# Example: +# +# Input: n = 1 +# Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] +# Note: +# The order of output does not matter. +# The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". + + +class Solution(object): + def readBinaryWatch(self, num): + """ + :type num: int + :rtype: List[str] + """ + def bit_count(bits): + count = 0 + while bits: + bits &= bits-1 + count += 1 + return count + + return ['%d:%02d' % (h, m) + for h in xrange(12) for m in xrange(60) + if bit_count(h) + bit_count(m) == num] From 33dd97e7e21ff28abcfdbee218fa4e888406298a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 18:12:51 +0800 Subject: [PATCH 2810/4971] Create remove-k-digits.cpp --- C++/remove-k-digits.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/remove-k-digits.cpp diff --git a/C++/remove-k-digits.cpp b/C++/remove-k-digits.cpp new file mode 100644 index 000000000..bc25f33c2 --- /dev/null +++ b/C++/remove-k-digits.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + string removeKdigits(string num, int k) { + // If a digit is greater than next one, delete it. + string s; + for (const auto c : num) { + while (k > 0 && !s.empty() && s.back() > c) { + s.pop_back(); + --k; + } + s.push_back(c); + } + + // If all digits are increasingly sorted, delete last. + s.resize(s.length() - k); + + // Strip all leading '0' + return s.empty() || s == "0" ? "0" : s.substr(s.find_first_not_of('0')); + } +}; From 3823da8ff85f1460aee8e9ae84ad9c9812e07026 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 18:20:19 +0800 Subject: [PATCH 2811/4971] Create remove-k-digits.py --- Python/remove-k-digits.py | 40 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/remove-k-digits.py diff --git a/Python/remove-k-digits.py b/Python/remove-k-digits.py new file mode 100644 index 000000000..3560f59cc --- /dev/null +++ b/Python/remove-k-digits.py @@ -0,0 +1,40 @@ +# Time: O(n) +# Space: O(n) + +# Given a non-negative integer num represented as a string, +# remove k digits from the number so that the new number is the smallest possible. +# +# Note: +# The length of num is less than 105 and will be >= k. +# The given num does not contain any leading zero. +# Example 1: +# +# Input: num = "1432219", k = 3 +# Output: "1219" +# Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. +# Example 2: +# +# Input: num = "10200", k = 1 +# Output: "200" +# Explanation: Remove the leading 1 and the number is 200. +# Note that the output must not contain leading zeroes. +# Example 3: +# +# Input: num = "10", k = 2 +# Output: "0" +# Explanation: Remove all the digits from the number and it is left with nothing which is 0. + +class Solution(object): + def removeKdigits(self, num, k): + """ + :type num: str + :type k: int + :rtype: str + """ + result = [] + for d in num: + while k and result and result[-1] > d: + result.pop() + k -= 1 + result.append(d) + return ''.join(result).lstrip('0')[:-k or None] or '0' From a367a2c3f4c7c29dd1cbaf28a1ec74bc985da0fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 18:21:22 +0800 Subject: [PATCH 2812/4971] Update remove-k-digits.py --- Python/remove-k-digits.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/remove-k-digits.py b/Python/remove-k-digits.py index 3560f59cc..ec30523a3 100644 --- a/Python/remove-k-digits.py +++ b/Python/remove-k-digits.py @@ -5,7 +5,7 @@ # remove k digits from the number so that the new number is the smallest possible. # # Note: -# The length of num is less than 105 and will be >= k. +# The length of num is less than 10^5 and will be >= k. # The given num does not contain any leading zero. # Example 1: # From 8928f43dc96c47ebd04ae4b3534880f03930e697 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 20:08:28 +0800 Subject: [PATCH 2813/4971] Create frog-jump.py --- Python/frog-jump.py | 57 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Python/frog-jump.py diff --git a/Python/frog-jump.py b/Python/frog-jump.py new file mode 100644 index 000000000..fb1df7037 --- /dev/null +++ b/Python/frog-jump.py @@ -0,0 +1,57 @@ +# Time: O(n^2) +# Space: O(n) + +# A frog is crossing a river. The river is divided into x units and +# at each unit there may or may not exist a stone. +# The frog can jump on a stone, but it must not jump into the water. +# +# Given a list of stones' positions (in units) in sorted ascending order, +# determine if the frog is able to cross the river by landing on the last stone. +# Initially, the frog is on the first stone and assume the first jump must be 1 unit. +# +# If the frog has just jumped k units, then its next jump must be +# either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction. +# +# Note: +# +# The number of stones is ≥ 2 and is < 1,100. +# Each stone's position will be a non-negative integer < 231. +# The first stone's position is always 0. +# Example 1: +# +# [0,1,3,5,6,8,12,17] +# +# There are a total of 8 stones. +# The first stone at the 0th unit, second stone at the 1st unit, +# third stone at the 3rd unit, and so on... +# The last stone at the 17th unit. +# +# Return true. The frog can jump to the last stone by jumping +# 1 unit to the 2nd stone, then 2 units to the 3rd stone, then +# 2 units to the 4th stone, then 3 units to the 6th stone, +# 4 units to the 7th stone, and 5 units to the 8th stone. +# Example 2: +# +# [0,1,2,3,4,8,9,11] +# +# Return false. There is no way to jump to the last stone as +# the gap between the 5th and 6th stone is too large. + +class Solution(object): + def canCross(self, stones): + """ + :type stones: List[int] + :rtype: bool + """ + dp = [False for _ in xrange(len(stones))] + dp[0] = True + + for i in xrange(1, len(stones)): + for j in reversed(xrange(i)): + if stones[i] - stones[j] > j + 1: + break + if dp[j] and ((stones[i] - stones[j]) in ([j-1, j, j+1] if i != 1 else [1])): + dp[i] = True + break + + return dp[-1] From c6a169814934ddc9f7f25f549966796ef8193017 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 20:33:51 +0800 Subject: [PATCH 2814/4971] Update frog-jump.py --- Python/frog-jump.py | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index fb1df7037..6f564c76e 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -1,4 +1,4 @@ -# Time: O(n^2) +# Time: O(nlogn) # Space: O(n) # A frog is crossing a river. The river is divided into x units and @@ -37,7 +37,38 @@ # Return false. There is no way to jump to the last stone as # the gap between the 5th and 6th stone is too large. +# DP with binary search class Solution(object): + def canCross(self, stones): + """ + :type stones: List[int] + :rtype: bool + """ + def findStones(stones, i): + result = [] + if i == 0: + if stones[1] == 1: + result.append(1) + else: + a = bisect.bisect_left(stones, stones[i] + i-1) + b = bisect.bisect_left(stones, stones[i] + i) + c = bisect.bisect_left(stones, stones[i] + i+1) + if a != len(stones) and stones[a] == stones[i] + i-1: result.append(a) + if b != len(stones) and stones[b] == stones[i] + i: result.append(b) + if c != len(stones) and stones[c] == stones[i] + i+1: result.append(c) + return result + + dp = [False for _ in xrange(len(stones))] + dp[0] = True + for i in xrange(len(stones)-1): + for j in findStones(stones, i): + dp[j] = True + return dp[-1] + + +# Time: O(n^2) +# Space: O(n) +class Solution2(object): def canCross(self, stones): """ :type stones: List[int] From 96f0e38e6090ce0a7695bd230c641993c6ed0e38 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 20:37:33 +0800 Subject: [PATCH 2815/4971] Update frog-jump.py --- Python/frog-jump.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 6f564c76e..407279b21 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -57,12 +57,13 @@ def findStones(stones, i): if b != len(stones) and stones[b] == stones[i] + i: result.append(b) if c != len(stones) and stones[c] == stones[i] + i+1: result.append(c) return result - + dp = [False for _ in xrange(len(stones))] dp[0] = True for i in xrange(len(stones)-1): - for j in findStones(stones, i): - dp[j] = True + if dp[i]: + for j in findStones(stones, i): + dp[j] = True return dp[-1] From a08dda7a6dd699d6f9c1093cd4e533387048e0c5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 20:40:16 +0800 Subject: [PATCH 2816/4971] Update frog-jump.py --- Python/frog-jump.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 407279b21..b5cbb2ab7 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -14,7 +14,7 @@ # # Note: # -# The number of stones is ≥ 2 and is < 1,100. +# The number of stones is >= 2 and is < 1,100. # Each stone's position will be a non-negative integer < 231. # The first stone's position is always 0. # Example 1: @@ -50,14 +50,12 @@ def findStones(stones, i): if stones[1] == 1: result.append(1) else: - a = bisect.bisect_left(stones, stones[i] + i-1) - b = bisect.bisect_left(stones, stones[i] + i) - c = bisect.bisect_left(stones, stones[i] + i+1) - if a != len(stones) and stones[a] == stones[i] + i-1: result.append(a) - if b != len(stones) and stones[b] == stones[i] + i: result.append(b) - if c != len(stones) and stones[c] == stones[i] + i+1: result.append(c) + for k in (i-1, i, i+1): + j = bisect.bisect_left(stones, stones[i] + k) + if j != len(stones) and stones[j] == stones[i] + k: + result.append(j) return result - + dp = [False for _ in xrange(len(stones))] dp[0] = True for i in xrange(len(stones)-1): From 2e4194b97926fed7e2901669d682824e3ae18403 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 20:48:48 +0800 Subject: [PATCH 2817/4971] Update frog-jump.py --- Python/frog-jump.py | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index b5cbb2ab7..6d77c57a2 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -1,4 +1,4 @@ -# Time: O(nlogn) +# Time: O(n) # Space: O(n) # A frog is crossing a river. The river is divided into x units and @@ -37,8 +37,41 @@ # Return false. There is no way to jump to the last stone as # the gap between the 5th and 6th stone is too large. -# DP with binary search +# DP with hash table class Solution(object): + def canCross(self, stones): + """ + :type stones: List[int] + :rtype: bool + """ + def findStones(stones, lookup, i): + result = [] + if i == 0: + if stones[1] == stones[0] + 1: + result.append(1) + else: + for k in (i-1, i, i+1): + if stones[i] + k in lookup: + result.append(lookup[stones[i] + k]) + return result + + lookup = {} + for i in xrange(len(stones)): + lookup[stones[i]] = i + + dp = [False for _ in xrange(len(stones))] + dp[0] = True + for i in xrange(len(stones)-1): + if dp[i]: + for j in findStones(stones, lookup, i): + dp[j] = True + return dp[-1] + + +# Time: O(nlogn) +# Space: O(n) +# DP with binary search +class Solution2(object): def canCross(self, stones): """ :type stones: List[int] @@ -67,7 +100,7 @@ def findStones(stones, i): # Time: O(n^2) # Space: O(n) -class Solution2(object): +class Solution3(object): def canCross(self, stones): """ :type stones: List[int] From 5dc0631aa4121ae776ee323fd2bfb51e43919b8b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 20:50:10 +0800 Subject: [PATCH 2818/4971] Update frog-jump.py --- Python/frog-jump.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 6d77c57a2..550ca5f82 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -44,16 +44,16 @@ def canCross(self, stones): :type stones: List[int] :rtype: bool """ - def findStones(stones, lookup, i): - result = [] + def findJumpStones(stones, lookup, i): + jump_stones = [] if i == 0: if stones[1] == stones[0] + 1: - result.append(1) + jump_stones.append(1) else: for k in (i-1, i, i+1): if stones[i] + k in lookup: - result.append(lookup[stones[i] + k]) - return result + jump_stones.append(lookup[stones[i] + k]) + return jump_stones lookup = {} for i in xrange(len(stones)): @@ -63,7 +63,7 @@ def findStones(stones, lookup, i): dp[0] = True for i in xrange(len(stones)-1): if dp[i]: - for j in findStones(stones, lookup, i): + for j in findJumpStones(stones, lookup, i): dp[j] = True return dp[-1] @@ -77,23 +77,23 @@ def canCross(self, stones): :type stones: List[int] :rtype: bool """ - def findStones(stones, i): - result = [] + def findJumpStones(stones, i): + jump_stones = [] if i == 0: if stones[1] == 1: - result.append(1) + jump_stones.append(1) else: for k in (i-1, i, i+1): j = bisect.bisect_left(stones, stones[i] + k) if j != len(stones) and stones[j] == stones[i] + k: - result.append(j) - return result + jump_stones.append(j) + return jump_stones dp = [False for _ in xrange(len(stones))] dp[0] = True for i in xrange(len(stones)-1): if dp[i]: - for j in findStones(stones, i): + for j in findJumpStones(stones, i): dp[j] = True return dp[-1] From 888449ec9f913585c4faf95acfae1dbf4e30fc4e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 20:53:02 +0800 Subject: [PATCH 2819/4971] Update frog-jump.py --- Python/frog-jump.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 550ca5f82..c11f538f8 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -80,7 +80,7 @@ def canCross(self, stones): def findJumpStones(stones, i): jump_stones = [] if i == 0: - if stones[1] == 1: + if stones[1] == stones[0] + 1: jump_stones.append(1) else: for k in (i-1, i, i+1): From aa48a1ba631846f3452f2f68fc05be6e6d911de5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 22:45:05 +0800 Subject: [PATCH 2820/4971] Create nth-digit.cpp --- C++/nth-digit.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/nth-digit.cpp diff --git a/C++/nth-digit.cpp b/C++/nth-digit.cpp new file mode 100644 index 000000000..c30adbf0b --- /dev/null +++ b/C++/nth-digit.cpp @@ -0,0 +1,20 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int findNthDigit(int n) { + int digit_len = 1; + while (n > digit_len * 9 * pow(10, digit_len - 1)) { + n -= digit_len * 9 * pow(10, digit_len - 1); + ++digit_len; + } + + const int num = pow(10, digit_len - 1) + (n - 1) / digit_len; + + int nth_digit = num / pow(10, (digit_len - 1) - (n - 1) % digit_len); + nth_digit %= 10; + + return nth_digit; + } +}; From f13d86e5d4abc0edaff6c6b96e5d76337a0fbf61 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 22:45:38 +0800 Subject: [PATCH 2821/4971] Update nth-digit.cpp --- C++/nth-digit.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/nth-digit.cpp b/C++/nth-digit.cpp index c30adbf0b..afe69e929 100644 --- a/C++/nth-digit.cpp +++ b/C++/nth-digit.cpp @@ -6,7 +6,7 @@ class Solution { int findNthDigit(int n) { int digit_len = 1; while (n > digit_len * 9 * pow(10, digit_len - 1)) { - n -= digit_len * 9 * pow(10, digit_len - 1); + n -= digit_len * 9 * pow(10, digit_len - 1); ++digit_len; } From 2390640a9159951f1da853b424185ca6f779bddb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 22:56:15 +0800 Subject: [PATCH 2822/4971] Create binary-watch.cpp --- C++/binary-watch.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/binary-watch.cpp diff --git a/C++/binary-watch.cpp b/C++/binary-watch.cpp new file mode 100644 index 000000000..f033592ae --- /dev/null +++ b/C++/binary-watch.cpp @@ -0,0 +1,28 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + vector readBinaryWatch(int num) { + vector result; + for (int h = 0; h < 12; ++h) { + for (int m = 0; m < 60; ++m) { + if (bit_count(h) + bit_count(m) == num) { + const auto hour = to_string(h); + const auto minute = m < 10 ? "0" + to_string(m) : to_string(m); + result.emplace_back(hour + ":" + minute); + } + } + } + return result; + } + +private: + int bit_count(int bits) { + int count = 0; + for (; bits; bits &= bits - 1) { + ++count; + } + return count; + } +}; From 0144ffeb35cc40dc243f33907c685b6de3d693df Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 23:06:48 +0800 Subject: [PATCH 2823/4971] Create frog-jump.cpp --- C++/frog-jump.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 C++/frog-jump.cpp diff --git a/C++/frog-jump.cpp b/C++/frog-jump.cpp new file mode 100644 index 000000000..a8b9dabe9 --- /dev/null +++ b/C++/frog-jump.cpp @@ -0,0 +1,43 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + bool canCross(vector& stones) { + unordered_map lookup; + for (int i = 0; i < stones.size(); ++i) { + lookup[stones[i]] = i; + } + + vector dp(stones.size()); + dp[0] = true; + for (int i = 0; i < stones.size(); ++i) { + if (dp[i]) { + for (const auto& j : findJumpStones(stones, lookup, i)) { + dp[j] = true; + } + } + } + return dp.back(); + } + +private: + vector findJumpStones(const vector& stones, + const unordered_map& lookup, + int i) { + vector jump_stones; + if (i == 0) { + if (stones[1] == stones[0] + 1) { + jump_stones.emplace_back(1); + } + } else { + for (const auto& k : {i - 1, i, i + 1}) { + const auto it = lookup.find(stones[i] + k); + if (it != lookup.end()) { + jump_stones.emplace_back(it->second); + } + } + } + return jump_stones; + } +}; From ec3e66b3230f47001cb7d817fd649a5280ff315c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 23:13:50 +0800 Subject: [PATCH 2824/4971] Update README.md --- README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 20cc96fe6..a9cc9f932 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-399%20%2F%20399-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-403%20%2F%20403-ff69b4.svg) -Up to date (2016-09-11), there are `382` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-09-18), there are `386` 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 `399` questions. +Here is the classification of all `403` 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.) @@ -58,6 +58,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | LintCode | 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./C++/find-the-difference.cpp) [Python](./Python/find-the-difference.py) | _O(n)_ | _O(1)_ | Easy | | 393 | [UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./C++/utf-8-validation.cpp) [Python](./Python/utf-8-validation.py) | _O(n)_ | _O(1)_ | Medium | | +401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./C++/binary-watch.cpp) [Python](./Python/binary-watch.py) | _O(1)_ | _O(1)_ | Easy | | +403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n)_ | Hard || ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -279,6 +281,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 390 | [Elimination Game](https://leetcode.com/problems/elimination-game/) | [C++](./C++/elimination-game.cpp) [Python](./Python/elimination-game.py) | _O(logn)_ | _O(1)_ | Medium || 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./C++/perfect-rectangle.cpp) [Python](./Python/perfect-rectangle.py) | _O(n)_ | _O(n)_ | Hard | | 398 | [Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./C++/random-pick-index.cpp) [Python](./Python/random-pick-index.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | +400 | [Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./C++/nth-digit.cpp) [Python](./Python/nth-digit.py) | _O(logn)_ | _O(1)_ | Easy ||| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -499,6 +502,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 376| [Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/)| [C++](./C++/wiggle-subsequence.cpp) [Python](./Python/wiggle-subsequence.py) | _O(n)_ | _O(1)_ | Medium || 392| [Is Subsequence](https://leetcode.com/problems/is-subsequence/)| [C++](./C++/is-subsequence.cpp) [Python](./Python/is-subsequence.py) | _O(n)_ | _O(1)_ | Medium || 397| [Integer Replacement](https://leetcode.com/problems/integer-replacement/)| [C++](./C++/integer-replacement.cpp) [Python](./Python/integer-replacement.py) | _O(n)_ | _O(1)_ | Easy || Math +402 | [Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./C++/remove-k-digits.cpp) [Python](./Python/remove-k-digits.py) | _O(n)_ | _O(n)_ | Medium | LintCode | --- ## Design From 6d6d0ffe264adeda70e2257c8c1280d95c6f469a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 23:15:39 +0800 Subject: [PATCH 2825/4971] Update nth-digit.py --- Python/nth-digit.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/nth-digit.py b/Python/nth-digit.py index e8a71b89a..e0c7b72a3 100644 --- a/Python/nth-digit.py +++ b/Python/nth-digit.py @@ -39,7 +39,7 @@ def findNthDigit(self, n): num = 10 ** (digit_len-1) + (n-1)/digit_len - nth_digit = num / (10 ** (digit_len-1 - (n-1)%digit_len)) + nth_digit = num / (10 ** ((digit_len-1) - ((n-1)%digit_len))) nth_digit %= 10 return nth_digit From 089147bac9d90ebcf8f86875d201830b60653cfc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 23:17:06 +0800 Subject: [PATCH 2826/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a9cc9f932..a9be3de9f 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./C++/find-the-difference.cpp) [Python](./Python/find-the-difference.py) | _O(n)_ | _O(1)_ | Easy | | 393 | [UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./C++/utf-8-validation.cpp) [Python](./Python/utf-8-validation.py) | _O(n)_ | _O(1)_ | Medium | | 401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./C++/binary-watch.cpp) [Python](./Python/binary-watch.py) | _O(1)_ | _O(1)_ | Easy | | -403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n)_ | Hard || ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -484,6 +483,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 368| [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [C++](./C++/largest-divisible-subset.cpp) [Python](./Python/largest-divisible-subset.py) | _O(n^2)_ | _O(n)_ | Medium | | | 375| [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)| [C++](./C++/guess-number-higher-or-lower-ii.cpp) [Python](./Python/guess-number-higher-or-lower-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium | | 377| [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/)| [C++](./C++/combination-sum-iv.cpp) [Python](./Python/combination-sum-iv.py) | _O(nlogn + n * t)_ | _O(t)_ | Medium | | +403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n)_ | Hard || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From bf75439e6c51f7eb0f3dfccf57857ec8b0d97ba9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 23:18:28 +0800 Subject: [PATCH 2827/4971] Update frog-jump.py --- Python/frog-jump.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index c11f538f8..fd071a27f 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -56,8 +56,8 @@ def findJumpStones(stones, lookup, i): return jump_stones lookup = {} - for i in xrange(len(stones)): - lookup[stones[i]] = i + for k, v in enumerate(stones): + lookup[v] = k dp = [False for _ in xrange(len(stones))] dp[0] = True From 40c5430a25aef999fc251e84176305fe55351434 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 23:20:14 +0800 Subject: [PATCH 2828/4971] Update frog-jump.py --- Python/frog-jump.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index fd071a27f..9ab6e5df6 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -61,7 +61,7 @@ def findJumpStones(stones, lookup, i): dp = [False for _ in xrange(len(stones))] dp[0] = True - for i in xrange(len(stones)-1): + for i in xrange(len(stones)): if dp[i]: for j in findJumpStones(stones, lookup, i): dp[j] = True @@ -91,7 +91,7 @@ def findJumpStones(stones, i): dp = [False for _ in xrange(len(stones))] dp[0] = True - for i in xrange(len(stones)-1): + for i in xrange(len(stones)): if dp[i]: for j in findJumpStones(stones, i): dp[j] = True From d75aeb0d97c53c1ce57d5412a3b918e813ce8ed2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Sep 2016 02:23:20 +0800 Subject: [PATCH 2829/4971] Update frog-jump.cpp --- C++/frog-jump.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/frog-jump.cpp b/C++/frog-jump.cpp index a8b9dabe9..b84eda7d1 100644 --- a/C++/frog-jump.cpp +++ b/C++/frog-jump.cpp @@ -13,7 +13,7 @@ class Solution { dp[0] = true; for (int i = 0; i < stones.size(); ++i) { if (dp[i]) { - for (const auto& j : findJumpStones(stones, lookup, i)) { + for (const auto& j : findStones(stones, lookup, i)) { dp[j] = true; } } @@ -22,22 +22,22 @@ class Solution { } private: - vector findJumpStones(const vector& stones, + vector findNextStones(const vector& stones, const unordered_map& lookup, int i) { - vector jump_stones; + vector next_stones; if (i == 0) { if (stones[1] == stones[0] + 1) { - jump_stones.emplace_back(1); + next_stones.emplace_back(1); } } else { for (const auto& k : {i - 1, i, i + 1}) { const auto it = lookup.find(stones[i] + k); if (it != lookup.end()) { - jump_stones.emplace_back(it->second); + next_stones.emplace_back(it->second); } } } - return jump_stones; + return next_stones; } }; From 19d2bdfbb51a40686c6ad937369ebae8a710c4d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Sep 2016 02:24:08 +0800 Subject: [PATCH 2830/4971] Update frog-jump.py --- Python/frog-jump.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 9ab6e5df6..1b4eb16d7 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -44,16 +44,16 @@ def canCross(self, stones): :type stones: List[int] :rtype: bool """ - def findJumpStones(stones, lookup, i): - jump_stones = [] + def findNextStones(stones, lookup, i): + next_stones = [] if i == 0: if stones[1] == stones[0] + 1: - jump_stones.append(1) + next_stones.append(1) else: for k in (i-1, i, i+1): if stones[i] + k in lookup: - jump_stones.append(lookup[stones[i] + k]) - return jump_stones + next_stones.append(lookup[stones[i] + k]) + return next_stones lookup = {} for k, v in enumerate(stones): @@ -63,7 +63,7 @@ def findJumpStones(stones, lookup, i): dp[0] = True for i in xrange(len(stones)): if dp[i]: - for j in findJumpStones(stones, lookup, i): + for j in findNextStones(stones, lookup, i): dp[j] = True return dp[-1] @@ -77,23 +77,23 @@ def canCross(self, stones): :type stones: List[int] :rtype: bool """ - def findJumpStones(stones, i): - jump_stones = [] + def findNextStones(stones, i): + next_stones = [] if i == 0: if stones[1] == stones[0] + 1: - jump_stones.append(1) + next_stones.append(1) else: for k in (i-1, i, i+1): j = bisect.bisect_left(stones, stones[i] + k) if j != len(stones) and stones[j] == stones[i] + k: - jump_stones.append(j) - return jump_stones + next_stones.append(j) + return next_stones dp = [False for _ in xrange(len(stones))] dp[0] = True for i in xrange(len(stones)): if dp[i]: - for j in findJumpStones(stones, i): + for j in findNextStones(stones, i): dp[j] = True return dp[-1] From 8d46096d7e2e8e705455a4832f9bae949cc16ca7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Sep 2016 02:27:12 +0800 Subject: [PATCH 2831/4971] Update frog-jump.py --- Python/frog-jump.py | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 1b4eb16d7..acca37580 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -46,13 +46,9 @@ def canCross(self, stones): """ def findNextStones(stones, lookup, i): next_stones = [] - if i == 0: - if stones[1] == stones[0] + 1: - next_stones.append(1) - else: - for k in (i-1, i, i+1): - if stones[i] + k in lookup: - next_stones.append(lookup[stones[i] + k]) + for k in (i-1, i, i+1): + if stones[i] + k in lookup: + next_stones.append(lookup[stones[i] + k]) return next_stones lookup = {} @@ -79,14 +75,10 @@ def canCross(self, stones): """ def findNextStones(stones, i): next_stones = [] - if i == 0: - if stones[1] == stones[0] + 1: - next_stones.append(1) - else: - for k in (i-1, i, i+1): - j = bisect.bisect_left(stones, stones[i] + k) - if j != len(stones) and stones[j] == stones[i] + k: - next_stones.append(j) + for k in (i-1, i, i+1): + j = bisect.bisect_left(stones, stones[i] + k) + if j != len(stones) and stones[j] == stones[i] + k: + next_stones.append(j) return next_stones dp = [False for _ in xrange(len(stones))] From d919379d8f0d8d9632a5ce2005370ad53555fbfd Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Sep 2016 02:29:09 +0800 Subject: [PATCH 2832/4971] Update frog-jump.cpp --- C++/frog-jump.cpp | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/C++/frog-jump.cpp b/C++/frog-jump.cpp index b84eda7d1..80217343a 100644 --- a/C++/frog-jump.cpp +++ b/C++/frog-jump.cpp @@ -13,7 +13,7 @@ class Solution { dp[0] = true; for (int i = 0; i < stones.size(); ++i) { if (dp[i]) { - for (const auto& j : findStones(stones, lookup, i)) { + for (const auto& j : findNextStones(stones, lookup, i)) { dp[j] = true; } } @@ -26,18 +26,13 @@ class Solution { const unordered_map& lookup, int i) { vector next_stones; - if (i == 0) { - if (stones[1] == stones[0] + 1) { - next_stones.emplace_back(1); - } - } else { - for (const auto& k : {i - 1, i, i + 1}) { - const auto it = lookup.find(stones[i] + k); - if (it != lookup.end()) { - next_stones.emplace_back(it->second); - } + for (const auto& k : {i - 1, i, i + 1}) { + const auto it = lookup.find(stones[i] + k); + if (it != lookup.end()) { + next_stones.emplace_back(it->second); } } return next_stones; } }; + From 40de65b65331b512caac1e9471d8caf57c46b406 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Sep 2016 02:30:57 +0800 Subject: [PATCH 2833/4971] Update frog-jump.cpp --- C++/frog-jump.cpp | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/C++/frog-jump.cpp b/C++/frog-jump.cpp index 80217343a..7db1de215 100644 --- a/C++/frog-jump.cpp +++ b/C++/frog-jump.cpp @@ -13,26 +13,15 @@ class Solution { dp[0] = true; for (int i = 0; i < stones.size(); ++i) { if (dp[i]) { - for (const auto& j : findNextStones(stones, lookup, i)) { - dp[j] = true; + for (const auto& k : {i - 1, i, i + 1}) { + const auto it = lookup.find(stones[i] + k); + if (it != lookup.end()) { + dp[it->second] = true; + } } } } return dp.back(); } - -private: - vector findNextStones(const vector& stones, - const unordered_map& lookup, - int i) { - vector next_stones; - for (const auto& k : {i - 1, i, i + 1}) { - const auto it = lookup.find(stones[i] + k); - if (it != lookup.end()) { - next_stones.emplace_back(it->second); - } - } - return next_stones; - } }; From 106217c7bf9b88553eec2ff5723f04192a443127 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Sep 2016 02:32:30 +0800 Subject: [PATCH 2834/4971] Update frog-jump.py --- Python/frog-jump.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index acca37580..14cc01150 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -44,13 +44,6 @@ def canCross(self, stones): :type stones: List[int] :rtype: bool """ - def findNextStones(stones, lookup, i): - next_stones = [] - for k in (i-1, i, i+1): - if stones[i] + k in lookup: - next_stones.append(lookup[stones[i] + k]) - return next_stones - lookup = {} for k, v in enumerate(stones): lookup[v] = k @@ -59,8 +52,9 @@ def findNextStones(stones, lookup, i): dp[0] = True for i in xrange(len(stones)): if dp[i]: - for j in findNextStones(stones, lookup, i): - dp[j] = True + for k in (i-1, i, i+1): + if stones[i] + k in lookup: + dp[lookup[stones[i] + k]] = True return dp[-1] From 3a7bf98586b483faa623adf3878176a50e062e3f Mon Sep 17 00:00:00 2001 From: xiaoF Date: Mon, 19 Sep 2016 21:31:21 +0900 Subject: [PATCH 2835/4971] Update merge-k-sorted-lists.py --- Python/merge-k-sorted-lists.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/merge-k-sorted-lists.py b/Python/merge-k-sorted-lists.py index 584c2c17b..edc3c9d4a 100644 --- a/Python/merge-k-sorted-lists.py +++ b/Python/merge-k-sorted-lists.py @@ -12,7 +12,7 @@ def __init__(self, x): def __repr__(self): if self: - return "{} -> {}".format(self.val, + return "{} -> {}".format(self.val, self.next) # Merge two by two solution. From f7db9683466121ebb72012d9a155c07c6d890e4a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Sep 2016 21:39:05 +0800 Subject: [PATCH 2836/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a9be3de9f..9a7930a9e 100644 --- a/README.md +++ b/README.md @@ -488,7 +488,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Greedy # | 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 || +11| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [C++](./C++/container-with-most-water.cpp) [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 || From f9fedc4285545b689440f9e9ea65f0b83f304f1a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Sep 2016 09:31:35 +0800 Subject: [PATCH 2837/4971] Update maximum-subarray.py --- Python/maximum-subarray.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/Python/maximum-subarray.py b/Python/maximum-subarray.py index 50ff72130..9c5f5ede9 100644 --- a/Python/maximum-subarray.py +++ b/Python/maximum-subarray.py @@ -12,15 +12,20 @@ # If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. # -class Solution: - # @param A, a list of integers - # @return an integer - def maxSubArray(self, A): +class Solution(object): + def maxSubArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + if max(nums) < 0: + return max(nums) global_max, local_max = float("-inf"), 0 - for x in A: + for x in nums: local_max = max(0, local_max + x) global_max = max(global_max, local_max) return global_max + if __name__ == "__main__": - print Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]) \ No newline at end of file + print Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]) From 679707a239a5cf03201841d061d67bd04fe3374b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Sep 2016 23:40:39 +0800 Subject: [PATCH 2838/4971] Update and rename trap.cpp to trapping-rain-water.cpp --- C++/trap.cpp | 30 ------------------------------ C++/trapping-rain-water.cpp | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 30 deletions(-) delete mode 100644 C++/trap.cpp create mode 100644 C++/trapping-rain-water.cpp diff --git a/C++/trap.cpp b/C++/trap.cpp deleted file mode 100644 index cb25e875e..000000000 --- a/C++/trap.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(1) - -class Solution { - public: - int trap(int A[], int n) { - int max = 0; - for(int i = 0; i < n; ++i) { - if(A[i] > A[max]) - max = i; - } - - int water = 0; - for(int i = 0, top = 0; i < max; ++i) { - if(A[i] > top) - top = A[i]; - else - water += top - A[i]; - } - - for(int i = n - 1, top = 0; i > max; --i) { - if(A[i] > top) - top = A[i]; - else - water += top - A[i]; - } - - return water; - } -}; diff --git a/C++/trapping-rain-water.cpp b/C++/trapping-rain-water.cpp new file mode 100644 index 000000000..082772360 --- /dev/null +++ b/C++/trapping-rain-water.cpp @@ -0,0 +1,35 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int trap(vector& height) { + if (height.empty()) { + return 0; + } + + int i = 0, j = height.size() - 1; + int left_height = height[0]; + int right_height = height[height.size() - 1]; + int trap = 0; + + while (i < j) { + if (left_height < right_height) { + ++i; + // Fill in the gap. + trap += max(0, left_height - height[i]); + // Update current max height from left. + left_height = max(left_height, height[i]); + } + else { + --j; + // Fill in the gap. + trap += max(0, right_height - height[j]); + // Update current max height from right. + right_height = max(right_height, height[j]); + } + } + + return trap; + } +}; From 31cdc04d0b5cc65140a4cede59545faaa35fb4ad Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Sep 2016 23:41:18 +0800 Subject: [PATCH 2839/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9a7930a9e..befbd8c01 100644 --- a/README.md +++ b/README.md @@ -489,7 +489,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 11| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [C++](./C++/container-with-most-water.cpp) [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 +42| [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [C++](./C++/trapping-rain-water.cpp) [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 || From c344848d02479ccc3d60a513a85a39342fb36cd4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Sep 2016 10:25:16 +0800 Subject: [PATCH 2840/4971] Update frog-jump.py --- Python/frog-jump.py | 72 +++++++-------------------------------------- 1 file changed, 11 insertions(+), 61 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 14cc01150..3dfa66977 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -1,4 +1,4 @@ -# Time: O(n) +# Time: O(n) ~ O(n^2) # Space: O(n) # A frog is crossing a river. The river is divided into x units and @@ -44,63 +44,13 @@ def canCross(self, stones): :type stones: List[int] :rtype: bool """ - lookup = {} - for k, v in enumerate(stones): - lookup[v] = k - - dp = [False for _ in xrange(len(stones))] - dp[0] = True - for i in xrange(len(stones)): - if dp[i]: - for k in (i-1, i, i+1): - if stones[i] + k in lookup: - dp[lookup[stones[i] + k]] = True - return dp[-1] - - -# Time: O(nlogn) -# Space: O(n) -# DP with binary search -class Solution2(object): - def canCross(self, stones): - """ - :type stones: List[int] - :rtype: bool - """ - def findNextStones(stones, i): - next_stones = [] - for k in (i-1, i, i+1): - j = bisect.bisect_left(stones, stones[i] + k) - if j != len(stones) and stones[j] == stones[i] + k: - next_stones.append(j) - return next_stones - - dp = [False for _ in xrange(len(stones))] - dp[0] = True - for i in xrange(len(stones)): - if dp[i]: - for j in findNextStones(stones, i): - dp[j] = True - return dp[-1] - - -# Time: O(n^2) -# Space: O(n) -class Solution3(object): - def canCross(self, stones): - """ - :type stones: List[int] - :rtype: bool - """ - dp = [False for _ in xrange(len(stones))] - dp[0] = True - - for i in xrange(1, len(stones)): - for j in reversed(xrange(i)): - if stones[i] - stones[j] > j + 1: - break - if dp[j] and ((stones[i] - stones[j]) in ([j-1, j, j+1] if i != 1 else [1])): - dp[i] = True - break - - return dp[-1] + if stones[1] != 1: + return False + lookup = {s: set() for s in stones} + lookup[1].add(1) + for i in stones[:-1]: + for j in lookup[i]: + for k in xrange(j-1, j+2): + if k > 0 and i+k in lookup: + lookup[i+k].add(k) + return bool(lookup[stones[-1]]) From 09f18b5afce7d9bc824ddeb8522374286cf15cdc Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Sep 2016 10:25:39 +0800 Subject: [PATCH 2841/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index befbd8c01..af8fc37ef 100644 --- a/README.md +++ b/README.md @@ -483,7 +483,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 368| [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [C++](./C++/largest-divisible-subset.cpp) [Python](./Python/largest-divisible-subset.py) | _O(n^2)_ | _O(n)_ | Medium | | | 375| [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)| [C++](./C++/guess-number-higher-or-lower-ii.cpp) [Python](./Python/guess-number-higher-or-lower-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium | | 377| [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/)| [C++](./C++/combination-sum-iv.cpp) [Python](./Python/combination-sum-iv.py) | _O(nlogn + n * t)_ | _O(t)_ | Medium | | -403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n)_ | Hard || +403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n) ~ O(n^2)_ | _O(n)_ | Hard || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From b893de4e6e04a2ed223f88239158a9a3635873d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Sep 2016 10:30:50 +0800 Subject: [PATCH 2842/4971] Update frog-jump.py --- Python/frog-jump.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 3dfa66977..fc38efa47 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -46,7 +46,7 @@ def canCross(self, stones): """ if stones[1] != 1: return False - lookup = {s: set() for s in stones} + lookup = {i: set() for i in stones} lookup[1].add(1) for i in stones[:-1]: for j in lookup[i]: From a14e4569647b33f3a3f00d8c1faa8918ca6140e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Sep 2016 10:38:15 +0800 Subject: [PATCH 2843/4971] Update frog-jump.py --- Python/frog-jump.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index fc38efa47..53949977f 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -46,11 +46,11 @@ def canCross(self, stones): """ if stones[1] != 1: return False - lookup = {i: set() for i in stones} + lookup = {s: set() for s in stones} lookup[1].add(1) - for i in stones[:-1]: - for j in lookup[i]: + for s in stones[:-1]: + for j in lookup[s]: for k in xrange(j-1, j+2): - if k > 0 and i+k in lookup: - lookup[i+k].add(k) + if k > 0 and s+k in lookup: + lookup[s+k].add(k) return bool(lookup[stones[-1]]) From 3a4110ea55a00d46cce56b42feb2abeffc0818c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Sep 2016 10:38:21 +0800 Subject: [PATCH 2844/4971] Update frog-jump.cpp --- C++/frog-jump.cpp | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/C++/frog-jump.cpp b/C++/frog-jump.cpp index 7db1de215..5cfac9747 100644 --- a/C++/frog-jump.cpp +++ b/C++/frog-jump.cpp @@ -1,27 +1,29 @@ -// Time: O(n) +// Time: O(n) ~ O(n^2) // Space: O(n) class Solution { public: bool canCross(vector& stones) { - unordered_map lookup; - for (int i = 0; i < stones.size(); ++i) { - lookup[stones[i]] = i; + if (stones[1] != 1) { + return false; } - vector dp(stones.size()); - dp[0] = true; - for (int i = 0; i < stones.size(); ++i) { - if (dp[i]) { - for (const auto& k : {i - 1, i, i + 1}) { - const auto it = lookup.find(stones[i] + k); - if (it != lookup.end()) { - dp[it->second] = true; + unordered_map> lookup; + for (const auto& s: stones) { + lookup.emplace(s, {unordered_set()}); + } + lookup[1].emplace(1); + + for (int i = 0; i + 1 < stones.size(); ++i) { + for (const auto& j : lookup[stones[i]]) { + for (const auto& k : {j - 1, j, j + 1}) { + if (k > 0 && lookup.count(stones[i] + k)) { + lookup[stones[i] + k].emplace(k); } } } } - return dp.back(); + + return !lookup[stones.back()].empty(); } }; - From 1013ae7eb58a0fc6df0be9eab4367749145b343c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Sep 2016 10:41:17 +0800 Subject: [PATCH 2845/4971] Update frog-jump.py --- Python/frog-jump.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 53949977f..94323044a 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -46,11 +46,12 @@ def canCross(self, stones): """ if stones[1] != 1: return False + lookup = {s: set() for s in stones} lookup[1].add(1) for s in stones[:-1]: for j in lookup[s]: - for k in xrange(j-1, j+2): + for k in (j-1, j, j+1): if k > 0 and s+k in lookup: lookup[s+k].add(k) return bool(lookup[stones[-1]]) From 466aaf422cda7450b3fb2f29e304c7a841dba974 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Sep 2016 10:53:23 +0800 Subject: [PATCH 2846/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index af8fc37ef..befbd8c01 100644 --- a/README.md +++ b/README.md @@ -483,7 +483,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 368| [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [C++](./C++/largest-divisible-subset.cpp) [Python](./Python/largest-divisible-subset.py) | _O(n^2)_ | _O(n)_ | Medium | | | 375| [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)| [C++](./C++/guess-number-higher-or-lower-ii.cpp) [Python](./Python/guess-number-higher-or-lower-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium | | 377| [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/)| [C++](./C++/combination-sum-iv.cpp) [Python](./Python/combination-sum-iv.py) | _O(nlogn + n * t)_ | _O(t)_ | Medium | | -403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n) ~ O(n^2)_ | _O(n)_ | Hard || +403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n)_ | Hard || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 714f95ca80c51ee2078867f0a5ce246a5c08c5a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Sep 2016 10:56:18 +0800 Subject: [PATCH 2847/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index befbd8c01..4adbf097f 100644 --- a/README.md +++ b/README.md @@ -483,7 +483,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 368| [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [C++](./C++/largest-divisible-subset.cpp) [Python](./Python/largest-divisible-subset.py) | _O(n^2)_ | _O(n)_ | Medium | | | 375| [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)| [C++](./C++/guess-number-higher-or-lower-ii.cpp) [Python](./Python/guess-number-higher-or-lower-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium | | 377| [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/)| [C++](./C++/combination-sum-iv.cpp) [Python](./Python/combination-sum-iv.py) | _O(nlogn + n * t)_ | _O(t)_ | Medium | | -403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n)_ | Hard || +403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n) ~ (n^2)_ | Hard || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 53b8d23d007da9daeb145cd8bcf2634bf3211ad4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Sep 2016 10:56:37 +0800 Subject: [PATCH 2848/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4adbf097f..a93368fab 100644 --- a/README.md +++ b/README.md @@ -483,7 +483,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 368| [Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/) | [C++](./C++/largest-divisible-subset.cpp) [Python](./Python/largest-divisible-subset.py) | _O(n^2)_ | _O(n)_ | Medium | | | 375| [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)| [C++](./C++/guess-number-higher-or-lower-ii.cpp) [Python](./Python/guess-number-higher-or-lower-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium | | 377| [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/)| [C++](./C++/combination-sum-iv.cpp) [Python](./Python/combination-sum-iv.py) | _O(nlogn + n * t)_ | _O(t)_ | Medium | | -403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n) ~ (n^2)_ | Hard || +403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n) ~ O(n^2)_ | Hard || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 9f72b0730614f123ae9b1b8a4d11b5fead5233c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Sep 2016 22:17:38 +0800 Subject: [PATCH 2849/4971] Update frog-jump.cpp --- C++/frog-jump.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/C++/frog-jump.cpp b/C++/frog-jump.cpp index 5cfac9747..e9dcb774a 100644 --- a/C++/frog-jump.cpp +++ b/C++/frog-jump.cpp @@ -8,22 +8,22 @@ class Solution { return false; } - unordered_map> lookup; + unordered_map> last_jump_units; for (const auto& s: stones) { - lookup.emplace(s, {unordered_set()}); + last_jump_units.emplace(s, {unordered_set()}); } - lookup[1].emplace(1); + last_jump_units[1].emplace(1); for (int i = 0; i + 1 < stones.size(); ++i) { - for (const auto& j : lookup[stones[i]]) { + for (const auto& j : last_jump_units[stones[i]]) { for (const auto& k : {j - 1, j, j + 1}) { - if (k > 0 && lookup.count(stones[i] + k)) { - lookup[stones[i] + k].emplace(k); + if (k > 0 && last_jump_units.count(stones[i] + k)) { + last_jump_units[stones[i] + k].emplace(k); } } } } - return !lookup[stones.back()].empty(); + return !last_jump_units[stones.back()].empty(); } }; From 507a34a6909420218b8bc85378a92b7fb8ec511f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Sep 2016 22:18:04 +0800 Subject: [PATCH 2850/4971] Update frog-jump.py --- Python/frog-jump.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 94323044a..447071fbe 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -47,11 +47,11 @@ def canCross(self, stones): if stones[1] != 1: return False - lookup = {s: set() for s in stones} - lookup[1].add(1) + last_jump_units = {s: set() for s in stones} + last_jump_units[1].add(1) for s in stones[:-1]: - for j in lookup[s]: + for j in last_jump_units[s]: for k in (j-1, j, j+1): - if k > 0 and s+k in lookup: - lookup[s+k].add(k) - return bool(lookup[stones[-1]]) + if k > 0 and s+k in last_jump_units: + last_jump_units[s+k].add(k) + return bool(last_jump_units[stones[-1]]) From 21aca9d85b0ccc1f86cb51248d07628ef289bf61 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 16:52:28 +0800 Subject: [PATCH 2851/4971] Create queue-reconstruction-by-height.cpp --- C++/queue-reconstruction-by-height.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/queue-reconstruction-by-height.cpp diff --git a/C++/queue-reconstruction-by-height.cpp b/C++/queue-reconstruction-by-height.cpp new file mode 100644 index 000000000..1dbc3cb7c --- /dev/null +++ b/C++/queue-reconstruction-by-height.cpp @@ -0,0 +1,17 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + vector> reconstructQueue(vector>& people) { + sort(people.begin(), people.end(), + [](const pair& a, pair& b) { + return b.first == a.first ? a.second < b.second : b.first < a.first; + }); + vector> result; + for (const auto& p : people) { + result.insert(result.begin() + p.second, p); + } + return result; + } +}; From 75d4fe643c01460a7d6db230023e8dabc6661135 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 16:54:19 +0800 Subject: [PATCH 2852/4971] Create queue-reconstruction-by-height.py --- Python/queue-reconstruction-by-height.py | 31 ++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/queue-reconstruction-by-height.py diff --git a/Python/queue-reconstruction-by-height.py b/Python/queue-reconstruction-by-height.py new file mode 100644 index 000000000..73a8010ba --- /dev/null +++ b/Python/queue-reconstruction-by-height.py @@ -0,0 +1,31 @@ +# Time: O(n^2) +# Space: O(n) + +# Suppose you have a random list of people standing in a queue. +# Each person is described by a pair of integers (h, k), +# where h is the height of the person and k is the number of people +# in front of this person who have a height greater than or equal to h. +# Write an algorithm to reconstruct the queue. +# +# Note: +# The number of people is less than 1,100. +# +# Example +# +# Input: +# [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] +# +# Output: +# [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] + +class Solution(object): + def reconstructQueue(self, people): + """ + :type people: List[List[int]] + :rtype: List[List[int]] + """ + people.sort(key=lambda x: (-x[0], x[1])) + result = [] + for p in people: + result.insert(p[1], p) + return result From 3bc71e80fe42f0177b0afd062722b01738c8e9a9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 17:03:00 +0800 Subject: [PATCH 2853/4971] Create convert-a-number-to-hexadecimal.cpp --- C++/convert-a-number-to-hexadecimal.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/convert-a-number-to-hexadecimal.cpp diff --git a/C++/convert-a-number-to-hexadecimal.cpp b/C++/convert-a-number-to-hexadecimal.cpp new file mode 100644 index 000000000..8808b9328 --- /dev/null +++ b/C++/convert-a-number-to-hexadecimal.cpp @@ -0,0 +1,25 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + string toHex(int num) { + if (!num) { + return "0"; + } + + string result; + while (num && result.length() != sizeof(int) * 2) { + int hex = num & 15; + if (hex < 10) { + result.push_back('0' + hex); + } else { + result.push_back('a' + hex - 10); + } + num >>= 4; + } + reverse(result.begin(), result.end()); + + return result; + } +}; From 0dde5a5bae09ea9f498684f650ef26fdc66231cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 17:11:30 +0800 Subject: [PATCH 2854/4971] Create convert-a-number-to-hexadecimal.py --- Python/convert-a-number-to-hexadecimal.py | 56 +++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/convert-a-number-to-hexadecimal.py diff --git a/Python/convert-a-number-to-hexadecimal.py b/Python/convert-a-number-to-hexadecimal.py new file mode 100644 index 000000000..49617b167 --- /dev/null +++ b/Python/convert-a-number-to-hexadecimal.py @@ -0,0 +1,56 @@ +# Time: O(logn) +# Space: O(1) + +# Given an integer, write an algorithm to convert it to hexadecimal. +# For negative integer, two’s complement method is used. +# +# IMPORTANT: +# You must not use any method provided by the library which converts/formats +# the number to hex directly. Such solution will result in disqualification of +# all your submissions to this problem. Users may report such solutions after the +# contest ends and we reserve the right of final decision and interpretation +# in the case of reported solutions. +# +# Note: +# +# All letters in hexadecimal (a-f) must be in lowercase. +# The hexadecimal string must not contain extra leading 0s. If the number is zero, +# it is represented by a single zero character '0'; otherwise, +# the first character in the hexadecimal string will not be the zero character. +# The given number is guaranteed to fit within the range of a 32-bit signed integer. +# You must not use any method provided by the library which converts/formats the number to hex directly. +# Example 1: +# +# Input: +# 26 +# +# Output: +# "1a" +# Example 2: +# +# Input: +# -1 +# +# Output: +# "ffffffff" + +class Solution(object): + def toHex(self, num): + """ + :type num: int + :rtype: str + """ + if not num: + return "0" + + result = [] + while num and len(result) != 8: + h = num & 15 + if h < 10: + result.append(str(chr(ord('0') + h))) + else: + result.append(str(chr(ord('a') + h-10))) + num >>= 4 + result.reverse() + + return "".join(result) From 6961418006e8cced45d5d69c29c18607ddc42a44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 17:19:00 +0800 Subject: [PATCH 2855/4971] Create sum-of-left-leaves.py --- Python/sum-of-left-leaves.py | 38 ++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/sum-of-left-leaves.py diff --git a/Python/sum-of-left-leaves.py b/Python/sum-of-left-leaves.py new file mode 100644 index 000000000..4ca0bd5c0 --- /dev/null +++ b/Python/sum-of-left-leaves.py @@ -0,0 +1,38 @@ +# Time: O(n) +# Space: O(h) + +# Find the sum of all left leaves in a given binary tree. +# +# Example: +# +# 3 +# / \ +# 9 20 +# / \ +# 15 7 +# +# There are two left leaves in the binary tree, +# with values 9 and 15 respectively. Return 24. + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def sumOfLeftLeaves(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def sumOfLeftLeavesHelper(root, is_left): + if not root: + return 0 + if not root.left and not root.right: + return root.val if is_left else 0 + return sumOfLeftLeavesHelper(root.left, True) + \ + sumOfLeftLeavesHelper(root.right, False) + + return sumOfLeftLeavesHelper(root, False) From 66572ef731adeafd3fe8bda35c87bf06d1c64b27 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 17:22:03 +0800 Subject: [PATCH 2856/4971] Create sum-of-left-leaves.cpp --- C++/sum-of-left-leaves.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/sum-of-left-leaves.cpp diff --git a/C++/sum-of-left-leaves.cpp b/C++/sum-of-left-leaves.cpp new file mode 100644 index 000000000..21f4ac16a --- /dev/null +++ b/C++/sum-of-left-leaves.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 sumOfLeftLeaves(TreeNode* root) { + return sumOfLeftLeavesHelper(root, false); + } + +private: + int sumOfLeftLeavesHelper(TreeNode* root, bool is_left) { + if (!root) { + return 0; + } + if (!root->left && !root->right) { + return is_left ? root->val : 0; + } + return sumOfLeftLeavesHelper(root->left, true) + + sumOfLeftLeavesHelper(root->right, false); + } +}; From 06241a141f2119e44faa92907fd3d698886c8ea7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 17:25:18 +0800 Subject: [PATCH 2857/4971] Create trapping-rain-water-ii.cpp --- C++/trapping-rain-water-ii.cpp | 75 ++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 C++/trapping-rain-water-ii.cpp diff --git a/C++/trapping-rain-water-ii.cpp b/C++/trapping-rain-water-ii.cpp new file mode 100644 index 000000000..2bd58d895 --- /dev/null +++ b/C++/trapping-rain-water-ii.cpp @@ -0,0 +1,75 @@ +// Time: O(m * n * log(m + n)) ~ O(m * n * log(m * n)) +// Space: O(m * n) + +class Solution { +public: + int trapRainWater(vector>& heightMap) { + if (heightMap.empty()) { + return 0; + } + + // Init m_, n_, is_visited_. + m_ = heightMap.size(); + n_ = heightMap[0].size(); + is_visited_ = vector>(m_, vector(n_, false)); + + int trap = 0; + + // Put the cells on the border into min heap. + for (int i = 0; i < m_; ++i) { + heap_.emplace(Cell{i, 0, heightMap[i][0]}); + heap_.emplace(Cell{i, n_ - 1, heightMap[i][n_ - 1]}); + } + for (int j = 0; j < n_; ++j) { + heap_.emplace(Cell{0, j, heightMap[0][j]}); + heap_.emplace(Cell{m_ - 1, j, heightMap[m_ - 1][j]}); + } + const vector> directions{{0, -1}, {0, 1}, + {-1, 0}, {1, 0}}; + // BFS with priority queue (min heap) + while (!heap_.empty()) { + Cell c = heap_.top(); + heap_.pop(); + is_visited_[c.i][c.j] = true; + for (const auto& d : directions) { + trap += fill(heightMap, c.i + d.first, c.j + d.second, c.height); + } + } + + return trap; + } + +private: + int fill(const vector>& heightMap, int i, int j, int height) { + // Out of border. + if ( i < 0 || i >= m_ || j < 0 || j >= n_) { + return 0; + } + + // Fill unvisited cell. + if (!is_visited_[i][j]) { + is_visited_[i][j] = true; // Marked as visited. + heap_.emplace(Cell{i, j, max(height, heightMap[i][j])}); + return max(0, height - heightMap[i][j]); // Fill in the gap. + } + + return 0; + } + + struct Cell { + int i; + int j; + int height; + }; + + struct Compare { + bool operator()(const Cell& a, const Cell& b) { + return a.height > b.height; + } + }; + + int m_; + int n_; + vector> is_visited_; + priority_queue, Compare> heap_; // Use min heap to get the lowerest cell. +}; From d2667eca8ed8201827c808d42fd195d07cd8ecb2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 17:49:45 +0800 Subject: [PATCH 2858/4971] Update trapping-rain-water-ii.cpp --- C++/trapping-rain-water-ii.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/C++/trapping-rain-water-ii.cpp b/C++/trapping-rain-water-ii.cpp index 2bd58d895..70bbabbbc 100644 --- a/C++/trapping-rain-water-ii.cpp +++ b/C++/trapping-rain-water-ii.cpp @@ -18,11 +18,15 @@ class Solution { // Put the cells on the border into min heap. for (int i = 0; i < m_; ++i) { heap_.emplace(Cell{i, 0, heightMap[i][0]}); + is_visited_[i][0] = true; heap_.emplace(Cell{i, n_ - 1, heightMap[i][n_ - 1]}); + is_visited_[i][n_ - 1] = true; } for (int j = 0; j < n_; ++j) { heap_.emplace(Cell{0, j, heightMap[0][j]}); + is_visited_[0][j] = true; heap_.emplace(Cell{m_ - 1, j, heightMap[m_ - 1][j]}); + is_visited_[m_ - 1][j] = true; } const vector> directions{{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; @@ -30,7 +34,6 @@ class Solution { while (!heap_.empty()) { Cell c = heap_.top(); heap_.pop(); - is_visited_[c.i][c.j] = true; for (const auto& d : directions) { trap += fill(heightMap, c.i + d.first, c.j + d.second, c.height); } @@ -48,8 +51,8 @@ class Solution { // Fill unvisited cell. if (!is_visited_[i][j]) { - is_visited_[i][j] = true; // Marked as visited. heap_.emplace(Cell{i, j, max(height, heightMap[i][j])}); + is_visited_[i][j] = true; // Marked as visited. return max(0, height - heightMap[i][j]); // Fill in the gap. } From 1206cf90f26bbe7839b52c741132c2694c6bda12 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 17:53:07 +0800 Subject: [PATCH 2859/4971] Create trapping-rain-water-ii.py --- Python/trapping-rain-water-ii.py | 60 ++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/trapping-rain-water-ii.py diff --git a/Python/trapping-rain-water-ii.py b/Python/trapping-rain-water-ii.py new file mode 100644 index 000000000..921f8197c --- /dev/null +++ b/Python/trapping-rain-water-ii.py @@ -0,0 +1,60 @@ +# Time: O(m * n * log(m + n)) ~ O(m * n * log(m * n)) +# Space: O(m * n) + +# Given an m x n matrix of positive integers representing the height of each unit cell in +# a 2D elevation map, compute the volume of water it is able to trap after raining. +# +# Note: +# Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000. +# +# Example: +# +# Given the following 3x6 height map: +# [ +# [1,4,3,1,3,2], +# [3,2,1,3,2,4], +# [2,3,3,2,3,1] +# ] +# +# Return 4. + +from heapq import heappush, heappop + +class Solution(object): + def trapRainWater(self, heightMap): + """ + :type heightMap: List[List[int]] + :rtype: int + """ + m = len(heightMap) + if not m: + return 0 + n = len(heightMap[0]) + if not n: + return 0 + + visited = [[False for i in xrange(n)] for j in xrange(m)] + + heap = [] + for i in xrange(m): + heappush(heap, [heightMap[i][0], i, 0]) + visited[i][0] = True + heappush(heap, [heightMap[i][n-1], i, n-1]) + visited[i][n-1] = True + for j in xrange(n): + heappush(heap, [heightMap[0][j], 0, j]) + visited[0][j] = True + heappush(heap, [heightMap[m-1][j], m-1, j]) + visited[m-1][j] = True + + trap = 0 + while heap: + height, i, j = heappop(heap) + for (dx, dy) in [(1,0), (-1,0), (0,1), (0,-1)]: + x, y = i+dx, j+dy + if 0 <= x < m and 0 <= y < n and not visited[x][y]: + trap += max(0, height - heightMap[x][y]) # how much water at the cell + heappush(heap, [max(height, heightMap[x][y]), x, y]) + visited[x][y] = True + + return trap From 9b2120873d4418057712fe9e2a341924d8f929a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 17:54:12 +0800 Subject: [PATCH 2860/4971] Update trapping-rain-water-ii.cpp --- C++/trapping-rain-water-ii.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/C++/trapping-rain-water-ii.cpp b/C++/trapping-rain-water-ii.cpp index 70bbabbbc..97c231218 100644 --- a/C++/trapping-rain-water-ii.cpp +++ b/C++/trapping-rain-water-ii.cpp @@ -4,13 +4,16 @@ class Solution { public: int trapRainWater(vector>& heightMap) { - if (heightMap.empty()) { - return 0; - } - // Init m_, n_, is_visited_. m_ = heightMap.size(); + if (!m_) { + return 0; + } n_ = heightMap[0].size(); + if (!n_) { + return 0; + } + is_visited_ = vector>(m_, vector(n_, false)); int trap = 0; From 321eb2cc3497ce3dd0e2510fcbcb3cbe540f31ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 18:05:01 +0800 Subject: [PATCH 2861/4971] Update README.md --- README.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a93368fab..2224b1fd1 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-403%20%2F%20403-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-407%20%2F%20407-ff69b4.svg) -Up to date (2016-09-18), there are `386` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-09-25), there are `390` 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 `403` questions. +Here is the classification of all `407` 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.) @@ -128,6 +128,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | | 383| [Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./C++/ransom-note.cpp) [Python](./Python/ransom-note.py) | _O(n)_ | _O(1)_ | Easy | EPI | +405| [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./C++/convert-a-number-to-hexadecimal.cpp) [Python](./Python/convert-a-number-to-hexadecimal.py) | _O(n)_ | _O(1)_ | Easy | | ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -189,6 +190,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 358| [Rearrange String k Distance Apart](https://leetcode.com/problems/rearrange-string-k-distance-apart/)| [C++](./C++/rearrange-string-k-distance-apart.cpp) [Python](./Python/rearrange-string-k-distance-apart.py) | _O(n)_ | _O(n)_ | Hard |📖| Greedy, Heap | 373 | [Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/) | [C++](./C++/find-k-pairs-with-smallest-sums.cpp) [Python](./Python/find-k-pairs-with-smallest-sums.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium ||| 378 | [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/) | [C++](./C++/kth-smallest-element-in-a-sorted-matrix.cpp) [Python](./Python/kth-smallest-element-in-a-sorted-matrix.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium | LintCode || +407 | [Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/) | [C++](./C++/trapping-rain-water-ii.cpp) [Python](./Python/trapping-rain-water-ii.py) | _O(m * n * (logm + logn))_ | _O(m * n)_ | Hard | LintCode || ## Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -300,6 +302,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | 347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(n)_ | Medium | | Quick Select, Heap | +406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n^2)_ | _O(n)_ | Medium | | | + ## Two Pointers # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -343,6 +347,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 |📖| 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 || 395| [Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./C++/longest-substring-with-at-least-k-repeating-characters.cpp) [Python](./Python/longest-substring-with-at-least-k-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || +404| [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./C++/sum-of-left-leaves.cpp) [Python](./Python/sum-of-left-leaves.py) | _O(n)_ | _O(h)_ | Easy || ## Binary Search # | Title | Solution | Time | Space | Difficulty | Tag | Note From d13adb98227a24dff65f2e0b8485b3101829a7e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 18:06:43 +0800 Subject: [PATCH 2862/4971] Update trapping-rain-water-ii.py --- Python/trapping-rain-water-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/trapping-rain-water-ii.py b/Python/trapping-rain-water-ii.py index 921f8197c..86cf58e37 100644 --- a/Python/trapping-rain-water-ii.py +++ b/Python/trapping-rain-water-ii.py @@ -53,7 +53,7 @@ def trapRainWater(self, heightMap): for (dx, dy) in [(1,0), (-1,0), (0,1), (0,-1)]: x, y = i+dx, j+dy if 0 <= x < m and 0 <= y < n and not visited[x][y]: - trap += max(0, height - heightMap[x][y]) # how much water at the cell + trap += max(0, height - heightMap[x][y]) heappush(heap, [max(height, heightMap[x][y]), x, y]) visited[x][y] = True From 623bf43486187c1b6c4c0f97d3cba4c13c7b1cbd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 18:09:13 +0800 Subject: [PATCH 2863/4971] Update trapping-rain-water-ii.py --- Python/trapping-rain-water-ii.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Python/trapping-rain-water-ii.py b/Python/trapping-rain-water-ii.py index 86cf58e37..8a1037979 100644 --- a/Python/trapping-rain-water-ii.py +++ b/Python/trapping-rain-water-ii.py @@ -33,28 +33,28 @@ def trapRainWater(self, heightMap): if not n: return 0 - visited = [[False for i in xrange(n)] for j in xrange(m)] + is_visited = [[False for i in xrange(n)] for j in xrange(m)] heap = [] for i in xrange(m): heappush(heap, [heightMap[i][0], i, 0]) - visited[i][0] = True + is_visited[i][0] = True heappush(heap, [heightMap[i][n-1], i, n-1]) - visited[i][n-1] = True + is_visited[i][n-1] = True for j in xrange(n): heappush(heap, [heightMap[0][j], 0, j]) - visited[0][j] = True + is_visited[0][j] = True heappush(heap, [heightMap[m-1][j], m-1, j]) - visited[m-1][j] = True + is_visited[m-1][j] = True trap = 0 while heap: height, i, j = heappop(heap) for (dx, dy) in [(1,0), (-1,0), (0,1), (0,-1)]: x, y = i+dx, j+dy - if 0 <= x < m and 0 <= y < n and not visited[x][y]: + if 0 <= x < m and 0 <= y < n and not is_visited[x][y]: trap += max(0, height - heightMap[x][y]) heappush(heap, [max(height, heightMap[x][y]), x, y]) - visited[x][y] = True + is_visited[x][y] = True return trap From 1762506bf4b336304aa513a96fc058eb2c95c85f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Sep 2016 23:34:42 +0800 Subject: [PATCH 2864/4971] Update queue-reconstruction-by-height.cpp --- C++/queue-reconstruction-by-height.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/queue-reconstruction-by-height.cpp b/C++/queue-reconstruction-by-height.cpp index 1dbc3cb7c..14e3b7a4d 100644 --- a/C++/queue-reconstruction-by-height.cpp +++ b/C++/queue-reconstruction-by-height.cpp @@ -5,9 +5,9 @@ class Solution { public: vector> reconstructQueue(vector>& people) { sort(people.begin(), people.end(), - [](const pair& a, pair& b) { - return b.first == a.first ? a.second < b.second : b.first < a.first; - }); + [](const pair& a, pair& b) { + return b.first == a.first ? a.second < b.second : b.first < a.first; + }); vector> result; for (const auto& p : people) { result.insert(result.begin() + p.second, p); From e7a983792e610eec37740f6902030e687d07b493 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Sep 2016 00:29:10 +0800 Subject: [PATCH 2865/4971] Update queue-reconstruction-by-height.py --- Python/queue-reconstruction-by-height.py | 31 ++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/Python/queue-reconstruction-by-height.py b/Python/queue-reconstruction-by-height.py index 73a8010ba..7863a79ff 100644 --- a/Python/queue-reconstruction-by-height.py +++ b/Python/queue-reconstruction-by-height.py @@ -1,4 +1,4 @@ -# Time: O(n^2) +# Time: O(n * sqrt(n)) # Space: O(n) # Suppose you have a random list of people standing in a queue. @@ -24,7 +24,34 @@ def reconstructQueue(self, people): :type people: List[List[int]] :rtype: List[List[int]] """ - people.sort(key=lambda x: (-x[0], x[1])) + people.sort(key=lambda (h, k): (-h, k)) + + blocks = [[]] + for p in people: + index = p[1] + + for i, block in enumerate(blocks): + if index <= len(block): + break + index -= len(block) + block.insert(index, p) + + if len(block) * len(block) > len(people): + blocks.insert(i+1, block[len(block)/2:]) + del block[len(block)/2:] + + return [p for block in blocks for p in block] + + +# Time: O(n^2) +# Space: O(n) +class Solution2(object): + def reconstructQueue(self, people): + """ + :type people: List[List[int]] + :rtype: List[List[int]] + """ + people.sort(key=lambda (h, k): (-h, k)) result = [] for p in people: result.insert(p[1], p) From 99345effe1fa77846e39844cc8ab9933cb30fab4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Sep 2016 00:47:42 +0800 Subject: [PATCH 2866/4971] Update queue-reconstruction-by-height.cpp --- C++/queue-reconstruction-by-height.cpp | 42 +++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/C++/queue-reconstruction-by-height.cpp b/C++/queue-reconstruction-by-height.cpp index 14e3b7a4d..8d2e2af31 100644 --- a/C++/queue-reconstruction-by-height.cpp +++ b/C++/queue-reconstruction-by-height.cpp @@ -1,7 +1,47 @@ -// Time: O(n^2) +// Time: O(n * sqrt(n)) // Space: O(n) class Solution { +public: + vector> reconstructQueue(vector>& people) { + sort(people.begin(), people.end(), + [](const pair& a, pair& b) { + return b.first == a.first ? a.second < b.second : b.first < a.first; + }); + + vector>> blocks(1); + for (const auto& p : people) { + auto index = p.second; + int i = 0; + for (; i < blocks.size(); ++i) { + if (index <= blocks[i].size()) { + break; + } + index -= blocks[i].size(); + } + blocks[i].insert(blocks[i].begin() + index, p); + + if (blocks[i].size() * blocks[i].size() > people.size()) { + blocks.insert(blocks.begin() + i + 1, + vector>(blocks[i].begin() + blocks[i].size() / 2, + blocks[i].end())); + blocks[i].erase(blocks[i].begin() + blocks[i].size() / 2, blocks[i].end()); + } + } + + vector> result; + for (const auto& block : blocks) { + for (const auto& p : block) { + result.emplace_back(p); + } + } + return result; + } +}; + +// Time: O(n^2) +// Space: O(n) +class Solution2 { public: vector> reconstructQueue(vector>& people) { sort(people.begin(), people.end(), From eb71301d2eff6491fdb6dc2a375108df8b02bb30 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Sep 2016 00:48:58 +0800 Subject: [PATCH 2867/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2224b1fd1..5bbf6f261 100644 --- a/README.md +++ b/README.md @@ -302,7 +302,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | 347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(n)_ | Medium | | Quick Select, Heap | -406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n^2)_ | _O(n)_ | Medium | | | +406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium | | | ## Two Pointers From dc491937681399c682994249526637dcd3b94c0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Sep 2016 00:50:10 +0800 Subject: [PATCH 2868/4971] Update queue-reconstruction-by-height.cpp --- C++/queue-reconstruction-by-height.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/queue-reconstruction-by-height.cpp b/C++/queue-reconstruction-by-height.cpp index 8d2e2af31..eeffd314e 100644 --- a/C++/queue-reconstruction-by-height.cpp +++ b/C++/queue-reconstruction-by-height.cpp @@ -19,12 +19,12 @@ class Solution { } index -= blocks[i].size(); } - blocks[i].insert(blocks[i].begin() + index, p); + blocks[i].emplace(blocks[i].begin() + index, p); if (blocks[i].size() * blocks[i].size() > people.size()) { - blocks.insert(blocks.begin() + i + 1, - vector>(blocks[i].begin() + blocks[i].size() / 2, - blocks[i].end())); + blocks.emplace(blocks.begin() + i + 1, + vector>(blocks[i].begin() + blocks[i].size() / 2, + blocks[i].end())); blocks[i].erase(blocks[i].begin() + blocks[i].size() / 2, blocks[i].end()); } } @@ -50,7 +50,7 @@ class Solution2 { }); vector> result; for (const auto& p : people) { - result.insert(result.begin() + p.second, p); + result.emplace(result.begin() + p.second, p); } return result; } From 9ed183c3023a826cb229808a088f45b153cbbae8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Sep 2016 00:56:32 +0800 Subject: [PATCH 2869/4971] Update queue-reconstruction-by-height.cpp --- C++/queue-reconstruction-by-height.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/queue-reconstruction-by-height.cpp b/C++/queue-reconstruction-by-height.cpp index eeffd314e..8e89d5cce 100644 --- a/C++/queue-reconstruction-by-height.cpp +++ b/C++/queue-reconstruction-by-height.cpp @@ -23,8 +23,8 @@ class Solution { if (blocks[i].size() * blocks[i].size() > people.size()) { blocks.emplace(blocks.begin() + i + 1, - vector>(blocks[i].begin() + blocks[i].size() / 2, - blocks[i].end())); + blocks[i].begin() + blocks[i].size() / 2, + blocks[i].end()); blocks[i].erase(blocks[i].begin() + blocks[i].size() / 2, blocks[i].end()); } } From 967ccfea7b0052b1ad28f0201443d11d85cf6070 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Sep 2016 00:57:07 +0800 Subject: [PATCH 2870/4971] Update queue-reconstruction-by-height.cpp --- C++/queue-reconstruction-by-height.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/queue-reconstruction-by-height.cpp b/C++/queue-reconstruction-by-height.cpp index 8e89d5cce..0f5bf98cf 100644 --- a/C++/queue-reconstruction-by-height.cpp +++ b/C++/queue-reconstruction-by-height.cpp @@ -5,9 +5,9 @@ class Solution { public: vector> reconstructQueue(vector>& people) { sort(people.begin(), people.end(), - [](const pair& a, pair& b) { - return b.first == a.first ? a.second < b.second : b.first < a.first; - }); + [](const pair& a, pair& b) { + return b.first == a.first ? a.second < b.second : b.first < a.first; + }); vector>> blocks(1); for (const auto& p : people) { From eb0bf842f2912e7928455d8e602c81d566543929 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Sep 2016 21:37:58 +0800 Subject: [PATCH 2871/4971] Create binary-tree-level-order-traversal.cpp --- C++/binary-tree-level-order-traversal.cpp | 42 +++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/binary-tree-level-order-traversal.cpp diff --git a/C++/binary-tree-level-order-traversal.cpp b/C++/binary-tree-level-order-traversal.cpp new file mode 100644 index 000000000..96e751a8c --- /dev/null +++ b/C++/binary-tree-level-order-traversal.cpp @@ -0,0 +1,42 @@ +// 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> levelOrder(TreeNode* root) { + vector> result; + queue que; + + if (root != nullptr) { + que.emplace(root); + } + + while (!que.empty()) { + vector level; + int size = que.size(); + for (int i = 0; i < size; i++) { + auto *front = que.front(); + que.pop(); + level.emplace_back(front->val); + if (front->left != nullptr) { + que.emplace(front->left); + } + if (front->right != nullptr) { + que.emplace(front->right); + } + } + result.emplace_back(move(level)); + } + + return result; + } +}; From f427a8b2d41834fb0c4b3d8687af23faeed75339 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Sep 2016 21:38:58 +0800 Subject: [PATCH 2872/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5bbf6f261..41bca8948 100644 --- a/README.md +++ b/README.md @@ -385,7 +385,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Breadth-First Search # | 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 || +102| [Binary Tree z Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [C++](./C++/binary-tree-level-order-traversal.cpp) [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 || From 48bc0080359d7b2af95f10a80794397466639a5a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Sep 2016 21:39:28 +0800 Subject: [PATCH 2873/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 41bca8948..e9e3cd3ef 100644 --- a/README.md +++ b/README.md @@ -385,7 +385,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Breadth-First Search # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- -102| [Binary Tree z Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [C++](./C++/binary-tree-level-order-traversal.cpp) [Python](./Python/binary-tree-level-order-traversal.py)| _O(n)_| _O(n)_| Easy || +102| [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)| [C++](./C++/binary-tree-level-order-traversal.cpp) [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 || From 12fc8eaf9f1d7b81b2a6e0cc9d4a23efb8e780f7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 29 Sep 2016 23:05:09 +0800 Subject: [PATCH 2874/4971] Update and rename buildTreeWithPreOrder.cpp to construct-binary-tree-from-preorder-and-inorder-traversal.cpp --- C++/buildTreeWithPreOrder.cpp | 35 --------------- ...ee-from-preorder-and-inorder-traversal.cpp | 43 +++++++++++++++++++ 2 files changed, 43 insertions(+), 35 deletions(-) delete mode 100644 C++/buildTreeWithPreOrder.cpp create mode 100644 C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp diff --git a/C++/buildTreeWithPreOrder.cpp b/C++/buildTreeWithPreOrder.cpp deleted file mode 100644 index e5c1b0dde..000000000 --- a/C++/buildTreeWithPreOrder.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(logn) - -/** - * Definition for binary tree - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - public: - TreeNode* buildTree(vector& preorder, vector& inorder) { - return buildTree(begin(preorder), end(preorder), begin(inorder), end(inorder)); - } - - private: - template - TreeNode* buildTree(InputIterator pre_first, InputIterator pre_last, InputIterator in_first, InputIterator in_last) { - if(pre_first == pre_last) - return NULL; - if(in_first == in_last) - return NULL; - - auto root = new TreeNode(*pre_first); - auto inRootPos = find(in_first, in_last, *pre_first); - auto leftSize = distance(in_first, inRootPos); - root->left = buildTree(next(pre_first), next(pre_first, leftSize + 1), in_first, inRootPos); - root->right = buildTree(next(pre_first, leftSize + 1), pre_last, next(inRootPos), in_last); - - return root; - } -}; diff --git a/C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp b/C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp new file mode 100644 index 000000000..6657abdd1 --- /dev/null +++ b/C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp @@ -0,0 +1,43 @@ +// 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: + TreeNode* buildTree(vector& preorder, vector& inorder) { + unordered_map in_entry_idx_map; + for (size_t i = 0; i < inorder.size(); ++i) { + in_entry_idx_map.emplace(inorder[i], i); + } + return ReconstructPreInOrdersHelper(preorder, 0, preorder.size(), inorder, 0, inorder.size(), + in_entry_idx_map); + } + + // Reconstructs the binary tree from pre[pre_s : pre_e - 1] and + // in[in_s : in_e - 1]. + TreeNode *ReconstructPreInOrdersHelper(const vector& preorder, size_t pre_s, size_t pre_e, + const vector& inorder, size_t in_s, size_t in_e, + const unordered_map& in_entry_idx_map) { + if (pre_s == pre_e || in_s == in_e) { + return nullptr; + } + + auto idx = in_entry_idx_map.at(preorder[pre_s]); + auto left_tree_size = idx - in_s; + + auto node = new TreeNode(preorder[pre_s]); + node->left = ReconstructPreInOrdersHelper(preorder, pre_s + 1, pre_s + 1 + left_tree_size, + inorder, in_s, idx, in_entry_idx_map); + node->right = ReconstructPreInOrdersHelper(preorder, pre_s + 1 + left_tree_size, pre_e, + inorder, idx + 1, in_e, in_entry_idx_map); + return node; + } +}; From edc578edf7b48996a51d07eea05aaf242cd21559 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 29 Sep 2016 23:06:19 +0800 Subject: [PATCH 2875/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9e3cd3ef..b5714c4f9 100644 --- a/README.md +++ b/README.md @@ -330,7 +330,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 98| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[C++](./C++/validate-binary-search-tree.cpp) [Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || 100| [Same Tree](https://leetcode.com/problems/same-tree/) |[C+](./C++/same-tree.cpp) [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/)| [C++](./C++/maximum-depth-of-binary-tree.cpp) [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 || +105| [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [C++](./C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp) [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 || From 4ed5b25769756c022cf7f1784a216bc6764b9ae4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 29 Sep 2016 23:07:06 +0800 Subject: [PATCH 2876/4971] Update construct-binary-tree-from-preorder-and-inorder-traversal.cpp --- ...onstruct-binary-tree-from-preorder-and-inorder-traversal.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp b/C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp index 6657abdd1..f6281ebbb 100644 --- a/C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp +++ b/C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(h) +// Space: O(n) /** * Definition for a binary tree node. From 6380bc849fbe3b39555a5392a1b009b8628c91ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Oct 2016 23:16:52 +0800 Subject: [PATCH 2877/4971] Create construct-binary-tree-from-inorder-and-postorder-traversal.cpp --- ...e-from-inorder-and-postorder-traversal.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp diff --git a/C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp b/C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp new file mode 100644 index 000000000..399af20c8 --- /dev/null +++ b/C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp @@ -0,0 +1,43 @@ +// 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: + TreeNode* buildTree(vector& inorder, vector& postorder) { + unordered_map in_entry_idx_map; + for (size_t i = 0; i < inorder.size(); ++i) { + in_entry_idx_map.emplace(inorder[i], i); + } + return ReconstructPostInOrdersHelper(postorder, 0, postorder.size(), inorder, 0, inorder.size(), + in_entry_idx_map); + } + + TreeNode * ReconstructPostInOrdersHelper(const vector& postorder, size_t post_s, size_t post_e, + const vector& inorder, size_t in_s, size_t in_e, + const unordered_map& in_entry_idx_map) { + if (post_s == post_e || in_s == in_e) { + return nullptr; + } + + auto idx = in_entry_idx_map.at(postorder[post_e - 1]); + auto left_tree_size = idx - in_s; + + TreeNode *node = new TreeNode(postorder[post_e - 1]); + // Recursively builds the left subtree. + node->left =ReconstructPostInOrdersHelper(postorder, post_s, post_s + left_tree_size, + inorder, in_s, idx, in_entry_idx_map); + // Recursively builds the right subtree. + node->right = ReconstructPostInOrdersHelper(postorder, post_s + left_tree_size, post_e - 1, + inorder, idx + 1, in_e, in_entry_idx_map); + return node; + } +}; From b68ba6737caefe34ee81eab7dd08124fa16bd78b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Oct 2016 23:17:38 +0800 Subject: [PATCH 2878/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b5714c4f9..d0d61a0d6 100644 --- a/README.md +++ b/README.md @@ -331,7 +331,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 100| [Same Tree](https://leetcode.com/problems/same-tree/) |[C+](./C++/same-tree.cpp) [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/)| [C++](./C++/maximum-depth-of-binary-tree.cpp) [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/) | [C++](./C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp) [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 || +106| [Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | [C++](./C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp) [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 || From 062e052fb6b17add75bdb10a8c634bc6f3191a86 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Oct 2016 23:19:17 +0800 Subject: [PATCH 2879/4971] Delete construct-binary-tree-from-inorder-and-postorder-traversal.cpp --- ...e-from-inorder-and-postorder-traversal.cpp | 43 ------------------- 1 file changed, 43 deletions(-) delete mode 100644 C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp diff --git a/C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp b/C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp deleted file mode 100644 index 399af20c8..000000000 --- a/C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// 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: - TreeNode* buildTree(vector& inorder, vector& postorder) { - unordered_map in_entry_idx_map; - for (size_t i = 0; i < inorder.size(); ++i) { - in_entry_idx_map.emplace(inorder[i], i); - } - return ReconstructPostInOrdersHelper(postorder, 0, postorder.size(), inorder, 0, inorder.size(), - in_entry_idx_map); - } - - TreeNode * ReconstructPostInOrdersHelper(const vector& postorder, size_t post_s, size_t post_e, - const vector& inorder, size_t in_s, size_t in_e, - const unordered_map& in_entry_idx_map) { - if (post_s == post_e || in_s == in_e) { - return nullptr; - } - - auto idx = in_entry_idx_map.at(postorder[post_e - 1]); - auto left_tree_size = idx - in_s; - - TreeNode *node = new TreeNode(postorder[post_e - 1]); - // Recursively builds the left subtree. - node->left =ReconstructPostInOrdersHelper(postorder, post_s, post_s + left_tree_size, - inorder, in_s, idx, in_entry_idx_map); - // Recursively builds the right subtree. - node->right = ReconstructPostInOrdersHelper(postorder, post_s + left_tree_size, post_e - 1, - inorder, idx + 1, in_e, in_entry_idx_map); - return node; - } -}; From 2d4e24bd98d2e1526a4e47e333c0e6cefb8c8759 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Oct 2016 23:20:05 +0800 Subject: [PATCH 2880/4971] Update and rename buildTreeWithPostOrder.cpp to construct-binary-tree-from-inorder-and-postorder-traversal.cpp --- C++/buildTreeWithPostOrder.cpp | 35 --------------- ...e-from-inorder-and-postorder-traversal.cpp | 43 +++++++++++++++++++ 2 files changed, 43 insertions(+), 35 deletions(-) delete mode 100644 C++/buildTreeWithPostOrder.cpp create mode 100644 C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp diff --git a/C++/buildTreeWithPostOrder.cpp b/C++/buildTreeWithPostOrder.cpp deleted file mode 100644 index 7510393a9..000000000 --- a/C++/buildTreeWithPostOrder.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(logn) - -/** - * Definition for binary tree - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - public: - TreeNode *buildTree(vector &inorder, vector &postorder) { - return buildTree(begin(inorder), end(inorder), begin(postorder), end(postorder)); - } - private: - template - TreeNode *buildTree(InputIterator in_first, InputIterator in_last, InputIterator post_first, InputIterator post_last) { - if(in_first == in_last) - return NULL; - if(post_first == post_last) - return NULL; - - auto root = new TreeNode(*prev(post_last)); - auto inRootPos = find(in_first, in_last, *prev(post_last)); - auto leftSize = distance(in_first, inRootPos); - root->left = buildTree(in_first, inRootPos, post_first, next(post_first, leftSize)); - root->right = buildTree(next(inRootPos), in_last, next(post_first, leftSize), prev(post_last)); - - return root; - } - -}; diff --git a/C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp b/C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp new file mode 100644 index 000000000..399af20c8 --- /dev/null +++ b/C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp @@ -0,0 +1,43 @@ +// 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: + TreeNode* buildTree(vector& inorder, vector& postorder) { + unordered_map in_entry_idx_map; + for (size_t i = 0; i < inorder.size(); ++i) { + in_entry_idx_map.emplace(inorder[i], i); + } + return ReconstructPostInOrdersHelper(postorder, 0, postorder.size(), inorder, 0, inorder.size(), + in_entry_idx_map); + } + + TreeNode * ReconstructPostInOrdersHelper(const vector& postorder, size_t post_s, size_t post_e, + const vector& inorder, size_t in_s, size_t in_e, + const unordered_map& in_entry_idx_map) { + if (post_s == post_e || in_s == in_e) { + return nullptr; + } + + auto idx = in_entry_idx_map.at(postorder[post_e - 1]); + auto left_tree_size = idx - in_s; + + TreeNode *node = new TreeNode(postorder[post_e - 1]); + // Recursively builds the left subtree. + node->left =ReconstructPostInOrdersHelper(postorder, post_s, post_s + left_tree_size, + inorder, in_s, idx, in_entry_idx_map); + // Recursively builds the right subtree. + node->right = ReconstructPostInOrdersHelper(postorder, post_s + left_tree_size, post_e - 1, + inorder, idx + 1, in_e, in_entry_idx_map); + return node; + } +}; From 4a9f60a1df53f2c24343fb127bfaa165ee2dbbdb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 2 Oct 2016 23:34:28 +0800 Subject: [PATCH 2881/4971] Create split-array-largest-sum.cpp --- C++/split-array-largest-sum.cpp | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/split-array-largest-sum.cpp diff --git a/C++/split-array-largest-sum.cpp b/C++/split-array-largest-sum.cpp new file mode 100644 index 000000000..a931dd520 --- /dev/null +++ b/C++/split-array-largest-sum.cpp @@ -0,0 +1,37 @@ +// Time: O(nlogn) +// Space: O(1) + +class Solution { +public: + int splitArray(vector& nums, int m) { + int left = 0, right = 0; + for (const auto& num : nums) { + left = max(left, num); + right += num; + } + + while (left <= right) { + int mid = left + (right - left) / 2; + if (canSplit(nums, m, mid)) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } + +private: + bool canSplit(vector& nums, int m, int sum) { + int cnt = 1; + int curr_sum = 0; + for (const auto& num : nums) { + curr_sum += num; + if (curr_sum > sum) { + curr_sum = num; + ++cnt; + } + } + return cnt <= m; + } +}; From 84b82d51c682e4143e0ed4c96efcd45f812127a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 2 Oct 2016 23:35:25 +0800 Subject: [PATCH 2882/4971] Update split-array-largest-sum.cpp --- C++/split-array-largest-sum.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/split-array-largest-sum.cpp b/C++/split-array-largest-sum.cpp index a931dd520..6281d174e 100644 --- a/C++/split-array-largest-sum.cpp +++ b/C++/split-array-largest-sum.cpp @@ -11,7 +11,7 @@ class Solution { } while (left <= right) { - int mid = left + (right - left) / 2; + const auto mid = left + (right - left) / 2; if (canSplit(nums, m, mid)) { right = mid - 1; } else { @@ -23,8 +23,7 @@ class Solution { private: bool canSplit(vector& nums, int m, int sum) { - int cnt = 1; - int curr_sum = 0; + int cnt = 1, curr_sum = 0; for (const auto& num : nums) { curr_sum += num; if (curr_sum > sum) { From 73f620915ee3d68b457b1e2adc77fe27dbdd0004 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 2 Oct 2016 23:43:10 +0800 Subject: [PATCH 2883/4971] Create longest-palindrome.cpp --- C++/longest-palindrome.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/longest-palindrome.cpp diff --git a/C++/longest-palindrome.cpp b/C++/longest-palindrome.cpp new file mode 100644 index 000000000..019ceb2f8 --- /dev/null +++ b/C++/longest-palindrome.cpp @@ -0,0 +1,13 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int longestPalindrome(string s) { + int odds = 0; + for (auto c = 'A'; c <= 'z'; ++c) { + odds += count(s.cbegin(), s.cend(), c) & 1; + } + return s.length() - odds + (odds > 0); + } +}; From 1e33f2160cd0f12172ba7838c3db08ce93c3f436 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 2 Oct 2016 23:54:01 +0800 Subject: [PATCH 2884/4971] Create valid-word-abbreviation.cpp --- C++/valid-word-abbreviation.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/valid-word-abbreviation.cpp diff --git a/C++/valid-word-abbreviation.cpp b/C++/valid-word-abbreviation.cpp new file mode 100644 index 000000000..a60bcf47d --- /dev/null +++ b/C++/valid-word-abbreviation.cpp @@ -0,0 +1,30 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool validWordAbbreviation(string word, string abbr) { + int i = 0, digit = 0; + for (const auto& c : abbr) { + if (isdigit(c)) { + if (digit == 0 && c == '0') { + return false; + } + digit *= 10; + digit += c - '0'; + } else { + if (digit) { + i += digit; + digit = 0; + } + if (i >= word.length() || word[i++] != c) { + return false; + } + } + } + if (digit) { + i += digit; + } + return i == word.length(); + } +}; From 3ef6be20d4eb98e05d79159486b907bdfe523a72 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Oct 2016 21:26:50 +0800 Subject: [PATCH 2885/4971] Update split-array-largest-sum.cpp --- C++/split-array-largest-sum.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/split-array-largest-sum.cpp b/C++/split-array-largest-sum.cpp index 6281d174e..b39e527a5 100644 --- a/C++/split-array-largest-sum.cpp +++ b/C++/split-array-largest-sum.cpp @@ -1,4 +1,4 @@ -// Time: O(nlogn) +// Time: O(nlogs), s is the sum of nums // Space: O(1) class Solution { From 0795585e9efbf453b9c3cbab88fd523a15cab46f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 5 Oct 2016 23:43:41 +0800 Subject: [PATCH 2886/4971] Create split-array-largest-sum.py --- Python/split-array-largest-sum.py | 52 +++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/split-array-largest-sum.py diff --git a/Python/split-array-largest-sum.py b/Python/split-array-largest-sum.py new file mode 100644 index 000000000..5c67d4692 --- /dev/null +++ b/Python/split-array-largest-sum.py @@ -0,0 +1,52 @@ +# Time: O(nlogs), s is the sum of nums +# Space: O(1) + +# Given an array which consists of non-negative integers and an integer m, +# you can split the array into m non-empty continuous subarrays. +# Write an algorithm to minimize the largest sum among these m subarrays. +# +# Note: +# Given m satisfies the following constraint: 1 <= m <= length(nums) <= 14,000. +# +# Examples: +# +# Input: +# nums = [7,2,5,10,8] +# m = 2 +# +# Output: +# 18 +# +# Explanation: +# There are four ways to split nums into two subarrays. +# The best way is to split it into [7,2,5] and [10,8], +# where the largest sum among the two subarrays is only 18. + +class Solution(object): + def splitArray(self, nums, m): + """ + :type nums: List[int] + :type m: int + :rtype: int + """ + def canSplit(nums, m, s): + cnt, curr_sum = 1, 0 + for num in nums: + curr_sum += num + if curr_sum > s: + curr_sum = num + cnt += 1 + return cnt <= m + + left, right = 0, 0 + for num in nums: + left = max(left, num) + right += num + + while left <= right: + mid = left + (right - left) / 2; + if canSplit(nums, m, mid): + right = mid - 1 + else: + left = mid + 1 + return left From 6331b906254e2050eac3067a460f646cbb5977b0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 00:30:26 +0800 Subject: [PATCH 2887/4971] Create minimum-unique-word-abbreviation.cpp --- C++/minimum-unique-word-abbreviation.cpp | 96 ++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 C++/minimum-unique-word-abbreviation.cpp diff --git a/C++/minimum-unique-word-abbreviation.cpp b/C++/minimum-unique-word-abbreviation.cpp new file mode 100644 index 000000000..c63d4e713 --- /dev/null +++ b/C++/minimum-unique-word-abbreviation.cpp @@ -0,0 +1,96 @@ +// Time: O(2^n) +// Space: O(n) + +class Solution { +public: + string minAbbreviation(string target, vector& dictionary) { + vector bits_dict; + int bit_candidates = 0; + dict_to_bits_dict(target, dictionary, &bits_dict, &bit_candidates); + + int min_len = numeric_limits::max(), min_abbr = 0; + dfs(target, bit_candidates, 1, 0, &bits_dict, &min_len, &min_abbr); + + return bits_to_abbr(target, min_abbr); + } + +private: + void dfs(const string& target, int bit_candidates, int bit, int mask, + vector *bits_dict, int *min_len, int *min_abbr) { + + const auto len = abbr_len(target, mask); + if (len >= *min_len) { + return; + } + + bool match = true; + for (const auto& d : *bits_dict) { + if ((mask & d) == 0) { + match = false; + break; + } + } + if (match) { + *min_len = len; + *min_abbr = mask; + } else { + for (int b = bit; b < (1 << target.length()); b <<= 1) { + if (bit_candidates & b) { + dfs(target, bit_candidates, b << 1, mask | b, bits_dict, min_len, min_abbr); + } + } + } + } + + void dict_to_bits_dict(const string& target, const vector& dictionary, + vector *bits_dict, int *bit_candidates) { + for (const auto& w : dictionary) { + int word = 0; + if (w.length() != target.length()) { + continue; + } + for (int i = target.length() - 1, bit = 1; i >= 0; --i, bit <<= 1) { + if (target[i] != w[i]) { + word |= bit; + } + } + bits_dict->emplace_back(word); + *bit_candidates |= word; + } + } + + int abbr_len(const string& target, int mask) { + int count = 0; + for (int b = 1; b < (1 << target.length());) { + if ((mask & b) == 0) { + for (; b < (1 << target.length()) && (mask & b) == 0; b <<= 1); + } else { + b <<= 1; + } + ++count; + } + return count; + } + + string bits_to_abbr(const string& target, int min_abbr) { + vector tmp; + for (int i = target.length() - 1, pre = i; i >= 0; --i, min_abbr >>= 1) { + if (min_abbr & 1) { + if (pre - i > 0) { + tmp.emplace_back(to_string(pre - i)); + } + pre = i - 1; + tmp.emplace_back(string(1, target[i])); + } else if (i == 0) { + tmp.emplace_back(to_string(pre - i + 1)); + } + } + reverse(tmp.begin(), tmp.end()); + + string abbr; + for (const auto& s : tmp) { + abbr += s; + } + return abbr; + } +}; From cb13c906a53ea901a514300ee4155ae1695b778c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 00:31:56 +0800 Subject: [PATCH 2888/4971] Update minimum-unique-word-abbreviation.cpp --- C++/minimum-unique-word-abbreviation.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/minimum-unique-word-abbreviation.cpp b/C++/minimum-unique-word-abbreviation.cpp index c63d4e713..b132dd9c3 100644 --- a/C++/minimum-unique-word-abbreviation.cpp +++ b/C++/minimum-unique-word-abbreviation.cpp @@ -15,7 +15,7 @@ class Solution { } private: - void dfs(const string& target, int bit_candidates, int bit, int mask, + void dfs(const string& target, int bit_candidates, int bits, int mask, vector *bits_dict, int *min_len, int *min_abbr) { const auto len = abbr_len(target, mask); @@ -34,7 +34,7 @@ class Solution { *min_len = len; *min_abbr = mask; } else { - for (int b = bit; b < (1 << target.length()); b <<= 1) { + for (int b = bits; b < (1 << target.length()); b <<= 1) { if (bit_candidates & b) { dfs(target, bit_candidates, b << 1, mask | b, bits_dict, min_len, min_abbr); } From f53695c9c9906dc6a4e483e1557b879c5c2c8e18 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 00:36:11 +0800 Subject: [PATCH 2889/4971] Update minimum-unique-word-abbreviation.cpp --- C++/minimum-unique-word-abbreviation.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/minimum-unique-word-abbreviation.cpp b/C++/minimum-unique-word-abbreviation.cpp index b132dd9c3..968796906 100644 --- a/C++/minimum-unique-word-abbreviation.cpp +++ b/C++/minimum-unique-word-abbreviation.cpp @@ -45,17 +45,17 @@ class Solution { void dict_to_bits_dict(const string& target, const vector& dictionary, vector *bits_dict, int *bit_candidates) { for (const auto& w : dictionary) { - int word = 0; + int bits = 0; if (w.length() != target.length()) { continue; } for (int i = target.length() - 1, bit = 1; i >= 0; --i, bit <<= 1) { if (target[i] != w[i]) { - word |= bit; + bits |= bit; } } - bits_dict->emplace_back(word); - *bit_candidates |= word; + bits_dict->emplace_back(bits); + *bit_candidates |= bits; } } From a93bffb949e91df7ad20273235f48a0f4f0217f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 21:56:33 +0800 Subject: [PATCH 2890/4971] Update design-snake-game.cpp --- C++/design-snake-game.cpp | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/C++/design-snake-game.cpp b/C++/design-snake-game.cpp index b3946edc2..432e19114 100644 --- a/C++/design-snake-game.cpp +++ b/C++/design-snake-game.cpp @@ -1,5 +1,5 @@ -// Time: O(s) per move, s is the current length of the snake. -// Space: O(s) +// Time: O(1) per move +// Space: O(s), s is the current length of the snake. class SnakeGame { public: @@ -11,6 +11,8 @@ class SnakeGame { SnakeGame(int width, int height, vector> food) : width_{width}, height_{height}, score_{0}, food_{food.begin(), food.end()}, snake_{{0, 0}} { + + lookup_.emplace(0); } /** Moves the snake. @@ -21,7 +23,9 @@ class SnakeGame { const auto x = snake_.back().first + direction_[direction].first; const auto y = snake_.back().second + direction_[direction].second; const auto tail = snake_.back(); - + + auto it = lookup_.find(hash(snake_.front().first, snake_.front().second)); + lookup_.erase(it); snake_.pop_front(); if (!valid(x, y)) { return -1; @@ -29,8 +33,10 @@ class SnakeGame { ++score_; food_.pop_front(); snake_.push_front(tail); + lookup_.emplace(hash(tail.first, tail.second)); } snake_.push_back({x, y}); + lookup_.emplace(hash(x, y)); return score_; } @@ -39,15 +45,16 @@ class SnakeGame { if (x < 0 || x >= height_ || y < 0 || y >= width_) { return false; } - for (const auto& p : snake_) { - if (x == p.first && y == p.second) { - return false; - } - } - return true; + return lookup_.find(hash(x, y)) == lookup_.end(); + } + + int hash(int x, int y) { + return x * width_ + y; } + int width_, height_, score_; deque> food_, snake_; + unordered_multiset lookup_; unordered_map> direction_ = {{"U", {-1, 0}}, {"L", {0, -1}}, {"R", {0, 1}}, {"D", {1, 0}}}; }; @@ -58,4 +65,3 @@ class SnakeGame { * int param_1 = obj.move(direction); */ - From d0730e6297b78ff7082f4d310fbc6784d355f839 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 21:58:01 +0800 Subject: [PATCH 2891/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d0d61a0d6..c7ef2b95a 100644 --- a/README.md +++ b/README.md @@ -515,7 +515,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 284| [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [C++](./C++/peeking-iterator.cpp) [Python](./Python/peeking-iterator.py) | _O(1)_ | _O(1)_ | Medium || 348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_| _O(n^2)_| Medium |📖|| -353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(s)_| _O(s)_| Medium |📖| Deque | +353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(1)_| _O(s)_| Medium |📖| Deque | 355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_| _O(t + f)_| Hard | LintCode | Heap | 359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | [C++](./C++/logger-rate-limiter.cpp) [Python](./Python/logger-rate-limiter.py) | _O(1), amortized_ | _O(k)_| Easy |📖| Deque | 362| [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [C++](./C++/design-hit-counter.cpp) [Python](./Python/design-hit-counter.py) | _O(1), amortized_ | _O(k)_| Medium |📖| Deque | From dcf6f72e24257df8235a7cc814f3826d998b6f4b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 22:02:26 +0800 Subject: [PATCH 2892/4971] Update design-snake-game.py --- Python/design-snake-game.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Python/design-snake-game.py b/Python/design-snake-game.py index ff62d38ba..134dbcae3 100644 --- a/Python/design-snake-game.py +++ b/Python/design-snake-game.py @@ -1,5 +1,5 @@ -# Time: O(s) per move, s is the current length of the snake. -# Space: O(s) +# Time: O(1) per move +# Space: O(s), s is the current length of the snake. from collections import deque @@ -22,8 +22,9 @@ def __init__(self, width,height,food): self.__food = deque(food) self.__snake = deque([(0, 0)]) self.__direction = {"U":(-1, 0), "L":(0, -1), "R":(0, 1), "D":(1, 0)}; + self.__lookup = collections.defaultdict(int) + self.__lookup[(0, 0)] += 1 - def move(self, direction): """ Moves the snake. @@ -36,11 +37,14 @@ def move(self, direction): def valid(x, y): return 0 <= x < self.__height and \ 0 <= y < self.__width and \ - (x, y) not in self.__snake - + (x, y) not in self.__lookup d = self.__direction[direction] x, y = self.__snake[-1][0] + d[0], self.__snake[-1][1] + d[1] + tail = self.__snake[-1] + self.__lookup[self.__snake[0]] -= 1 + if self.__lookup[self.__snake[0]] == 0: + self.__lookup.pop(self.__snake[0]) self.__snake.popleft() if not valid(x, y): return -1 @@ -48,7 +52,9 @@ def valid(x, y): self.__score += 1 self.__food.popleft() self.__snake.appendleft(tail) - self.__snake.append((x, y)) + self.__lookup[tail] += 1 + self.__snake += (x, y), + self.__lookup[(x, y)] += 1 return self.__score From e0f4f72336ed1e4c8b2ef6e03fb30bfe93c83d30 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 22:10:12 +0800 Subject: [PATCH 2893/4971] Create longest-palindrome.py --- Python/longest-palindrome.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/longest-palindrome.py diff --git a/Python/longest-palindrome.py b/Python/longest-palindrome.py new file mode 100644 index 000000000..562f9abdd --- /dev/null +++ b/Python/longest-palindrome.py @@ -0,0 +1,32 @@ +# Time: O(n) +# Space: O(1) + +# Given a string which consists of lowercase or uppercase letters, +# find the length of the longest palindromes that can be built with those letters. +# +# This is case sensitive, for example "Aa" is not considered a palindrome here. +# +# Note: +# Assume the length of given string will not exceed 1,010. +# +# Example: +# +# Input: +# "abccccdd" +# +# Output: +# 7 +# +# Explanation: +# One longest palindrome that can be built is "dccaccd", whose length is 7. + +class Solution(object): + def longestPalindrome(self, s): + """ + :type s: str + :rtype: int + """ + odds = 0 + for k, v in collections.Counter(s).iteritems(): + odds += v & 1 + return len(s) - odds + int(odds > 0) From db8e306c020396ae1d04f2948e266b9bbc9d764e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 22:16:11 +0800 Subject: [PATCH 2894/4971] Create valid-word-abbreviation.py --- Python/valid-word-abbreviation.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Python/valid-word-abbreviation.py diff --git a/Python/valid-word-abbreviation.py b/Python/valid-word-abbreviation.py new file mode 100644 index 000000000..e14d474e7 --- /dev/null +++ b/Python/valid-word-abbreviation.py @@ -0,0 +1,28 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def validWordAbbreviation(self, word, abbr): + """ + :type word: str + :type abbr: str + :rtype: bool + """ + i , digit = 0, 0 + for c in abbr: + if c.isdigit(): + if digit == 0 and c == '0': + return False + digit *= 10 + digit += int(c) + else: + if digit: + i += digit + digit = 0 + if i >= len(word) or word[i] != c: + return False + i += 1 + if digit: + i += digit + + return i == len(word) From 8d26e70bb05f9efcc0a5fdd21f60960734e0e3dd Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 22:48:33 +0800 Subject: [PATCH 2895/4971] Create minimum-unique-word-abbreviation.py --- Python/minimum-unique-word-abbreviation.py | 40 ++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/minimum-unique-word-abbreviation.py diff --git a/Python/minimum-unique-word-abbreviation.py b/Python/minimum-unique-word-abbreviation.py new file mode 100644 index 000000000..73dbfab2e --- /dev/null +++ b/Python/minimum-unique-word-abbreviation.py @@ -0,0 +1,40 @@ +# Time: O(2^n) +# Space: O(n) + +class Solution(object): + def minAbbreviation(self, target, dictionary): + """ + :type target: str + :type dictionary: List[str] + :rtype: str + """ + def bits_len(target, bits): + return sum((bits >> i) & 3 == 0 for i in xrange(len(target)-1)) + + diffs = set() + for word in dictionary: + if len(word) != len(target): + continue + diffs.add(sum(2**i for i, c in enumerate(word) if target[i] != c)) + + if not diffs: + return str(len(target)) + + bits = 2**len(target) - 1 + for i in xrange(2**len(target)): + if all(d & i for d in diffs) and bits_len(target, i) > bits_len(target, bits): + bits = i + + abbr = [] + pre = 0 + for i in xrange(len(target)): + if bits & 1: + if i - pre > 0: + abbr.append(str(i - pre)) + pre = i + 1 + abbr.append(str(target[i])) + elif i == len(target) - 1: + abbr.append(str(i - pre + 1)) + bits >>= 1 + + return "".join(abbr) From 5292d058f4226a5544fdf2d906d93532f0f59b89 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 22:54:03 +0800 Subject: [PATCH 2896/4971] Update minimum-unique-word-abbreviation.py --- Python/minimum-unique-word-abbreviation.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/minimum-unique-word-abbreviation.py b/Python/minimum-unique-word-abbreviation.py index 73dbfab2e..03f82e052 100644 --- a/Python/minimum-unique-word-abbreviation.py +++ b/Python/minimum-unique-word-abbreviation.py @@ -11,11 +11,11 @@ def minAbbreviation(self, target, dictionary): def bits_len(target, bits): return sum((bits >> i) & 3 == 0 for i in xrange(len(target)-1)) - diffs = set() + diffs = [] for word in dictionary: if len(word) != len(target): continue - diffs.add(sum(2**i for i, c in enumerate(word) if target[i] != c)) + diffs.append(sum(2**i for i, c in enumerate(word) if target[i] != c)) if not diffs: return str(len(target)) From 1f59f00937299fbcbbeb1e998eb6c123410a420a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 23:22:33 +0800 Subject: [PATCH 2897/4971] Update minimum-unique-word-abbreviation.py --- Python/minimum-unique-word-abbreviation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/minimum-unique-word-abbreviation.py b/Python/minimum-unique-word-abbreviation.py index 03f82e052..3a3f3324b 100644 --- a/Python/minimum-unique-word-abbreviation.py +++ b/Python/minimum-unique-word-abbreviation.py @@ -9,7 +9,7 @@ def minAbbreviation(self, target, dictionary): :rtype: str """ def bits_len(target, bits): - return sum((bits >> i) & 3 == 0 for i in xrange(len(target)-1)) + return sum(((bits >> i) & 3) == 0 for i in xrange(len(target)-1)) diffs = [] for word in dictionary: From f01d6c6435c99a7dc8ddb4aa4a1ce98c147a6b28 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 23:24:16 +0800 Subject: [PATCH 2898/4971] Update minimum-unique-word-abbreviation.cpp --- C++/minimum-unique-word-abbreviation.cpp | 107 +++++++++-------------- 1 file changed, 43 insertions(+), 64 deletions(-) diff --git a/C++/minimum-unique-word-abbreviation.cpp b/C++/minimum-unique-word-abbreviation.cpp index 968796906..3d15a89b3 100644 --- a/C++/minimum-unique-word-abbreviation.cpp +++ b/C++/minimum-unique-word-abbreviation.cpp @@ -4,93 +4,72 @@ class Solution { public: string minAbbreviation(string target, vector& dictionary) { - vector bits_dict; - int bit_candidates = 0; - dict_to_bits_dict(target, dictionary, &bits_dict, &bit_candidates); + vector diffs; + dictionary_to_diffs(target, dictionary, &diffs); - int min_len = numeric_limits::max(), min_abbr = 0; - dfs(target, bit_candidates, 1, 0, &bits_dict, &min_len, &min_abbr); - - return bits_to_abbr(target, min_abbr); - } - -private: - void dfs(const string& target, int bit_candidates, int bits, int mask, - vector *bits_dict, int *min_len, int *min_abbr) { - - const auto len = abbr_len(target, mask); - if (len >= *min_len) { - return; + if (diffs.empty()) { + return to_string(target.length()); } - bool match = true; - for (const auto& d : *bits_dict) { - if ((mask & d) == 0) { - match = false; - break; - } - } - if (match) { - *min_len = len; - *min_abbr = mask; - } else { - for (int b = bits; b < (1 << target.length()); b <<= 1) { - if (bit_candidates & b) { - dfs(target, bit_candidates, b << 1, mask | b, bits_dict, min_len, min_abbr); + int bits = (1 << target.length()) - 1; + for (int i = 0; i < (1 << target.length()); ++i) { + if (all_of(diffs.begin(), diffs.end(), [&i](int d) { return d & i; } )) { + if (bits_len(target, i) > bits_len(target, bits)) { + bits = i; } } } + + return bits_to_abbr(target, bits); } - void dict_to_bits_dict(const string& target, const vector& dictionary, - vector *bits_dict, int *bit_candidates) { - for (const auto& w : dictionary) { - int bits = 0; - if (w.length() != target.length()) { +private: + void dictionary_to_diffs(const string& target, const vector& dictionary, + vector *diffs) { + + for (const auto& word : dictionary) { + if (word.length() != target.length()) { continue; } - for (int i = target.length() - 1, bit = 1; i >= 0; --i, bit <<= 1) { - if (target[i] != w[i]) { - bits |= bit; + + int bits = 0; + for (int i = 0; i < word.length(); ++i) { + if (target[i] != word[i]) { + bits |= 1 << i; } } - bits_dict->emplace_back(bits); - *bit_candidates |= bits; + diffs->emplace_back(bits); } } - int abbr_len(const string& target, int mask) { - int count = 0; - for (int b = 1; b < (1 << target.length());) { - if ((mask & b) == 0) { - for (; b < (1 << target.length()) && (mask & b) == 0; b <<= 1); - } else { - b <<= 1; + int bits_len(const string& target, int bits) { + int sum = 0; + + for (int i = 0; i < target.length() - 1; ++i) { + if (((bits >> i) & 3) == 0) { + ++sum; } - ++count; } - return count; + + return sum; } - string bits_to_abbr(const string& target, int min_abbr) { - vector tmp; - for (int i = target.length() - 1, pre = i; i >= 0; --i, min_abbr >>= 1) { - if (min_abbr & 1) { - if (pre - i > 0) { - tmp.emplace_back(to_string(pre - i)); + string bits_to_abbr(const string& target, int bits) { + string abbr; + + int pre = 0; + for (int i = 0, prev = 0; i < target.length(); ++i, bits >>= 1) { + if (bits & 1) { + if (i - pre > 0) { + abbr += to_string(i - pre); } - pre = i - 1; - tmp.emplace_back(string(1, target[i])); - } else if (i == 0) { - tmp.emplace_back(to_string(pre - i + 1)); + pre = i + 1; + abbr.push_back(target[i]); + } else if (i == target.length() - 1) { + abbr += to_string(i - pre + 1); } } - reverse(tmp.begin(), tmp.end()); - string abbr; - for (const auto& s : tmp) { - abbr += s; - } return abbr; } }; From 9639e82726dcddfcda4d64d4306719f7a2259e81 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 6 Oct 2016 23:32:25 +0800 Subject: [PATCH 2899/4971] Update README.md --- README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c7ef2b95a..b396ade46 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-407%20%2F%20407-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-411%20%2F%20411-ff69b4.svg) -Up to date (2016-09-25), there are `390` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-10-02), there are `394` 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 `407` questions. +Here is the classification of all `411` 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 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./C++/find-the-difference.cpp) [Python](./Python/find-the-difference.py) | _O(n)_ | _O(1)_ | Easy | | 393 | [UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./C++/utf-8-validation.cpp) [Python](./Python/utf-8-validation.py) | _O(n)_ | _O(1)_ | Medium | | 401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./C++/binary-watch.cpp) [Python](./Python/binary-watch.py) | _O(1)_ | _O(1)_ | Easy | | +411 | [Minimum Unique Word Abbreviation](https://leetcode.com/problems/minimum-unique-word-abbreviation/) | [C++](./C++/minimum-unique-word-abbreviation.cpp) [Python](./Python/minimum-unique-word-abbreviation.py) | _O(2^n)_ | _O(n)_ | Hard | 📖 | ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -129,6 +130,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 | | 383| [Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./C++/ransom-note.cpp) [Python](./Python/ransom-note.py) | _O(n)_ | _O(1)_ | Easy | EPI | 405| [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./C++/convert-a-number-to-hexadecimal.cpp) [Python](./Python/convert-a-number-to-hexadecimal.py) | _O(n)_ | _O(1)_ | Easy | | +408| [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) | [C++](./C++/valid-word-abbreviation.cpp) [Python](./Python/valid-word-abbreviation.py) | _O(n)_ | _O(1)_ | Easy | 📖 | ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -241,6 +243,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(n)_| _O(n)_| Medium |📖| Hash, Two Pointers | 387| [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/first-unique-character-in-a-string.cpp) [Python](./Python/first-unique-character-in-a-string.py) | _O(n)_| _O(n)_| Easy ||| 388| [Longest Absolute File Path](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/longest-absolute-file-path.cpp) [Python](./Python/longest-absolute-file-path.py) | _O(n)_| _O(d)_| Medium || Stack | +409| [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./C++/longest-palindrome.cpp) [Python](./Python/longest-palindrome.py) | _O(n)_| _O(1)_| Easy ||| ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -371,6 +374,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 363| [Max Sum of Rectangle No Larger Than K](https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/) | [C++](./C++/max-sum-of-sub-matrix-no-larger-than-k.cpp) [Python](./Python/max-sum-of-sub-matrix-no-larger-than-k.py) | _O(min(m, n)^2 * max(m, n) * logn(max(m, n)))_ | _O(max(m, n))_ | Hard ||| 367| [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/)| [C++](./C++/valid-perfect-square.cpp) [Python](./Python/valid-perfect-square.py) | _O(logn)_ | _O(1)_ | Medium | | 374| [Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/)| [C++](./C++/guess-number-higher-or-lower.cpp) [Python](./Python/guess-number-higher-or-lower.py) | _O(logn)_ | _O(1)_ | Easy | | +410| [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/)| [C++](./C++/split-array-largest-sum.cpp) [Python](./Python/split-array-largest-sum.py) | _O(nlogs)_ | _O(1)_ | Hard | | ## Binary Search Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note From 3c678ba7f7ff864ae0666f5c07efe1e5403f26cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Oct 2016 23:44:25 +0800 Subject: [PATCH 2900/4971] Update and rename sortedListToBST.cpp to convert-sorted-array-to-binary-search-tree.cpp --- ...ert-sorted-array-to-binary-search-tree.cpp | 29 ++++++++++++ C++/sortedListToBST.cpp | 46 ------------------- 2 files changed, 29 insertions(+), 46 deletions(-) create mode 100644 C++/convert-sorted-array-to-binary-search-tree.cpp delete mode 100644 C++/sortedListToBST.cpp diff --git a/C++/convert-sorted-array-to-binary-search-tree.cpp b/C++/convert-sorted-array-to-binary-search-tree.cpp new file mode 100644 index 000000000..35f3ad883 --- /dev/null +++ b/C++/convert-sorted-array-to-binary-search-tree.cpp @@ -0,0 +1,29 @@ +// Time: O(n) +// Space: O(logn) + +/** + * 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* sortedArrayToBST(vector& nums) { + return sortedArrayToBSTHelper(nums, 0, nums.size() - 1); + } + +private: + TreeNode *sortedArrayToBSTHelper(vector &nums, int start, int end) { + if (start <= end) { + TreeNode *node = new TreeNode(nums[start + (end - start) / 2]); + node->left = sortedArrayToBSTHelper(nums, start, start + (end - start) / 2 - 1); + node->right = sortedArrayToBSTHelper(nums, start + (end - start) / 2 + 1, end); + return node; + } + return nullptr; + } +}; diff --git a/C++/sortedListToBST.cpp b/C++/sortedListToBST.cpp deleted file mode 100644 index 6ea2911a0..000000000 --- a/C++/sortedListToBST.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// Time Complexity: O(n) -// Space Complexity: O(logn) - -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -/** - * Definition for binary tree - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution { - public: - TreeNode *sortedListToBST(ListNode *head) { - int len = 0; - - ListNode *p = head; - while(p) { - p = p->next; - ++len; - } - - return sortedListToBST(head, len); - } - - private: - TreeNode *sortedListToBST(ListNode *&head, int len) { - if(!len || !head) - return NULL; - TreeNode *left = sortedListToBST(head, len / 2); - TreeNode *parent = new TreeNode(head->val); - parent->left = left; - head = head->next; - parent->right = sortedListToBST(head, (len % 2 != 0)? len / 2: len / 2 - 1); - return parent; - } -}; From 35b8f83c3017bab7b6185c16ae93687b3927f1d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Oct 2016 23:45:00 +0800 Subject: [PATCH 2901/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b396ade46..61029db38 100644 --- a/README.md +++ b/README.md @@ -335,7 +335,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 104| [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)| [C++](./C++/maximum-depth-of-binary-tree.cpp) [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/) | [C++](./C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp) [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/) | [C++](./C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp) [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 || +108| [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | [C++](./C++/convert-sorted-array-to-binary-search-tree.cpp) [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 || From ded44cec00d1f235eb145a7387dfea5effa51ba6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Oct 2016 23:18:01 +0800 Subject: [PATCH 2902/4971] Create partition-equal-subset-sum.py --- Python/partition-equal-subset-sum.py | 42 ++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/partition-equal-subset-sum.py diff --git a/Python/partition-equal-subset-sum.py b/Python/partition-equal-subset-sum.py new file mode 100644 index 000000000..962974fe2 --- /dev/null +++ b/Python/partition-equal-subset-sum.py @@ -0,0 +1,42 @@ +# Time: O(n * s), s is the sum of nums +# Space: O(s) + +# Given a non-empty array containing only positive integers, +# find if the array can be partitioned into two subsets +# such that the sum of elements in both subsets is equal. +# +# Note: +# Both the array size and each of the array element will not exceed 100. +# +# Example 1: +# +# Input: [1, 5, 11, 5] +# +# Output: true +# +# Explanation: The array can be partitioned as [1, 5, 5] and [11]. +# Example 2: +# +# Input: [1, 2, 3, 5] +# +# Output: false +# +# Explanation: The array cannot be partitioned into equal sum subsets. + +class Solution(object): + def canPartition(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + s = sum(nums) + if s % 2: + return False + + dp = [False] * (s/2 + 1) + dp[0] = True + for num in nums: + for i in xrange(1, len(dp)): + if num <= i: + dp[i] = dp[i] or dp[i - num] + return dp[-1] From 9f2b80bdc545e27fbf1148ca29161bd4ca080cfc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Oct 2016 23:19:15 +0800 Subject: [PATCH 2903/4971] Create partition-equal-subset-sum.cpp --- C++/partition-equal-subset-sum.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/partition-equal-subset-sum.cpp diff --git a/C++/partition-equal-subset-sum.cpp b/C++/partition-equal-subset-sum.cpp new file mode 100644 index 000000000..d9723bb52 --- /dev/null +++ b/C++/partition-equal-subset-sum.cpp @@ -0,0 +1,23 @@ +// Time: O(n * s), s is the sum of nums. +// Space: O(s) + +class Solution { +public: + bool canPartition(vector& nums) { + const auto sum = accumulate(nums.cbegin(), nums.cend(), 0); + if (sum % 2) { + return false; + } + + vector dp(sum / 2 + 1); + dp[0] = true; + for (const auto& num : nums) { + for (int i = 1; i < dp.size(); ++i) { + if (num <= i) { + dp[i] = dp[i] || dp[i - num]; + } + } + } + return dp.back(); + } +}; From 3f3f07575fd8fe515329f56b34de18fae0fa64f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Oct 2016 23:30:02 +0800 Subject: [PATCH 2904/4971] Create add-strings.cpp --- C++/add-strings.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/add-strings.cpp diff --git a/C++/add-strings.cpp b/C++/add-strings.cpp new file mode 100644 index 000000000..11c811ee6 --- /dev/null +++ b/C++/add-strings.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string addStrings(string num1, string num2) { + string result; + + for (int i = num1.size() - 1, j = num2.size() - 1, carry = 0; + i >= 0 || j >= 0 || carry; + carry /= 10) { + + if (i >= 0) { + carry += num1[i--] - '0'; + } + if (j >= 0) { + carry += num2[j--] - '0'; + } + result += to_string(carry % 10); + } + reverse(result.begin(), result.end()); + + return result; + } +}; From 883b826729a15cb21143bb28e9d7d2fb7af38d47 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 00:03:46 +0800 Subject: [PATCH 2905/4971] Create add-strings.py --- Python/add-strings.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/add-strings.py diff --git a/Python/add-strings.py b/Python/add-strings.py new file mode 100644 index 000000000..4c13bc69a --- /dev/null +++ b/Python/add-strings.py @@ -0,0 +1,36 @@ +# Time: O(n) +# Space: O(1) + +# Given two non-negative numbers num1 and num2 represented as string, +# return the sum of num1 and num2. +# +# Note: +# +# The length of both num1 and num2 is < 5100. +# Both num1 and num2 contains only digits 0-9. +# Both num1 and num2 does not contain any leading zero. +# You must not use any built-in BigInteger library or +# convert the inputs to integer directly. + +class Solution(object): + def addStrings(self, num1, num2): + """ + :type num1: str + :type num2: str + :rtype: str + """ + result = [] + i, j, carry = len(num1) - 1, len(num2) - 1, 0 + + while i >= 0 or j >= 0 or carry: + if i >= 0: + carry += ord(num1[i]) - ord('0'); + i -= 1 + if j >= 0: + carry += ord(num2[j]) - ord('0'); + j -= 1 + result.append(str(carry % 10)) + carry /= 10 + result.reverse() + + return "".join(result) From 548b75adb741817c8cb8a09bc811fc496b488434 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 01:20:17 +0800 Subject: [PATCH 2906/4971] Create pacific-atlantic-water-flow.cpp --- C++/pacific-atlantic-water-flow.cpp | 50 +++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 C++/pacific-atlantic-water-flow.cpp diff --git a/C++/pacific-atlantic-water-flow.cpp b/C++/pacific-atlantic-water-flow.cpp new file mode 100644 index 000000000..1128de3e5 --- /dev/null +++ b/C++/pacific-atlantic-water-flow.cpp @@ -0,0 +1,50 @@ +// Time: O(m * n) +// Space: O(m * n) + +class Solution { +public: + + vector> pacificAtlantic(vector>& matrix) { + if (matrix.empty()) { + return {}; + } + + vector> res; + const auto m = matrix.size(), n = matrix[0].size(); + vector> visited(m, vector(n)); + + for (int i = 0; i < m; ++i) { + pacificAtlanticHelper(matrix, i, 0, numeric_limits::min(), PACIFIC, &visited, &res); + pacificAtlanticHelper(matrix, i, n - 1, numeric_limits::min(), ATLANTIC, &visited, &res); + } + for (int j = 0; j < n; ++j) { + pacificAtlanticHelper(matrix, 0, j, numeric_limits::min(), PACIFIC, &visited, &res); + pacificAtlanticHelper(matrix, m - 1, j, numeric_limits::min(), ATLANTIC, &visited, &res); + } + + return res; + } + +private: + void pacificAtlanticHelper(const vector>& matrix, int x, int y, int prev_height, int prev_val, + vector> *visited, vector> *res) { + + if (x < 0 || x >= matrix.size() || + y < 0 || y >= matrix[0].size() || + matrix[x][y] < prev_height || ((*visited)[x][y] | prev_val) == (*visited)[x][y]) { + return; + } + + (*visited)[x][y] |= prev_val; + if ((*visited)[x][y] == (PACIFIC | ATLANTIC)) { + res->emplace_back(x, y); + } + + for (const auto& dir : directions) { + pacificAtlanticHelper(matrix, x + dir.first, y + dir.second, matrix[x][y], (*visited)[x][y], visited, res); + } + } + + enum ocean { PACIFIC = 1, ATLANTIC = 2 }; + const vector> directions{ {0, -1}, {0, 1}, {-1, 0}, {1, 0} }; +}; From c79be6b666078ea47bf0566e42cd9ab8be4d404e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 01:38:20 +0800 Subject: [PATCH 2907/4971] Create pacific-atlantic-water-flow.py --- Python/pacific-atlantic-water-flow.py | 68 +++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Python/pacific-atlantic-water-flow.py diff --git a/Python/pacific-atlantic-water-flow.py b/Python/pacific-atlantic-water-flow.py new file mode 100644 index 000000000..57a0566e2 --- /dev/null +++ b/Python/pacific-atlantic-water-flow.py @@ -0,0 +1,68 @@ +# Time: O(m * n) +# Space: O(m * n) + +# Given an m x n matrix of non-negative integers representing the height of +# each unit cell in a continent, the "Pacific ocean" touches the left and +# top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges. +# +# Water can only flow in four directions (up, down, left, or right) +# from a cell to another one with height equal or lower. +# +# Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean. +# +# Note: +# The order of returned grid coordinates does not matter. +# Both m and n are less than 150. +# Example: +# +# Given the following 5x5 matrix: +# +# Pacific ~ ~ ~ ~ ~ +# ~ 1 2 2 3 (5) * +# ~ 3 2 3 (4) (4) * +# ~ 2 4 (5) 3 1 * +# ~ (6) (7) 1 4 5 * +# ~ (5) 1 1 2 4 * +# * * * * * Atlantic +# +# Return: +# +# [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix). + +class Solution(object): + def pacificAtlantic(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[List[int]] + """ + PACIFIC, ATLANTIC = 1, 2 + + def pacificAtlanticHelper(matrix, x, y, prev_height, prev_val, visited, res): + if (not 0 <= x < len(matrix)) or \ + (not 0 <= y < len(matrix[0])) or \ + matrix[x][y] < prev_height or \ + (visited[x][y] | prev_val) == visited[x][y]: + return + + visited[x][y] |= prev_val + if visited[x][y] == (PACIFIC | ATLANTIC): + res.append((x, y)) + + for d in [(0, -1), (0, 1), (-1, 0), (1, 0)]: + pacificAtlanticHelper(matrix, x + d[0], y + d[1], matrix[x][y], visited[x][y], visited, res) + + if not matrix: + return [] + + res = [] + m, n = len(matrix),len(matrix[0]) + visited = [[0 for _ in xrange(n)] for _ in xrange(m)] + + for i in xrange(m): + pacificAtlanticHelper(matrix, i, 0, float("-inf"), PACIFIC, visited, res) + pacificAtlanticHelper(matrix, i, n - 1, float("-inf"), ATLANTIC, visited, res) + for j in xrange(n): + pacificAtlanticHelper(matrix, 0, j, float("-inf"), PACIFIC, visited, res) + pacificAtlanticHelper(matrix, m - 1, j, float("-inf"), ATLANTIC, visited, res) + + return res From e5a44a4eb6b01399221178b774e696a3c88eb903 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 02:05:42 +0800 Subject: [PATCH 2908/4971] Create sentence-screen-fitting.cpp --- C++/sentence-screen-fitting.cpp | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/sentence-screen-fitting.cpp diff --git a/C++/sentence-screen-fitting.cpp b/C++/sentence-screen-fitting.cpp new file mode 100644 index 000000000..cebd38b0d --- /dev/null +++ b/C++/sentence-screen-fitting.cpp @@ -0,0 +1,35 @@ +// Time: O(r + n * c) +// Space: O(n) + +class Solution { +public: + int wordsTyping(vector& sentence, int rows, int cols) { + vector wc(sentence.size()); + for (int i = 0; i < sentence.size(); ++i) { + wc[i] = wordsFit(sentence, i, cols); + } + + int words = 0, start = 0; + for (int i = 0; i < rows; ++i) { + words += wc[start]; + start = (start + wc[start]) % sentence.size(); + } + return words / sentence.size(); + } + +private: + int wordsFit(const vector& sentence, int start, int cols) { + if (sentence[start].length() > cols) { + return 0; + } + + int sum = sentence[start].length(), count = 1; + for (int i = (start + 1) % sentence.size(); ; i = (i + 1) % sentence.size()) { + if (sum + 1 + sentence[i].length() > cols) { + return count; + } + sum += 1 + sentence[i].length(); + ++count; + } + } +}; From 9554f486dc8485bf888989ee174376025e134e44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 02:13:23 +0800 Subject: [PATCH 2909/4971] Update sentence-screen-fitting.cpp --- C++/sentence-screen-fitting.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/sentence-screen-fitting.cpp b/C++/sentence-screen-fitting.cpp index cebd38b0d..e63cf0072 100644 --- a/C++/sentence-screen-fitting.cpp +++ b/C++/sentence-screen-fitting.cpp @@ -24,12 +24,12 @@ class Solution { } int sum = sentence[start].length(), count = 1; - for (int i = (start + 1) % sentence.size(); ; i = (i + 1) % sentence.size()) { - if (sum + 1 + sentence[i].length() > cols) { - return count; - } + for (int i = (start + 1) % sentence.size(); + sum + 1 + sentence[i].length() <= cols; + i = (i + 1) % sentence.size()) { sum += 1 + sentence[i].length(); ++count; } + return count; } }; From 7ce112d77032e1f1eec680d823ce4639d37300ef Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 02:15:02 +0800 Subject: [PATCH 2910/4971] Create sentence-screen-fitting.py --- Python/sentence-screen-fitting.py | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/sentence-screen-fitting.py diff --git a/Python/sentence-screen-fitting.py b/Python/sentence-screen-fitting.py new file mode 100644 index 000000000..91f45ca0c --- /dev/null +++ b/Python/sentence-screen-fitting.py @@ -0,0 +1,32 @@ +# Time: O(r + n * c) +# Space: O(n) + +class Solution(object): + def wordsTyping(self, sentence, rows, cols): + """ + :type sentence: List[str] + :type rows: int + :type cols: int + :rtype: int + """ + def words_fit(sentence, start, cols): + if len(sentence[start]) > cols: + return 0 + + s, count = len(sentence[start]), 1 + i = (start + 1) % len(sentence) + while s + 1 + len(sentence[i]) <= cols: + s += 1 + len(sentence[i]) + count += 1 + i = (i + 1) % len(sentence) + return count + + wc = [0] * len(sentence) + for i in xrange(len(sentence)): + wc[i] = words_fit(sentence, i, cols) + + words, start = 0, 0 + for i in xrange(rows): + words += wc[start] + start = (start + wc[start]) % len(sentence) + return words / len(sentence) From 35681edba5e9abd3e12a60ccb6343924631d138f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 15:41:37 +0800 Subject: [PATCH 2911/4971] Create fizz-buzz.cpp --- C++/fizz-buzz.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/fizz-buzz.cpp diff --git a/C++/fizz-buzz.cpp b/C++/fizz-buzz.cpp new file mode 100644 index 000000000..d7477648c --- /dev/null +++ b/C++/fizz-buzz.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector fizzBuzz(int n) { + vector result; + + for (int i = 1; i <= n; ++i) { + if (i % 15 == 0) { + result.emplace_back("FizzBuzz"); + } else if (i % 5 == 0) { + result.emplace_back("Buzz"); + } else if (i % 3 == 0) { + result.emplace_back("Fizz"); + } else { + result.emplace_back(to_string(i)); + } + } + + return result; + } +}; From 820f3c57dc307de20af93c805ec386563ba0a4c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 15:45:39 +0800 Subject: [PATCH 2912/4971] Create fizz-buzz.py --- Python/fizz-buzz.py | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/fizz-buzz.py diff --git a/Python/fizz-buzz.py b/Python/fizz-buzz.py new file mode 100644 index 000000000..a1937869a --- /dev/null +++ b/Python/fizz-buzz.py @@ -0,0 +1,51 @@ +# Time: O(n) +# Space: O(1) + +# Write a program that outputs the string representation of numbers from 1 to n. +# +# But for multiples of three it should output “Fizz” instead of the number and for +# the multiples of five output “Buzz”. For numbers which are multiples of both three +# and five output “FizzBuzz”. +# +# Example: +# +# n = 15, +# +# Return: +# [ +# "1", +# "2", +# "Fizz", +# "4", +# "Buzz", +# "Fizz", +# "7", +# "8", +# "Fizz", +# "Buzz", +# "11", +# "Fizz", +# "13", +# "14", +# "FizzBuzz" +# ] + +class Solution(object): + def fizzBuzz(self, n): + """ + :type n: int + :rtype: List[str] + """ + result = [] + + for i in xrange(1, n+1): + if i % 15 == 0: + result.append("FizzBuzz") + elif i % 5 == 0: + result.append("Buzz") + elif i % 3 == 0: + result.append("Fizz") + else: + result.append(str(i)) + + return result From 72127618c70c612fb7be63e80c25d41179082121 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 15:46:59 +0800 Subject: [PATCH 2913/4971] Create arithmetic-slices.cpp --- C++/arithmetic-slices.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 C++/arithmetic-slices.cpp diff --git a/C++/arithmetic-slices.cpp b/C++/arithmetic-slices.cpp new file mode 100644 index 000000000..5239f6c5f --- /dev/null +++ b/C++/arithmetic-slices.cpp @@ -0,0 +1,16 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int numberOfArithmeticSlices(vector& A) { + int res = 0, i = 0; + for (int i = 0; i + 2 < A.size(); ++i) { + const auto start = i; + while (A[i + 2] + A[i] == 2 * A[i + 1]) { + res += (i++) - start + 1; + } + } + return res; + } +}; From 80e16cfb35b77fb5b7294d6eda7da73cccf6e7eb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 15:52:34 +0800 Subject: [PATCH 2914/4971] Update arithmetic-slices.cpp --- C++/arithmetic-slices.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/arithmetic-slices.cpp b/C++/arithmetic-slices.cpp index 5239f6c5f..f6430fbac 100644 --- a/C++/arithmetic-slices.cpp +++ b/C++/arithmetic-slices.cpp @@ -7,7 +7,7 @@ class Solution { int res = 0, i = 0; for (int i = 0; i + 2 < A.size(); ++i) { const auto start = i; - while (A[i + 2] + A[i] == 2 * A[i + 1]) { + while (i + 2 < A.size() && A[i + 2] + A[i] == 2 * A[i + 1]) { res += (i++) - start + 1; } } From 093e8c8ebb315044fc58dcb90d9dd2b42aded9da Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 15:54:24 +0800 Subject: [PATCH 2915/4971] Create arithmetic-slices.py --- Python/arithmetic-slices.py | 44 +++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/arithmetic-slices.py diff --git a/Python/arithmetic-slices.py b/Python/arithmetic-slices.py new file mode 100644 index 000000000..6bdbee58a --- /dev/null +++ b/Python/arithmetic-slices.py @@ -0,0 +1,44 @@ +# Time: O(n) +# Space: O(1) + +# A sequence of number is called arithmetic if it consists of at least three elements +# and if the difference between any two consecutive elements is the same. +# +# For example, these are arithmetic sequence: +# +# 1, 3, 5, 7, 9 +# 7, 7, 7, 7 +# 3, -1, -5, -9 +# The following sequence is not arithmetic. +# +# 1, 1, 2, 5, 7 +# +# A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair +# of integers (P, Q) such that 0 <= P < Q < N. +# +# A slice (P, Q) of array A is called arithmetic if the sequence: +# A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q. +# +# The function should return the number of arithmetic slices in the array A. +# +# Example: +# +# A = [1, 2, 3, 4] +# +# return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself. + +class Solution(object): + def numberOfArithmeticSlices(self, A): + """ + :type A: List[int] + :rtype: int + """ + res, i = 0, 0 + while i+2 < len(A): + start = i + while i+2 < len(A) and A[i+2] + A[i] == 2*A[i+1]: + res += i - start + 1 + i += 1 + i += 1 + + return res From 048ff7c72144dd6bd1155715b9947f2f552dd52e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 16:09:19 +0800 Subject: [PATCH 2916/4971] Rename arithmetic-slices.cpp to third-maximum-number.cpp --- C++/third-maximum-number.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/third-maximum-number.cpp diff --git a/C++/third-maximum-number.cpp b/C++/third-maximum-number.cpp new file mode 100644 index 000000000..b52c7bd3c --- /dev/null +++ b/C++/third-maximum-number.cpp @@ -0,0 +1,30 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int thirdMax(vector& nums) { + int count = 0; + vector top(3, numeric_limits::min()); + for (const auto& num : nums) { + if (num > top[0]) { + top[2] = top[1]; + top[1] = top[0]; + top[0] = num; + ++count; + } else if (num != top[0] && num > top[1]) { + top[2] = top[1]; + top[1] = num; + ++count; + } else if (num != top[0] && num != top[1] && num >= top[2]) { + top[2] = num; + ++count; + } + } + + if (count < 3) { + return top[0]; + } + return top[2]; + } +}; From 9f96a4f34a269315a042c2fc07f97e0df112f08a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 16:13:25 +0800 Subject: [PATCH 2917/4971] Create third-maximum-number.py --- Python/third-maximum-number.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Python/third-maximum-number.py diff --git a/Python/third-maximum-number.py b/Python/third-maximum-number.py new file mode 100644 index 000000000..02e43e5d4 --- /dev/null +++ b/Python/third-maximum-number.py @@ -0,0 +1,33 @@ +# Time: O(n) +# Space: O(1) + +# Given an array of integers, return the 3rd Maximum Number in this array, +# if it doesn't exist, return the Maximum Number. +# The time complexity must be O(n) or less. + +class Solution(object): + def thirdMax(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + count = 0 + top = [float("-inf")] * 3 + for num in nums: + if num > top[0]: + top[2] = top[1] + top[1] = top[0] + top[0] = num + count += 1 + elif num != top[0] and num > top[1]: + top[2] = top[1] + top[1] = num + count += 1 + elif num != top[0] and num != top[1] and num >= top[2]: + top[2] = num + count += 1 + + if count < 3: + return top[0] + + return top[2] From 63f59214430fb899cd1436532b310d1687f33f55 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Oct 2016 16:14:39 +0800 Subject: [PATCH 2918/4971] Update third-maximum-number.cpp --- C++/third-maximum-number.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/third-maximum-number.cpp b/C++/third-maximum-number.cpp index b52c7bd3c..c07234f4f 100644 --- a/C++/third-maximum-number.cpp +++ b/C++/third-maximum-number.cpp @@ -6,6 +6,7 @@ class Solution { int thirdMax(vector& nums) { int count = 0; vector top(3, numeric_limits::min()); + for (const auto& num : nums) { if (num > top[0]) { top[2] = top[1]; From f5190e9b3fd959596b55211fb9862fe7872c1613 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 11 Oct 2016 09:38:47 +0800 Subject: [PATCH 2919/4971] Update third-maximum-number.py --- Python/third-maximum-number.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Python/third-maximum-number.py b/Python/third-maximum-number.py index 02e43e5d4..ec9e2152f 100644 --- a/Python/third-maximum-number.py +++ b/Python/third-maximum-number.py @@ -15,13 +15,10 @@ def thirdMax(self, nums): top = [float("-inf")] * 3 for num in nums: if num > top[0]: - top[2] = top[1] - top[1] = top[0] - top[0] = num + top[0], top[1], top[2] = num, top[0], top[1] count += 1 elif num != top[0] and num > top[1]: - top[2] = top[1] - top[1] = num + top[1], top[2] = num, top[1] count += 1 elif num != top[0] and num != top[1] and num >= top[2]: top[2] = num From 573e1674f15f32f27df8d0db7f90d06025da3724 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 11 Oct 2016 21:28:18 +0800 Subject: [PATCH 2920/4971] Update README.md --- README.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 61029db38..d78988015 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-411%20%2F%20411-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-418%20%2F%20418-ff69b4.svg) -Up to date (2016-10-02), there are `394` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-10-09), there are `401` 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 `411` questions. +Here is the classification of all `418` 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.) @@ -104,6 +104,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 370| [Range Addition](https://leetcode.com/problems/range-addition/) | [C++](./C++/range-addition.cpp) [Python](./Python/range-addition.py) | _O(k + n)_ | _O(1)_ | Medium |📖|| 384| [Shuffle an Array](https://leetcode.com/problems/shuffle-an-array/) | [C++](./C++/shuffle-an-array.cpp) [Python](./Python/shuffle-an-array.py) | _O(n)_ | _O(n)_ | Medium | EPI || 396| [Rotate Function](https://leetcode.com/problems/rotate-function/) | [C++](./C++/rotate-function.cpp) [Python](./Python/rotate-function.py) | _O(n)_ | _O(1)_ | Easy ||| +412| [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./C++/fizz-buzz.cpp) [Python](./Python/fizz-buzz.py) | _O(n)_ | _O(1)_ | Easy ||| +414| [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./C++/third-maximum-number.cpp) [Python](./Python/third-maximum-number.py) | _O(n)_ | _O(1)_ | Easy ||| ## String # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -131,6 +133,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 383| [Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./C++/ransom-note.cpp) [Python](./Python/ransom-note.py) | _O(n)_ | _O(1)_ | Easy | EPI | 405| [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./C++/convert-a-number-to-hexadecimal.cpp) [Python](./Python/convert-a-number-to-hexadecimal.py) | _O(n)_ | _O(1)_ | Easy | | 408| [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) | [C++](./C++/valid-word-abbreviation.cpp) [Python](./Python/valid-word-abbreviation.py) | _O(n)_ | _O(1)_ | Easy | 📖 | +415| [Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./C++/add-strings.cpp) [Python](./Python/add-strings.py) | _O(n)_ | _O(1)_ | Easy | | ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -286,6 +289,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 391 | [Perfect Rectangle](https://leetcode.com/problems/perfect-rectangle/) | [C++](./C++/perfect-rectangle.cpp) [Python](./Python/perfect-rectangle.py) | _O(n)_ | _O(n)_ | Hard | | 398 | [Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./C++/random-pick-index.cpp) [Python](./Python/random-pick-index.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 400 | [Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./C++/nth-digit.cpp) [Python](./Python/nth-digit.py) | _O(logn)_ | _O(1)_ | Easy ||| +413 | [Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./C++/arithmetic-slices.cpp) [Python](./Python/arithmetic-slices.py) | _O(n)_ | _O(1)_ | Medium ||| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -423,6 +427,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 364| [Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii/) | [C++](./C++/nested-list-weight-sum-ii.cpp) [Python](./Python/nested-list-weight-sum-ii.py) | _O(n)_ | _O(h)_ | Medium |📖|| 366| [Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/) | [C++](./C++/find-leaves-of-binary-tree.cpp) [Python](./Python/find-leaves-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium |📖|| 399| [Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./C++/evaluate-division.cpp) [Python](./Python/evaluate-division.py) | _O(q * \|V\|!)_ | _O(e)_ | Medium ||| +417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -493,6 +498,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 375| [Guess Number Higher or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/)| [C++](./C++/guess-number-higher-or-lower-ii.cpp) [Python](./Python/guess-number-higher-or-lower-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium | | 377| [Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/)| [C++](./C++/combination-sum-iv.cpp) [Python](./Python/combination-sum-iv.py) | _O(nlogn + n * t)_ | _O(t)_ | Medium | | 403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n) ~ O(n^2)_ | Hard || +416 | [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) | [C++](./C++/partition-equal-subset-sum.cpp) [Python](./Python/partition-equal-subset-sum.py) | _O(n * s)_ | _O(s)_ | Medium || +418 | [Sentence Screen Fitting](https://leetcode.com/problems/sentence-screen-fitting/) | [C++](./C++/sentence-screen-fitting.cpp) [Python](./Python/sentence-screen-fitting.py) | _O(r + n * c)_ | _O(n)_ | Medium |📖| ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From a1878b9c0f773be208f237a8f27c9ca5e5222db6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Oct 2016 21:33:42 +0800 Subject: [PATCH 2921/4971] Create convert-sorted-list-to-binary-search-tree.cpp --- ...vert-sorted-list-to-binary-search-tree.cpp | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 C++/convert-sorted-list-to-binary-search-tree.cpp diff --git a/C++/convert-sorted-list-to-binary-search-tree.cpp b/C++/convert-sorted-list-to-binary-search-tree.cpp new file mode 100644 index 000000000..d173c96c6 --- /dev/null +++ b/C++/convert-sorted-list-to-binary-search-tree.cpp @@ -0,0 +1,47 @@ +// Time: O(n) +// Space: O(logn) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +/** + * 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* sortedListToBST(ListNode* head) { + auto curr = head; + int n = 0; + while (curr) { + curr = curr->next; + ++n; + } + return BuildBSTFromSortedDoublyListHelper(&head, 0, n); + } + + TreeNode * BuildBSTFromSortedDoublyListHelper(ListNode **head, int s, int e) { + if (s == e) { + return nullptr; + } + + int m = s + ((e - s) / 2); + auto left = BuildBSTFromSortedDoublyListHelper(head, s, m); + auto curr = new TreeNode((*head)->val); + + *head = (*head)->next; + curr->left = left; + curr->right = BuildBSTFromSortedDoublyListHelper(head, m + 1, e); + return curr; + } +}; From d44e3a67325c399d262e44c3ab7b434607028703 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 14 Oct 2016 21:34:30 +0800 Subject: [PATCH 2922/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d78988015..6dd7f1879 100644 --- a/README.md +++ b/README.md @@ -340,7 +340,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 105| [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [C++](./C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp) [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/) | [C++](./C++/construct-binary-tree-from-inorder-and-postorder-traversal.cpp) [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/) | [C++](./C++/convert-sorted-array-to-binary-search-tree.cpp) [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 || +109| [Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/) | [C++](./C++/convert-sorted-list-to-binary-search-tree.cpp) [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 || From ca12920327dcebc7c7516e56613ffc205f35b75e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Oct 2016 22:52:35 +0800 Subject: [PATCH 2923/4971] Create valid-word-square.cpp --- C++/valid-word-square.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/valid-word-square.cpp diff --git a/C++/valid-word-square.cpp b/C++/valid-word-square.cpp new file mode 100644 index 000000000..430ecfa97 --- /dev/null +++ b/C++/valid-word-square.cpp @@ -0,0 +1,17 @@ +// Time: O(m * n) +// Space: O(1) + +class Solution { +public: + bool validWordSquare(vector& words) { + for (int i = 0; i < words.size(); ++i) { + for (int j = 0; j < words[i].size(); ++j) { + if (j >= words.size() || words[j].size() <= i || + words[j][i] != words[i][j]) { + return false; + } + } + } + return true; + } +}; From d46290651c1408d2bb63787964680d525901d8a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Oct 2016 23:04:04 +0800 Subject: [PATCH 2924/4971] Create reconstruct-original-digits-from-english.py --- ...econstruct-original-digits-from-english.py | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/reconstruct-original-digits-from-english.py diff --git a/Python/reconstruct-original-digits-from-english.py b/Python/reconstruct-original-digits-from-english.py new file mode 100644 index 000000000..ff7797bde --- /dev/null +++ b/Python/reconstruct-original-digits-from-english.py @@ -0,0 +1,49 @@ +# Time: O(n) +# Space: O(1) + +# Given a non-empty string containing an out-of-order English representation +# of digits 0-9, output the digits in ascending order. +# +# Note: +# Input contains only lowercase English letters. +# Input is guaranteed to be valid and can be transformed to its original digits. +# That means invalid inputs such as "abc" or "zerone" are not permitted. +# Input length is less than 50,000. +# Example 1: +# Input: "owoztneoer" +# +# Output: "012" +# Example 2: +# Input: "fviefuro" +# +# Output: "45" + +from collections import Counter + +class Solution(object): + def originalDigits(self, s): + """ + :type s: str + :rtype: str + """ + # The count of each char in each number string. + cnts = [Counter(_) for _ in ["zero", "one", "two", "three", \ + "four", "five", "six", "seven", \ + "eight", "nine"]] + + # The order for greedy method. + order = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] + + # The unique char in the order. + unique_chars = ['z', 'o', 'w', 't', 'u', \ + 'f', 'x', 's', 'g', 'n'] + + cnt = Counter(list(s)) + res = [] + for i in order: + while cnt[unique_chars[i]] > 0: + cnt -= cnts[i] + res.append(i) + res.sort() + + return "".join(map(str, res)) From ab8346413b7cd09bd4cf880ab3aa3cb854ad41e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Oct 2016 21:13:58 +0800 Subject: [PATCH 2925/4971] Create longest-repeating-character-replacement.cpp --- ...ongest-repeating-character-replacement.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/longest-repeating-character-replacement.cpp diff --git a/C++/longest-repeating-character-replacement.cpp b/C++/longest-repeating-character-replacement.cpp new file mode 100644 index 000000000..4ebf4696e --- /dev/null +++ b/C++/longest-repeating-character-replacement.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O() + +class Solution { +public: + int characterReplacement(string s, int k) { + vector cache(26); + + int i = 0, j = 0, times = k, res = 0; + for (; j < s.size(); ++j) { + ++cache[s[j] - 'A']; + if (s[j] != s[i]) { + --times; + if (times < 0) { + res = max(res, j - i); + while (i < j && k - (j - i + 1 - cache[s[i] - 'A']) < 0) { + --cache[s[i++] - 'A']; + } + times = k - (j - i + 1 - cache[s[i] - 'A']); + } + } + } + return max(res, j - i + min(i, times)); + } +}; From 7e9a6ca514f451144aaf83e21303044fb2c678ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Oct 2016 00:14:41 +0800 Subject: [PATCH 2926/4971] Create word-squares.cpp --- C++/word-squares.cpp | 62 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 C++/word-squares.cpp diff --git a/C++/word-squares.cpp b/C++/word-squares.cpp new file mode 100644 index 000000000..11d66497c --- /dev/null +++ b/C++/word-squares.cpp @@ -0,0 +1,62 @@ +// Time: O(n^2 * n!) +// Space: O(n^2) + +class Solution { +private: + struct TrieNode { + vector indices; + vector children; + TrieNode() : children(26, nullptr) {} + }; + + TrieNode *buildTrie(const vector& words) { + TrieNode *root = new TrieNode(); + for (int j = 0; j < words.size(); ++j) { + TrieNode* t = root; + for (int i = 0; i < words[j].size(); ++i) { + if (!t->children[words[j][i] - 'a']) { + t->children[words[j][i] - 'a'] = new TrieNode(); + } + t = t->children[words[j][i] - 'a']; + t->indices.push_back(j); + } + } + return root; + } + +public: + vector> wordSquares(vector& words) { + vector> result; + + TrieNode *trie = buildTrie(words); + vector curr; + for (const auto& s : words) { + curr.emplace_back(s); + wordSquaresHelper(words, trie, &curr, &result); + curr.pop_back(); + } + + return result; + } + +private: + void wordSquaresHelper(const vector& words, TrieNode *trie, vector *curr, + vector> *result) { + if (curr->size() >= words[0].length()) { + return result->emplace_back(*curr); + } + + TrieNode *node = trie; + for (int i = 0; i < curr->size(); ++i) { + if (!(node = node->children[(*curr)[i][curr->size()] - 'a'])) { + return; + } + } + + for (const auto& i : node->indices) { + curr->emplace_back(words[i]); + wordSquaresHelper(words, trie, curr, result); + curr->pop_back(); + } + } +}; From 14485741f35fbc9f4277d34e8bbff93dc66d7d09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Oct 2016 00:34:35 +0800 Subject: [PATCH 2927/4971] Create reconstruct-original-digits-from-english.cpp --- ...construct-original-digits-from-english.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/reconstruct-original-digits-from-english.cpp diff --git a/C++/reconstruct-original-digits-from-english.cpp b/C++/reconstruct-original-digits-from-english.cpp new file mode 100644 index 000000000..8c8a8d575 --- /dev/null +++ b/C++/reconstruct-original-digits-from-english.cpp @@ -0,0 +1,40 @@ + +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string originalDigits(string s) { + const vector numbers{"zero", "one", "two", "three", + "four", "five", "six", "seven", + "eight", "nine"}; + vector> cnts(numbers.size(), vector(26)); + for (int i = 0; i < numbers.size(); ++i) { + for (const auto& c : numbers[i]) { + ++cnts[i][c - 'a']; + } + } + + // The order for greedy method. + vector order{0, 2, 4, 6, 8, 1, 3, 5, 7, 9}; + + // The unique char in the order. + vector unique_chars{'z', 'o', 'w', 't', 'u', 'f', 'x', 's', 'g', 'n'}; + vector cnt(26); + for (const auto& c : s) { + ++cnt[c - 'a']; + } + + string result; + for (const auto& i : order) { + while (cnt[unique_chars[i] - 'a'] > 0) { + for (int j = 0; j < cnt.size(); ++j) { + cnt[j] -= cnts[i][j]; + } + result += to_string(i); + } + } + sort(result.begin(), result.end()); + return result; + } +}; From f52b131a151babce9e054524fabe7283119faa5b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Oct 2016 00:35:56 +0800 Subject: [PATCH 2928/4971] Update reconstruct-original-digits-from-english.cpp --- C++/reconstruct-original-digits-from-english.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/reconstruct-original-digits-from-english.cpp b/C++/reconstruct-original-digits-from-english.cpp index 8c8a8d575..3b8f64548 100644 --- a/C++/reconstruct-original-digits-from-english.cpp +++ b/C++/reconstruct-original-digits-from-english.cpp @@ -1,4 +1,3 @@ - // Time: O(n) // Space: O(1) @@ -31,7 +30,7 @@ class Solution { for (int j = 0; j < cnt.size(); ++j) { cnt[j] -= cnts[i][j]; } - result += to_string(i); + result.push_back(i + '0'); } } sort(result.begin(), result.end()); From 55d9eb75ab0b68f17493924f3dfd4cd582db0f6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Oct 2016 00:47:56 +0800 Subject: [PATCH 2929/4971] Create battleships-in-a-board.cpp --- C++/battleships-in-a-board.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/battleships-in-a-board.cpp diff --git a/C++/battleships-in-a-board.cpp b/C++/battleships-in-a-board.cpp new file mode 100644 index 000000000..f3bd89683 --- /dev/null +++ b/C++/battleships-in-a-board.cpp @@ -0,0 +1,21 @@ +// Time: O(m * n) +// Space: O(1) + +class Solution { +public: + int countBattleships(vector>& board) { + if (board.empty() || board[0].empty()) { + return 0; + } + + int cnt = 0; + for (int i = 0; i < board.size(); ++i) { + for (int j = 0; j < board[0].size(); ++j) { + cnt += board[i][j] == 'X' && + (i == 0 || board[i - 1][j] != 'X') && + (j == 0 || board[i][j - 1] != 'X'); + } + } + return cnt; + } +}; From 0c53580697b05fadb3981d97bd25f1d9da65fd2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Oct 2016 01:06:12 +0800 Subject: [PATCH 2930/4971] Create maximum-xor-of-two-numbers-in-an-array.cpp --- ...maximum-xor-of-two-numbers-in-an-array.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/maximum-xor-of-two-numbers-in-an-array.cpp diff --git a/C++/maximum-xor-of-two-numbers-in-an-array.cpp b/C++/maximum-xor-of-two-numbers-in-an-array.cpp new file mode 100644 index 000000000..8822939f9 --- /dev/null +++ b/C++/maximum-xor-of-two-numbers-in-an-array.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int findMaximumXOR(vector& nums) { + int result = 0; + + for (int i = 31; i >= 0; --i) { + result <<= 1; + unordered_set prefixes; + for (const auto& n : nums) { + prefixes.emplace(n >> i); + } + for (const auto& p : prefixes) { + if (prefixes.count((result | 1) ^ p)) { + ++result; + break; + } + } + } + + return result; + } +}; From 149d23b037317fa0f6ae0bb9e90af505aebfa845 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Oct 2016 20:30:02 +0800 Subject: [PATCH 2931/4971] Create strong-password-checker.cpp --- C++/strong-password-checker.cpp | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 C++/strong-password-checker.cpp diff --git a/C++/strong-password-checker.cpp b/C++/strong-password-checker.cpp new file mode 100644 index 000000000..cf3b19b44 --- /dev/null +++ b/C++/strong-password-checker.cpp @@ -0,0 +1,47 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int strongPasswordChecker(string s) { + int missing_type_cnt = 3; + missing_type_cnt -= static_cast(any_of(s.begin(), s.end(), [](char c){ return isdigit(c); })); + missing_type_cnt -= static_cast(any_of(s.begin(), s.end(), [](char c){ return isupper(c); })); + missing_type_cnt -= static_cast(any_of(s.begin(), s.end(), [](char c){ return islower(c); })); + int total_change_cnt = 0; + int one_change_cnt = 0, two_change_cnt = 0, three_change_cnt = 0; + for (int i = 2; i < s.length();) { + if (s[i] == s[i - 1] && s[i - 1] == s[i - 2]) { + int length = 2; + while (i < s.length() && s[i] == s[i - 1]) { + ++length; + ++i; + } + total_change_cnt += length / 3; + if (length % 3 == 0) { + ++one_change_cnt; + } else if (length % 3 == 1) { + ++two_change_cnt; + } else { + ++three_change_cnt; + } + } else { + ++i; + } + } + + if (s.length() < 6) { + return max(missing_type_cnt, 6 - static_cast(s.length())); + } else if (s.length() <= 20) { + return max(missing_type_cnt, total_change_cnt); + } + + int delete_cnt = s.length() - 20; + + total_change_cnt -= min(delete_cnt, one_change_cnt) / 1; + total_change_cnt -= min(max(delete_cnt - one_change_cnt, 0), two_change_cnt * 2) / 2; + total_change_cnt -= min(max(delete_cnt - one_change_cnt - 2 * two_change_cnt, 0), three_change_cnt * 3) / 3; + + return delete_cnt + max(missing_type_cnt, total_change_cnt); + } +}; From 213b57a85d9e55835dfaa151245d1e067077fbea Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Oct 2016 20:32:02 +0800 Subject: [PATCH 2932/4971] Create strong-password-checker.py --- Python/strong-password-checker.py | 61 +++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/strong-password-checker.py diff --git a/Python/strong-password-checker.py b/Python/strong-password-checker.py new file mode 100644 index 000000000..90269f9fc --- /dev/null +++ b/Python/strong-password-checker.py @@ -0,0 +1,61 @@ +# Time: O(n) +# Space: O(1) + +# A password is considered strong if below conditions are all met: +# +# It has at least 6 characters and at most 20 characters. +# It must contain at least one lowercase letter, at least one uppercase letter, +# and at least one digit. +# It must NOT contain three repeating characters in a row ("...aaa..." is weak, +# but "...aa...a..." is strong, assuming other conditions are met). +# Write a function strongPasswordChecker(s), that takes a string s as input, +# and return the MINIMUM change required to make s a strong password. If s is already strong, return 0. +# +# Insertion, deletion or replace of any one character are all considered as one change. + +class Solution(object): + def strongPasswordChecker(self, s): + """ + :type s: str + :rtype: int + """ + missing_type_cnt = 3 + if any('a' <= c <= 'z' for c in s): + missing_type_cnt -= 1 + if any('A' <= c <= 'Z' for c in s): + missing_type_cnt -= 1 + if any(c.isdigit() for c in s): + missing_type_cnt -= 1 + + total_change_cnt = 0 + one_change_cnt, two_change_cnt, three_change_cnt = 0, 0, 0 + i = 2 + while i < len(s): + if s[i] == s[i-1] == s[i-2]: + length = 2 + while i < len(s) and s[i] == s[i-1]: + length += 1 + i += 1 + + total_change_cnt += length / 3 + if length % 3 == 0: + one_change_cnt += 1 + elif length % 3 == 1: + two_change_cnt += 1 + else: + three_change_cnt += 1 + else: + i += 1 + + if len(s) < 6: + return max(missing_type_cnt, 6 - len(s)) + elif len(s) <= 20: + return max(missing_type_cnt, total_change_cnt) + else: + delete_cnt = len(s) - 20 + + total_change_cnt -= min(delete_cnt, one_change_cnt * 1) / 1 + total_change_cnt -= min(max(delete_cnt - one_change_cnt, 0), two_change_cnt * 2) / 2 + total_change_cnt -= min(max(delete_cnt - one_change_cnt - 2 * two_change_cnt, 0), three_change_cnt * 3) / 3 + + return delete_cnt + max(missing_type_cnt, total_change_cnt) From a5c7ad537e6d7525125b170896cc94c6a50368df Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Oct 2016 20:34:12 +0800 Subject: [PATCH 2933/4971] Update strong-password-checker.cpp --- C++/strong-password-checker.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/strong-password-checker.cpp b/C++/strong-password-checker.cpp index cf3b19b44..fa8cf5854 100644 --- a/C++/strong-password-checker.cpp +++ b/C++/strong-password-checker.cpp @@ -8,6 +8,7 @@ class Solution { missing_type_cnt -= static_cast(any_of(s.begin(), s.end(), [](char c){ return isdigit(c); })); missing_type_cnt -= static_cast(any_of(s.begin(), s.end(), [](char c){ return isupper(c); })); missing_type_cnt -= static_cast(any_of(s.begin(), s.end(), [](char c){ return islower(c); })); + int total_change_cnt = 0; int one_change_cnt = 0, two_change_cnt = 0, three_change_cnt = 0; for (int i = 2; i < s.length();) { From 938e5038a0c19f1f2dc7cf7eb570537e8407b50b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Oct 2016 20:46:10 +0800 Subject: [PATCH 2934/4971] Create all-oone-data-structure.cpp --- C++/all-oone-data-structure.cpp | 79 +++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 C++/all-oone-data-structure.cpp diff --git a/C++/all-oone-data-structure.cpp b/C++/all-oone-data-structure.cpp new file mode 100644 index 000000000..f3f81ccb5 --- /dev/null +++ b/C++/all-oone-data-structure.cpp @@ -0,0 +1,79 @@ +// Time: O(1), per operation +// Space: O(k) + +class AllOne { +public: + /** Initialize your data structure here. */ + AllOne() { + + } + + /** Inserts a new key with value 1. Or increments an existing key by 1. */ + void inc(string key) { + if (!bucketOfKey_.count(key)) { + bucketOfKey_[key] = buckets_.insert(buckets_.begin(), {0, {key}}); + } + + auto next = bucketOfKey_[key], bucket = next++; + if (next == buckets_.end() || next->value > bucket->value + 1) { + next = buckets_.insert(next, {bucket->value + 1, {}}); + } + next->keys.insert(key); + bucketOfKey_[key] = next; + + bucket->keys.erase(key); + if (bucket->keys.empty()) { + buckets_.erase(bucket); + } + } + + /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ + void dec(string key) { + if (!bucketOfKey_.count(key)) { + return; + } + + auto prev = bucketOfKey_[key], bucket = prev--; + bucketOfKey_.erase(key); + if (bucket->value > 1) { + if (bucket == buckets_.begin() || prev->value < bucket->value - 1) { + prev = buckets_.insert(bucket, {bucket->value - 1, {}}); + } + prev->keys.insert(key); + bucketOfKey_[key] = prev; + } + + bucket->keys.erase(key); + if (bucket->keys.empty()) { + buckets_.erase(bucket); + } + } + + /** Returns one of the keys with maximal value. */ + string getMaxKey() { + return buckets_.empty() ? "" : *(buckets_.rbegin()->keys.begin()); + } + + /** Returns one of the keys with Minimal value. */ + string getMinKey() { + return buckets_.empty() ? "" : *(buckets_.begin()->keys.begin()); + } + +private: + struct Bucket { + int value; + unordered_set keys; + }; + list buckets_; + unordered_map::iterator> bucketOfKey_; +}; + +/** + * Your AllOne object will be instantiated and called as such: + * AllOne obj = new AllOne(); + * obj.inc(key); + * obj.dec(key); + * string param_3 = obj.getMaxKey(); + * string param_4 = obj.getMinKey(); + */ + From 344a0f258a9b5be166223bd1926986134331ec7f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Oct 2016 21:00:50 +0800 Subject: [PATCH 2935/4971] Create minimum-genetic-mutation.cpp --- C++/minimum-genetic-mutation.cpp | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/minimum-genetic-mutation.cpp diff --git a/C++/minimum-genetic-mutation.cpp b/C++/minimum-genetic-mutation.cpp new file mode 100644 index 000000000..9aa1defc6 --- /dev/null +++ b/C++/minimum-genetic-mutation.cpp @@ -0,0 +1,40 @@ +// Time: O(n * b), n is the length of gene string, b is size of bank +// Space: O(b) + +class Solution { +public: + int minMutation(string start, string end, vector& bank) { + unordered_map lookup; + for (const auto& b : bank) { + lookup.emplace(b, false); + } + + queue> q; + q.emplace(start, 0); + while (!q.empty()) { + string cur; + int level; + tie(cur, level) = q.front(); q.pop(); + + if (cur == end) { + return level; + } + + for (int i = 0; i < cur.size(); ++i) { + auto cur_copy = cur; + for (const auto& c : {'A', 'T', 'C', 'G'}) { + if (cur_copy[i] == c) { + continue; + } + cur_copy[i] = c; + if (lookup.count(cur_copy) && lookup[cur_copy] == false) { + q.emplace(cur_copy, level + 1); + lookup[cur_copy] = true; + } + } + } + } + + return -1; + } +}; From a4e65ab0398c116c78b54d8c069e5780bc9b01fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 20:10:38 +0800 Subject: [PATCH 2936/4971] Create all-oone-data-structure.py --- Python/all-oone-data-structure.py | 121 ++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 Python/all-oone-data-structure.py diff --git a/Python/all-oone-data-structure.py b/Python/all-oone-data-structure.py new file mode 100644 index 000000000..55327cdd6 --- /dev/null +++ b/Python/all-oone-data-structure.py @@ -0,0 +1,121 @@ +# Time: O(1), per operation +# Space: O(k) + +# Implement a data structure supporting the following operations: +# +# Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. +# Key is guaranteed to be a non-empty string. +# Dec(Key) - If Key's value is 1, remove it from the data structure. +# Otherwise decrements an existing key by 1. If the key does not exist, +# this function does nothing. Key is guaranteed to be a non-empty string. +# GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "". +# GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string "". +# Challenge: Perform all these in O(1) time complexity. + +class Node(object): + """ + double linked list node + """ + def __init__(self, value, keys): + self.value = value + self.keys = keys + self.prev = None + self.next = None + + +class LinkedList(object): + def __init__(self): + self.head, self.tail = Node(0, set()), Node(0, set()) + self.head.next, self.tail.prev = self.tail, self.head + + def insert(self, pos, node): + node.prev, node.next = pos.prev, pos + pos.prev.next, pos.prev = node, node + return node + + def erase(self, node): + node.prev.next, node.next.prev = node.next, node.prev + del node + + def empty(self): + return self.head.next is self.tail + + def begin(self): + return self.head.next + + def end(self): + return self.tail + + def front(self): + return self.head.next + + def back(self): + return self.tail.prev + + +class AllOne(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.bucket_of_key = {} + self.buckets = LinkedList() + + def inc(self, key): + """ + Inserts a new key with value 1. Or increments an existing key by 1. + :type key: str + :rtype: void + """ + if key not in self.bucket_of_key: + self.bucket_of_key[key] = self.buckets.insert(self.buckets.begin(), Node(0, set([key]))) + + bucket, next_bucket = self.bucket_of_key[key], self.bucket_of_key[key].next + if next_bucket is self.buckets.end() or next_bucket.value > bucket.value+1: + next_bucket = self.buckets.insert(next_bucket, Node(bucket.value+1, set())) + next_bucket.keys.add(key) + self.bucket_of_key[key] = next_bucket + + bucket.keys.remove(key) + if not bucket.keys: + self.buckets.erase(bucket) + + def dec(self, key): + """ + Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. + :type key: str + :rtype: void + """ + if key not in self.bucket_of_key: + return + + bucket, prev_bucket = self.bucket_of_key[key], self.bucket_of_key[key].prev + self.bucket_of_key.pop(key, None) + if bucket.value > 1: + if bucket is self.buckets.begin() or prev_bucket.value < bucket.value-1: + prev_bucket = self.buckets.insert(bucket, Node(bucket.value-1, set())) + prev_bucket.keys.add(key) + self.bucket_of_key[key] = prev_bucket + + bucket.keys.remove(key) + if not bucket.keys: + self.buckets.erase(bucket) + + def getMaxKey(self): + """ + Returns one of the keys with maximal value. + :rtype: str + """ + if self.buckets.empty(): + return "" + return iter(self.buckets.back().keys).next() + + def getMinKey(self): + """ + Returns one of the keys with Minimal value. + :rtype: str + """ + if self.buckets.empty(): + return "" + return iter(self.buckets.front().keys).next() From a91085fa10788e41dbf7d9ed2e1b0f00ab26a205 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 20:16:20 +0800 Subject: [PATCH 2937/4971] Create battleships-in-a-board.py --- Python/battleships-in-a-board.py | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/battleships-in-a-board.py diff --git a/Python/battleships-in-a-board.py b/Python/battleships-in-a-board.py new file mode 100644 index 000000000..69a62369a --- /dev/null +++ b/Python/battleships-in-a-board.py @@ -0,0 +1,42 @@ +# Time: O(m * n) +# Space: O(1) + +# Given an 2D board, count how many different battleships are in it. +# The battleships are represented with 'X's, empty slots are represented with '.'s. +# You may assume the following rules: +# +# You receive a valid board, made of only battleships or empty slots. +# Battleships can only be placed horizontally or vertically. In other words, +# they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), +# where N can be of any size. +# At least one horizontal or vertical cell separates between two battleships - +# there are no adjacent battleships. +# +# Example: +# X..X +# ...X +# ...X +# In the above board there are 2 battleships. +# Invalid Example: +# ...X +# XXXX +# ...X +# This is not a valid board - as battleships will always have a cell separating between them. +# Your algorithm should not modify the value of the board. + +class Solution(object): + def countBattleships(self, board): + """ + :type board: List[List[str]] + :rtype: int + """ + if not board or not board[0]: + return 0 + + cnt = 0 + for i in xrange(len(board)): + for j in xrange(len(board[0])): + cnt += int(board[i][j] == 'X' and \ + (i == 0 or board[i - 1][j] != 'X') and \ + (j == 0 or board[i][j - 1] != 'X')) + return cnt From 5ccdd94da662237d144a8b1aaa95f0fc7b5d4c3e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 20:19:44 +0800 Subject: [PATCH 2938/4971] Create maximum-xor-of-two-numbers-in-an-array.py --- .../maximum-xor-of-two-numbers-in-an-array.py | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/maximum-xor-of-two-numbers-in-an-array.py diff --git a/Python/maximum-xor-of-two-numbers-in-an-array.py b/Python/maximum-xor-of-two-numbers-in-an-array.py new file mode 100644 index 000000000..20f541afe --- /dev/null +++ b/Python/maximum-xor-of-two-numbers-in-an-array.py @@ -0,0 +1,36 @@ +# Time: O(n) +# Space: O(n) + +# Given a non-empty array of numbers, a0, a1, a2, ... , an-1, where 0 <= ai < 231. +# +# Find the maximum result of ai XOR aj, where 0 <= i, j < n. +# +# Could you do this in O(n) runtime? +# +# Example: +# +# Input: [3, 10, 5, 25, 2, 8] +# +# Output: 28 +# +# Explanation: The maximum result is 5 ^ 25 = 28. + +class Solution(object): + def findMaximumXOR(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + result = 0 + + for i in reversed(xrange(32)): + result <<= 1 + prefixes = set() + for n in nums: + prefixes.add(n >> i) + for p in prefixes: + if (result | 1) ^ p in prefixes: + result += 1 + break + + return result From efddcb306f8b69537360d6abdbcd5f0f5eeca98f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 20:24:38 +0800 Subject: [PATCH 2939/4971] Update valid-word-square.cpp --- C++/valid-word-square.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/valid-word-square.cpp b/C++/valid-word-square.cpp index 430ecfa97..300d53318 100644 --- a/C++/valid-word-square.cpp +++ b/C++/valid-word-square.cpp @@ -5,8 +5,8 @@ class Solution { public: bool validWordSquare(vector& words) { for (int i = 0; i < words.size(); ++i) { - for (int j = 0; j < words[i].size(); ++j) { - if (j >= words.size() || words[j].size() <= i || + for (int j = 0; j < words[i].size(); ++j) { + if (j >= words.size() || i >= words[j].size() || words[j][i] != words[i][j]) { return false; } From 6e292a6a91d954d7acc125a9c115be0d21ebdc18 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 20:26:21 +0800 Subject: [PATCH 2940/4971] Create valid-word-square.py --- Python/valid-word-square.py | 82 +++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Python/valid-word-square.py diff --git a/Python/valid-word-square.py b/Python/valid-word-square.py new file mode 100644 index 000000000..97a0d1064 --- /dev/null +++ b/Python/valid-word-square.py @@ -0,0 +1,82 @@ +# Time: O(m * n) +# Space: O(1) + +# Given a sequence of words, check whether it forms a valid word square. +# +# A sequence of words forms a valid word square if the kth row and +# column read the exact same string, where 0 ≤ k < max(numRows, numColumns). +# +# Note: +# The number of words given is at least 1 and does not exceed 500. +# Word length will be at least 1 and does not exceed 500. +# Each word contains only lowercase English alphabet a-z. +# Example 1: +# +# Input: +# [ +# "abcd", +# "bnrt", +# "crmy", +# "dtye" +# ] +# +# Output: +# true +# +# Explanation: +# The first row and first column both read "abcd". +# The second row and second column both read "bnrt". +# The third row and third column both read "crmy". +# The fourth row and fourth column both read "dtye". +# +# Therefore, it is a valid word square. +# Example 2: +# +# Input: +# [ +# "abcd", +# "bnrt", +# "crm", +# "dt" +# ] +# +# Output: +# true +# +# Explanation: +# The first row and first column both read "abcd". +# The second row and second column both read "bnrt". +# The third row and third column both read "crm". +# The fourth row and fourth column both read "dt". +# +# Therefore, it is a valid word square. +# Example 3: + +# Input: +# [ +# "ball", +# "area", +# "read", +# "lady" +# ] +# +# Output: +# false +# +# Explanation: +# The third row reads "read" while the third column reads "lead". +# +# Therefore, it is NOT a valid word square. + +class Solution(object): + def validWordSquare(self, words): + """ + :type words: List[str] + :rtype: bool + """ + for i in xrange(len(words)): + for j in xrange(len(words[i])): + if j >= len(words) or i >= len(words[j]) or \ + words[j][i] != words[i][j]: + return False + return True From 84d85b23cfe6601b832448921c908cc9a03d45cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 20:27:47 +0800 Subject: [PATCH 2941/4971] Update longest-repeating-character-replacement.cpp --- C++/longest-repeating-character-replacement.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-repeating-character-replacement.cpp b/C++/longest-repeating-character-replacement.cpp index 4ebf4696e..6eae51dd8 100644 --- a/C++/longest-repeating-character-replacement.cpp +++ b/C++/longest-repeating-character-replacement.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O() +// Space: O(1) class Solution { public: From 9b0c1b5e5c164d1cc5ba73b121ead43e2c737597 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 20:38:09 +0800 Subject: [PATCH 2942/4971] Update longest-repeating-character-replacement.cpp --- C++/longest-repeating-character-replacement.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/longest-repeating-character-replacement.cpp b/C++/longest-repeating-character-replacement.cpp index 6eae51dd8..78fe53af1 100644 --- a/C++/longest-repeating-character-replacement.cpp +++ b/C++/longest-repeating-character-replacement.cpp @@ -13,10 +13,10 @@ class Solution { --times; if (times < 0) { res = max(res, j - i); - while (i < j && k - (j - i + 1 - cache[s[i] - 'A']) < 0) { + while (i < j && times < 0) { --cache[s[i++] - 'A']; + times = k - (j - i + 1 - cache[s[i] - 'A']); } - times = k - (j - i + 1 - cache[s[i] - 'A']); } } } From 66d0753d759bf7c264b84a7c9b5c3c3422339c94 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 20:47:27 +0800 Subject: [PATCH 2943/4971] Create longest-repeating-character-replacement.py --- ...longest-repeating-character-replacement.py | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Python/longest-repeating-character-replacement.py diff --git a/Python/longest-repeating-character-replacement.py b/Python/longest-repeating-character-replacement.py new file mode 100644 index 000000000..64810432f --- /dev/null +++ b/Python/longest-repeating-character-replacement.py @@ -0,0 +1,57 @@ +# Time: O(n) +# Space: O(1) + +# Given a string that consists of only uppercase English letters, +# you can replace any letter in the string with another letter at most k times. +# Find the length of a longest substring containing all repeating letters +# you can get after performing the above operations. +# +# Note: +# Both the string's length and k will not exceed 104. +# +# Example 1: +# +# Input: +# s = "ABAB", k = 2 +# +# Output: +# 4 +# +# Explanation: +# Replace the two 'A's with two 'B's or vice versa. +# Example 2: +# +# Input: +# s = "AABABBA", k = 1 +# +# Output: +# 4 +# +# Explanation: +# Replace the one 'A' in the middle with 'B' and form "AABBBBA". +# The substring "BBBB" has the longest repeating letters, which is 4. + +class Solution(object): + def characterReplacement(self, s, k): + """ + :type s: str + :type k: int + :rtype: int + """ + res = 0 + + cnts = [0] * 26 + times, i, j = k, 0, 0 + while j < len(s): + cnts[ord(s[j]) - ord('A')] += 1 + if s[j] != s[i]: + times -= 1 + if times < 0: + res = max(res, j - i) + while i < j and times < 0: + cnts[ord(s[i]) - ord('A')] -= 1 + i += 1 + times = k - (j - i + 1 - cnts[ord(s[i]) - ord('A')]) + j += 1 + + return max(res, j - i + min(i, times)) From e494a46f300fc78d5e5c302871e1fa7d072fced0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 20:48:58 +0800 Subject: [PATCH 2944/4971] Delete valid-word-square.py --- Python/valid-word-square.py | 82 ------------------------------------- 1 file changed, 82 deletions(-) delete mode 100644 Python/valid-word-square.py diff --git a/Python/valid-word-square.py b/Python/valid-word-square.py deleted file mode 100644 index 97a0d1064..000000000 --- a/Python/valid-word-square.py +++ /dev/null @@ -1,82 +0,0 @@ -# Time: O(m * n) -# Space: O(1) - -# Given a sequence of words, check whether it forms a valid word square. -# -# A sequence of words forms a valid word square if the kth row and -# column read the exact same string, where 0 ≤ k < max(numRows, numColumns). -# -# Note: -# The number of words given is at least 1 and does not exceed 500. -# Word length will be at least 1 and does not exceed 500. -# Each word contains only lowercase English alphabet a-z. -# Example 1: -# -# Input: -# [ -# "abcd", -# "bnrt", -# "crmy", -# "dtye" -# ] -# -# Output: -# true -# -# Explanation: -# The first row and first column both read "abcd". -# The second row and second column both read "bnrt". -# The third row and third column both read "crmy". -# The fourth row and fourth column both read "dtye". -# -# Therefore, it is a valid word square. -# Example 2: -# -# Input: -# [ -# "abcd", -# "bnrt", -# "crm", -# "dt" -# ] -# -# Output: -# true -# -# Explanation: -# The first row and first column both read "abcd". -# The second row and second column both read "bnrt". -# The third row and third column both read "crm". -# The fourth row and fourth column both read "dt". -# -# Therefore, it is a valid word square. -# Example 3: - -# Input: -# [ -# "ball", -# "area", -# "read", -# "lady" -# ] -# -# Output: -# false -# -# Explanation: -# The third row reads "read" while the third column reads "lead". -# -# Therefore, it is NOT a valid word square. - -class Solution(object): - def validWordSquare(self, words): - """ - :type words: List[str] - :rtype: bool - """ - for i in xrange(len(words)): - for j in xrange(len(words[i])): - if j >= len(words) or i >= len(words[j]) or \ - words[j][i] != words[i][j]: - return False - return True From cc1d7f389e7ea60de593a0be158dc00aa7f044e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 20:49:21 +0800 Subject: [PATCH 2945/4971] Create valid-word-square.py --- Python/valid-word-square.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Python/valid-word-square.py diff --git a/Python/valid-word-square.py b/Python/valid-word-square.py new file mode 100644 index 000000000..8f9fe8c4a --- /dev/null +++ b/Python/valid-word-square.py @@ -0,0 +1,15 @@ +# Time: O(m * n) +# Space: O(1) + +class Solution(object): + def validWordSquare(self, words): + """ + :type words: List[str] + :rtype: bool + """ + for i in xrange(len(words)): + for j in xrange(len(words[i])): + if j >= len(words) or i >= len(words[j]) or \ + words[j][i] != words[i][j]: + return False + return True From 7ce1d197925771f0b0ab9224f31aa99f7bf51e0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 23:30:13 +0800 Subject: [PATCH 2946/4971] Create word-squares.py --- Python/word-squares.py | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/word-squares.py diff --git a/Python/word-squares.py b/Python/word-squares.py new file mode 100644 index 000000000..370fbab07 --- /dev/null +++ b/Python/word-squares.py @@ -0,0 +1,51 @@ +# Time: O(n^2 * n!) +# Space: O(n^2) + +class TrieNode(object): + def __init__(self): + self.indices = [] + self.children = [None] * 26 + + def insert(self, words, i): + cur = self + for c in words[i]: + if not cur.children[ord(c)-ord('a')]: + cur.children[ord(c)-ord('a')] = TrieNode() + cur = cur.children[ord(c)-ord('a')] + cur.indices.append(i) + + +class Solution(object): + def wordSquares(self, words): + """ + :type words: List[str] + :rtype: List[List[str]] + """ + result = [] + + trie = TrieNode() + for i in xrange(len(words)): + trie.insert(words, i) + + curr = [] + for s in words: + curr.append(s) + self.wordSquaresHelper(words, trie, curr, result); + curr.pop(); + + return result + + def wordSquaresHelper(self, words, trie, curr, result): + if len(curr) >= len(words[0]): + return result.append(list(curr)) + + node = trie; + for s in curr: + node = node.children[ord(s[len(curr)]) - ord('a')] + if not node: + return + + for i in node.indices: + curr.append(words[i]) + self.wordSquaresHelper(words, trie, curr, result) + curr.pop() From 4e80f5b194c813ded5973ce70a6bb6626662160d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 23:31:33 +0800 Subject: [PATCH 2947/4971] Update word-squares.py --- Python/word-squares.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/word-squares.py b/Python/word-squares.py index 370fbab07..59d69b9e6 100644 --- a/Python/word-squares.py +++ b/Python/word-squares.py @@ -30,8 +30,8 @@ def wordSquares(self, words): curr = [] for s in words: curr.append(s) - self.wordSquaresHelper(words, trie, curr, result); - curr.pop(); + self.wordSquaresHelper(words, trie, curr, result) + curr.pop() return result @@ -39,7 +39,7 @@ def wordSquaresHelper(self, words, trie, curr, result): if len(curr) >= len(words[0]): return result.append(list(curr)) - node = trie; + node = trie for s in curr: node = node.children[ord(s[len(curr)]) - ord('a')] if not node: From 0c701a90f009d040a51e62e6031f680bdc68e2e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 22 Oct 2016 23:48:32 +0800 Subject: [PATCH 2948/4971] Create minimum-genetic-mutation.py --- Python/minimum-genetic-mutation.py | 66 ++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Python/minimum-genetic-mutation.py diff --git a/Python/minimum-genetic-mutation.py b/Python/minimum-genetic-mutation.py new file mode 100644 index 000000000..900510bb7 --- /dev/null +++ b/Python/minimum-genetic-mutation.py @@ -0,0 +1,66 @@ +# Time: O(n * b), n is the length of gene string, b is size of bank +# Space: O(b) + +# A gene string can be represented by an 8-character long string, +# with choices from "A","C","G","T". +# Suppose we need to investigate about a mutation (mutation from "start" to "end"), +# where ONE mutation is defined as ONE single character changed in the gene string. +# For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation. +# Also, there is a given gene "bank", which records all the valid gene mutations. +# A gene must be in the bank to make it a valid gene string. +# +# Now, given 3 things - start, end, bank, +# your task is to determine what is the minimum number of mutations needed to +# mutate from "start" to "end". If there is no such a mutation, return -1. +# +# NOTE: 1. Starting point is assumed to be valid, so it might not be included in the bank. +# 2. If multiple mutations are needed, all mutations during in the sequence must be valid. +# +# For example, +# +# bank: "AACCGGTA" +# start: "AACCGGTT" +# end: "AACCGGTA" +# return: 1 +# +# bank: "AACCGGTA", "AACCGCTA", "AAACGGTA" +# start: "AACCGGTT" +# end: "AAACGGTA" +# return: 2 +# +# bank: "AAAACCCC", "AAACCCCC", "AACCCCCC" +# start: "AAAAACCC" +# end: "AACCCCCC" +# return: 3 + +from collections import deque + +class Solution(object): + def minMutation(self, start, end, bank): + """ + :type start: str + :type end: str + :type bank: List[str] + :rtype: int + """ + lookup = {} + for b in bank: + lookup[b] = False + + q = deque([(start, 0)]) + while q: + cur, level = q.popleft() + if cur == end: + return level + + for i in xrange(len(cur)): + for c in ['A', 'T', 'C', 'G']: + if cur[i] == c: + continue + + next_str = cur[:i] + c + cur[i+1:] + if next_str in lookup and lookup[next_str] == False: + q.append((next_str, level+1)) + lookup[next_str] = True + + return -1 From 547780ad2d95ae00ef2de5e928870c3b33693c8b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 00:00:50 +0800 Subject: [PATCH 2949/4971] Update README.md --- README.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6dd7f1879..cb3e31aa8 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-418%20%2F%20418-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-425%20%2F%20425-ff69b4.svg) -Up to date (2016-10-09), there are `401` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-10-22), there are `408` 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 `418` questions. +Here is the classification of all `425` 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.) @@ -60,6 +60,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 393 | [UTF-8 Validation](https://leetcode.com/problems/utf-8-validation/) | [C++](./C++/utf-8-validation.cpp) [Python](./Python/utf-8-validation.py) | _O(n)_ | _O(1)_ | Medium | | 401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./C++/binary-watch.cpp) [Python](./Python/binary-watch.py) | _O(1)_ | _O(1)_ | Easy | | 411 | [Minimum Unique Word Abbreviation](https://leetcode.com/problems/minimum-unique-word-abbreviation/) | [C++](./C++/minimum-unique-word-abbreviation.cpp) [Python](./Python/minimum-unique-word-abbreviation.py) | _O(2^n)_ | _O(n)_ | Hard | 📖 | +421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [C++](./C++/maximum-xor-of-two-numbers-in-an-array.cpp) [Python](./Python/maximum-xor-of-two-numbers-in-an-array.py) | _O(n)_ | _O(1)_ | Medium || ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -106,6 +107,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 396| [Rotate Function](https://leetcode.com/problems/rotate-function/) | [C++](./C++/rotate-function.cpp) [Python](./Python/rotate-function.py) | _O(n)_ | _O(1)_ | Easy ||| 412| [Fizz Buzz](https://leetcode.com/problems/fizz-buzz/) | [C++](./C++/fizz-buzz.cpp) [Python](./Python/fizz-buzz.py) | _O(n)_ | _O(1)_ | Easy ||| 414| [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./C++/third-maximum-number.cpp) [Python](./Python/third-maximum-number.py) | _O(n)_ | _O(1)_ | Easy ||| +419| [Battleships in a Board](https://leetcode.com/problems/battleships-in-a-board/) | [C++](./C++/battleships-in-a-board.cpp) [Python](./Python/battleships-in-a-board.py) | _O(m * n)_ | _O(1)_ | Medium ||| +422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| ## String # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -134,6 +137,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 405| [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./C++/convert-a-number-to-hexadecimal.cpp) [Python](./Python/convert-a-number-to-hexadecimal.py) | _O(n)_ | _O(1)_ | Easy | | 408| [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) | [C++](./C++/valid-word-abbreviation.cpp) [Python](./Python/valid-word-abbreviation.py) | _O(n)_ | _O(1)_ | Easy | 📖 | 415| [Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./C++/add-strings.cpp) [Python](./Python/add-strings.py) | _O(n)_ | _O(1)_ | Easy | | +420| [Strong Password Checker](https://leetcode.com/problems/strong-password-checker/) | [C++](./C++/strong-password-checker.cpp) [Python](./Python/strong-password-checker.py) | _O(n)_ | _O(1)_ | Hard | | ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -247,6 +251,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 387| [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/first-unique-character-in-a-string.cpp) [Python](./Python/first-unique-character-in-a-string.py) | _O(n)_| _O(n)_| Easy ||| 388| [Longest Absolute File Path](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/longest-absolute-file-path.cpp) [Python](./Python/longest-absolute-file-path.py) | _O(n)_| _O(d)_| Medium || Stack | 409| [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./C++/longest-palindrome.cpp) [Python](./Python/longest-palindrome.py) | _O(n)_| _O(1)_| Easy ||| +424| [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) | [C++](./C++/longest-repeating-character-replacement.cpp) [Python](./Python/longest-repeating-character-replacement.py) | _O(n)_| _O(1)_| Medium ||| ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -290,6 +295,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 398 | [Random Pick Index](https://leetcode.com/problems/random-pick-index/) | [C++](./C++/random-pick-index.cpp) [Python](./Python/random-pick-index.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 400 | [Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./C++/nth-digit.cpp) [Python](./Python/nth-digit.py) | _O(logn)_ | _O(1)_ | Easy ||| 413 | [Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./C++/arithmetic-slices.cpp) [Python](./Python/arithmetic-slices.py) | _O(n)_ | _O(1)_ | Medium ||| +423 | [Reconstruct Original Digits from English](https://leetcode.com/problems/reconstruct-original-digits-from-english/) | [C++](./C++/reconstruct-original-digits-from-english.cpp) [Python](./Python/reconstruct-original-digits-from-english.py) | _O(n)_ | _O(1)_ | Medium | [GCJ2016 - Round 1B](https://code.google.com/codejam/contest/11254486/dashboard#s=p0)|| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -456,6 +462,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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(n * 2^n)_ | _O(n)_ | Medium |📖|| +425| [Word Squares](https://leetcode.com/problems/word-squares/) | [C++](./C++/word-squares.cpp) [Python](./Python/word-squares.py) | _O(n^2 * n!)_ | _O(n^2)_ | Hard |📖|| ## Dynamic Programming # | Title | Solution | Time | Space | Difficulty | Tag | Note From 413f1a5ad1c622dd9bf7ebeda9fa48bcb620c498 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 00:06:20 +0800 Subject: [PATCH 2950/4971] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index cb3e31aa8..64c37d016 100644 --- a/README.md +++ b/README.md @@ -413,6 +413,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | 📖 | +433| [Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation/)| [C++](./C++/minimum-genetic-mutation.cpp) [Python](./Python/minimum-genetic-mutation.py) | _O(n * b)_ | _O(b)_ | Medium || ## Depth-First Search # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -540,6 +541,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 379| [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) | [C++](./C++/design-phone-directory.cpp) [Python](./Python/design-phone-directory.py) | _O(1)_ | _O(n)_| Medium |📖| | 380| [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./C++/insert-delete-getrandom-o1.cpp) [Python](./Python/insert-delete-getrandom-o1.py) | _O(1)_ | _O(n)_| Medium || | 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_| Medium || | +432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From d700f4e804f31e8578c5dca25bab8638559216d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 14:47:55 +0800 Subject: [PATCH 2951/4971] Create ternary-expression-parser.cpp --- C++/ternary-expression-parser.cpp | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/ternary-expression-parser.cpp diff --git a/C++/ternary-expression-parser.cpp b/C++/ternary-expression-parser.cpp new file mode 100644 index 000000000..29add16dd --- /dev/null +++ b/C++/ternary-expression-parser.cpp @@ -0,0 +1,32 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + string parseTernary(string expression) { + if (expression.empty()) { + return ""; + } + + string stack; + for (int i = expression.length() - 1; i >= 0; --i) { + auto c = expression[i]; + if (!stack.empty() && stack.back() == '?') { + stack.pop_back(); // pop '?' + auto first = stack.back(); stack.pop_back(); + stack.pop_back(); // pop ':' + auto second = stack.back(); stack.pop_back(); + + if (c == 'T') { + stack.push_back(first); + } else { + stack.push_back(second); + } + } else { + stack.push_back(c); + } + } + + return string(1, stack.back()); + } +}; From dcfe039e5bcb84ef40de016af48cd4c7e75efce7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 17:28:46 +0800 Subject: [PATCH 2952/4971] Create k-th-smallest-in-lexicographical-order.cpp --- ...k-th-smallest-in-lexicographical-order.cpp | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 C++/k-th-smallest-in-lexicographical-order.cpp diff --git a/C++/k-th-smallest-in-lexicographical-order.cpp b/C++/k-th-smallest-in-lexicographical-order.cpp new file mode 100644 index 000000000..2e9f66f04 --- /dev/null +++ b/C++/k-th-smallest-in-lexicographical-order.cpp @@ -0,0 +1,56 @@ +// Time: O(logn * logn) +// Space: O(logn) + +class Solution { +public: + int findKthNumber(int n, int k) { + int result = 0; + int cur = 0; + int index = 0; + for (int i = 1; i <= 9; ++i, cur /= 10) { + cur = cur * 10 + i; + int cnt = count(n, cur); + if (k > cnt + index) { + index += cnt; + continue; + } + if (cur <= n && findKthNumberHelper(n, k, cur, &index, &result)) { + break; + } + } + return result; + } + +private: + bool findKthNumberHelper(int n, int k, int cur, int *index, int *result) { + ++(*index); + if (*index == k) { + *result = cur; + return true; + } + for (int i = 0; i <= 9; ++i, cur /= 10) { + cur = cur * 10 + i; + int cnt = count(n, cur); + if (k > cnt + *index) { + *index += cnt; + continue; + } + if (cur <= n && findKthNumberHelper(n, k, cur, index, result)) { + return true; + } + } + return false; + } + + int count(int n, long long prefix) { // Time: O(logn) + int result = 0; + int number = 1; + while (prefix <= n) { + result += number; + prefix *= 10; + number *= 10; + } + result -= max(number / 10 - (n - prefix / 10 + 1), static_cast(0)); + return result; + } +}; From 87ce300752ac653259a4234ab6f65881a85877d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 17:36:34 +0800 Subject: [PATCH 2953/4971] Update k-th-smallest-in-lexicographical-order.cpp --- ...k-th-smallest-in-lexicographical-order.cpp | 27 +++++++------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/C++/k-th-smallest-in-lexicographical-order.cpp b/C++/k-th-smallest-in-lexicographical-order.cpp index 2e9f66f04..b6b71c0a4 100644 --- a/C++/k-th-smallest-in-lexicographical-order.cpp +++ b/C++/k-th-smallest-in-lexicographical-order.cpp @@ -5,30 +5,21 @@ class Solution { public: int findKthNumber(int n, int k) { int result = 0; - int cur = 0; - int index = 0; - for (int i = 1; i <= 9; ++i, cur /= 10) { - cur = cur * 10 + i; - int cnt = count(n, cur); - if (k > cnt + index) { - index += cnt; - continue; - } - if (cur <= n && findKthNumberHelper(n, k, cur, &index, &result)) { - break; - } - } + int cur = 0, index = 0; + findKthNumberHelper(n, k, cur, &index, &result); return result; } private: bool findKthNumberHelper(int n, int k, int cur, int *index, int *result) { - ++(*index); - if (*index == k) { - *result = cur; - return true; + if (cur) { + ++(*index); + if (*index == k) { + *result = cur; + return true; + } } - for (int i = 0; i <= 9; ++i, cur /= 10) { + for (int i = (cur == 0 ? 1 : 0); i <= 9; ++i, cur /= 10) { cur = cur * 10 + i; int cnt = count(n, cur); if (k > cnt + *index) { From 4a5e09c064f4db05dac21fee4ef036e50e4ed9b0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 18:16:17 +0800 Subject: [PATCH 2954/4971] Create path-sum-iii.cpp --- C++/path-sum-iii.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/path-sum-iii.cpp diff --git a/C++/path-sum-iii.cpp b/C++/path-sum-iii.cpp new file mode 100644 index 000000000..5d20da082 --- /dev/null +++ b/C++/path-sum-iii.cpp @@ -0,0 +1,30 @@ +// Time: O(n^2) +// 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 pathSum(TreeNode* root, int sum) { + if (!root) { + return 0; + } + return pathSumHelper(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum); + } + +private: + int pathSumHelper(TreeNode* root, int prev, int sum) { + if (!root) { + return 0; + } + int curr = prev + root->val; + return (curr == sum) + pathSumHelper(root->left, curr, sum) + pathSumHelper(root->right, curr, sum); + } +}; From 3c08b00226ee1cae6f87c80791563257af8409a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 18:26:43 +0800 Subject: [PATCH 2955/4971] Create find-all-anagrams-in-a-string.cpp --- C++/find-all-anagrams-in-a-string.cpp | 28 +++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/find-all-anagrams-in-a-string.cpp diff --git a/C++/find-all-anagrams-in-a-string.cpp b/C++/find-all-anagrams-in-a-string.cpp new file mode 100644 index 000000000..2be245df7 --- /dev/null +++ b/C++/find-all-anagrams-in-a-string.cpp @@ -0,0 +1,28 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector findAnagrams(string s, string p) { + vector result; + if (p.empty() || s.empty()) { + return result; + } + + vector cnts(26); + for (const auto& c : p) { + ++cnts[c - 'a']; + } + + for (int left = 0, right = 0; right < s.length(); ++right) { + --cnts[s[right] - 'a']; + while (left <= right && cnts[s[right] - 'a'] < 0) { + ++cnts[s[left++] - 'a']; + } + if (right - left + 1 == p.length()) { + result.emplace_back(left); + } + } + return result; + } +}; From d3a08bb0a71269b2f228a06b39eaba7cf96345d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 18:32:05 +0800 Subject: [PATCH 2956/4971] Create find-all-anagrams-in-a-string.py --- Python/find-all-anagrams-in-a-string.py | 59 +++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/find-all-anagrams-in-a-string.py diff --git a/Python/find-all-anagrams-in-a-string.py b/Python/find-all-anagrams-in-a-string.py new file mode 100644 index 000000000..e80e46ee0 --- /dev/null +++ b/Python/find-all-anagrams-in-a-string.py @@ -0,0 +1,59 @@ +# Time: O(n) +# Space: O(1) + +# Given a string s and a non-empty string p, find all the start indices +# of p's anagrams in s. +# +# Strings consists of lowercase English letters only and the length of +# both strings s and p will not be larger than 20,100. +# +# The order of output does not matter. +# +# Example 1: +# +# Input: +# s: "cbaebabacd" p: "abc" +# +# Output: +# [0, 6] +# +# Explanation: +# The substring with start index = 0 is "cba", which is an anagram of "abc". +# The substring with start index = 6 is "bac", which is an anagram of "abc". +# Example 2: +# +# Input: +# s: "abab" p: "ab" +# +# Output: +# [0, 1, 2] +# +# Explanation: +# The substring with start index = 0 is "ab", which is an anagram of "ab". +# The substring with start index = 1 is "ba", which is an anagram of "ab". +# The substring with start index = 2 is "ab", which is an anagram of "ab". + +class Solution(object): + def findAnagrams(self, s, p): + """ + :type s: str + :type p: str + :rtype: List[int] + """ + result = [] + + cnts = [0] * 26 + for c in p: + cnts[ord(c) - ord('a')] += 1 + + left, right = 0, 0 + while right < len(s): + cnts[ord(s[right]) - ord('a')] -= 1 + while left <= right and cnts[ord(s[right]) - ord('a')] < 0: + cnts[ord(s[left]) - ord('a')] += 1 + left += 1 + if right - left + 1 == len(p): + result.append(left) + right += 1 + + return result From dd7c3acb1ef3421c0abac110a63292ed7f36e7be Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 18:37:43 +0800 Subject: [PATCH 2957/4971] Create path-sum-iii.py --- Python/path-sum-iii.py | 59 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/path-sum-iii.py diff --git a/Python/path-sum-iii.py b/Python/path-sum-iii.py new file mode 100644 index 000000000..a02b434f0 --- /dev/null +++ b/Python/path-sum-iii.py @@ -0,0 +1,59 @@ +# Time: O(n^2) +# Space: O(h) + +# You are given a binary tree in which each node contains an integer value. +# +# Find the number of paths that sum to a given value. +# +# The path does not need to start or end at the root or a leaf, +# but it must go downwards (traveling only from parent nodes to child nodes). +# +# The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. +# +# Example: +# +# root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 +# +# 10 +# / \ +# 5 -3 +# / \ \ +# 3 2 11 +# / \ \ +# 3 -2 1 +# +# Return 3. The paths that sum to 8 are: +# +# 1. 5 -> 3 +# 2. 5 -> 2 -> 1 +# 3. -3 -> 11 + +# 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 pathSum(self, root, sum): + """ + :type root: TreeNode + :type sum: int + :rtype: int + """ + def pathSumHelper(root, prev, sum): + if not root: + return 0 + + curr = prev + root.val; + return int(curr == sum) + \ + pathSumHelper(root.left, curr, sum) + \ + pathSumHelper(root.right, curr, sum) + + if not root: + return 0 + + return pathSumHelper(root, 0, sum) + \ + self.pathSum(root.left, sum) + \ + self.pathSum(root.right, sum) From ad450d02e67da53c7d02579b63b31a885c3df01f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 18:42:21 +0800 Subject: [PATCH 2958/4971] Create ternary-expression-parser.py --- Python/ternary-expression-parser.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python/ternary-expression-parser.py diff --git a/Python/ternary-expression-parser.py b/Python/ternary-expression-parser.py new file mode 100644 index 000000000..f8928be3e --- /dev/null +++ b/Python/ternary-expression-parser.py @@ -0,0 +1,29 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def parseTernary(self, expression): + """ + :type expression: str + :rtype: str + """ + if not expression: + return "" + + stack = [] + for c in expression[::-1]: + if stack and stack[-1] == '?': + stack.pop() # pop '?' + first = stack.pop() + stack.pop() # pop ':' + second = stack.pop() + + if c == 'T': + stack.append(first) + else: + stack.append(second) + else: + stack.append(c) + + + return str(stack[-1]) From 9d64360011cc4958f31c9b14b9709610ecc34a9b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 18:42:42 +0800 Subject: [PATCH 2959/4971] Update ternary-expression-parser.cpp --- C++/ternary-expression-parser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/ternary-expression-parser.cpp b/C++/ternary-expression-parser.cpp index 29add16dd..d71e836dc 100644 --- a/C++/ternary-expression-parser.cpp +++ b/C++/ternary-expression-parser.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(n) +// Space: O(1) class Solution { public: From d833bfa0a6dc09871a7d93c63482484173c6c010 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 18:45:23 +0800 Subject: [PATCH 2960/4971] Update k-th-smallest-in-lexicographical-order.cpp --- C++/k-th-smallest-in-lexicographical-order.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/k-th-smallest-in-lexicographical-order.cpp b/C++/k-th-smallest-in-lexicographical-order.cpp index b6b71c0a4..9216c2670 100644 --- a/C++/k-th-smallest-in-lexicographical-order.cpp +++ b/C++/k-th-smallest-in-lexicographical-order.cpp @@ -5,8 +5,8 @@ class Solution { public: int findKthNumber(int n, int k) { int result = 0; - int cur = 0, index = 0; - findKthNumberHelper(n, k, cur, &index, &result); + int index = 0; + findKthNumberHelper(n, k, 0, &index, &result); return result; } From 4bece6d5da065c3e60192a47bc2c01ff105a1ecb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 19:29:47 +0800 Subject: [PATCH 2961/4971] Create k-th-smallest-in-lexicographical-order.py --- .../k-th-smallest-in-lexicographical-order.py | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/k-th-smallest-in-lexicographical-order.py diff --git a/Python/k-th-smallest-in-lexicographical-order.py b/Python/k-th-smallest-in-lexicographical-order.py new file mode 100644 index 000000000..701945f8d --- /dev/null +++ b/Python/k-th-smallest-in-lexicographical-order.py @@ -0,0 +1,56 @@ +# Time: O(logn * logn) +# Space: O(logn) + +# Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n. +# +# Note: 1 <= k <= n <= 109. +# +# Example: +# +# Input: +# n: 13 k: 2 +# +# Output: +# 10 +# +# Explanation: +# The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], +# so the second smallest number is 10. + +class Solution(object): + def findKthNumber(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + def count(n, prefix): + result, number = 0, 1 + while prefix <= n: + result += number + prefix *= 10 + number *= 10 + result -= max(number/10 - (n - prefix/10 + 1), 0) + return result + + def findKthNumberHelper(n, k, cur, index): + if cur: + index += 1 + if index == k: + return (cur, index) + + i = int(cur == 0) + while i <= 9: + cur = cur * 10 + i + cnt = count(n, cur) + if k > cnt + index: + index += cnt + elif cur <= n: + result = findKthNumberHelper(n, k, cur, index) + if result[0]: + return result + i += 1 + cur /= 10 + return (0, index) + + return findKthNumberHelper(n, k, 0, 0)[0] From a9022059fa12eafda64a1b867a4f7fa0b158ba08 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 19:42:50 +0800 Subject: [PATCH 2962/4971] Update README.md --- README.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 64c37d016..c770bdbfe 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-425%20%2F%20425-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-429%20%2F%20429-ff69b4.svg) -Up to date (2016-10-22), there are `408` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-10-23), there are `412` 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 `425` questions. +Here is the classification of all `429` 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.) @@ -181,7 +181,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(h)_ | Medium |📖| Iterator | 385| [Mini Parser](https://leetcode.com/problems/mini-parser/)| [C++](./C++/mini-parser.cpp) [Python](./Python/mini-parser.py) | _O(n)_ | _O(h)_ | Medium ||| 394| [Decode String](https://leetcode.com/problems/decode-string/)| [C++](./C++/decode-string.cpp) [Python](./Python/decode-string.py) | _O(n)_ | _O(h)_ | Medium ||| - +439| [Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser/) | [C++](./C++/ternary-expression-parser.cpp) [Python](./Python/ternary-expression-parser.py) | _O(n)_ | _O(1)_ | Easy |📖| ## Queue # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -252,6 +252,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 388| [Longest Absolute File Path](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/longest-absolute-file-path.cpp) [Python](./Python/longest-absolute-file-path.py) | _O(n)_| _O(d)_| Medium || Stack | 409| [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./C++/longest-palindrome.cpp) [Python](./Python/longest-palindrome.py) | _O(n)_| _O(1)_| Easy ||| 424| [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) | [C++](./C++/longest-repeating-character-replacement.cpp) [Python](./Python/longest-repeating-character-replacement.py) | _O(n)_| _O(1)_| Medium ||| +438| [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [C++](./C++/find-all-anagrams-in-a-string.cpp) [Python](./Python/find-all-anagrams-in-a-string.py) | _O(n)_ | _O(1)_ | Easy || ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -361,6 +362,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || 395| [Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./C++/longest-substring-with-at-least-k-repeating-characters.cpp) [Python](./Python/longest-substring-with-at-least-k-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 404| [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./C++/sum-of-left-leaves.cpp) [Python](./Python/sum-of-left-leaves.py) | _O(n)_ | _O(h)_ | Easy || +437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n^2)_ | _O(h)_ | Easy || +440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn * logn)_ | _O(logn)_ | Hard || ## Binary Search # | Title | Solution | Time | Space | Difficulty | Tag | Note From bb166741a6412f049f29e9b16cd1017e78b404c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 19:44:45 +0800 Subject: [PATCH 2963/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c770bdbfe..255283523 100644 --- a/README.md +++ b/README.md @@ -363,7 +363,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 395| [Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./C++/longest-substring-with-at-least-k-repeating-characters.cpp) [Python](./Python/longest-substring-with-at-least-k-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 404| [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./C++/sum-of-left-leaves.cpp) [Python](./Python/sum-of-left-leaves.py) | _O(n)_ | _O(h)_ | Easy || 437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n^2)_ | _O(h)_ | Easy || -440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn * logn)_ | _O(logn)_ | Hard || ## Binary Search # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -438,6 +437,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 366| [Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/) | [C++](./C++/find-leaves-of-binary-tree.cpp) [Python](./Python/find-leaves-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium |📖|| 399| [Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./C++/evaluate-division.cpp) [Python](./Python/evaluate-division.py) | _O(q * \|V\|!)_ | _O(e)_ | Medium ||| 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || +440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn * logn)_ | _O(logn)_ | Hard || ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note From 6fa12cc2d603d8133844492563d227b154edc138 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 19:46:28 +0800 Subject: [PATCH 2964/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 255283523..5a8f46af0 100644 --- a/README.md +++ b/README.md @@ -181,7 +181,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 341| [Flatten Nested List Iterator](https://leetcode.com/problems/flatten-nested-list-iterator/)| [C++](./C++/flatten-nested-list-iterator.cpp) [Python](./Python/flatten-nested-list-iterator.py) | _O(n)_ | _O(h)_ | Medium |📖| Iterator | 385| [Mini Parser](https://leetcode.com/problems/mini-parser/)| [C++](./C++/mini-parser.cpp) [Python](./Python/mini-parser.py) | _O(n)_ | _O(h)_ | Medium ||| 394| [Decode String](https://leetcode.com/problems/decode-string/)| [C++](./C++/decode-string.cpp) [Python](./Python/decode-string.py) | _O(n)_ | _O(h)_ | Medium ||| -439| [Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser/) | [C++](./C++/ternary-expression-parser.cpp) [Python](./Python/ternary-expression-parser.py) | _O(n)_ | _O(1)_ | Easy |📖| +439| [Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser/) | [C++](./C++/ternary-expression-parser.cpp) [Python](./Python/ternary-expression-parser.py) | _O(n)_ | _O(1)_ | Medium |📖| ## Queue # | Title | Solution | Time | Space | Difficulty | Tag | Note From 1a594dd969b202a4ae1f001b2db78ff85a8b0484 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 21:47:46 +0800 Subject: [PATCH 2965/4971] Update k-th-smallest-in-lexicographical-order.cpp --- ...k-th-smallest-in-lexicographical-order.cpp | 48 ++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/C++/k-th-smallest-in-lexicographical-order.cpp b/C++/k-th-smallest-in-lexicographical-order.cpp index 9216c2670..e67dd9446 100644 --- a/C++/k-th-smallest-in-lexicographical-order.cpp +++ b/C++/k-th-smallest-in-lexicographical-order.cpp @@ -1,7 +1,53 @@ -// Time: O(logn * logn) +// Time: O(logn) // Space: O(logn) class Solution { +public: + int findKthNumber(int n, int k) { + int result = 0; + + vector cnts(10); + for (int i = 1; i < 10; i++) { + cnts[i] = cnts[i - 1] * 10 + 1; + } + + vector nums; + for (int i = n; i > 0; i /= 10) { + nums.push_back(i % 10); + } + int total = n; + int target = 0; + for (int i = nums.size() - 1; i >= 0 && k; --i) { + target = target * 10 + nums[i]; + const auto start = i == nums.size() - 1 ? 1 : 0; + for (int j = start; j < 10; ++j) { + int candidate = result * 10 + j; + int num; + if (candidate < target) { + num = cnts[i + 1]; + } else if (candidate > target) { + num = cnts[i]; + } else { + num = total - cnts[i + 1] * (j - start) - cnts[i] * (9 - j); + } + if (k > num) { + k -= num; + } else { + result = candidate; + --k; + total = num - 1; + break; + } + } + } + return result; + } +}; + + +// Time: O(logn * logn) +// Space: O(logn) +class Solution2 { public: int findKthNumber(int n, int k) { int result = 0; From 9cdc88fd430a2fc9d12297907d22db5fa7da98a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 21:56:03 +0800 Subject: [PATCH 2966/4971] Update k-th-smallest-in-lexicographical-order.cpp --- C++/k-th-smallest-in-lexicographical-order.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/k-th-smallest-in-lexicographical-order.cpp b/C++/k-th-smallest-in-lexicographical-order.cpp index e67dd9446..e6b7e80c0 100644 --- a/C++/k-th-smallest-in-lexicographical-order.cpp +++ b/C++/k-th-smallest-in-lexicographical-order.cpp @@ -7,7 +7,7 @@ class Solution { int result = 0; vector cnts(10); - for (int i = 1; i < 10; i++) { + for (int i = 1; i <= 9; ++i) { cnts[i] = cnts[i - 1] * 10 + 1; } @@ -20,7 +20,7 @@ class Solution { for (int i = nums.size() - 1; i >= 0 && k; --i) { target = target * 10 + nums[i]; const auto start = i == nums.size() - 1 ? 1 : 0; - for (int j = start; j < 10; ++j) { + for (int j = start; j <= 9; ++j) { int candidate = result * 10 + j; int num; if (candidate < target) { From fd41f31faad02c071894f3731cbfad50d8db7673 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 21:56:56 +0800 Subject: [PATCH 2967/4971] Update k-th-smallest-in-lexicographical-order.py --- .../k-th-smallest-in-lexicographical-order.py | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/Python/k-th-smallest-in-lexicographical-order.py b/Python/k-th-smallest-in-lexicographical-order.py index 701945f8d..8bf04e9a2 100644 --- a/Python/k-th-smallest-in-lexicographical-order.py +++ b/Python/k-th-smallest-in-lexicographical-order.py @@ -1,4 +1,4 @@ -# Time: O(logn * logn) +# Time: O(logn) # Space: O(logn) # Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n. @@ -18,6 +18,49 @@ # so the second smallest number is 10. class Solution(object): + def findKthNumber(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + result = 0 + + cnts = [0] * 10 + for i in xrange(1, 10): + cnts[i] = cnts[i - 1] * 10 + 1 + nums = [] + i = n + while i: + nums.append(i % 10) + i /= 10 + total, target = n, 0 + i = len(nums) - 1 + while i >= 0 and k > 0: + target = target*10 + nums[i] + start = int(i == len(nums)-1) + for j in xrange(start, 10): + candidate = result*10 + j + if candidate < target: + num = cnts[i+1] + elif candidate > target: + num = cnts[i] + else: + num = total - cnts[i + 1]*(j-start) - cnts[i]*(9-j) + if k > num: + k -= num + else: + result = candidate + k -= 1 + total = num-1 + break + i -= 1 + return result + + +# Time: O(logn * logn) +# Space: O(logn) +class Solution2(object): def findKthNumber(self, n, k): """ :type n: int From 1ef45e5f91fad2270d1aa3965d834787a7d8b9d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 21:57:32 +0800 Subject: [PATCH 2968/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5a8f46af0..b6a887171 100644 --- a/README.md +++ b/README.md @@ -437,7 +437,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 366| [Find Leaves of Binary Tree](https://leetcode.com/problems/find-leaves-of-binary-tree/) | [C++](./C++/find-leaves-of-binary-tree.cpp) [Python](./Python/find-leaves-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium |📖|| 399| [Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./C++/evaluate-division.cpp) [Python](./Python/evaluate-division.py) | _O(q * \|V\|!)_ | _O(e)_ | Medium ||| 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || -440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn * logn)_ | _O(logn)_ | Hard || +440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn)_ | _O(logn)_ | Hard || ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note From f729cdfed1bd9759b7e347e6a13d29d3ab5beed8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 21:58:33 +0800 Subject: [PATCH 2969/4971] Update k-th-smallest-in-lexicographical-order.py --- Python/k-th-smallest-in-lexicographical-order.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/k-th-smallest-in-lexicographical-order.py b/Python/k-th-smallest-in-lexicographical-order.py index 8bf04e9a2..4a969c6d5 100644 --- a/Python/k-th-smallest-in-lexicographical-order.py +++ b/Python/k-th-smallest-in-lexicographical-order.py @@ -29,11 +29,13 @@ def findKthNumber(self, n, k): cnts = [0] * 10 for i in xrange(1, 10): cnts[i] = cnts[i - 1] * 10 + 1 + nums = [] i = n while i: nums.append(i % 10) i /= 10 + total, target = n, 0 i = len(nums) - 1 while i >= 0 and k > 0: @@ -55,6 +57,7 @@ def findKthNumber(self, n, k): total = num-1 break i -= 1 + return result From fdfd31874147e96da2a6aaed27fb8c28cbea283f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 22:39:49 +0800 Subject: [PATCH 2970/4971] Update k-th-smallest-in-lexicographical-order.cpp --- C++/k-th-smallest-in-lexicographical-order.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/k-th-smallest-in-lexicographical-order.cpp b/C++/k-th-smallest-in-lexicographical-order.cpp index e6b7e80c0..4e9783a99 100644 --- a/C++/k-th-smallest-in-lexicographical-order.cpp +++ b/C++/k-th-smallest-in-lexicographical-order.cpp @@ -13,7 +13,7 @@ class Solution { vector nums; for (int i = n; i > 0; i /= 10) { - nums.push_back(i % 10); + nums.emplace_back(i % 10); } int total = n; int target = 0; From 46320d5c4ae80afd5a4a0dcece86ffe0794aa198 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Oct 2016 22:40:53 +0800 Subject: [PATCH 2971/4971] Update k-th-smallest-in-lexicographical-order.cpp --- C++/k-th-smallest-in-lexicographical-order.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/k-th-smallest-in-lexicographical-order.cpp b/C++/k-th-smallest-in-lexicographical-order.cpp index 4e9783a99..48f9fbfb9 100644 --- a/C++/k-th-smallest-in-lexicographical-order.cpp +++ b/C++/k-th-smallest-in-lexicographical-order.cpp @@ -21,7 +21,7 @@ class Solution { target = target * 10 + nums[i]; const auto start = i == nums.size() - 1 ? 1 : 0; for (int j = start; j <= 9; ++j) { - int candidate = result * 10 + j; + const auto candidate = result * 10 + j; int num; if (candidate < target) { num = cnts[i + 1]; @@ -44,7 +44,6 @@ class Solution { } }; - // Time: O(logn * logn) // Space: O(logn) class Solution2 { From b3de78c66430798237d7b146871ef5bef5377fb3 Mon Sep 17 00:00:00 2001 From: meixu song Date: Tue, 25 Oct 2016 13:08:52 +0800 Subject: [PATCH 2972/4971] Update coin-change.cpp change for overflow cases --- C++/coin-change.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/coin-change.cpp b/C++/coin-change.cpp index 87f16941d..ff87539f0 100644 --- a/C++/coin-change.cpp +++ b/C++/coin-change.cpp @@ -10,7 +10,7 @@ class Solution { for (int i = 0; i <= amount; ++i) { if (amounts[i] != numeric_limits::max()) { for (const auto& coin : coins) { - if (i + coin <= amount) { + if (coin <= numeric_limits::max() - i && i + coin <= amount) { amounts[i + coin] = min(amounts[i + coin], amounts[i] + 1); } } From e7951ff3e5e9221385ec7b4bdebad9fdc4edc59b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Oct 2016 23:05:14 +0800 Subject: [PATCH 2973/4971] Create find-all-duplicates-in-an-array.cpp --- C++/find-all-duplicates-in-an-array.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/find-all-duplicates-in-an-array.cpp diff --git a/C++/find-all-duplicates-in-an-array.cpp b/C++/find-all-duplicates-in-an-array.cpp new file mode 100644 index 000000000..f28e7219d --- /dev/null +++ b/C++/find-all-duplicates-in-an-array.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector findDuplicates(vector& nums) { + vector result; + int i = 0; + while (i < nums.size()) { + if (nums[i] != nums[nums[i] - 1]) { + swap(nums[i], nums[nums[i] - 1]); + } else { + ++i; + } + } + for (i = 0; i < nums.size(); ++i) { + if (nums[i] != i + 1) { + result.emplace_back(nums[i]); + } + } + return result; + } +}; From 81a7ef6192fc239b477617b841eff5562519b57a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Oct 2016 23:14:40 +0800 Subject: [PATCH 2974/4971] Create find-all-duplicates-in-an-array.py --- Python/find-all-duplicates-in-an-array.py | 35 +++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/find-all-duplicates-in-an-array.py diff --git a/Python/find-all-duplicates-in-an-array.py b/Python/find-all-duplicates-in-an-array.py new file mode 100644 index 000000000..79c8b174c --- /dev/null +++ b/Python/find-all-duplicates-in-an-array.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(1) + +# Given an array of integers, 1 <= a[i] <= n (n = size of array), +# some elements appear twice and others appear once. +# Find all the elements that appear twice in this array. +# Could you do it without extra space and in O(n) runtime? +# +# Example: +# Input +# +# [4,3,2,7,8,2,3,1] +# +# Output +# +# [2,3] + +class Solution(object): + def findDuplicates(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + result = [] + i = 0 + while i < len(nums): + if nums[i] != nums[nums[i]-1]: + nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] + else: + i += 1 + + for i in xrange(len(nums)): + if i != nums[i]-1: + result.append(nums[i]) + return result From 1acac9e85d740719c15dc94befab910da8d8ee5a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Oct 2016 23:19:37 +0800 Subject: [PATCH 2975/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b6a887171..8bbaa2557 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 414| [Third Maximum Number](https://leetcode.com/problems/third-maximum-number/) | [C++](./C++/third-maximum-number.cpp) [Python](./Python/third-maximum-number.py) | _O(n)_ | _O(1)_ | Easy ||| 419| [Battleships in a Board](https://leetcode.com/problems/battleships-in-a-board/) | [C++](./C++/battleships-in-a-board.cpp) [Python](./Python/battleships-in-a-board.py) | _O(m * n)_ | _O(1)_ | Medium ||| 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| +442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| ## String # | Title | Solution | Time | Space | Difficulty | Tag | Note From 83a060ddae52337482f2af2cc140fe7ebaa96602 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 25 Oct 2016 23:20:13 +0800 Subject: [PATCH 2976/4971] Update find-all-duplicates-in-an-array.cpp --- C++/find-all-duplicates-in-an-array.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/find-all-duplicates-in-an-array.cpp b/C++/find-all-duplicates-in-an-array.cpp index f28e7219d..5cc2e8b93 100644 --- a/C++/find-all-duplicates-in-an-array.cpp +++ b/C++/find-all-duplicates-in-an-array.cpp @@ -14,7 +14,7 @@ class Solution { } } for (i = 0; i < nums.size(); ++i) { - if (nums[i] != i + 1) { + if (i != nums[i] - 1) { result.emplace_back(nums[i]); } } From cc40d1716343b04c6ef081cee3f5ce0b7fd0c53b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Oct 2016 22:25:53 +0800 Subject: [PATCH 2977/4971] Create non-overlapping-intervals.cpp --- C++/non-overlapping-intervals.cpp | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/non-overlapping-intervals.cpp diff --git a/C++/non-overlapping-intervals.cpp b/C++/non-overlapping-intervals.cpp new file mode 100644 index 000000000..54728e436 --- /dev/null +++ b/C++/non-overlapping-intervals.cpp @@ -0,0 +1,32 @@ +// Time: O(nlogn) +// Space: O(1) + +/** + * 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 eraseOverlapIntervals(vector& intervals) { + sort(intervals.begin(), intervals.end(), + [](const Interval& a, const Interval& b) { return a.start < b.start; }); + + int result = 0, prev = 0; + for (int i = 1; i < intervals.size(); ++i) { + if (intervals[i].start < intervals[prev].end) { + if (intervals[i].end < intervals[prev].end) { + prev = i; + } + ++result; + } else { + prev = i; + } + } + return result; + } +}; From 98da66f6f966d563d31fe631919e43bf1523283f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Oct 2016 22:33:32 +0800 Subject: [PATCH 2978/4971] Create non-overlapping-intervals.py --- Python/non-overlapping-intervals.py | 50 +++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/non-overlapping-intervals.py diff --git a/Python/non-overlapping-intervals.py b/Python/non-overlapping-intervals.py new file mode 100644 index 000000000..16a204dd6 --- /dev/null +++ b/Python/non-overlapping-intervals.py @@ -0,0 +1,50 @@ +# Time: O(nlogn) +# Space: O(1) + +# Given a collection of intervals, find the minimum number of intervals +# you need to remove to make the rest of the intervals non-overlapping. +# +# Note: +# You may assume the interval's end point is always bigger than its start point. +# Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other. +# Example 1: +# Input: [ [1,2], [2,3], [3,4], [1,3] ] +# +# Output: 1 +# +# Explanation: [1,3] can be removed and the rest of intervals are non-overlapping. +# Example 2: +# Input: [ [1,2], [1,2], [1,2] ] +# +# Output: 2 +# +# Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping. +# Example 3: +# Input: [ [1,2], [2,3] ] +# +# Output: 0 +# +# Explanation: You don't need to remove any of the intervals since they're already non-overlapping. + +# Definition for an interval. +# class Interval(object): +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class Solution(object): + def eraseOverlapIntervals(self, intervals): + """ + :type intervals: List[Interval] + :rtype: int + """ + intervals.sort(key=lambda interval: interval.start) + result, prev = 0, 0 + for i in xrange(1, len(intervals)): + if intervals[i].start < intervals[prev].end: + if intervals[i].end < intervals[prev].end: + prev = i + result += 1 + else: + prev = i + return result From 7c521fe8fc45b3b7dbbac1370608a040de2d441e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Oct 2016 22:48:48 +0800 Subject: [PATCH 2979/4971] Create find-right-interval.py --- Python/find-right-interval.py | 55 +++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/find-right-interval.py diff --git a/Python/find-right-interval.py b/Python/find-right-interval.py new file mode 100644 index 000000000..8c1a9a9a2 --- /dev/null +++ b/Python/find-right-interval.py @@ -0,0 +1,55 @@ +# Time: O(nlogn) +# Space: O(n) + +# Given a set of intervals, for each of the interval i, +# check if there exists an interval j whose start point is bigger than or +# equal to the end point of the interval i, which can be called that j is on the "right" of i. +# +# For any interval i, you need to store the minimum interval j's index, +# which means that the interval j has the minimum start point to +# build the "right" relationship for interval i. If the interval j doesn't exist, +# store -1 for the interval i. Finally, you need output the stored value of each interval as an array. +# +# Note: +# You may assume the interval's end point is always bigger than its start point. +# You may assume none of these intervals have the same start point. +# Example 1: +# Input: [ [1,2] ] +# +# Output: [-1] +# +# Explanation: There is only one interval in the collection, so it outputs -1. +# Example 2: +# Input: [ [3,4], [2,3], [1,2] ] +# +# Output: [-1, 0, 1] +# +# Explanation: There is no satisfied "right" interval for [3,4]. +# For [2,3], the interval [3,4] has minimum-"right" start point; +# For [1,2], the interval [2,3] has minimum-"right" start point. +# Example 3: +# Input: [ [1,4], [2,3], [3,4] ] +# +# Output: [-1, 2, -1] +# +# Explanation: There is no satisfied "right" interval for [1,4] and [3,4]. +# For [2,3], the interval [3,4] has minimum-"right" start point. +# +# Definition for an interval. +# class Interval(object): +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class Solution(object): + def findRightInterval(self, intervals): + """ + :type intervals: List[Interval] + :rtype: List[int] + """ + sorted_intervals = sorted((interval.start, i) for i, interval in enumerate(intervals)) + result = [] + for interval in intervals: + idx = bisect.bisect_left(sorted_intervals, (interval.end,)) + result.append(sorted_intervals[idx][1] if idx < len(sorted_intervals) else -1) + return result From b335c5316f3e83a68132c741eef372d9d9082cdb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Oct 2016 22:52:49 +0800 Subject: [PATCH 2980/4971] Create find-right-interval.cpp --- C++/find-right-interval.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/find-right-interval.cpp diff --git a/C++/find-right-interval.cpp b/C++/find-right-interval.cpp new file mode 100644 index 000000000..9dfd70af0 --- /dev/null +++ b/C++/find-right-interval.cpp @@ -0,0 +1,31 @@ +// 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: + vector findRightInterval(vector& intervals) { + map lookup; + vector result; + for (int i = 0; i < intervals.size(); ++i) { + lookup[intervals[i].start] = i; + } + for (const auto& interval : intervals) { + const auto it = lookup.lower_bound(interval.end); + if (it == lookup.end()) { + result.emplace_back(-1); + } else { + result.emplace_back(it->second); + } + } + return result; + } +}; From a2d4032044d436a4719c6572b9aea96d038b88cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Oct 2016 23:13:50 +0800 Subject: [PATCH 2981/4971] Create arranging-coins.cpp --- C++/arranging-coins.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/arranging-coins.cpp diff --git a/C++/arranging-coins.cpp b/C++/arranging-coins.cpp new file mode 100644 index 000000000..7a7d2754d --- /dev/null +++ b/C++/arranging-coins.cpp @@ -0,0 +1,18 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int arrangeCoins(int n) { + long long left = 1, right = n; + while (left <= right) { + const auto mid = left + (right - left) / 2; + if (2L * n < mid * (mid + 1)) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left - 1; + } +}; From 88b1c9782317f0578e59cdbdfe5c051414bc86c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Oct 2016 23:16:31 +0800 Subject: [PATCH 2982/4971] Create arranging-coins.py --- Python/arranging-coins.py | 46 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/arranging-coins.py diff --git a/Python/arranging-coins.py b/Python/arranging-coins.py new file mode 100644 index 000000000..a05fbb520 --- /dev/null +++ b/Python/arranging-coins.py @@ -0,0 +1,46 @@ +# Time: O(logn) +# Space: O(1) + +# You have a total of n coins that you want to form in a staircase shape, +# where every k-th row must have exactly k coins. +# +# Given n, find the total number of full staircase rows that can be formed. +# +# n is a non-negative integer and fits within the range of a 32-bit signed integer. +# +# Example 1: +# +# n = 5 +# +# The coins can form the following rows: +# ¤ +# ¤ ¤ +# ¤ ¤ +# +# Because the 3rd row is incomplete, we return 2. +# Example 2: +# +# n = 8 +# +# The coins can form the following rows: +# ¤ +# ¤ ¤ +# ¤ ¤ ¤ +# ¤ ¤ +# +# Because the 4th row is incomplete, we return 3. + +class Solution(object): + def arrangeCoins(self, n): + """ + :type n: int + :rtype: int + """ + left, right = 1, n + while left <= right: + mid = left + (right - left) / 2 + if 2 * n < mid * (mid+1): + right = mid - 1 + else: + left = mid + 1 + return left - 1 From d3e0fad1a9d2d52f888859417f6c8e112165dafb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Oct 2016 23:23:44 +0800 Subject: [PATCH 2983/4971] Update arranging-coins.py --- Python/arranging-coins.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Python/arranging-coins.py b/Python/arranging-coins.py index a05fbb520..f4e3de1df 100644 --- a/Python/arranging-coins.py +++ b/Python/arranging-coins.py @@ -31,6 +31,17 @@ # Because the 4th row is incomplete, we return 3. class Solution(object): + def arrangeCoins(self, n): + """ + :type n: int + :rtype: int + """ + return int((math.sqrt(8*n+1)-1) / 2) # sqrt is O(logn) time. + + +# Time: O(logn) +# Space: O(1) +class Solution2(object): def arrangeCoins(self, n): """ :type n: int From 597d7600fdcd126d7e639beded8d614f3f6bf370 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Oct 2016 23:26:29 +0800 Subject: [PATCH 2984/4971] Update arranging-coins.cpp --- C++/arranging-coins.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/C++/arranging-coins.cpp b/C++/arranging-coins.cpp index 7a7d2754d..f25a3e364 100644 --- a/C++/arranging-coins.cpp +++ b/C++/arranging-coins.cpp @@ -2,6 +2,15 @@ // Space: O(1) class Solution { +public: + int arrangeCoins(int n) { + return static_cast((sqrt(8.0 * n + 1) - 1) / 2); + } +}; + +// Time: O(logn) +// Space: O(1) +class Solution2 { public: int arrangeCoins(int n) { long long left = 1, right = n; From deb2fd7561403940c7aa844fc7cd44a6036930a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Nov 2016 00:03:22 +0800 Subject: [PATCH 2985/4971] Create sequence-reconstruction.py --- Python/sequence-reconstruction.py | 49 +++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/sequence-reconstruction.py diff --git a/Python/sequence-reconstruction.py b/Python/sequence-reconstruction.py new file mode 100644 index 000000000..ba78bc91c --- /dev/null +++ b/Python/sequence-reconstruction.py @@ -0,0 +1,49 @@ +# Time: O(|V| + |E|) +# Space: O(|E|) + +class Solution(object): + def sequenceReconstruction(self, org, seqs): + """ + :type org: List[int] + :type seqs: List[List[int]] + :rtype: bool + """ + graph = collections.defaultdict(set) + indegree = collections.defaultdict(int) + integer_set = set() + for seq in seqs: + for i in seq: + integer_set.add(i) + if len(seq) == 1: + if seq[0] not in indegree: + indegree[seq[0]] = 0 + continue + for i in xrange(len(seq)-1): + if seq[i] not in indegree: + indegree[seq[i]] = 0 + if seq[i+1] not in graph[seq[i]]: + graph[seq[i]].add(seq[i+1]) + indegree[seq[i+1]] += 1 + + cnt_of_zero_indegree = 0 + res, q = [], [] + for i in indegree: + if indegree[i] == 0: + cnt_of_zero_indegree += 1 + if cnt_of_zero_indegree > 1: + return False + q.append(i) + + while q: + i = q.pop() + res.append(i) + cnt_of_zero_indegree = 0 + for j in graph[i]: + indegree[j] -= 1 + if indegree[j] == 0: + cnt_of_zero_indegree += 1 + if cnt_of_zero_indegree > 1: + return False + q.append(j) + + return res == org and set(org) == integer_set From 0c086a7aa1d1ce13c96c56e1722a6fa49a0d5b6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Nov 2016 23:33:31 +0800 Subject: [PATCH 2986/4971] Update sequence-reconstruction.py --- Python/sequence-reconstruction.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/sequence-reconstruction.py b/Python/sequence-reconstruction.py index ba78bc91c..dfee00077 100644 --- a/Python/sequence-reconstruction.py +++ b/Python/sequence-reconstruction.py @@ -26,7 +26,8 @@ def sequenceReconstruction(self, org, seqs): indegree[seq[i+1]] += 1 cnt_of_zero_indegree = 0 - res, q = [], [] + res = [] + q = [] for i in indegree: if indegree[i] == 0: cnt_of_zero_indegree += 1 @@ -45,5 +46,5 @@ def sequenceReconstruction(self, org, seqs): if cnt_of_zero_indegree > 1: return False q.append(j) - - return res == org and set(org) == integer_set + return res == org and len(org) == len(integer_set) + From 728153d853fee92cc1b677d32557552d232c7f8b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 00:07:50 +0800 Subject: [PATCH 2987/4971] Create sequence-reconstruction.cpp --- C++/sequence-reconstruction.cpp | 36 +++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C++/sequence-reconstruction.cpp diff --git a/C++/sequence-reconstruction.cpp b/C++/sequence-reconstruction.cpp new file mode 100644 index 000000000..2778589d1 --- /dev/null +++ b/C++/sequence-reconstruction.cpp @@ -0,0 +1,36 @@ +// Time: O(n * s), n is the size of org, s is the size of seqs +// Space: O(n) + +class Solution { +public: + bool sequenceReconstruction(vector& org, vector>& seqs) { + if (seqs.empty()) { + return false; + } + vector pos(org.size() + 1); + for (int i = 0; i < org.size(); ++i) { + pos[org[i]] = i; + } + + vector is_matched(org.size() + 1); + int cnt_to_match = org.size() - 1; + for (const auto& seq : seqs) { + for (int i = 0; i < seq.size(); ++i) { + if (seq[i] <= 0 || seq[i] > org.size()) { + return false; + } + if (i == 0) { + continue; + } + if (pos[seq[i - 1]] >= pos[seq[i]]) { + return false; + } + if (is_matched[seq[i - 1]] == false && pos[seq[i - 1]] + 1 == pos[seq[i]]) { + is_matched[seq[i - 1]] = true; + --cnt_to_match; + } + } + } + return cnt_to_match == 0; + } +}; From 616e690f4a2646deed14470ac736b025173be26a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 00:13:23 +0800 Subject: [PATCH 2988/4971] Update sequence-reconstruction.py --- Python/sequence-reconstruction.py | 36 +++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/Python/sequence-reconstruction.py b/Python/sequence-reconstruction.py index dfee00077..8b492df2a 100644 --- a/Python/sequence-reconstruction.py +++ b/Python/sequence-reconstruction.py @@ -1,7 +1,39 @@ -# Time: O(|V| + |E|) -# Space: O(|E|) +# Time: O(n * s), n is the size of org, s is the size of seqs +# Space: O(n) class Solution(object): + def sequenceReconstruction(self, org, seqs): + """ + :type org: List[int] + :type seqs: List[List[int]] + :rtype: bool + """ + if not seqs: + return False + pos = [0] * (len(org) + 1) + for i in xrange(len(org)): + pos[org[i]] = i + + is_matched = [False] * (len(org) + 1) + cnt_to_match = len(org) - 1 + for seq in seqs: + for i in xrange(len(seq)): + if not 0 < seq[i] <= len(org): + return False + if i == 0: + continue + if pos[seq[i-1]] >= pos[seq[i]]: + return False + if is_matched[seq[i-1]] == False and pos[seq[i-1]] + 1 == pos[seq[i]]: + is_matched[seq[i-1]] = True + cnt_to_match -= 1 + + return cnt_to_match == 0 + + +# Time: O(|V| + |E|) +# Space: O(|E|) +class Solution2(object): def sequenceReconstruction(self, org, seqs): """ :type org: List[int] From e698759553fc1e74ecb8243e0a5b0b17f14f671b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 00:39:30 +0800 Subject: [PATCH 2989/4971] Create add-two-numbers-ii.cpp --- C++/add-two-numbers-ii.cpp | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 C++/add-two-numbers-ii.cpp diff --git a/C++/add-two-numbers-ii.cpp b/C++/add-two-numbers-ii.cpp new file mode 100644 index 000000000..a1f4707d9 --- /dev/null +++ b/C++/add-two-numbers-ii.cpp @@ -0,0 +1,51 @@ +// Time: O(m + n) +// Space: O(m + n) + +/** + * 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) { + stack stk1, stk2; + while (l1) { + stk1.emplace(l1->val); + l1 = l1->next; + } + while (l2) { + stk2.emplace(l2->val); + l2 = l2->next; + } + + ListNode *prev = nullptr, *head = nullptr; + int sum = 0; + while (!stk1.empty() || !stk2.empty()) { + sum /= 10; + if (!stk1.empty()) { + sum += stk1.top(); + stk1.pop(); + } + + if (!stk2.empty()) { + sum += stk2.top(); + stk2.pop(); + } + + head = new ListNode(sum % 10); + head->next = prev; + prev = head; + } + + if (sum >= 10) { + head = new ListNode(sum / 10); + head->next = prev; + } + + return head; + } +}; From ebb710c1a7ebb0d5700800da189a1093390a2801 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 00:44:46 +0800 Subject: [PATCH 2990/4971] Create add-two-numbers-ii.py --- Python/add-two-numbers-ii.py | 56 ++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/add-two-numbers-ii.py diff --git a/Python/add-two-numbers-ii.py b/Python/add-two-numbers-ii.py new file mode 100644 index 000000000..cde8fc554 --- /dev/null +++ b/Python/add-two-numbers-ii.py @@ -0,0 +1,56 @@ +# Time: O(m + n) +# Space: O(m + n) + +# You are given two linked lists representing two non-negative numbers. +# The most significant digit comes first and each of their nodes contain a single digit. +# Add the two numbers and return it as a linked list. +# +# You may assume the two numbers do not contain any leading zero, except the number 0 itself. +# +# Follow up: +# What if you cannot modify the input lists? In other words, reversing the lists is not allowed. +# +# Example: +# +# Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) +# Output: 7 -> 8 -> 0 -> 7 + +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def addTwoNumbers(self, l1, l2): + """ + :type l1: ListNode + :type l2: ListNode + :rtype: ListNode + """ + stk1, stk2 = [], [] + while l1: + stk1.append(l1.val) + l1 = l1.next + while l2: + stk2.append(l2.val) + l2 = l2.next + + prev, head = None, None + sum = 0 + while stk1 or stk2: + sum /= 10 + if stk1: + sum += stk1.pop() + if stk2: + sum += stk2.pop() + + head = ListNode(sum % 10) + head.next = prev + prev = head + + if sum >= 10: + head = ListNode(sum / 10) + head.next = prev + + return head From 2a8f063e3de814a7e3c604ae01839937a2e78c1e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 00:54:11 +0800 Subject: [PATCH 2991/4971] Create find-all-numbers-disappeared-in-an-array.cpp --- ...nd-all-numbers-disappeared-in-an-array.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/find-all-numbers-disappeared-in-an-array.cpp diff --git a/C++/find-all-numbers-disappeared-in-an-array.cpp b/C++/find-all-numbers-disappeared-in-an-array.cpp new file mode 100644 index 000000000..920f3420f --- /dev/null +++ b/C++/find-all-numbers-disappeared-in-an-array.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector findDisappearedNumbers(vector& nums) { + for (int i = 0; i < nums.size(); ++i) { + if (nums[abs(nums[i]) - 1] > 0) { + nums[abs(nums[i]) - 1] *= -1; + } + } + + vector result; + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] > 0) { + result.emplace_back(i + 1); + } else { + nums[i] *= -1; + } + } + return result; + } +}; From 43cc70370b24304989e947641563831752c3406e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 00:57:29 +0800 Subject: [PATCH 2992/4971] Create find-all-numbers-disappeared-in-an-array. --- .../find-all-numbers-disappeared-in-an-array. | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/find-all-numbers-disappeared-in-an-array. diff --git a/Python/find-all-numbers-disappeared-in-an-array. b/Python/find-all-numbers-disappeared-in-an-array. new file mode 100644 index 000000000..9a56a4370 --- /dev/null +++ b/Python/find-all-numbers-disappeared-in-an-array. @@ -0,0 +1,36 @@ +# Time: O(n) +# Space: O(1) + +# Given an array of integers where 1 <= a[i] <= n (n = size of array), +# some elements appear twice and others appear once. +# +# Find all the elements of [1, n] inclusive that do not appear in this array. +# +# Could you do it without extra space and in O(n) runtime? +# You may assume the returned list does not count as extra space. +# +# Example: +# +# Input: +# [4,3,2,7,8,2,3,1] +# +# Output: +# [5,6] + +class Solution(object): + def findDisappearedNumbers(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + for i in xrange(len(nums)): + if nums[abs(nums[i]) - 1] > 0: + nums[abs(nums[i]) - 1] *= -1 + + result = [] + for i in xrange(len(nums)): + if nums[i] > 0: + result.append(i+1) + else: + nums[i] *= -1 + return result From ca25fd2908e8489101d163655032cf9add7658be Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 01:07:51 +0800 Subject: [PATCH 2993/4971] Create serialize-and-deserialize-bst.py --- Python/serialize-and-deserialize-bst.py | 72 +++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Python/serialize-and-deserialize-bst.py diff --git a/Python/serialize-and-deserialize-bst.py b/Python/serialize-and-deserialize-bst.py new file mode 100644 index 000000000..48dc7cdbc --- /dev/null +++ b/Python/serialize-and-deserialize-bst.py @@ -0,0 +1,72 @@ +# Time: 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 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 search tree. +# There is no restriction on how your serialization/deserialization algorithm should work. +# You just need to ensure that a binary search tree can be serialized to a string and +# this string can be deserialized to the original tree structure. +# +# The encoded string should be as compact as possible. +# +# 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 preOrder(node, vals): + if node: + vals.append(node.val) + preOrder(node.left, vals) + preOrder(node.right, vals) + + vals = [] + preOrder(root, vals) + + return ' '.join(map(str, vals)) + + + def deserialize(self, data): + """Decodes your encoded data to tree. + + :type data: str + :rtype: TreeNode + """ + def build(minVal, maxVal, vals): + if not vals: + return None + + if minVal < vals[0] < maxVal: + val = vals.popleft() + node = TreeNode(val) + node.left = build(minVal, val, vals) + node.right = build(val, maxVal, vals) + return node + else: + return None + + vals = collections.deque([int(val) for val in data.split()]) + + return build(float('-inf'), float('inf'), vals) + + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.deserialize(codec.serialize(root)) From 391eaaf355663c9d349b8bad010a7adf146ebf80 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 01:24:48 +0800 Subject: [PATCH 2994/4971] Create sort-characters-by-frequency.py --- Python/sort-characters-by-frequency.py | 56 ++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/sort-characters-by-frequency.py diff --git a/Python/sort-characters-by-frequency.py b/Python/sort-characters-by-frequency.py new file mode 100644 index 000000000..6dea9bc94 --- /dev/null +++ b/Python/sort-characters-by-frequency.py @@ -0,0 +1,56 @@ +# Time: O(n) +# Space: O(n) + +# Input: +# "tree" +# +# Output: +# "eert" +# +# Explanation: +# 'e' appears twice while 'r' and 't' both appear once. +# So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. +# Example 2: +# +# Input: +# "cccaaa" +# +# Output: +# "cccaaa" +# +# Explanation: +# Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. +# Note that "cacaca" is incorrect, as the same characters must be together. +# Example 3: +# +# Input: +# "Aabb" +# +# Output: +# "bbAa" +# +# Explanation: +# "bbaA" is also a valid answer, but "Aabb" is incorrect. +# Note that 'A' and 'a' are treated as two different characters. + +class Solution(object): + def frequencySort(self, s): + """ + :type s: str + :rtype: str + """ + freq = collections.defaultdict(int) + for c in s: + freq[c] += 1 + + counts = [""] * (len(s)+1) + for c in freq: + count = freq[c] + counts[count] += c + + result = "" + for count in reversed(xrange(len(counts)-1)): + for c in counts[count]: + result += c * count + + return result From 0381a9b56593e2b0b843cde4dbdf138dc7e493d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 01:35:41 +0800 Subject: [PATCH 2995/4971] Create delete-node-in-a-bst.cpp --- C++/delete-node-in-a-bst.cpp | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 C++/delete-node-in-a-bst.cpp diff --git a/C++/delete-node-in-a-bst.cpp b/C++/delete-node-in-a-bst.cpp new file mode 100644 index 000000000..237fb89b7 --- /dev/null +++ b/C++/delete-node-in-a-bst.cpp @@ -0,0 +1,43 @@ +// 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* deleteNode(TreeNode* root, int key) { + if (!root) { + return nullptr; + } + if (root->val > key) { + root->left = deleteNode(root->left, key); + } else if (root->val < key) { + root->right = deleteNode(root->right, key); + } else { + if (!root->left) { + auto right = root->right; + delete root; + return right; + } else if (!root->right) { + auto left = root->left; + delete root; + return left; + } else { + auto successor = root->right; + while (successor->left) { + successor = successor->left; + } + root->val = successor->val; + root->right = deleteNode(root->right, successor->val); + } + } + return root; + } +}; From f1e5cc690771f47f78ff8cccf40b402505f05925 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 01:43:39 +0800 Subject: [PATCH 2996/4971] Update sort-characters-by-frequency.py --- Python/sort-characters-by-frequency.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/sort-characters-by-frequency.py b/Python/sort-characters-by-frequency.py index 6dea9bc94..72712cf14 100644 --- a/Python/sort-characters-by-frequency.py +++ b/Python/sort-characters-by-frequency.py @@ -45,8 +45,7 @@ def frequencySort(self, s): counts = [""] * (len(s)+1) for c in freq: - count = freq[c] - counts[count] += c + counts[freq[c]] += c result = "" for count in reversed(xrange(len(counts)-1)): From 51999c2cd097d8a3a27b60d8f1791434a7827075 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 01:46:24 +0800 Subject: [PATCH 2997/4971] Create sort-characters-by-frequency.cpp --- C++/sort-characters-by-frequency.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/sort-characters-by-frequency.cpp diff --git a/C++/sort-characters-by-frequency.cpp b/C++/sort-characters-by-frequency.cpp new file mode 100644 index 000000000..c37dd4fe2 --- /dev/null +++ b/C++/sort-characters-by-frequency.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + string frequencySort(string s) { + unordered_map freq; + for (const auto& c : s) { + ++freq[c]; + } + + vector counts(s.size() + 1); + for (const auto& kvp : freq) { + counts[kvp.second].push_back(kvp.first); + } + + string result; + for (int count = counts.size() - 1; count >= 0; --count) { + for (const auto& c : counts[count]) { + result += string(count, c); + } + } + + return result; + } +}; From d6bcecfa82af425539056b86c8b170867d4110dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 01:52:16 +0800 Subject: [PATCH 2998/4971] Create delete-node-in-a-bst.py --- Python/delete-node-in-a-bst.py | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/delete-node-in-a-bst.py diff --git a/Python/delete-node-in-a-bst.py b/Python/delete-node-in-a-bst.py new file mode 100644 index 000000000..04dd96f59 --- /dev/null +++ b/Python/delete-node-in-a-bst.py @@ -0,0 +1,42 @@ +# Time: O(h) +# 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 deleteNode(self, root, key): + """ + :type root: TreeNode + :type key: int + :rtype: TreeNode + """ + if not root: + return root + + if root.val > key: + root.left = deleteNode(root.left, key) + elif root.val < key: + root.right = deleteNode(root.right, key) + else: + if not root.left: + right = root.right + del root + return right + elif not root.right: + left = root.left + del root + return left + else: + successor = root.right + while successor.left: + successor = successor.left + + root.val = successor.val + root.right = deleteNode(root.right, successor.val) + + return root From 8b4354c98a2a011ba8c4f6e156a121f9071272f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 02:24:21 +0800 Subject: [PATCH 2999/4971] Create serialize-and-deserialize-bst.cpp --- C++/serialize-and-deserialize-bst.cpp | 59 +++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 C++/serialize-and-deserialize-bst.cpp diff --git a/C++/serialize-and-deserialize-bst.cpp b/C++/serialize-and-deserialize-bst.cpp new file mode 100644 index 000000000..91c71f0e7 --- /dev/null +++ b/C++/serialize-and-deserialize-bst.cpp @@ -0,0 +1,59 @@ +// 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 Codec { +public: + + // Encodes a tree to a single string. + string serialize(TreeNode* root) { + string data; + serializeHelper(root, &data); + return data; + } + + // Decodes your encoded data to tree. + TreeNode* deserialize(string data) { + int i = 0; + return deserializeHelper(numeric_limits::min(), numeric_limits::max(), data, &i); + } + + +private: + void serializeHelper(TreeNode *node, string *data) { + if (node) { + *data += to_string(node->val) + " "; + serializeHelper(node->left, data); + serializeHelper(node->right, data); + } + } + + TreeNode* deserializeHelper(int minVal, int maxVal, const string& data, int *i) { + if (*i == data.length()) { + return nullptr; + } + int j = data.find(' ', *i); + auto val = stoi(data.substr(*i, j - *i)); + if (minVal < val && val < maxVal) { + auto node = new TreeNode(val); + *i = j + 1; + node->left = deserializeHelper(minVal, val, data, i); + node->right = deserializeHelper(val, maxVal, data, i); + return node; + } else { + return nullptr; + } + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.deserialize(codec.serialize(root)); From 429231d1758840f6639e7e466670320820d9efbe Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 02:26:40 +0800 Subject: [PATCH 3000/4971] Update serialize-and-deserialize-bst.py --- Python/serialize-and-deserialize-bst.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Python/serialize-and-deserialize-bst.py b/Python/serialize-and-deserialize-bst.py index 48dc7cdbc..811fa44c2 100644 --- a/Python/serialize-and-deserialize-bst.py +++ b/Python/serialize-and-deserialize-bst.py @@ -31,14 +31,14 @@ def serialize(self, root): :type root: TreeNode :rtype: str """ - def preOrder(node, vals): + def serializeHelper(node, vals): if node: vals.append(node.val) - preOrder(node.left, vals) - preOrder(node.right, vals) + serializeHelper(node.left, vals) + serializeHelper(node.right, vals) vals = [] - preOrder(root, vals) + serializeHelper(root, vals) return ' '.join(map(str, vals)) @@ -49,22 +49,22 @@ def deserialize(self, data): :type data: str :rtype: TreeNode """ - def build(minVal, maxVal, vals): + def deserializeHelper(minVal, maxVal, vals): if not vals: return None if minVal < vals[0] < maxVal: val = vals.popleft() node = TreeNode(val) - node.left = build(minVal, val, vals) - node.right = build(val, maxVal, vals) + node.left = deserializeHelper(minVal, val, vals) + node.right = deserializeHelper(val, maxVal, vals) return node else: return None vals = collections.deque([int(val) for val in data.split()]) - return build(float('-inf'), float('inf'), vals) + return deserializeHelper(float('-inf'), float('inf'), vals) # Your Codec object will be instantiated and called as such: From a2f278fd7fa7430c599e619b386f9159f3daf868 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 02:27:05 +0800 Subject: [PATCH 3001/4971] Update serialize-and-deserialize-bst.cpp --- C++/serialize-and-deserialize-bst.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/serialize-and-deserialize-bst.cpp b/C++/serialize-and-deserialize-bst.cpp index 91c71f0e7..8ac849122 100644 --- a/C++/serialize-and-deserialize-bst.cpp +++ b/C++/serialize-and-deserialize-bst.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(n) +// Space: O(h) /** * Definition for a binary tree node. From 93e4b48740ab71a6002d5ecb359efb4e3ce2fd7d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 17:26:39 +0800 Subject: [PATCH 3002/4971] Update README.md --- README.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8bbaa2557..9730cbbd1 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-429%20%2F%20429-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-434%20%2F%20434-ff69b4.svg) -Up to date (2016-10-23), there are `412` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-10-30), there are `417` 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 `429` questions. +Here is the classification of all `434` 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.) @@ -110,6 +110,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 419| [Battleships in a Board](https://leetcode.com/problems/battleships-in-a-board/) | [C++](./C++/battleships-in-a-board.cpp) [Python](./Python/battleships-in-a-board.py) | _O(m * n)_ | _O(1)_ | Medium ||| 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| +448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| + ## String # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -160,6 +162,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | 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 | | 369| [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [C++](./C++/plus-one-linked-list.cpp) [Python](./Python/plus-one-linked-list.py) | _O(n)_ | _O(1)_ | Medium | 📖 | Two Pointers | +445| [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/)| [C++](./C++/add-two-numbers-ii.cpp) [Python](./Python/add-two-numbers-ii.py) | _O(m + n)_ | _O(m + n)_ | Medium ||| ## Stack # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -298,6 +301,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 400 | [Nth Digit](https://leetcode.com/problems/nth-digit/) | [C++](./C++/nth-digit.cpp) [Python](./Python/nth-digit.py) | _O(logn)_ | _O(1)_ | Easy ||| 413 | [Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./C++/arithmetic-slices.cpp) [Python](./Python/arithmetic-slices.py) | _O(n)_ | _O(1)_ | Medium ||| 423 | [Reconstruct Original Digits from English](https://leetcode.com/problems/reconstruct-original-digits-from-english/) | [C++](./C++/reconstruct-original-digits-from-english.cpp) [Python](./Python/reconstruct-original-digits-from-english.py) | _O(n)_ | _O(1)_ | Medium | [GCJ2016 - Round 1B](https://code.google.com/codejam/contest/11254486/dashboard#s=p0)|| +441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [C++](./C++/arranging-coins.cpp) [Python](./Python/arranging-coins.py) | _O(nlogn)_ | _O(1)_ | Easy || Binary Search| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -318,6 +322,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)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | 347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(n)_ | Medium | | Quick Select, Heap | 406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium | | | +451| [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/) | [C++](./C++/sort-characters-by-frequency.cpp) [Python](./Python/sort-characters-by-frequency.py) | _O(n)_ | _O(n)_ | Medium | | | ## Two Pointers @@ -388,6 +393,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 367| [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/)| [C++](./C++/valid-perfect-square.cpp) [Python](./Python/valid-perfect-square.py) | _O(logn)_ | _O(1)_ | Medium | | 374| [Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/)| [C++](./C++/guess-number-higher-or-lower.cpp) [Python](./Python/guess-number-higher-or-lower.py) | _O(logn)_ | _O(1)_ | Easy | | 410| [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/)| [C++](./C++/split-array-largest-sum.cpp) [Python](./Python/split-array-largest-sum.py) | _O(nlogs)_ | _O(1)_ | Hard | | +436 | [Find Right Interval](https://leetcode.com/problems/find-right-interval/) | [C++](./C++/find-right-interval.cpp) [Python](./Python/find-right-interval.py) | _O(nlogn)_ | _O(n)_ | Medium | | ## Binary Search Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -398,6 +404,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | 📖 | 352 | [Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/) | [C++](./C++/data-stream-as-disjoint-intervals.cpp) [Python](./Python/data-stream-as-disjoint-intervals.py) | _O(logn)_ | _O(n)_ | Hard | | +449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/)| [C++](./C++/serialize-and-deserialize-bst.cpp) [Python](./Python/serialize-and-deserialize-bst.py)| _O(n)_ | _O(h)_ | Medium | | | +450|[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/)| [C++](./C++/delete-node-in-a-bst.cpp) [Python](./Python/delete-node-in-a-bst.py)| _O(h)_ | _O(h)_ | Medium | | | ## Breadth-First Search # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -417,6 +425,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | 📖 | 433| [Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation/)| [C++](./C++/minimum-genetic-mutation.cpp) [Python](./Python/minimum-genetic-mutation.py) | _O(n * b)_ | _O(b)_ | Medium || +444| [Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction/)| [C++](./C++/sequence-reconstruction.cpp) [Python](./Python/sequence-reconstruction.py) | _O(n * s)_ | _O(n)_ | Medium |📖| Topological Sort | ## Depth-First Search # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -531,6 +540,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 392| [Is Subsequence](https://leetcode.com/problems/is-subsequence/)| [C++](./C++/is-subsequence.cpp) [Python](./Python/is-subsequence.py) | _O(n)_ | _O(1)_ | Medium || 397| [Integer Replacement](https://leetcode.com/problems/integer-replacement/)| [C++](./C++/integer-replacement.cpp) [Python](./Python/integer-replacement.py) | _O(n)_ | _O(1)_ | Easy || Math 402 | [Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./C++/remove-k-digits.cpp) [Python](./Python/remove-k-digits.py) | _O(n)_ | _O(n)_ | Medium | LintCode | +435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | --- ## Design From 858c55d0345898f56efa3c88b0519d941fb12a3c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 17:38:30 +0800 Subject: [PATCH 3003/4971] Create minimum-moves-to-equal-array-elements.cpp --- C++/minimum-moves-to-equal-array-elements.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 C++/minimum-moves-to-equal-array-elements.cpp diff --git a/C++/minimum-moves-to-equal-array-elements.cpp b/C++/minimum-moves-to-equal-array-elements.cpp new file mode 100644 index 000000000..330d91dbd --- /dev/null +++ b/C++/minimum-moves-to-equal-array-elements.cpp @@ -0,0 +1,10 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int minMoves(vector& nums) { + return accumulate(nums.cbegin(), nums.cend(), 0) - + nums.size() * *min_element(nums.cbegin(), nums.cend()); + } +}; From 35f981754bfe01352815edab466326b0cf2c78f6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 17:40:19 +0800 Subject: [PATCH 3004/4971] Create minimum-moves-to-equal-array-elements.py --- .../minimum-moves-to-equal-array-elements.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/minimum-moves-to-equal-array-elements.py diff --git a/Python/minimum-moves-to-equal-array-elements.py b/Python/minimum-moves-to-equal-array-elements.py new file mode 100644 index 000000000..fd4afdff2 --- /dev/null +++ b/Python/minimum-moves-to-equal-array-elements.py @@ -0,0 +1,27 @@ +# Time: O(n) +# Space: O(1) + +# Given a non-empty integer array of size n, +# find the minimum number of moves required to make all array elements equal, +# where a move is incrementing n - 1 elements by 1. +# +# Example: +# +# Input: +# [1,2,3] +# +# Output: +# 3 +# +# Explanation: +# Only three moves are needed (remember each move increments two elements): +# +# [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] + +class Solution(object): + def minMoves(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + return sum(nums) - len(nums) * min(nums) From 6732efa6aeaf1522b382022835ec777f8f0ec280 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 17:47:24 +0800 Subject: [PATCH 3005/4971] Create number-of-boomerangs.cpp --- C++/number-of-boomerangs.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/number-of-boomerangs.cpp diff --git a/C++/number-of-boomerangs.cpp b/C++/number-of-boomerangs.cpp new file mode 100644 index 000000000..6d36e4070 --- /dev/null +++ b/C++/number-of-boomerangs.cpp @@ -0,0 +1,29 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + int numberOfBoomerangs(vector>& points) { + int result = 0; + for (int i = 0; i < points.size(); ++i) { + unordered_map group; + for (int j = 0; j < points.size(); ++j) { + if (j == i) { + continue; + } + + const auto dy = points[i].second - points[j].second; + const auto dx = points[i].first - points[j].first; + ++group[dx * dx + dy * dy]; + } + + for (const auto& p : group) { + if (p.second > 1) { + result += p.second * (p.second - 1); + } + } + } + + return result; + } +}; From d6e35975f5edd73f22135c15864506ef9854b273 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 17:52:51 +0800 Subject: [PATCH 3006/4971] Update number-of-boomerangs.cpp --- C++/number-of-boomerangs.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/number-of-boomerangs.cpp b/C++/number-of-boomerangs.cpp index 6d36e4070..e5b813cc8 100644 --- a/C++/number-of-boomerangs.cpp +++ b/C++/number-of-boomerangs.cpp @@ -5,15 +5,15 @@ class Solution { public: int numberOfBoomerangs(vector>& points) { int result = 0; + for (int i = 0; i < points.size(); ++i) { unordered_map group; for (int j = 0; j < points.size(); ++j) { if (j == i) { continue; } - - const auto dy = points[i].second - points[j].second; const auto dx = points[i].first - points[j].first; + const auto dy = points[i].second - points[j].second; ++group[dx * dx + dy * dy]; } From 53333714bfa29ddb4ca079033a6abf1c1203eb9b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 17:54:17 +0800 Subject: [PATCH 3007/4971] Create number-of-boomerangs.py --- Python/number-of-boomerangs.py | 41 ++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/number-of-boomerangs.py diff --git a/Python/number-of-boomerangs.py b/Python/number-of-boomerangs.py new file mode 100644 index 000000000..6ef7f4b28 --- /dev/null +++ b/Python/number-of-boomerangs.py @@ -0,0 +1,41 @@ +# Time: O(n^2) +# Space: O(n) + +# Given n points in the plane that are all pairwise distinct, +# a "boomerang" is a tuple of points (i, j, k) such that the distance +# between i and j equals the distance between i and k (the order of the tuple matters). +# +# Find the number of boomerangs. You may assume that n will be at most 500 +# and coordinates of points are all in the range [-10000, 10000] (inclusive). +# +# Example: +# Input: +# [[0,0],[1,0],[2,0]] +# +# Output: +# 2 +# +# Explanation: +# The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]] + +class Solution(object): + def numberOfBoomerangs(self, points): + """ + :type points: List[List[int]] + :rtype: int + """ + result = 0 + + for i in xrange(len(points)): + group = collections.defaultdict(int) + for j in xrange(len(points)): + if j == i: + continue + dx, dy = points[i][0] - points[j][0], points[i][1] - points[j][1] + group[dx**2 + dy**2] += 1 + + for _, v in group.iteritems(): + if v > 1: + result += v * (v-1) + + return result From 681b06927ad23c4e26c39ceb4e2e315c3276117e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 18:22:12 +0800 Subject: [PATCH 3008/4971] Create minimum-number-of-arrows-to-burst-balloons.cpp --- ...mum-number-of-arrows-to-burst-balloons.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/minimum-number-of-arrows-to-burst-balloons.cpp diff --git a/C++/minimum-number-of-arrows-to-burst-balloons.cpp b/C++/minimum-number-of-arrows-to-burst-balloons.cpp new file mode 100644 index 000000000..2bc27dbc0 --- /dev/null +++ b/C++/minimum-number-of-arrows-to-burst-balloons.cpp @@ -0,0 +1,26 @@ +// Time: O(nlogn) +// Space: O(1) + +class Solution { +public: + int findMinArrowShots(vector>& points) { + if (points.empty()) { + return 0; + } + + sort(points.begin(), points.end()); + + int result = 0; + for (int i = 0; i < points.size(); ++i) { + int j = i + 1; + int right_bound = points[i].second; + while (j < points.size() && points[j].first <= right_bound) { + right_bound = min(right_bound, points[j].second); + ++j; + } + ++result; + i = j - 1; + } + return result; + } +}; From 95f05177298b959ddb3579312d0f164bf46a7a7d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 18:27:07 +0800 Subject: [PATCH 3009/4971] Create minimum-number-of-arrows-to-burst-balloons.py --- ...imum-number-of-arrows-to-burst-balloons.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/minimum-number-of-arrows-to-burst-balloons.py diff --git a/Python/minimum-number-of-arrows-to-burst-balloons.py b/Python/minimum-number-of-arrows-to-burst-balloons.py new file mode 100644 index 000000000..04248ea80 --- /dev/null +++ b/Python/minimum-number-of-arrows-to-burst-balloons.py @@ -0,0 +1,48 @@ +# Time: O(nlogn) +# Space: O(1) + +# There are a number of spherical balloons spread in two-dimensional space. +# For each balloon, provided input is the start and end coordinates of the horizontal diameter. +# Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and +# end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons. +# +# An arrow can be shot up exactly vertically from different points along the x-axis. +# A balloon with xstart and xend bursts by an arrow shot at x if xstart <= x <= xend. +# There is no limit to the number of arrows that can be shot. +# An arrow once shot keeps travelling up infinitely. +# The problem is to find the minimum number of arrows that must be shot to burst all balloons. +# +# Example: +# +# Input: +# [[10,16], [2,8], [1,6], [7,12]] +# +# Output: +# 2 +# +# Explanation: +# One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) +# and another arrow at x = 11 (bursting the other two balloons). + +class Solution(object): + def findMinArrowShots(self, points): + """ + :type points: List[List[int]] + :rtype: int + """ + if not points: + return 0 + + points.sort() + + result = 0 + i = 0 + while i < len(points): + j = i + 1 + right_bound = points[i][1] + while j < len(points) and points[j][0] <= right_bound: + right_bound = min(right_bound, points[j][1]) + j += 1 + result += 1 + i = j + return result From 1e74b6fd95d23dcb5a69abdb523f0950d0a0f42c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 18:56:15 +0800 Subject: [PATCH 3010/4971] Create arithmetic-slices-ii-subsequence.py --- Python/arithmetic-slices-ii-subsequence.py | 58 ++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Python/arithmetic-slices-ii-subsequence.py diff --git a/Python/arithmetic-slices-ii-subsequence.py b/Python/arithmetic-slices-ii-subsequence.py new file mode 100644 index 000000000..37b18f126 --- /dev/null +++ b/Python/arithmetic-slices-ii-subsequence.py @@ -0,0 +1,58 @@ +# Time: O(n^2) +# Space: O(n * d) + +# A sequence of numbers is called arithmetic if it consists of at least three elements +# and if the difference between any two consecutive elements is the same. +# +# For example, these are arithmetic sequences: +# +# 1, 3, 5, 7, 9 +# 7, 7, 7, 7 +# 3, -1, -5, -9 +# The following sequence is not arithmetic. +# +# 1, 1, 2, 5, 7 +# +# A zero-indexed array A consisting of N numbers is given. +# A subsequence slice of that array is any sequence of integers (P0, P1, ..., Pk) +# such that 0 ≤ P0 < P1 < ... < Pk < N. +# +# A subsequence slice (P0, P1, ..., Pk) of array A is called arithmetic +# if the sequence A[P0], A[P1], ..., A[Pk-1], A[Pk] is arithmetic. In particular, this means that k >= 2. +# +# The function should return the number of arithmetic subsequence slices in the array A. +# +# The input contains N integers. Every integer is in the range of -2^31 and 2^31-1 and 0 <= N <= 1000. +# The output is guaranteed to be less than 2^31-1. +# +# +# Example: +# +# Input: [2, 4, 6, 8, 10] +# +# Output: 7 +# +# Explanation: +# All arithmetic subsequence slices are: +# [2,4,6] +# [4,6,8] +# [6,8,10] +# [2,4,6,8] +# [4,6,8,10] +# [2,4,6,8,10] +# [2,6,10] + +class Solution(object): + def numberOfArithmeticSlices(self, A): + """ + :type A: List[int] + :rtype: int + """ + result = 0 + dp = [{} for i in xrange(len(A))] + for i in xrange(1, len(A)): + for j in xrange(i): + cnt = dp[j].get(A[i] - A[j], 0) + 1 + dp[i][A[i] - A[j]] = dp[i].get(A[i] - A[j], 0) + cnt + result += cnt - 1 + return result From 137f58f4b2dfbf3e0db329f128ea3aea05266be3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 18:57:37 +0800 Subject: [PATCH 3011/4971] Create arithmetic-slices-ii-subsequence.cpp --- C++/arithmetic-slices-ii-subsequence.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/arithmetic-slices-ii-subsequence.cpp diff --git a/C++/arithmetic-slices-ii-subsequence.cpp b/C++/arithmetic-slices-ii-subsequence.cpp new file mode 100644 index 000000000..a604ccaae --- /dev/null +++ b/C++/arithmetic-slices-ii-subsequence.cpp @@ -0,0 +1,17 @@ +// Time: O(n^2) +// Space: O(n * d) + +class Solution_TLE { +public: + int numberOfArithmeticSlices(vector& A) { + int result = 0; + vector> dp(A.size()); + for (int i = 1; i < A.size(); ++i) { + for (int j = 0; j < i; ++j) { + dp[i][static_cast(A[i]) - A[j]] += dp[j][static_cast(A[i]) - A[j]] + 1; + result += dp[j][static_cast(A[i]) - A[j]]; + } + } + return result; + } +}; From 43d20a29c38d47f597a6c221679faa3bbd9cf190 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 19:23:17 +0800 Subject: [PATCH 3012/4971] Update arithmetic-slices-ii-subsequence.py --- Python/arithmetic-slices-ii-subsequence.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Python/arithmetic-slices-ii-subsequence.py b/Python/arithmetic-slices-ii-subsequence.py index 37b18f126..30418e704 100644 --- a/Python/arithmetic-slices-ii-subsequence.py +++ b/Python/arithmetic-slices-ii-subsequence.py @@ -49,10 +49,12 @@ def numberOfArithmeticSlices(self, A): :rtype: int """ result = 0 - dp = [{} for i in xrange(len(A))] + dp = [collections.defaultdict(int) for i in xrange(len(A))] for i in xrange(1, len(A)): for j in xrange(i): - cnt = dp[j].get(A[i] - A[j], 0) + 1 - dp[i][A[i] - A[j]] = dp[i].get(A[i] - A[j], 0) + cnt - result += cnt - 1 + diff = A[i]-A[j] + dp[i][diff] += 1 + if diff in dp[j]: + dp[i][diff] += dp[j][diff] + result += dp[j][diff] return result From 586aabb7df366ea691102c559f1bcb2643c3382f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Nov 2016 19:25:34 +0800 Subject: [PATCH 3013/4971] Update arithmetic-slices-ii-subsequence.cpp --- C++/arithmetic-slices-ii-subsequence.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/C++/arithmetic-slices-ii-subsequence.cpp b/C++/arithmetic-slices-ii-subsequence.cpp index a604ccaae..90c942883 100644 --- a/C++/arithmetic-slices-ii-subsequence.cpp +++ b/C++/arithmetic-slices-ii-subsequence.cpp @@ -1,15 +1,19 @@ // Time: O(n^2) // Space: O(n * d) -class Solution_TLE { +class Solution_MLE { public: int numberOfArithmeticSlices(vector& A) { int result = 0; vector> dp(A.size()); for (int i = 1; i < A.size(); ++i) { for (int j = 0; j < i; ++j) { - dp[i][static_cast(A[i]) - A[j]] += dp[j][static_cast(A[i]) - A[j]] + 1; - result += dp[j][static_cast(A[i]) - A[j]]; + const auto diff = static_cast(A[i]) - A[j]; + ++dp[i][diff]; + if (dp[j].count(diff)) { + dp[i][diff] += dp[j][diff]; + result += dp[j][diff]; + } } } return result; From a3e2b857c2bfe6985f46e9b4c53d520d6709cf48 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 12 Nov 2016 20:01:59 +0800 Subject: [PATCH 3014/4971] Update arithmetic-slices-ii-subsequence.cpp --- C++/arithmetic-slices-ii-subsequence.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/arithmetic-slices-ii-subsequence.cpp b/C++/arithmetic-slices-ii-subsequence.cpp index 90c942883..5e20aacf1 100644 --- a/C++/arithmetic-slices-ii-subsequence.cpp +++ b/C++/arithmetic-slices-ii-subsequence.cpp @@ -1,7 +1,7 @@ // Time: O(n^2) // Space: O(n * d) -class Solution_MLE { +class Solution { public: int numberOfArithmeticSlices(vector& A) { int result = 0; From b7480da29153c94fd1a06b3c39a64cca06e08bdf Mon Sep 17 00:00:00 2001 From: Ben Haines Date: Tue, 15 Nov 2016 23:00:58 -0500 Subject: [PATCH 3015/4971] Fixes incorrect link. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9730cbbd1..36cd81768 100644 --- a/README.md +++ b/README.md @@ -253,7 +253,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 340| [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-k-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| 356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(n)_| _O(n)_| Medium |📖| Hash, Two Pointers | 387| [First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/first-unique-character-in-a-string.cpp) [Python](./Python/first-unique-character-in-a-string.py) | _O(n)_| _O(n)_| Easy ||| -388| [Longest Absolute File Path](https://leetcode.com/problems/first-unique-character-in-a-string/) | [C++](./C++/longest-absolute-file-path.cpp) [Python](./Python/longest-absolute-file-path.py) | _O(n)_| _O(d)_| Medium || Stack | +388| [Longest Absolute File Path](https://leetcode.com/problems/longest-absolute-file-path/) | [C++](./C++/longest-absolute-file-path.cpp) [Python](./Python/longest-absolute-file-path.py) | _O(n)_| _O(d)_| Medium || Stack | 409| [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./C++/longest-palindrome.cpp) [Python](./Python/longest-palindrome.py) | _O(n)_| _O(1)_| Easy ||| 424| [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) | [C++](./C++/longest-repeating-character-replacement.cpp) [Python](./Python/longest-repeating-character-replacement.py) | _O(n)_| _O(1)_| Medium ||| 438| [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [C++](./C++/find-all-anagrams-in-a-string.cpp) [Python](./Python/find-all-anagrams-in-a-string.py) | _O(n)_ | _O(1)_ | Easy || From 289d11663b245486af57b4d050af7b07a82fd847 Mon Sep 17 00:00:00 2001 From: Ben Haines Date: Thu, 17 Nov 2016 02:45:12 -0500 Subject: [PATCH 3016/4971] Updates difficulty levels to match LeetCode --- README.md | 52 ++++++++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 36cd81768..04a47f73e 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Bit Manipulation # | 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 || +136 | [Single Number](https://leetcode.com/problems/single-number/) | [C++](./C++/single-number.cpp) [Python](./Python/single-number.py) | _O(n)_ | _O(1)_ | Easy || 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 || @@ -80,7 +80,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/)| [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 || +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)_ | Easy || 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 |📖| @@ -89,7 +89,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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/) | [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 | | +228 | [Summary Ranges](https://leetcode.com/problems/summary-ranges/) | [C++] (./C++/summary-ranges.cpp) [Python] (./Python/summary-ranges.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 | 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 | @@ -99,7 +99,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(m * n)_ | _O(m + 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)_ | Hard |📖|| 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 ||| 370| [Range Addition](https://leetcode.com/problems/range-addition/) | [C++](./C++/range-addition.cpp) [Python](./Python/range-addition.py) | _O(k + n)_ | _O(1)_ | Medium |📖|| @@ -134,7 +134,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` 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 | 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 | | +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)_ | Hard | | 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 | | 383| [Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./C++/ransom-note.cpp) [Python](./Python/ransom-note.py) | _O(n)_ | _O(1)_ | Easy | EPI | 405| [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./C++/convert-a-number-to-hexadecimal.cpp) [Python](./Python/convert-a-number-to-hexadecimal.py) | _O(n)_ | _O(1)_ | Easy | | @@ -148,7 +148,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 || 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./C++/merge-two-sorted-lists.cpp) [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | | Heap, Divide and Conquer -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 || +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)_ | Easy || 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 || @@ -160,7 +160,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 | -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 | | +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)_ | Medium | | 369| [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [C++](./C++/plus-one-linked-list.cpp) [Python](./Python/plus-one-linked-list.py) | _O(n)_ | _O(1)_ | Medium | 📖 | Two Pointers | 445| [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/)| [C++](./C++/add-two-numbers-ii.cpp) [Python](./Python/add-two-numbers-ii.py) | _O(m + n)_ | _O(m + n)_ | Medium ||| @@ -176,7 +176,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [C++](./C++/evaluate-reverse-polish-notation.cpp) [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || 155| [Min Stack](https://leetcode.com/problems/min-stack/) | [C++](./C++/min-stack.cpp) [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || 173| [Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) | [C++](./C++/binary-search-tree-iterator.cpp) [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)_| Hard || 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 |📖|| @@ -215,7 +215,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 208 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | [C++](./C++/implement-trie-prefix-tree.cpp) [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 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 +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)_ | Hard | 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, Divide and Conquer | @@ -248,7 +248,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)_| Easy | 📖 | +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 | 📖 | 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 | | | 340| [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [C++](./C++/longest-substring-with-at-most-k-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-k-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| 356| [Line Reflection](https://leetcode.com/problems/line-reflection/) | [C++](./C++/line-reflection.cpp) [Python](./Python/line-reflection.py) | _O(n)_| _O(n)_| Medium |📖| Hash, Two Pointers | @@ -262,7 +262,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates # | Title | Solution | Time | Space | Difficulty | Tag | Note -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [C++](./C++/lru-cache.cpp) [Python](./Python/lru-cache.py) | _O(1)_ | _O(k)_ | 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)_ | Easy || ## Math # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -281,14 +281,14 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 171| [Excel Sheet Column Number](https://leetcode.com/problems/excel-sheet-column-number/) | [C++](./C++/excel-sheet-column-number.cpp) [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || 172| [Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/) | [C++](./C++/factorial-trailing-zeroes.cpp) [Python](./Python/factorial-trailing-zeroes.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 || -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(1)_ | _O(1)_ | Medium | CTCI, LintCode| +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(1)_ | _O(1)_ | Hard | 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(1)_ | _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 ||| -335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | [C++](./C++/self-crossing.cpp) [Python](./Python/self-crossing.py) | _O(n)_ | _O(1)_ | Medium ||| +335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | [C++](./C++/self-crossing.cpp) [Python](./Python/self-crossing.py) | _O(n)_ | _O(1)_ | Hard ||| 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./C++/counting-bits.cpp) [Python](./Python/counting-bits.py) | _O(n)_ | _O(n)_ | Medium ||| 343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(1)_ | Medium || Tricky, DP | 365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || Euclidean Algorithm | @@ -330,7 +330,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates -----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- 19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [C++](./C++/remove-nth-node-from-end-of-list.cpp) [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || 86| [Partition List](https://leetcode.com/problems/partition-list/)| [C++](./C++/partition-list.cpp) [Python](./Python/partition-list.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 || +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)_ | Easy || 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/)| [C++](./C++/reorder-list.cpp) [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/) | [C++](./C++/two-sum-ii-input-array-is-sorted.cpp) [Python](./Python/two-sum-ii-input-array-is-sorted.py) | _O(n)_ | _O(1)_ | Medium | | @@ -387,7 +387,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 | 📖 | +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)_ | Hard | 📖 | 354| [Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes/) | [C++](./C++/russian-doll-envelopes.cpp) [Python](./Python/russian-doll-envelopes.py) | _O(nlogn)_ | _O(1)_ | Hard ||| 363| [Max Sum of Rectangle No Larger Than K](https://leetcode.com/problems/max-sum-of-sub-matrix-no-larger-than-k/) | [C++](./C++/max-sum-of-sub-matrix-no-larger-than-k.cpp) [Python](./Python/max-sum-of-sub-matrix-no-larger-than-k.py) | _O(min(m, n)^2 * max(m, n) * logn(max(m, n)))_ | _O(max(m, n))_ | Hard ||| 367| [Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/)| [C++](./C++/valid-perfect-square.cpp) [Python](./Python/valid-perfect-square.py) | _O(logn)_ | _O(1)_ | Medium | | @@ -398,7 +398,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Binary Search Tree # | 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 || +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 | 📖 | @@ -439,8 +439,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 |📖|| 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 ||| +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)_ | Hard ||| +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)_ | Hard ||| 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 ||| 339| [Nested List Weight Sum](https://leetcode.com/problems/nested-list-weight-sum/) | [C++](./C++/nested-list-weight-sum.cpp) [Python](./Python/nested-list-weight-sum.py) | _O(n)_ | _O(h)_ | Easy |📖|| 364| [Nested List Weight Sum II](https://leetcode.com/problems/nested-list-weight-sum-ii/) | [C++](./C++/nested-list-weight-sum-ii.cpp) [Python](./Python/nested-list-weight-sum-ii.py) | _O(n)_ | _O(h)_ | Medium |📖|| @@ -458,7 +458,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || +47| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | 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 || @@ -510,7 +510,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 || +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)_ | Hard || 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 || 351| [Android Unlock Patterns](https://leetcode.com/problems/android-unlock-patterns/) | [C++](./C++/android-unlock-patterns.cpp) [Python](./Python/android-unlock-patterns.py) | _O(9^2 * 2^9)_ | _O(9 * 2^9)_ | Medium | 📖 | Backtracking | 357| [Count Numbers with Unique Digits](https://leetcode.com/problems/count-numbers-with-unique-digits/) | [C++](./C++/count-numbers-with-unique-digits.cpp) [Python](./Python/count-numbers-with-unique-digits.py) | _O(n)_ | _O(1)_ | Medium || Backtracking, Math | @@ -533,12 +533,12 @@ 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/)| [C++](./C++/candy.cpp) [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 || Ascending 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)_| Hard || Ascending 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)_ | Hard || 376| [Wiggle Subsequence](https://leetcode.com/problems/wiggle-subsequence/)| [C++](./C++/wiggle-subsequence.cpp) [Python](./Python/wiggle-subsequence.py) | _O(n)_ | _O(1)_ | Medium || 392| [Is Subsequence](https://leetcode.com/problems/is-subsequence/)| [C++](./C++/is-subsequence.cpp) [Python](./Python/is-subsequence.py) | _O(n)_ | _O(1)_ | Medium || -397| [Integer Replacement](https://leetcode.com/problems/integer-replacement/)| [C++](./C++/integer-replacement.cpp) [Python](./Python/integer-replacement.py) | _O(n)_ | _O(1)_ | Easy || Math +397| [Integer Replacement](https://leetcode.com/problems/integer-replacement/)| [C++](./C++/integer-replacement.cpp) [Python](./Python/integer-replacement.py) | _O(n)_ | _O(1)_ | Medium || Math 402 | [Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./C++/remove-k-digits.cpp) [Python](./Python/remove-k-digits.py) | _O(n)_ | _O(n)_ | Medium | LintCode | 435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | @@ -549,12 +549,12 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 284| [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [C++](./C++/peeking-iterator.cpp) [Python](./Python/peeking-iterator.py) | _O(1)_ | _O(1)_ | Medium || 348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_| _O(n^2)_| Medium |📖|| 353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(1)_| _O(s)_| Medium |📖| Deque | -355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_| _O(t + f)_| Hard | LintCode | Heap | +355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_| _O(t + f)_| Medium | LintCode | Heap | 359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | [C++](./C++/logger-rate-limiter.cpp) [Python](./Python/logger-rate-limiter.py) | _O(1), amortized_ | _O(k)_| Easy |📖| Deque | 362| [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [C++](./C++/design-hit-counter.cpp) [Python](./Python/design-hit-counter.py) | _O(1), amortized_ | _O(k)_| Medium |📖| Deque | 379| [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) | [C++](./C++/design-phone-directory.cpp) [Python](./Python/design-phone-directory.py) | _O(1)_ | _O(n)_| Medium |📖| | -380| [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./C++/insert-delete-getrandom-o1.cpp) [Python](./Python/insert-delete-getrandom-o1.py) | _O(1)_ | _O(n)_| Medium || | -381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_| Medium || | +380| [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./C++/insert-delete-getrandom-o1.cpp) [Python](./Python/insert-delete-getrandom-o1.py) | _O(1)_ | _O(n)_| Hard || | +381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_| Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | ## SQL From d608aa15826f5be8e62e122e31b81507b632adcb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Nov 2016 18:36:38 +0800 Subject: [PATCH 3017/4971] Update alien-dictionary.cpp --- C++/alien-dictionary.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/C++/alien-dictionary.cpp b/C++/alien-dictionary.cpp index f6eb45970..f7a8bc8f4 100644 --- a/C++/alien-dictionary.cpp +++ b/C++/alien-dictionary.cpp @@ -14,6 +14,10 @@ class Solution { } } for (int i = 1; i < words.size(); ++i) { + if (words[i - 1].length() > words[i].length() && + words[i - 1].substr(0, words[i].length()) == words[i]) { + return ""; + } findEdges(words[i - 1], words[i], &in_degree, &out_degree); } for (const auto& node : nodes) { From b9ebbc992437930637cb0e03ddb10ffb1855190a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Nov 2016 18:39:14 +0800 Subject: [PATCH 3018/4971] Update alien-dictionary.py --- Python/alien-dictionary.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index 08178ab1e..b9eccb43b 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -15,6 +15,9 @@ def alienOrder(self, words): nodes.add(c) for i in xrange(1, len(words)): + if len(words[i-1]) > len(words[i]) and \ + words[i-1][:len(words[i])] == words[i]: + return "" self.findEdges(words[i - 1], words[i], in_degree, out_degree) for node in nodes: @@ -68,6 +71,9 @@ def alienOrder(self, words): for node in nodes: ancestors[node] = [] for i in xrange(1, len(words)): + if len(words[i-1]) > len(words[i]) and \ + words[i-1][:len(words[i])] == words[i]: + return "" self.findEdges(words[i - 1], words[i], ancestors) # Output topological order by DFS. From e7670554014b7479611c8ec33f528a668b770a31 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 1 Dec 2016 20:27:56 +0800 Subject: [PATCH 3019/4971] Create lfu-cache.cpp --- C++/lfu-cache.cpp | 65 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 C++/lfu-cache.cpp diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp new file mode 100644 index 000000000..d3474e304 --- /dev/null +++ b/C++/lfu-cache.cpp @@ -0,0 +1,65 @@ +#include + +class LFUCache{ +public: + // @param capacity, an integer + LFUCache(int capacity) : capa_(capacity) { + } + + int get(int key) { + if (map_.find(key) != map_.end() && capa_) { + // It key exists, update it. + const auto value = map_[key]->value; + update(key, value); + return value; + } else { + return -1; + } + } + + void set(int key, int value) { + // If cache is full while inserting, remove the last one. + if (map_.find(key) == map_.end() && list_.size() == capa_ && capa_) { + auto del = list_.front(); list_.pop_front(); + map_.erase(del.key); + } + update(key, value); + } + +private: + struct node { + node(int k, int v, int f) : key(k), value(v), freq(f) {} + int key; + int value; + int freq; + }; + using List = list; + List list_; // key, value + unordered_map map_; // key, list iterator + int capa_; + + // Update (key, iterator of (key, value)) pair + void update(int key, int value) { + int freq = 0; + auto l_it = list_.begin(); + auto it = map_.find(key); + if (it != map_.end()) { + freq = it->second->freq; + l_it = next(it->second); + list_.erase(it->second); + } + ++freq; + while (l_it != list_.end() && freq >= l_it->freq) { + ++l_it; + } + map_[key] = list_.emplace(l_it, node(key, value, freq)); + } +}; + +/** + * Your LFUCache object will be instantiated and called as such: + * LFUCache obj = new LFUCache(capacity); + * int param_1 = obj.get(key); + * obj.set(key,value); + */ + From 7cf265bfc2771fa5e7bd61247c6066add31d70b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 1 Dec 2016 20:30:08 +0800 Subject: [PATCH 3020/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index d3474e304..24748cfa1 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -19,7 +19,10 @@ class LFUCache{ void set(int key, int value) { // If cache is full while inserting, remove the last one. - if (map_.find(key) == map_.end() && list_.size() == capa_ && capa_) { + if (!capa_) { + return; + } + if (map_.find(key) == map_.end() && list_.size() == capa_) { auto del = list_.front(); list_.pop_front(); map_.erase(del.key); } @@ -62,4 +65,3 @@ class LFUCache{ * int param_1 = obj.get(key); * obj.set(key,value); */ - From bb852096f4f0bad9aa47d92a5aac0e207ef7bcb0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 1 Dec 2016 20:31:53 +0800 Subject: [PATCH 3021/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index 24748cfa1..0e56fd451 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -17,16 +17,16 @@ class LFUCache{ } } - void set(int key, int value) { - // If cache is full while inserting, remove the last one. + void set(int key, int value) if (!capa_) { return; } + // If cache is full while inserting, remove the last one. if (map_.find(key) == map_.end() && list_.size() == capa_) { auto del = list_.front(); list_.pop_front(); map_.erase(del.key); } - update(key, value); + update(key, value); } private: From 853d6418b1e042c6a34286d987300630e6eadaf6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 1 Dec 2016 20:33:36 +0800 Subject: [PATCH 3022/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index 0e56fd451..c37a7626f 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -1,3 +1,6 @@ +// Time: O(1), per operation. +// Space: O(k), k is the capacity of cache. + #include class LFUCache{ From c4a7831a3bf3a50f26598b4e424382f9217118ca Mon Sep 17 00:00:00 2001 From: Hongyi Shen Date: Fri, 2 Dec 2016 11:16:48 -0800 Subject: [PATCH 3023/4971] Fix variable typo --- Python/excel-sheet-column-title.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/excel-sheet-column-title.py b/Python/excel-sheet-column-title.py index 7fd6ef869..a2160e9d5 100644 --- a/Python/excel-sheet-column-title.py +++ b/Python/excel-sheet-column-title.py @@ -19,7 +19,7 @@ def convertToTitle(self, n): :type n: int :rtype: str """ - result, dvd = "", num + result, dvd = "", n while dvd: result += chr((dvd - 1) % 26 + ord('A')) From 73213f22583b256944610d33592d9c4081d7b912 Mon Sep 17 00:00:00 2001 From: Daniil Sharou Date: Sun, 4 Dec 2016 22:14:29 -0800 Subject: [PATCH 3024/4971] fix typo in anagrams.py --- Python/anagrams.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/anagrams.py b/Python/anagrams.py index 74ce78394..7b4ff9628 100644 --- a/Python/anagrams.py +++ b/Python/anagrams.py @@ -23,5 +23,5 @@ def groupAnagrams(self, strs): if __name__ == "__main__": - result = Solution().anagrams(["cat", "dog", "act", "mac"]) + result = Solution().groupAnagrams(["cat", "dog", "act", "mac"]) print result From 31b98cb5ba3eefce5559980be48165a74618a6d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 21:39:21 +0800 Subject: [PATCH 3025/4971] Create number-of-segments-in-a-string.cpp --- C++/number-of-segments-in-a-string.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/number-of-segments-in-a-string.cpp diff --git a/C++/number-of-segments-in-a-string.cpp b/C++/number-of-segments-in-a-string.cpp new file mode 100644 index 000000000..73b078893 --- /dev/null +++ b/C++/number-of-segments-in-a-string.cpp @@ -0,0 +1,15 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int countSegments(string s) { + int result = static_cast(!s.empty() && s.back() != ' '); + for (int i = 1; i < s.size(); ++i) { + if (s[i] == ' ' && s[i - 1] != ' ') { + ++result; + } + } + return result; + } +}; From 4b95c819a8c950646b7645c686f08986fa9ce544 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 21:44:58 +0800 Subject: [PATCH 3026/4971] Create number-of-segments-in-a-string.py --- Python/number-of-segments-in-a-string.py | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/number-of-segments-in-a-string.py diff --git a/Python/number-of-segments-in-a-string.py b/Python/number-of-segments-in-a-string.py new file mode 100644 index 000000000..066b98208 --- /dev/null +++ b/Python/number-of-segments-in-a-string.py @@ -0,0 +1,26 @@ +# Time: O(n) +# Space: O(1) + +# Count the number of segments in a string, +# where a segment is defined to be a contiguous +# sequence of non-space characters. +# +# Please note that the string does not +# contain any non-printable characters. +# +# Example: +# +# Input: "Hello, my name is John" +# Output: 5 + +class Solution(object): + def countSegments(self, s): + """ + :type s: str + :rtype: int + """ + result = int(len(s) and s[-1] != ' ') + for i in xrange(1, len(s)): + if s[i] == ' ' and s[i-1] != ' ': + result += 1 + return result From 97f67a2e7cbc117a1d81821e060229199692246c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 21:55:57 +0800 Subject: [PATCH 3027/4971] Create 4sum-ii.py --- Python/4sum-ii.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/4sum-ii.py diff --git a/Python/4sum-ii.py b/Python/4sum-ii.py new file mode 100644 index 000000000..016952602 --- /dev/null +++ b/Python/4sum-ii.py @@ -0,0 +1,37 @@ +# Time: O(n^2) +# Space: O(n^2) + +# Given four lists A, B, C, D of integer values, +# compute how many tuples (i, j, k, l) there are +# such that A[i] + B[j] + C[k] + D[l] is zero. +# +# To make problem a bit easier, all A, B, C, D have same length of N where 0 <= N <= 500. +# All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. +# +# Example: +# +# Input: +# A = [ 1, 2] +# B = [-2,-1] +# C = [-1, 2] +# D = [ 0, 2] +# +# Output: +# 2 +# +# Explanation: +# The two tuples are: +# 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 +# 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 + +class Solution(object): + def fourSumCount(self, A, B, C, D): + """ + :type A: List[int] + :type B: List[int] + :type C: List[int] + :type D: List[int] + :rtype: int + """ + A_B_sum = collections.Counter(a+b for a in A for b in B) + return sum(A_B_sum[-c-d] for c in C for d in D) From f2b397cbab6df8c211440fa46e1978bb9e7e7c93 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 21:59:06 +0800 Subject: [PATCH 3028/4971] Create 4sum-ii.cpp --- C++/4sum-ii.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/4sum-ii.cpp diff --git a/C++/4sum-ii.cpp b/C++/4sum-ii.cpp new file mode 100644 index 000000000..925945787 --- /dev/null +++ b/C++/4sum-ii.cpp @@ -0,0 +1,23 @@ +// Time: O(n^2) +// Space: O(n^2) + +class Solution { +public: + int fourSumCount(vector& A, vector& B, vector& C, vector& D) { + unordered_map A_B_sum; + for (const auto& a : A) { + for (const auto& b : B) { + ++A_B_sum[a + b]; + } + } + int result = 0; + for (const auto& c : C) { + for (const auto& d : D) { + if (A_B_sum.find(-c - d) != A_B_sum.end()) { + result += A_B_sum[-c - d]; + } + } + } + return result; + } +}; From dec433d871dfc3854c8755c025f0699c921565b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 22:09:25 +0800 Subject: [PATCH 3029/4971] Create assign-cookies.py --- Python/assign-cookies.py | 50 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/assign-cookies.py diff --git a/Python/assign-cookies.py b/Python/assign-cookies.py new file mode 100644 index 000000000..839899646 --- /dev/null +++ b/Python/assign-cookies.py @@ -0,0 +1,50 @@ +# Time: O(nlogn) +# Space: O(1) + +# Assume you are an awesome parent and want to give your children some cookies. +# But, you should give each child at most one cookie. Each child i has a greed factor gi, +# which is the minimum size of a cookie that the child will be content with; +# and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, +# and the child i will be content. +# Your goal is to maximize the number of your content children and output the maximum number. +# +# Note: +# You may assume the greed factor is always positive. +# You cannot assign more than one cookie to one child. +# +# Example 1: +# Input: [1,2,3], [1,1] +# +# Output: 1 +# +# Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. +# And even though you have 2 cookies, since their size is both 1, +# you could only make the child whose greed factor is 1 content. +# You need to output 1. +# Example 2: +# Input: [1,2], [1,2,3] +# +# Output: 2 +# +# Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. +# You have 3 cookies and their sizes are big enough to gratify all of the children, +# You need to output 2. + +class Solution(object): + def findContentChildren(self, g, s): + """ + :type g: List[int] + :type s: List[int] + :rtype: int + """ + g.sort() + s.sort() + + result, i = 0, 0 + for j in xrange(len(s)): + if i == len(g): + break + if s[j] >= g[i]: + result += 1 + i += 1 + return result From 78c0329027e36ad5db5320a3d336eb9620e90b1a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 22:10:40 +0800 Subject: [PATCH 3030/4971] Create assign-cookies.cpp --- C++/assign-cookies.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/assign-cookies.cpp diff --git a/C++/assign-cookies.cpp b/C++/assign-cookies.cpp new file mode 100644 index 000000000..3daae8a7c --- /dev/null +++ b/C++/assign-cookies.cpp @@ -0,0 +1,22 @@ +// Time: O(nlogn) +// Space: O(1) + +class Solution { +public: + int findContentChildren(vector& g, vector& s) { + sort(g.begin(), g.end()); + sort(s.begin(), s.end()); + + int result = 0; + for (int i = 0, j = 0; j < s.size(); ++j) { + if (i == g.size()) { + break; + } + if (s[j] >= g[i]) { + ++i; + ++result; + } + } + return result; + } +}; From 0ce66aec06535467109e9c5acad57e0d8cbf1421 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 22:32:04 +0800 Subject: [PATCH 3031/4971] Create 132-pattern.cpp --- C++/132-pattern.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/132-pattern.cpp diff --git a/C++/132-pattern.cpp b/C++/132-pattern.cpp new file mode 100644 index 000000000..c854b5dd1 --- /dev/null +++ b/C++/132-pattern.cpp @@ -0,0 +1,21 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + bool find132pattern(vector& nums) { + int ak = numeric_limits::min(); + stack st; + for (int i = nums.size() - 1; i >= 0; --i) { + if (nums[i] < ak) { + return true; + } else { + while (!st.empty() && nums[i] > st.top()) { + ak = st.top(), st.pop(); + } + } + st.emplace(nums[i]); + } + return false; + } +}; From 8b90bd08fa28d549cd3ba06782349468ff2eb4c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 22:36:15 +0800 Subject: [PATCH 3032/4971] Create 132-pattern.py --- Python/132-pattern.py | 45 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/132-pattern.py diff --git a/Python/132-pattern.py b/Python/132-pattern.py new file mode 100644 index 000000000..0ad03e480 --- /dev/null +++ b/Python/132-pattern.py @@ -0,0 +1,45 @@ +# Time: O(n) +# Space: O(n) + +# Given a sequence of n integers a1, a2, ..., an, +# a 132 pattern is a subsequence ai, aj, ak such that i < j < k and +# ai < ak < aj. Design an algorithm that takes a list of n numbers as +# input and checks whether there is a 132 pattern in the list. +# +# Note: n will be less than 15,000. +# +# Example 1: +# Input: [1, 2, 3, 4] +# +# Output: False +# +# Explanation: There is no 132 pattern in the sequence. +# Example 2: +# Input: [3, 1, 4, 2] +# +# Output: True +# +# Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. +# Example 3: +# Input: [-1, 3, 2, 0] +# +# Output: True +# +# Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. + +class Solution(object): + def find132pattern(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + ak = float("-inf") + st = [] + for i in reversed(xrange(len(nums))): + if nums[i] < ak: + return True + else: + while st and nums[i] > st[-1]: + ak = st.pop() + st.append(nums[i]) + return False From 0c0d8691433e85502f29607511aa9a0a51416cc9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 23:22:08 +0800 Subject: [PATCH 3033/4971] Create repeated-substring-pattern.py --- Python/repeated-substring-pattern.py | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/repeated-substring-pattern.py diff --git a/Python/repeated-substring-pattern.py b/Python/repeated-substring-pattern.py new file mode 100644 index 000000000..1247843f8 --- /dev/null +++ b/Python/repeated-substring-pattern.py @@ -0,0 +1,45 @@ +# Time: O(n) +# Space: O(n) + +# Given a non-empty string check if it can be constructed by taking a substring of it +# and appending multiple copies of the substring together. +# You may assume the given string consists of lowercase English letters only and its length will not exceed 10000. +# +# Example 1: +# Input: "abab" +# +# Output: True +# +# Explanation: It's the substring "ab" twice. +# Example 2: +# Input: "aba" +# +# Output: False +# Example 3: +# Input: "abcabcabcabc" +# +# Output: True +# +# Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) + +# KMP solution. +class Solution(object): + def repeatedSubstringPattern(self, str): + """ + :type str: str + :rtype: bool + """ + 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 + + prefix = getPrefix(str) + return prefix[-1] != -1 and \ + (prefix[-1] + 1) % (len(str) - prefix[-1] - 1) == 0 From 112818b0097775061589159994bbb6973307d8c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 23:22:43 +0800 Subject: [PATCH 3034/4971] Create repeated-substring-pattern.cpp --- C++/repeated-substring-pattern.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/repeated-substring-pattern.cpp diff --git a/C++/repeated-substring-pattern.cpp b/C++/repeated-substring-pattern.cpp new file mode 100644 index 000000000..afd5e990e --- /dev/null +++ b/C++/repeated-substring-pattern.cpp @@ -0,0 +1,28 @@ +// Time: O(n) +// Space: O(n) + +// KMP solution. +class Solution { +public: + bool repeatedSubstringPattern(string str) { + vector prefix = getPrefix(str); + return prefix.back() != -1 && + (prefix.back() + 1) % (str.length() - prefix.back() - 1) == 0; + } + +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; + } +}; From b59cfd830cabc8ed7478aada96968eedfdea9513 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 23:35:23 +0800 Subject: [PATCH 3035/4971] Create minimum-moves-to-equal-array-elements-ii.py --- ...inimum-moves-to-equal-array-elements-ii.py | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/minimum-moves-to-equal-array-elements-ii.py diff --git a/Python/minimum-moves-to-equal-array-elements-ii.py b/Python/minimum-moves-to-equal-array-elements-ii.py new file mode 100644 index 000000000..1902794a8 --- /dev/null +++ b/Python/minimum-moves-to-equal-array-elements-ii.py @@ -0,0 +1,38 @@ +# Time: O(n) on average +# Space: O(1) + +from random import randint + +# Quick select solution. +class Solution(object): + def minMoves2(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + def kthElement(nums, k): + 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 + + 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 + + median = kthElement(nums, len(nums)/2 + 1) + return sum(abs(num - median) for num in nums) From 55cab67fe724f5904e87268cf4fca1089058b9ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Dec 2016 23:36:20 +0800 Subject: [PATCH 3036/4971] Create minimum-moves-to-equal-array-elements-ii.cpp --- ...minimum-moves-to-equal-array-elements-ii.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/minimum-moves-to-equal-array-elements-ii.cpp diff --git a/C++/minimum-moves-to-equal-array-elements-ii.cpp b/C++/minimum-moves-to-equal-array-elements-ii.cpp new file mode 100644 index 000000000..1597aa985 --- /dev/null +++ b/C++/minimum-moves-to-equal-array-elements-ii.cpp @@ -0,0 +1,17 @@ +// Time: O(n) on average +// Space: O(1) + +// Quick select solution. +class Solution { +public: + int minMoves2(vector& nums) { + auto it = nums.begin() + nums.size() / 2; + nth_element(nums.begin(), it, nums.end()); + const auto median = *it; + int result = 0; + for (const auto &i : nums) { + result += abs(i - median); + } + return result; + } +}; From 9f1b4fa9df095e37d35962650ef5b631c76261ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 00:36:54 +0800 Subject: [PATCH 3037/4971] Create island-perimeter.cpp --- C++/island-perimeter.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/island-perimeter.cpp diff --git a/C++/island-perimeter.cpp b/C++/island-perimeter.cpp new file mode 100644 index 000000000..2b60cee51 --- /dev/null +++ b/C++/island-perimeter.cpp @@ -0,0 +1,23 @@ +// Time: O(m * n) +// Space: O(1) + +class Solution { +public: + int islandPerimeter(vector>& grid) { + int count = 0, repeat = 0; + for (int i = 0; i < grid.size(); ++i) { + for (int j = 0; j < grid[i].size(); ++j) { + if (grid[i][j] == 1) { + ++count; + if (i != 0 && grid[i - 1][j] == 1) { + ++repeat; + } + if (j != 0 && grid[i][j - 1] == 1) { + ++repeat; + } + } + } + } + return 4 * count - 2 * repeat; + } +}; From e72327a7a20be6b1b10f72fb7720578263236dbb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 00:40:40 +0800 Subject: [PATCH 3038/4971] Create island-perimeter.py --- Python/island-perimeter.py | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/island-perimeter.py diff --git a/Python/island-perimeter.py b/Python/island-perimeter.py new file mode 100644 index 000000000..bf402961d --- /dev/null +++ b/Python/island-perimeter.py @@ -0,0 +1,41 @@ +# Time: O(m * n) +# Space: O(1) + +# You are given a map in form of a two-dimensional integer grid +# where 1 represents land and 0 represents water. +# Grid cells are connected horizontally/vertically (not diagonally). +# The grid is completely surrounded by water, and there is exactly one island +# (i.e., one or more connected land cells). +# The island doesn't have "lakes" (water inside that isn't connected to +# the water around the island). One cell is a square with side length 1. +# The grid is rectangular, width and height don't exceed 100. +# Determine the perimeter of the island. +# +# Example: +# +# [[0,1,0,0], +# [1,1,1,0], +# [0,1,0,0], +# [1,1,0,0]] +# +# Answer: 16 + + +class Solution(object): + def islandPerimeter(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + count, repeat = 0, 0 + + for i in xrange(len(grid)): + for j in xrange(len(grid[i])): + if grid[i][j] == 1: + count += 1 + if i != 0 and grid[i - 1][j] == 1: + repeat += 1 + if j != 0 and grid[i][j - 1] == 1: + repeat += 1 + + return 4*count - 2*repeat From ed803efde656929859b38269644ca5b07cc43854 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 01:17:25 +0800 Subject: [PATCH 3039/4971] Create can-i-win.py --- Python/can-i-win.py | 60 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/can-i-win.py diff --git a/Python/can-i-win.py b/Python/can-i-win.py new file mode 100644 index 000000000..1877b04e9 --- /dev/null +++ b/Python/can-i-win.py @@ -0,0 +1,60 @@ +# Time: O(n!) +# Space: O(n) + +# In the "100 game," two players take turns adding, to a running total, any integer from 1..10. +# The player who first causes the running total to reach or exceed 100 wins. +# +# What if we change the game so that players cannot re-use integers? +# +# For example, two players might take turns drawing from a common pool of numbers of 1..15 +# without replacement until they reach a total >= 100. +# +# Given an integer maxChoosableInteger and another integer desiredTotal, +# determine if the first player to move can force a win, assuming both players play optimally. +# +# You can always assume that maxChoosableInteger will not be larger than 20 and +# desiredTotal will not be larger than 300. +# +# Example +# +# Input: +# maxChoosableInteger = 10 +# desiredTotal = 11 +# +# Output: +# false +# +# Explanation: +# No matter which integer the first player choose, the first player will lose. +# The first player can choose an integer from 1 up to 10. +# If the first player choose 1, the second player can only choose integers from 2 up to 10. +# The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal. +# Same with other integers chosen by the first player, the second player will always win. + +# Memoization solution. +class Solution(object): + def canIWin(self, maxChoosableInteger, desiredTotal): + """ + :type maxChoosableInteger: int + :type desiredTotal: int + :rtype: bool + """ + def canIWinHelper(maxChoosableInteger, desiredTotal, visited, lookup): + if visited in lookup: + return lookup[visited] + + mask = 1 + for i in xrange(maxChoosableInteger): + if visited & mask == 0: + if i + 1 >= desiredTotal or \ + not canIWinHelper(maxChoosableInteger, desiredTotal - (i + 1), visited | mask, lookup): + lookup[visited] = True + return True + mask <<= 1 + lookup[visited] = False + return False + + if (1 + maxChoosableInteger) * (maxChoosableInteger / 2) < desiredTotal: + return False + + return canIWinHelper(maxChoosableInteger, desiredTotal, 0, {}) From 1dc0dcdf595899df3ee592865c4a21007b7fa26b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 01:27:31 +0800 Subject: [PATCH 3040/4971] Create can-i-win.cpp --- C++/can-i-win.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/can-i-win.cpp diff --git a/C++/can-i-win.cpp b/C++/can-i-win.cpp new file mode 100644 index 000000000..4906b6232 --- /dev/null +++ b/C++/can-i-win.cpp @@ -0,0 +1,35 @@ +// Time: O(n!) +// Space: O(n) + +class Solution { +public: + bool canIWin(int maxChoosableInteger, int desiredTotal) { + if ((1 + maxChoosableInteger) * (maxChoosableInteger / 2) < desiredTotal) { + return false; + } + unordered_map lookup; + return canIWinHelper(maxChoosableInteger, desiredTotal, 0, &lookup); + } + +private: + int canIWinHelper(int maxChoosableInteger, int desiredTotal, + int visited, unordered_map *lookup) { + + if (lookup->find(visited) != lookup->end()) { + return (*lookup)[visited]; + } + int mask = 1; + for (int i = 0; i < maxChoosableInteger; ++i) { + if (!(visited & mask)) { + if (i + 1 >= desiredTotal || + !canIWinHelper(maxChoosableInteger, desiredTotal - (i + 1), visited | mask, lookup)) { + (*lookup)[visited] = true; + return true; + } + } + mask <<= 1; + } + (*lookup)[visited] = false; + return false; + } +}; From b988f022d83cbf54e523749a587dff841b6f8f6a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 20:59:27 +0800 Subject: [PATCH 3041/4971] Create optimal-account-balancing.cpp --- C++/optimal-account-balancing.cpp | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 C++/optimal-account-balancing.cpp diff --git a/C++/optimal-account-balancing.cpp b/C++/optimal-account-balancing.cpp new file mode 100644 index 000000000..01b133c79 --- /dev/null +++ b/C++/optimal-account-balancing.cpp @@ -0,0 +1,48 @@ +// Time: O(2^n), n is the size of debt. +// Space: O(2^n) + +class Solution { +public: + int minTransfers(vector>& transactions) { + unordered_map account; + for (const auto& transaction: transactions) { + account[transaction[0]] += transaction[2]; + account[transaction[1]] -= transaction[2]; + } + + vector debt; + for (const auto& kvp: account) { + if (kvp.second) { + debt.emplace_back(kvp.second); + } + } + if (debt.empty()) { + return 0; + } + + const auto n = 1 << debt.size(); + vector dp(n, numeric_limits::max()), subset; + for (int i = 1; i < n; ++i) { + int net_debt = 0, number = 0; + for (int j = 0; j < debt.size(); ++j) { + if (i & 1 << j) { + net_debt += debt[j]; + ++number; + } + } + if (net_debt == 0) { + dp[i] = number - 1; + for (const auto& s: subset) { + if ((i & s) == s) { + if (dp[s] != numeric_limits::max() && + dp[i - s] != numeric_limits::max()) { + dp[i] = min(dp[i], dp[s] + dp[i - s]); + } + } + } + subset.emplace_back(i); + } + } + return dp.back(); + } +}; From 9d54a632ad38a79ab1d51827c41dea756004898f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 21:04:58 +0800 Subject: [PATCH 3042/4971] Update optimal-account-balancing.cpp --- C++/optimal-account-balancing.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/optimal-account-balancing.cpp b/C++/optimal-account-balancing.cpp index 01b133c79..581372047 100644 --- a/C++/optimal-account-balancing.cpp +++ b/C++/optimal-account-balancing.cpp @@ -5,13 +5,13 @@ class Solution { public: int minTransfers(vector>& transactions) { unordered_map account; - for (const auto& transaction: transactions) { + for (const auto& transaction : transactions) { account[transaction[0]] += transaction[2]; account[transaction[1]] -= transaction[2]; } vector debt; - for (const auto& kvp: account) { + for (const auto& kvp : account) { if (kvp.second) { debt.emplace_back(kvp.second); } From e7c330b26c4e4a6e574f39e1d43a92516b591d1b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 21:09:06 +0800 Subject: [PATCH 3043/4971] Update optimal-account-balancing.cpp --- C++/optimal-account-balancing.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/optimal-account-balancing.cpp b/C++/optimal-account-balancing.cpp index 581372047..31fb3648e 100644 --- a/C++/optimal-account-balancing.cpp +++ b/C++/optimal-account-balancing.cpp @@ -32,7 +32,7 @@ class Solution { } if (net_debt == 0) { dp[i] = number - 1; - for (const auto& s: subset) { + for (const auto& s : subset) { if ((i & s) == s) { if (dp[s] != numeric_limits::max() && dp[i - s] != numeric_limits::max()) { From c05ddab0854ee3d0f51562a5af11e7d99d05ac4a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 21:09:43 +0800 Subject: [PATCH 3044/4971] Create optimal-account-balancing.py --- Python/optimal-account-balancing.py | 38 +++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/optimal-account-balancing.py diff --git a/Python/optimal-account-balancing.py b/Python/optimal-account-balancing.py new file mode 100644 index 000000000..11edb2a34 --- /dev/null +++ b/Python/optimal-account-balancing.py @@ -0,0 +1,38 @@ +# Time: O(2^n), n is the size of debt. +# Space: O(2^n) + +class Solution(object): + def minTransfers(self, transactions): + """ + :type transactions: List[List[int]] + :rtype: int + """ + account = collections.defaultdict(int) + for transaction in transactions: + account[transaction[0]] += transaction[2] + account[transaction[1]] -= transaction[2] + + debt = [] + for v in account.values(): + if v: + debt.append(v) + + if not debt: + return 0 + + n = 1 << len(debt) + dp, subset = [float("inf")] * n, [] + for i in xrange(1, n): + net_debt, number = 0, 0 + for j in xrange(len(debt)): + if i & 1 << j: + net_debt += debt[j] + number += 1 + + if net_debt == 0: + dp[i] = number - 1 + for s in subset: + if (i & s) == s: + dp[i] = min(dp[i], dp[s] + dp[i - s]) + subset.append(i) + return dp[-1] From 44d8512ee638981deaccb2583ad70e0850fe15eb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 21:10:31 +0800 Subject: [PATCH 3045/4971] Update optimal-account-balancing.py --- Python/optimal-account-balancing.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/optimal-account-balancing.py b/Python/optimal-account-balancing.py index 11edb2a34..72dbac12c 100644 --- a/Python/optimal-account-balancing.py +++ b/Python/optimal-account-balancing.py @@ -28,7 +28,6 @@ def minTransfers(self, transactions): if i & 1 << j: net_debt += debt[j] number += 1 - if net_debt == 0: dp[i] = number - 1 for s in subset: From fc78d2a952a23e0d1e2148200e70116f59e9d277 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 21:40:53 +0800 Subject: [PATCH 3046/4971] Update optimal-account-balancing.cpp --- C++/optimal-account-balancing.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/optimal-account-balancing.cpp b/C++/optimal-account-balancing.cpp index 31fb3648e..32aa0826d 100644 --- a/C++/optimal-account-balancing.cpp +++ b/C++/optimal-account-balancing.cpp @@ -1,5 +1,5 @@ -// Time: O(2^n), n is the size of debt. -// Space: O(2^n) +// Time: O(n*2^n), n is the size of debt. +// Space: O(n*2^n) class Solution { public: From 4f62afa0a99b34686c31bc09d9ca7fe22ff00c2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 21:41:18 +0800 Subject: [PATCH 3047/4971] Update optimal-account-balancing.cpp --- C++/optimal-account-balancing.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/optimal-account-balancing.cpp b/C++/optimal-account-balancing.cpp index 32aa0826d..ec33dedef 100644 --- a/C++/optimal-account-balancing.cpp +++ b/C++/optimal-account-balancing.cpp @@ -1,5 +1,5 @@ -// Time: O(n*2^n), n is the size of debt. -// Space: O(n*2^n) +// Time: O(n * 2^n), n is the size of the debt. +// Space: O(n * 2^n) class Solution { public: From 77dafd85fe24c3620284cce5e56c26382d37ff3a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Dec 2016 21:41:42 +0800 Subject: [PATCH 3048/4971] Update optimal-account-balancing.py --- Python/optimal-account-balancing.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/optimal-account-balancing.py b/Python/optimal-account-balancing.py index 72dbac12c..4d409c853 100644 --- a/Python/optimal-account-balancing.py +++ b/Python/optimal-account-balancing.py @@ -1,5 +1,5 @@ -# Time: O(2^n), n is the size of debt. -# Space: O(2^n) +# Time: O(n * 2^n), n is the size of the debt. +# Space: O(n * 2^n) class Solution(object): def minTransfers(self, transactions): From 2987bfbe0dcfc8d742c061bb55512a91ff7e0647 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Dec 2016 22:30:22 +0800 Subject: [PATCH 3049/4971] Update shortest-word-distance-iii.py --- Python/shortest-word-distance-iii.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/shortest-word-distance-iii.py b/Python/shortest-word-distance-iii.py index d0ba8d235..021aea8f7 100644 --- a/Python/shortest-word-distance-iii.py +++ b/Python/shortest-word-distance-iii.py @@ -8,10 +8,11 @@ class Solution: # @return {integer} def shortestWordDistance(self, words, word1, word2): dist = float("inf") + is_same = (word1 == word2) i, index1, index2 = 0, None, None while i < len(words): if words[i] == word1: - if index1 is not None: + if is_same and index1 is not None: dist = min(dist, abs(index1 - i)) index1 = i elif words[i] == word2: From fe55698c05cb98a975a27b30f6b101ad91af2fea Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Dec 2016 22:31:57 +0800 Subject: [PATCH 3050/4971] Update shortest-word-distance-iii.cpp --- C++/shortest-word-distance-iii.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/shortest-word-distance-iii.cpp b/C++/shortest-word-distance-iii.cpp index 6c8a60392..6043f572f 100644 --- a/C++/shortest-word-distance-iii.cpp +++ b/C++/shortest-word-distance-iii.cpp @@ -5,9 +5,10 @@ class Solution { public: int shortestWordDistance(vector& words, string word1, string word2) { int dist = INT_MAX; + bool is_same = (word1 == word2); for (int i = 0, index1 = -1, index2 = -1; i < words.size(); ++i) { if (words[i] == word1) { - if (index1 != -1) { + if (is_same && index1 != -1) { dist = min(dist, abs(index1 - i)); } index1 = i; From e289705884a8bd9b43b31e92003c035792105c6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 12:42:49 +0800 Subject: [PATCH 3051/4971] Create hamming-distance.cpp --- C++/hamming-distance.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 C++/hamming-distance.cpp diff --git a/C++/hamming-distance.cpp b/C++/hamming-distance.cpp new file mode 100644 index 000000000..c3d858fab --- /dev/null +++ b/C++/hamming-distance.cpp @@ -0,0 +1,11 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int hammingDistance(int x, int y) { + int distance = 0; + for (int z = x ^ y; z; z &= z - 1, ++distance); + return distance; + } +}; From f9d8daed10790ad488409f3e24b1c7fb34ad0317 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 12:44:27 +0800 Subject: [PATCH 3052/4971] Update hamming-distance.cpp --- C++/hamming-distance.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/C++/hamming-distance.cpp b/C++/hamming-distance.cpp index c3d858fab..32424d864 100644 --- a/C++/hamming-distance.cpp +++ b/C++/hamming-distance.cpp @@ -5,7 +5,9 @@ class Solution { public: int hammingDistance(int x, int y) { int distance = 0; - for (int z = x ^ y; z; z &= z - 1, ++distance); + for (int z = x ^ y; z; z &= z - 1) { + ++distance; + } return distance; } }; From 9e44778e09ec597659f78d4c8ac2403b6e700d96 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 12:46:01 +0800 Subject: [PATCH 3053/4971] Create hamming-distance.py --- Python/hamming-distance.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/hamming-distance.py diff --git a/Python/hamming-distance.py b/Python/hamming-distance.py new file mode 100644 index 000000000..1c0b7ad52 --- /dev/null +++ b/Python/hamming-distance.py @@ -0,0 +1,37 @@ +# Time: O(1) +# Space: O(1) + +# The Hamming distance between two integers is the number of positions +# at which the corresponding bits are different. +# +# Given two integers x and y, calculate the Hamming distance. +# +# Note: +# 0 ≤ x, y < 231. +# +# Example: +# +# Input: x = 1, y = 4 +# +# Output: 2 +# +# Explanation: +# 1 (0 0 0 1) +# 4 (0 1 0 0) +# ↑ ↑ +# +# The above arrows point to positions where the corresponding bits are different. + +class Solution(object): + def hammingDistance(self, x, y): + """ + :type x: int + :type y: int + :rtype: int + """ + distance = 0 + z = x^y + while z: + distance += 1 + z &= z-1 + return distance From 45482ae24d8b465bd0e3f4732f55d8f3c5e81aff Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 13:38:24 +0800 Subject: [PATCH 3054/4971] Create count-the-repetitions.cpp --- C++/count-the-repetitions.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/count-the-repetitions.cpp diff --git a/C++/count-the-repetitions.cpp b/C++/count-the-repetitions.cpp new file mode 100644 index 000000000..2143fe51d --- /dev/null +++ b/C++/count-the-repetitions.cpp @@ -0,0 +1,30 @@ +// Time: O(s1 * n1) +// Space: O(s2) + +class Solution { +public: + int getMaxRepetitions(string s1, int n1, string s2, int n2) { + vector repeatCount(s2.size() + 1, 0); + unordered_map lookup; + int j = 0, count = 0; + for (int k = 1; k <= n1; ++k) { + for (int i = 0; i < s1.size(); ++i) { + if (s1[i] == s2[j]) { + j = (j + 1) % s2.size(); + count += (j == 0); + } + } + repeatCount[k] = count; + + if (lookup.find(j) != lookup.end()) { // cyclic + int i = lookup[j]; + int prefixCount = repeatCount[i]; + int patternCount = (repeatCount[k] - repeatCount[i]) * ((n1 - i) / (k - i)); + int suffixCount = repeatCount[i + (n1 - i) % (k - i)] - repeatCount[i]; + return (prefixCount + patternCount + suffixCount) / n2; + } + lookup[j] = k; + } + return repeatCount[n1] / n2; // not cyclic iff n1 <= s2 + } +}; From 559735bb63ec433cb63882e3d6281e36e69f0848 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 13:55:52 +0800 Subject: [PATCH 3055/4971] Update count-the-repetitions.cpp --- C++/count-the-repetitions.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/count-the-repetitions.cpp b/C++/count-the-repetitions.cpp index 2143fe51d..031653cf1 100644 --- a/C++/count-the-repetitions.cpp +++ b/C++/count-the-repetitions.cpp @@ -14,16 +14,16 @@ class Solution { count += (j == 0); } } - repeatCount[k] = count; if (lookup.find(j) != lookup.end()) { // cyclic int i = lookup[j]; int prefixCount = repeatCount[i]; - int patternCount = (repeatCount[k] - repeatCount[i]) * ((n1 - i) / (k - i)); + int patternCount = (count - repeatCount[i]) * ((n1 - i) / (k - i)); int suffixCount = repeatCount[i + (n1 - i) % (k - i)] - repeatCount[i]; return (prefixCount + patternCount + suffixCount) / n2; } lookup[j] = k; + repeatCount[k] = count; } return repeatCount[n1] / n2; // not cyclic iff n1 <= s2 } From 1250747f2719d2679b4ef7e1dc5863b83e6ed3a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 13:57:52 +0800 Subject: [PATCH 3056/4971] Create count-the-repetitions.py --- Python/count-the-repetitions.py | 51 +++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/count-the-repetitions.py diff --git a/Python/count-the-repetitions.py b/Python/count-the-repetitions.py new file mode 100644 index 000000000..e75583943 --- /dev/null +++ b/Python/count-the-repetitions.py @@ -0,0 +1,51 @@ +# Time: O(s1 * n1) +# Space: O(s2) + +# Define S = [s,n] as the string S which consists of n connected strings s. +# For example, ["abc", 3] ="abcabcabc". +# +# On the other hand, we define that string s1 can be obtained from string s2 +# if we can remove some characters from s2 such that it becomes s1. +# For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”. +# +# You are given two non-empty strings s1 and s2 (each at most 100 characters long) +# and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106. Now consider the strings S1 and S2, +# where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1. +# +# Example: +# +# Input: +# s1="acb", n1=4 +# s2="ab", n2=2 +# +# Return: +# 2 + +class Solution(object): + def getMaxRepetitions(self, s1, n1, s2, n2): + """ + :type s1: str + :type n1: int + :type s2: str + :type n2: int + :rtype: int + """ + repeat_count = [0] * (len(s2)+1) + lookup = {} + j, count = 0, 0 + for k in xrange(1, n1+1): + for i in xrange(len(s1)): + if s1[i] == s2[j]: + j = (j + 1) % len(s2) + count += (j == 0) + + if j in lookup: # cyclic + i = lookup[j] + prefix_count = repeat_count[i] + pattern_count = (count - repeat_count[i]) * ((n1 - i) // (k - i)) + suffix_count = repeat_count[i + (n1 - i) % (k - i)] - repeat_count[i] + return (prefix_count + pattern_count + suffix_count) / n2 + lookup[j] = k + repeat_count[k] = count + + return repeat_count[n1] / n2 # not cyclic iff n1 <= s2 From 1ea43661664cadb1b00c66a5d92bd1479850e5f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 14:00:43 +0800 Subject: [PATCH 3057/4971] Update count-the-repetitions.cpp --- C++/count-the-repetitions.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/count-the-repetitions.cpp b/C++/count-the-repetitions.cpp index 031653cf1..feb30272f 100644 --- a/C++/count-the-repetitions.cpp +++ b/C++/count-the-repetitions.cpp @@ -1,4 +1,4 @@ -// Time: O(s1 * n1) +// Time: O(s1 * min(s2, n1)) // Space: O(s2) class Solution { From 818e8b0f788c660a8f143444efb1ca18ee0aede7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 14:01:03 +0800 Subject: [PATCH 3058/4971] Update count-the-repetitions.py --- Python/count-the-repetitions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/count-the-repetitions.py b/Python/count-the-repetitions.py index e75583943..eeaee7b70 100644 --- a/Python/count-the-repetitions.py +++ b/Python/count-the-repetitions.py @@ -1,4 +1,4 @@ -# Time: O(s1 * n1) +# Time: O(s1 * min(s2, n1)) # Space: O(s2) # Define S = [s,n] as the string S which consists of n connected strings s. From 982aa8ed54267bff33d58a3126b55a4c4bc448de Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 14:24:52 +0800 Subject: [PATCH 3059/4971] Create unique-substrings-in-wraparound-string.py --- .../unique-substrings-in-wraparound-string.py | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/unique-substrings-in-wraparound-string.py diff --git a/Python/unique-substrings-in-wraparound-string.py b/Python/unique-substrings-in-wraparound-string.py new file mode 100644 index 000000000..33d6c3347 --- /dev/null +++ b/Python/unique-substrings-in-wraparound-string.py @@ -0,0 +1,45 @@ +# Time: O(n) +# Space: O(1) + +# Consider the string s to be the infinite wraparound string of +# "abcdefghijklmnopqrstuvwxyz", so s will look like this: +# "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". +# +# Now we have another string p. Your job is to find out +# how many unique non-empty substrings of p are present in s. +# In particular, your input is the string p and you need to output +# the number of different non-empty substrings of p in the string s. +# +# Note: p consists of only lowercase English letters and the size of p might be over 10000. +# +# Example 1: +# Input: "a" +# Output: 1 +# +# Explanation: Only the substring "a" of string "a" is in the string s. +# Example 2: +# Input: "cac" +# Output: 2 +# Explanation: There are two substrings "a", "c" of string "cac" in the string s. +# Example 3: +# Input: "zab" +# Output: 6 +# Explanation: There are six substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in the string s. + +class Solution(object): + def findSubstringInWraproundString(self, p): + """ + :type p: str + :rtype: int + """ + letters = [0] * 26 + result, length = 0, 0 + for i in xrange(len(p)): + curr = ord(p[i]) - ord('a') + if i > 0 and ord(p[i-1]) != (curr-1)%26 + ord('a'): + length = 0 + length += 1 + if length > letters[curr]: + result += length - letters[curr] + letters[curr] = length + return result From 543aa7d16ce712409784e28018c9242c27e0cff6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 14:25:48 +0800 Subject: [PATCH 3060/4971] Create unique-substrings-in-wraparound-string.cpp --- ...unique-substrings-in-wraparound-string.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/unique-substrings-in-wraparound-string.cpp diff --git a/C++/unique-substrings-in-wraparound-string.cpp b/C++/unique-substrings-in-wraparound-string.cpp new file mode 100644 index 000000000..dd4f847b7 --- /dev/null +++ b/C++/unique-substrings-in-wraparound-string.cpp @@ -0,0 +1,21 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findSubstringInWraproundString(string p) { + vector letters(26, 0); + int result = 0, len = 0; + for (int i = 0; i < p.length(); ++i) { + int curr = p[i] - 'a'; + if (i > 0 && p[i - 1] != (curr + 26 - 1) % 26 + 'a') { + len = 0; + } + if (++len > letters[curr]) { + result += len - letters[curr]; + letters[curr] = len; + } + } + return result; + } +}; From a2b7248fec950ce3d33bad598c9fbd4e9acf9a21 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 14:55:25 +0800 Subject: [PATCH 3061/4971] Create validate-ip-address.py --- Python/validate-ip-address.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/validate-ip-address.py diff --git a/Python/validate-ip-address.py b/Python/validate-ip-address.py new file mode 100644 index 000000000..06904a4dd --- /dev/null +++ b/Python/validate-ip-address.py @@ -0,0 +1,26 @@ +# Time: O(1) +# Space: O(1) + +class Solution(object): + def validIPAddress(self, IP): + """ + :type IP: str + :rtype: str + """ + blocks = IP.split('.') + if len(blocks) == 4: + for i in xrange(len(blocks)): + if not blocks[i].isdigit() or not 0 <= int(blocks[i]) < 256 or \ + (blocks[i][0] == '0' and len(blocks[i]) > 1): + return "Neither" + return "IPv4" + + blocks = IP.split(':') + if len(blocks) == 8: + for i in xrange(len(blocks)): + if not (1 <= len(blocks[i]) <= 4) or \ + not all(c in string.hexdigits for c in blocks[i]): + return "Neither" + return "IPv6" + return "Neither" + From 343af7b196021e4e3d7fe23f71218afc96c9ab87 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 14:57:51 +0800 Subject: [PATCH 3062/4971] Create validate-ip-address.cpp --- C++/validate-ip-address.cpp | 62 +++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 C++/validate-ip-address.cpp diff --git a/C++/validate-ip-address.cpp b/C++/validate-ip-address.cpp new file mode 100644 index 000000000..936451682 --- /dev/null +++ b/C++/validate-ip-address.cpp @@ -0,0 +1,62 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + string validIPAddress(string IP) { + stringstream ss(IP); + string block; + if (IP.substr(0, 4).find('.') != string::npos) { + for (int i = 0; i < 4; ++i) { + if (!getline(ss, block, '.') || !isValidIPv4Block(block)) { + return "Neither"; + } + } + if (ss.eof()) { + return "IPv4"; + } + } else if (IP.substr(0, 5).find(':') != string::npos) { + for (int i = 0; i < 8; ++i) { + if (!getline(ss, block, ':') || !isValidIPv6Block(block)) { + return "Neither"; + } + } + if (ss.eof()) { + return "IPv6"; + } + } + + return "Neither"; + } + +private: + bool isValidIPv4Block(const string& block) { + int num = 0; + if (block.size() > 0 && block.size() <= 3) { + for (int i = 0; i < block.size(); ++i) { + char c = block[i]; + if (!isalnum(c) || (i == 0 && c == '0' && block.size() > 1)) { + return false; + } else { + num *= 10; + num += c - '0'; + } + } + return num <= 255; + } + return false; + } + + bool isValidIPv6Block(const string& block) { + if (block.size() > 0 && block.size() <= 4) { + for (int i = 0; i < block.size(); ++i) { + char c = block[i]; + if (!isxdigit(c)) { + return false; + } + } + return true; + } + return false; + } +}; From 93dcfc61f4fa74b149e769649c8e5ad08dbede07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 14:59:51 +0800 Subject: [PATCH 3063/4971] Update validate-ip-address.py --- Python/validate-ip-address.py | 46 ++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/Python/validate-ip-address.py b/Python/validate-ip-address.py index 06904a4dd..50be7762d 100644 --- a/Python/validate-ip-address.py +++ b/Python/validate-ip-address.py @@ -1,6 +1,51 @@ # Time: O(1) # Space: O(1) +# In this problem, your job to write a function to check whether a input string +# is a valid IPv4 address or IPv6 address or neither. +# +# IPv4 addresses are canonically represented in dot-decimal notation, +# which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1; +# +# Besides, you need to keep in mind that leading zeros in the IPv4 is illegal. +# For example, the address 172.16.254.01 is illegal. +# +# IPv6 addresses are represented as eight groups of four hexadecimal digits, +# each group representing 16 bits. The groups are separated by colons (":"). +# For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a legal one. +# Also, we could omit some leading zeros among four hexadecimal digits and +# some low-case characters in the address to upper-case ones, +# so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases). +# +# However, we don't replace a consecutive group of zero value with a single empty group +# using two consecutive colons (::) to pursue simplicity. +# For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address. +# +# Besides, you need to keep in mind that extra leading zeros in the IPv6 is also illegal. +# For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is also illegal. +# +# Note: You could assume there is no extra space in the test cases and +# there may some special characters in the input string. +# +# Example 1: +# Input: "172.16.254.1" +# +# Output: "IPv4" +# +# Explanation: This is a valid IPv4 address, return "IPv4". +# Example 2: +# Input: "2001:0db8:85a3:0:0:8A2E:0370:7334" +# +# Output: "IPv6" +# +# Explanation: This is a valid IPv6 address, return "IPv6". +# Example 3: +# Input: "256.256.256.256" +# +# Output: "Neither" +# +# Explanation: This is neither a IPv4 address nor a IPv6 address. + class Solution(object): def validIPAddress(self, IP): """ @@ -23,4 +68,3 @@ def validIPAddress(self, IP): return "Neither" return "IPv6" return "Neither" - From cce60c462b855030a69f48278174fb9638036266 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 15:20:03 +0800 Subject: [PATCH 3064/4971] Create convex-polygon.cpp --- C++/convex-polygon.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/convex-polygon.cpp diff --git a/C++/convex-polygon.cpp b/C++/convex-polygon.cpp new file mode 100644 index 000000000..3582c3fdb --- /dev/null +++ b/C++/convex-polygon.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool isConvex(vector>& points) { + const auto det = [](const vector>& A) { + return A[0][0]*A[1][1] - A[0][1]*A[1][0]; + }; + long n = points.size(), prev = 0, curr; + for (int i = 0; i < n; ++i) { + vector> A; + for (int j = 1; j < 3; ++j) { + A.push_back({points[(i + j) % n][0] - points[i][0], points[(i + j) % n][1] - points[i][1]}); + } + if (curr = det(A)) { + if (curr * prev < 0) { + return false; + } + prev = curr; + } + } + return true; + } +}; From 623caf0b34941e1ccf44dfdd32437875d3902e20 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 15:52:20 +0800 Subject: [PATCH 3065/4971] Create convex-polygon.py --- Python/convex-polygon.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Python/convex-polygon.py diff --git a/Python/convex-polygon.py b/Python/convex-polygon.py new file mode 100644 index 000000000..27286efd6 --- /dev/null +++ b/Python/convex-polygon.py @@ -0,0 +1,22 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def isConvex(self, points): + """ + :type points: List[List[int]] + :rtype: bool + """ + def det(A): + return A[0][0]*A[1][1] - A[0][1]*A[1][0] + + n, prev, curr = len(points), 0, None + for i in xrange(len(points)): + A = [[points[(i+j) % n][0] - points[i][0], points[(i+j) % n][1] - points[i][1]] for j in (1, 2)] + curr = det(A) + if curr: + if curr * prev < 0: + return False + prev = curr + return True + From 70e3b342570d4a1f3249ade53c934f1f5333d30f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 16:30:57 +0800 Subject: [PATCH 3066/4971] Create encode-string-with-shortest-length.cpp --- C++/encode-string-with-shortest-length.cpp | 35 ++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/encode-string-with-shortest-length.cpp diff --git a/C++/encode-string-with-shortest-length.cpp b/C++/encode-string-with-shortest-length.cpp new file mode 100644 index 000000000..44c312b7e --- /dev/null +++ b/C++/encode-string-with-shortest-length.cpp @@ -0,0 +1,35 @@ +// Time: O(n^3) on average +// Space: O(n^2) + +class Solution { +public: + string encode(string s) { + vector> dp(s.length(), vector(s.length())); + for (int len = 1; len <= s.length(); ++len) { + for (int i = 0; i + len - 1 < s.length(); ++i) { + int j = i + len - 1; + dp[i][j] = s.substr(i, len); + for (int k = i; k < j; ++k) { + if (dp[i][k].length() + dp[k + 1][j].length() < dp[i][j].length()) { + dp[i][j] = dp[i][k] + dp[k + 1][j]; + } + } + string encoded_string = encode_substr(dp, s, i, j); + if (encoded_string.length() < dp[i][j].length()) { + dp[i][j] = encoded_string; + } + } + } + return dp[0][s.length() - 1]; + } + +private: + string encode_substr(const vector>& dp, const string& s, int i, int j) { + string temp = s.substr(i, j - i + 1); + auto pos = (temp + temp).find(temp, 1); // O(n) on average + if (pos >= temp.length()) { + return temp; + } + return to_string(temp.length() / pos) + '[' + dp[i][i + pos - 1] + ']'; + } +}; From 8782811e1ebca43dabe9e7619ad907ef028b3def Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 16:47:47 +0800 Subject: [PATCH 3067/4971] Create encode-string-with-shortest-length.py --- Python/encode-string-with-shortest-length.py | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Python/encode-string-with-shortest-length.py diff --git a/Python/encode-string-with-shortest-length.py b/Python/encode-string-with-shortest-length.py new file mode 100644 index 000000000..6988e6d4c --- /dev/null +++ b/Python/encode-string-with-shortest-length.py @@ -0,0 +1,28 @@ +# Time: O(n^3) on average +# Space: O(n^2) + +class Solution(object): + def encode(self, s): + """ + :type s: str + :rtype: str + """ + def encode_substr(dp, s, i, j): + temp = s[i:j+1] + pos = (temp + temp).find(temp, 1) # O(n) on average + if pos >= len(temp): + return temp + return str(len(temp)/pos) + '[' + dp[i][i + pos - 1] + ']' + + dp = [["" for _ in xrange(len(s))] for _ in xrange(len(s))] + for length in xrange(1, len(s)+1): + for i in xrange(len(s)+1-length): + j = i+length-1 + dp[i][j] = s[i:i+length] + for k in xrange(i, j): + if len(dp[i][k]) + len(dp[k+1][j]) < len(dp[i][j]): + dp[i][j] = dp[i][k] + dp[k+1][j] + encoded_string = encode_substr(dp, s, i, j) + if len(encoded_string) < len(dp[i][j]): + dp[i][j] = encoded_string + return dp[0][len(s) - 1] From 93470c2dc297e34a53640053c69f7eb224b89fc3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 16:59:17 +0800 Subject: [PATCH 3068/4971] Create concatenated-words.cpp --- C++/concatenated-words.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/concatenated-words.cpp diff --git a/C++/concatenated-words.cpp b/C++/concatenated-words.cpp new file mode 100644 index 000000000..ecb47e897 --- /dev/null +++ b/C++/concatenated-words.cpp @@ -0,0 +1,29 @@ +// Time: O(n * l^2) +// Space: O(n * l) + +class Solution { +public: + vector findAllConcatenatedWordsInADict(vector& words) { + unordered_set lookup(words.begin(), words.end()); + vector result; + for (const auto& word : words) { + vector dp(word.length() + 1); + dp[0] = true; + for (int i = 0; i < word.length(); ++i) { + if (!dp[i]) { + continue; + } + for (int j = i + 1; j <= word.length(); ++j) { + if (j - i < word.length() && lookup.count(word.substr(i, j - i))) { + dp[j] = true; + } + } + if (dp[word.length()]) { + result.emplace_back(word); + break; + } + } + } + return result; + } +}; From 7690f0e59ffd037e8da1561bd7694aca8b93b234 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 17:09:36 +0800 Subject: [PATCH 3069/4971] Create concatenated-words.py --- Python/concatenated-words.py | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/concatenated-words.py diff --git a/Python/concatenated-words.py b/Python/concatenated-words.py new file mode 100644 index 000000000..8d89f5e36 --- /dev/null +++ b/Python/concatenated-words.py @@ -0,0 +1,47 @@ +# Time: O(n * l^2) +# Space: O(n * l) + +# Given a list of words, please write a program that returns +# all concatenated words in the given list of words. +# +# A concatenated word is defined as a string that is comprised entirely of +# at least two shorter words in the given array. +# +# Example: +# Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] +# +# Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] +# +# Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; +# "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; +# "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". +# Note: +# The number of elements of the given array will not exceed 10,000 +# The length sum of elements in the given array will not exceed 600,000. +# All the input string will only include lower case letters. +# The returned elements order does not matter. + +class Solution(object): + def findAllConcatenatedWordsInADict(self, words): + """ + :type words: List[str] + :rtype: List[str] + """ + lookup = set(words) + result = [] + for word in words: + dp = [False] * (len(word)+1) + dp[0] = True + for i in xrange(len(word)): + if not dp[i]: + continue + + for j in xrange(i+1, len(word)+1): + if j - i < len(word) and word[i:j] in lookup: + dp[j] = True + + if dp[len(word)]: + result.append(word) + break + + return result From a30210a86c33f2212afa9939cafd36ea73ce93ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 20:26:57 +0800 Subject: [PATCH 3070/4971] Create matchsticks-to-square.cpp --- C++/matchsticks-to-square.cpp | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/matchsticks-to-square.cpp diff --git a/C++/matchsticks-to-square.cpp b/C++/matchsticks-to-square.cpp new file mode 100644 index 000000000..bcc9d4c83 --- /dev/null +++ b/C++/matchsticks-to-square.cpp @@ -0,0 +1,40 @@ +// Time: O(n * s * 2^n), s is the number of subset of which sum equals to side length. +// Space: O(n * (2^n + s)), + +class Solution { +public: + bool makesquare(vector& nums) { + int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum % 4) { + return false; + } + + const auto side_len = sum / 4; + const auto all = (1 << nums.size()) - 1; + + vector used_subsets; + vector valid_half_subsets(1 << nums.size()); + + for (int subset = 0; subset <= all; ++subset) { + int subset_sum = 0; + for (int i = 0; i < nums.size(); ++i) { + if (subset & (1 << i)) { + subset_sum += nums[i]; + } + } + if (subset_sum == side_len) { + for (const auto& used_subset : used_subsets) { + if ((used_subset & subset) == 0) { + int valid_half_subset = used_subset | subset; + valid_half_subsets[valid_half_subset] = true; + if (valid_half_subsets[all ^ valid_half_subset]) { + return true; + } + } + } + used_subsets.emplace_back(subset); + } + } + return false; + } +}; From 3c350f97921d55c32200b36965b1b56cd7e038cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 20:30:46 +0800 Subject: [PATCH 3071/4971] Update matchsticks-to-square.cpp --- C++/matchsticks-to-square.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/C++/matchsticks-to-square.cpp b/C++/matchsticks-to-square.cpp index bcc9d4c83..ef37a1f25 100644 --- a/C++/matchsticks-to-square.cpp +++ b/C++/matchsticks-to-square.cpp @@ -18,21 +18,21 @@ class Solution { for (int subset = 0; subset <= all; ++subset) { int subset_sum = 0; for (int i = 0; i < nums.size(); ++i) { - if (subset & (1 << i)) { - subset_sum += nums[i]; - } + if (subset & (1 << i)) { + subset_sum += nums[i]; + } } - if (subset_sum == side_len) { - for (const auto& used_subset : used_subsets) { - if ((used_subset & subset) == 0) { - int valid_half_subset = used_subset | subset; - valid_half_subsets[valid_half_subset] = true; - if (valid_half_subsets[all ^ valid_half_subset]) { - return true; - } - } + if (subset_sum == side_len) { + for (const auto& used_subset : used_subsets) { + if ((used_subset & subset) == 0) { + int valid_half_subset = used_subset | subset; + valid_half_subsets[valid_half_subset] = true; + if (valid_half_subsets[all ^ valid_half_subset]) { + return true; + } + } } - used_subsets.emplace_back(subset); + used_subsets.emplace_back(subset); } } return false; From d1271879cb1f912e52ec9ec5677cee01f066fc4c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 20:36:15 +0800 Subject: [PATCH 3072/4971] Update matchsticks-to-square.cpp --- C++/matchsticks-to-square.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/matchsticks-to-square.cpp b/C++/matchsticks-to-square.cpp index ef37a1f25..565a4211c 100644 --- a/C++/matchsticks-to-square.cpp +++ b/C++/matchsticks-to-square.cpp @@ -1,5 +1,5 @@ // Time: O(n * s * 2^n), s is the number of subset of which sum equals to side length. -// Space: O(n * (2^n + s)), +// Space: O(n * (2^n + s)) class Solution { public: From fb9116dc0a0bf1aa2cfba45424ac11ecb670ecd2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 20:37:37 +0800 Subject: [PATCH 3073/4971] Create matchsticks-to-square.py --- Python/matchsticks-to-square.py | 60 +++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/matchsticks-to-square.py diff --git a/Python/matchsticks-to-square.py b/Python/matchsticks-to-square.py new file mode 100644 index 000000000..9728cccff --- /dev/null +++ b/Python/matchsticks-to-square.py @@ -0,0 +1,60 @@ +# Time: O(n * s * 2^n), s is the number of subset of which sum equals to side length. +# Space: O(n * (2^n + s)) + +# Remember the story of Little Match Girl? By now, you know exactly +# what matchsticks the little match girl has, please find out a way +# you can make one square by using up all those matchsticks. +# You should not break any stick, but you can link them up, +# and each matchstick must be used exactly one time. +# +# Your input will be several matchsticks the girl has, +# represented with their stick length. +# Your output will either be true or false, +# to represent whether you could make one square using all the matchsticks the little match girl has. +# +# Example 1: +# Input: [1,1,2,2,2] +# Output: true +# +# Explanation: You can form a square with length 2, one side of the square came two sticks with length 1. +# Example 2: +# Input: [3,3,3,3,4] +# Output: false +# +# Explanation: You cannot find a way to form a square with all the matchsticks. +# Note: +# The length sum of the given matchsticks is in the range of 0 to 10^9. +# The length of the given matchstick array will not exceed 15. + +class Solution(object): + def makesquare(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + total_len = sum(nums) + if total_len % 4: + return False + + side_len = total_len / 4 + fullset = (1 << len(nums)) - 1 + + used_subsets = [] + valid_half_subsets = [0] * (1 << len(nums)) + + for subset in xrange(fullset+1): + subset_total_len = 0 + for i in xrange(len(nums)): + if subset & (1 << i): + subset_total_len += nums[i] + + if subset_total_len == side_len: + for used_subset in used_subsets: + if (used_subset & subset) == 0: + valid_half_subset = used_subset | subset + valid_half_subsets[valid_half_subset] = True + if valid_half_subsets[fullset ^ valid_half_subset]: + return True + used_subsets.append(subset) + + return False From c98b1ce474c458bc7b74e00b179f3bc8934a69a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 23:17:21 +0800 Subject: [PATCH 3074/4971] Create ones-and-zeroes.py --- Python/ones-and-zeroes.py | 48 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/ones-and-zeroes.py diff --git a/Python/ones-and-zeroes.py b/Python/ones-and-zeroes.py new file mode 100644 index 000000000..388bf960f --- /dev/null +++ b/Python/ones-and-zeroes.py @@ -0,0 +1,48 @@ +# Time: O(s * m * n), s is the size of the array. +# Space: O(m * n) + +# In the computer world, use restricted resource you have to +# generate maximum benefit is what we always want to pursue. +# +# For now, suppose you are a dominator of m 0s and n 1s respectively. +# On the other hand, there is an array with strings consisting of only 0s and 1s. +# +# Now your task is to find the maximum number of strings that you can form +# with given m 0s and n 1s. Each 0 and 1 can be used at most once. +# +# Note: +# The given numbers of 0s and 1s will both not exceed 100 +# The size of given string array won't exceed 600. +# Example 1: +# Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 +# Output: 4 +# +# Explanation: This are totally 4 strings can be formed +# by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0” +# Example 2: +# Input: Array = {"10", "0", "1"}, m = 1, n = 1 +# Output: 2 +# +# Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1". + +class Solution(object): + def findMaxForm(self, strs, m, n): + """ + :type strs: List[str] + :type m: int + :type n: int + :rtype: int + """ + dp = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)] + for s in strs: + zero_count, one_count = 0, 0 + for c in s: + if c == '0': + zero_count += 1 + elif c == '1': + one_count += 1 + + for i in reversed(xrange(zero_count, m+1)): + for j in reversed(xrange(one_count, n+1)): + dp[i][j] = max(dp[i][j], dp[i-zero_count][j-one_count]+1) + return dp[m][n] From 30a89e6f1235d0ac6b8374fef4903e97e85e280e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 23:18:02 +0800 Subject: [PATCH 3075/4971] Create ones-and-zeroes.cpp --- C++/ones-and-zeroes.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/ones-and-zeroes.cpp diff --git a/C++/ones-and-zeroes.cpp b/C++/ones-and-zeroes.cpp new file mode 100644 index 000000000..5abc12520 --- /dev/null +++ b/C++/ones-and-zeroes.cpp @@ -0,0 +1,26 @@ +// Time: O(s * m * n), s is the size of the array. +// Space: O(m * n) + +class Solution { +public: + int findMaxForm(vector& strs, int m, int n) { + vector> dp(m + 1, vector(n + 1)); + for (const auto &str : strs) { + int zero_count = 0, one_count = 0; + for (const auto& c : str) { + if (c == '0') { + ++zero_count; + } else if (c == '1') { + ++one_count; + } + } + + for (int i = m; i - zero_count >= 0; --i) { + for (int j = n; j - one_count >= 0; --j) { + dp[i][j] = max(dp[i][j], dp[i - zero_count][j - one_count] + 1); + } + } + } + return dp[m][n]; + } +}; From 4deef97889be7a97ea5ce217376ee1834228b2c5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 23:36:11 +0800 Subject: [PATCH 3076/4971] Create heaters.py --- Python/heaters.py | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/heaters.py diff --git a/Python/heaters.py b/Python/heaters.py new file mode 100644 index 000000000..65de830f7 --- /dev/null +++ b/Python/heaters.py @@ -0,0 +1,48 @@ +# Time: O((m + n) * logn), m is the number of the houses, n is the number of the heaters. +# Space: O(1) + +# Winter is coming! Your first job during the contest is to +# design a standard heater with fixed warm radius to warm all the houses. +# +# Now, you are given positions of houses and heaters on a horizontal line, +# find out minimum radius of heaters so that all houses could be covered by those heaters. +# +# So, your input will be the positions of houses and heaters seperately, +# and your expected output will be the minimum radius standard of heaters. +# +# Note: +# Numbers of houses and heaters you are given are non-negative and will not exceed 25000. +# Positions of houses and heaters you are given are non-negative and will not exceed 10^9. +# As long as a house is in the heaters' warm radius range, it can be warmed. +# All the heaters follow your radius standard and the warm radius will the same. +# Example 1: +# Input: [1,2,3],[2] +# Output: 1 +# Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, +# then all the houses can be warmed. +# Example 2: +# Input: [1,2,3,4],[1,4] +# Output: 1 +# Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, +# then all the houses can be warmed. + +class Solution(object): + def findRadius(self, houses, heaters): + """ + :type houses: List[int] + :type heaters: List[int] + :rtype: int + """ + heaters.sort() + min_radius = 0 + for house in houses: + equal_or_larger = bisect.bisect_left(heaters, house) + curr_radius = float("inf") + if equal_or_larger != len(heaters): + curr_radius = heaters[equal_or_larger] - house + if equal_or_larger != 0: + smaller = equal_or_larger-1 + curr_radius = min(curr_radius, house - heaters[smaller]) + min_radius = max(min_radius, curr_radius) + return min_radius + From d6ba0dd69e7c803e9faea080c83ad743fc1243da Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 23:36:48 +0800 Subject: [PATCH 3077/4971] Create heaters.cpp --- C++/heaters.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/heaters.cpp diff --git a/C++/heaters.cpp b/C++/heaters.cpp new file mode 100644 index 000000000..894800bea --- /dev/null +++ b/C++/heaters.cpp @@ -0,0 +1,23 @@ +// Time: O((m + n) * logn), m is the number of the houses, n is the number of the heaters. +// Space: O(1) + +class Solution { +public: + int findRadius(vector& houses, vector& heaters) { + sort(heaters.begin(), heaters.end()); + int min_radius = 0; + for (const auto& house : houses) { + auto equal_or_larger = lower_bound(heaters.cbegin(), heaters.cend(), house); + auto curr_radius = numeric_limits::max(); + if (equal_or_larger != heaters.cend()) { + curr_radius = *equal_or_larger - house; + } + if (equal_or_larger != heaters.cbegin()) { + auto smaller = prev(equal_or_larger); + curr_radius = min(curr_radius, house - *smaller); + } + min_radius = max(min_radius, curr_radius); + } + return min_radius; + } +}; From 1959a71da29fb22a49848207fa50141f697f8ac4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 23:55:38 +0800 Subject: [PATCH 3078/4971] Create total-hamming-distance.cpp --- C++/total-hamming-distance.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/total-hamming-distance.cpp diff --git a/C++/total-hamming-distance.cpp b/C++/total-hamming-distance.cpp new file mode 100644 index 000000000..1e029da58 --- /dev/null +++ b/C++/total-hamming-distance.cpp @@ -0,0 +1,17 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int totalHammingDistance(vector& nums) { + int result = 0; + for (int i = 0; i < 8 * sizeof(int); ++i) { + vector counts(2); + for (const auto& num : nums) { + ++counts[(num >> i) % 2]; + } + result += counts[0] * counts[1]; + } + return result; + } +}; From f20adefdb84e720aeb0bf37d5fa5b24b69bf699d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 23:58:04 +0800 Subject: [PATCH 3079/4971] Create total-hamming-distance.py --- Python/total-hamming-distance.py | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/total-hamming-distance.py diff --git a/Python/total-hamming-distance.py b/Python/total-hamming-distance.py new file mode 100644 index 000000000..fac26b25b --- /dev/null +++ b/Python/total-hamming-distance.py @@ -0,0 +1,34 @@ +# Time: O(n) +# Space: O(1) + +# The Hamming distance between two integers is the number of positions +# at which the corresponding bits are different. +# +# Now your job is to find the total Hamming distance between all pairs of the given numbers. +# +# Example: +# Input: 4, 14, 2 +# +# Output: 6 +# +# Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just +# showing the four bits relevant in this case). So the answer will be: +# HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. +# Note: +# Elements of the given array are in the range of 0 to 10^9 +# Length of the array will not exceed 10^4. + +class Solution(object): + def totalHammingDistance(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + result = 0 + for i in xrange(32): + counts = [0] * 2 + for num in nums: + counts[(num >> i) & 1] += 1 + result += counts[0] * counts[1] + return result + From 3adebff57ed2df84fd9bc22b8f5551638c95de9f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Dec 2016 23:58:49 +0800 Subject: [PATCH 3080/4971] Update total-hamming-distance.cpp --- C++/total-hamming-distance.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/total-hamming-distance.cpp b/C++/total-hamming-distance.cpp index 1e029da58..b9098e48e 100644 --- a/C++/total-hamming-distance.cpp +++ b/C++/total-hamming-distance.cpp @@ -8,7 +8,7 @@ class Solution { for (int i = 0; i < 8 * sizeof(int); ++i) { vector counts(2); for (const auto& num : nums) { - ++counts[(num >> i) % 2]; + ++counts[(num >> i) & 1]; } result += counts[0] * counts[1]; } From a4cd7ac95d3c82fe2255d2b518e3f57ba344c2ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Dec 2016 23:17:58 +0800 Subject: [PATCH 3081/4971] Create poor-pigs.cpp --- C++/poor-pigs.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 C++/poor-pigs.cpp diff --git a/C++/poor-pigs.cpp b/C++/poor-pigs.cpp new file mode 100644 index 000000000..bee9ffa4b --- /dev/null +++ b/C++/poor-pigs.cpp @@ -0,0 +1,9 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int poorPigs(int buckets, int minutesToDie, int minutesToTest) { + return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1)); + } +}; From bcaeab52fabf56b356b30f75a02319c1bd111c3e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Dec 2016 23:19:31 +0800 Subject: [PATCH 3082/4971] Create poor-pigs.py --- Python/poor-pigs.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/poor-pigs.py diff --git a/Python/poor-pigs.py b/Python/poor-pigs.py new file mode 100644 index 000000000..c5263a9d3 --- /dev/null +++ b/Python/poor-pigs.py @@ -0,0 +1,26 @@ +# Time: O(1) +# Space: O(1) + +# There are 1000 buckets, one and only one of them contains poison, +# the rest are filled with water. They all look the same. +# If a pig drinks that poison it will die within 15 minutes. +# What is the minimum amount of pigs you need to figure out +# which bucket contains the poison within one hour. +# +# Answer this question, and write an algorithm for the follow-up general case. +# +# Follow-up: +# +# If there are n buckets and a pig drinking poison will die within m minutes, +# how many pigs (x) you need to figure out the "poison" bucket within p minutes? +# There is exact one bucket with poison. + +class Solution(object): + def poorPigs(self, buckets, minutesToDie, minutesToTest): + """ + :type buckets: int + :type minutesToDie: int + :type minutesToTest: int + :rtype: int + """ + return int(math.ceil(math.log(buckets) / math.log(minutesToTest / minutesToDie + 1))) From e6a46329b5b01925210cef81242438fe10287957 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Dec 2016 23:57:30 +0800 Subject: [PATCH 3083/4971] Create circular-array-loop.cpp --- C++/circular-array-loop.cpp | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/circular-array-loop.cpp diff --git a/C++/circular-array-loop.cpp b/C++/circular-array-loop.cpp new file mode 100644 index 000000000..fe2d41662 --- /dev/null +++ b/C++/circular-array-loop.cpp @@ -0,0 +1,40 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool circularArrayLoop(vector& nums) { + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] == 0) { + continue; + } + int slow = i, fast = i; + while (nums[next(nums, slow)] * nums[i] > 0 && + nums[next(nums, fast)] * nums[i] > 0 && + nums[next(nums, next(nums, fast))] * nums[i] > 0) { + + slow = next(nums, slow); + fast = next(nums, next(nums, fast)); + if (slow == fast) { + if (slow == next(nums, slow)) { + break; + } + return true; + } + } + slow = i; + int val = nums[i]; + while (nums[slow] * val > 0) { + int tmp = next(nums, slow); + nums[slow] = 0; + slow = tmp; + } + } + return false; + } + +private: + int next(const vector& nums, int i) { + return ((i + nums[i]) + nums.size()) % nums.size(); + } +}; From 55a8322e319c0edf0293d0c97fe3d3d2f41ec5b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Dec 2016 00:03:40 +0800 Subject: [PATCH 3084/4971] Create circular-array-loop.py --- Python/circular-array-loop.py | 52 +++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/circular-array-loop.py diff --git a/Python/circular-array-loop.py b/Python/circular-array-loop.py new file mode 100644 index 000000000..de2bfd0ce --- /dev/null +++ b/Python/circular-array-loop.py @@ -0,0 +1,52 @@ +# Time: O(n) +# Space: O(1) + +# You are given an array of positive and negative integers. +# If a number n at an index is positive, then move forward n steps. +# Conversely, if it's negative (-n), move backward n steps. +# Assume the first element of the array is forward next to the last element, +# and the last element is backward next to the first element. +# Determine if there is a loop in this array. +# A loop starts and ends at a particular index with more than 1 element along the loop. +# The loop must be "forward" or "backward'. +# +# Example 1: Given the array [2, -1, 1, 2, 2], there is a loop, from index 0 -> 2 -> 3 -> 0. +# +# Example 2: Given the array [-1, 2], there is no loop. +# +# Note: The given array is guaranteed to contain no element "0". +# +# Can you do it in O(n) time complexity and O(1) space complexity? + +class Solution(object): + def circularArrayLoop(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + def next_index(nums, i): + return (i + nums[i]) % len(nums) + + for i in xrange(len(nums)): + if nums[i] == 0: + continue + + slow, fast = i, i + while nums[next_index(nums, slow)] * nums[i] > 0 and \ + nums[next_index(nums, fast)] * nums[i] > 0 and \ + nums[next_index(nums, next_index(nums, fast))] * nums[i] > 0: + slow = next_index(nums, slow) + fast = next_index(nums, next_index(nums, fast)) + if slow == fast: + if slow == next_index(nums, slow): + break + return True + + slow = i + val = nums[i] + while nums[slow] * val > 0: + tmp = next_index(nums, slow) + nums[slow] = 0 + slow = tmp + + return False From 63e3afc28a7d62d2de399d9f61fe0d9416dc0e09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Dec 2016 00:07:09 +0800 Subject: [PATCH 3085/4971] Update circular-array-loop.py --- Python/circular-array-loop.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/circular-array-loop.py b/Python/circular-array-loop.py index de2bfd0ce..f1b9e10e4 100644 --- a/Python/circular-array-loop.py +++ b/Python/circular-array-loop.py @@ -42,8 +42,7 @@ def next_index(nums, i): break return True - slow = i - val = nums[i] + slow, val = i, nums[i] while nums[slow] * val > 0: tmp = next_index(nums, slow) nums[slow] = 0 From cb409211a59e9b25d28a43c19abbcb50ae3326e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Dec 2016 00:17:32 +0800 Subject: [PATCH 3086/4971] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 04a47f73e..f076fbf28 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%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-434%20%2F%20434-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-468%20%2F%20468-ff69b4.svg) -Up to date (2016-10-30), there are `417` Algorithms / `13` Database / `4` Shell questions on [LeetCode Online Judge](https://leetcode.com/). +Up to date (2016-12-18), there are `447` Algorithms / `13` Database / `4` Shell / `4` Draft questions on [LeetCode Online Judge](https://leetcode.com/). The number of questions is increasing recently. -Here is the classification of all `434` questions. +Here is the classification of all `468` 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 5a51c3d9e1c1532372ee611de5f7799de5d950de Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Dec 2016 22:18:36 +0800 Subject: [PATCH 3087/4971] Update README.md --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index f076fbf28..4ce030260 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 408| [Valid Word Abbreviation](https://leetcode.com/problems/valid-word-abbreviation/) | [C++](./C++/valid-word-abbreviation.cpp) [Python](./Python/valid-word-abbreviation.py) | _O(n)_ | _O(1)_ | Easy | 📖 | 415| [Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./C++/add-strings.cpp) [Python](./Python/add-strings.py) | _O(n)_ | _O(1)_ | Easy | | 420| [Strong Password Checker](https://leetcode.com/problems/strong-password-checker/) | [C++](./C++/strong-password-checker.cpp) [Python](./Python/strong-password-checker.py) | _O(n)_ | _O(1)_ | Hard | | +434| [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/) | [C++](./C++/number-of-segments-in-a-string.cpp) [Python](./Python/number-of-segments-in-a-string.py) | _O(n)_ | _O(1)_ | Easy | | +459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy | `KMP Algorithm` | ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -186,6 +188,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 385| [Mini Parser](https://leetcode.com/problems/mini-parser/)| [C++](./C++/mini-parser.cpp) [Python](./Python/mini-parser.py) | _O(n)_ | _O(h)_ | Medium ||| 394| [Decode String](https://leetcode.com/problems/decode-string/)| [C++](./C++/decode-string.cpp) [Python](./Python/decode-string.py) | _O(n)_ | _O(h)_ | Medium ||| 439| [Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser/) | [C++](./C++/ternary-expression-parser.cpp) [Python](./Python/ternary-expression-parser.py) | _O(n)_ | _O(1)_ | Medium |📖| +456| [132 Pattern](https://leetcode.com/problems/132-pattern/) | [C++](./C++/132-pattern.cpp) [Python](./Python/132-pattern.py) | _O(n)_ | _O(n)_ | Medium || ## Queue # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -257,6 +260,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 409| [Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./C++/longest-palindrome.cpp) [Python](./Python/longest-palindrome.py) | _O(n)_| _O(1)_| Easy ||| 424| [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) | [C++](./C++/longest-repeating-character-replacement.cpp) [Python](./Python/longest-repeating-character-replacement.py) | _O(n)_| _O(1)_| Medium ||| 438| [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [C++](./C++/find-all-anagrams-in-a-string.cpp) [Python](./Python/find-all-anagrams-in-a-string.py) | _O(n)_ | _O(1)_ | Easy || +447| [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/) | [C++](./C++/number-of-boomerangs.cpp) [Python](./Python/number-of-boomerangs.py) | _O(n^2)_ | _O(n)_ | Easy || +454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -302,6 +307,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 413 | [Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./C++/arithmetic-slices.cpp) [Python](./Python/arithmetic-slices.py) | _O(n)_ | _O(1)_ | Medium ||| 423 | [Reconstruct Original Digits from English](https://leetcode.com/problems/reconstruct-original-digits-from-english/) | [C++](./C++/reconstruct-original-digits-from-english.cpp) [Python](./Python/reconstruct-original-digits-from-english.py) | _O(n)_ | _O(1)_ | Medium | [GCJ2016 - Round 1B](https://code.google.com/codejam/contest/11254486/dashboard#s=p0)|| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [C++](./C++/arranging-coins.cpp) [Python](./Python/arranging-coins.py) | _O(nlogn)_ | _O(1)_ | Easy || Binary Search| +453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| +458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -342,6 +349,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 349| [Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./C++/intersection-of-two-arrays.cpp) [Python](./Python/intersection-of-two-arrays.py) | _O(m + n)_ | _O(min(m, n))_ | Easy | EPI | Hash, Binary Search 350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash, Binary Search 360| [Sort Transformed Array](https://leetcode.com/problems/sort-transformed-array/) | [C++](./C++/sort-transformed-array.cpp) [Python](./Python/sort-transformed-array.py) | _O(n)_ | _O(1)_ | Medium |📖| +457| [Circular Array Loop](https://leetcode.com/problems/circular-array-loop/) | [C++](./C++/circular-array-loop.cpp) [Python](./Python/circular-array-loop.py) | _O(n)_ | _O(1)_ | Medium || ## Recursion # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -521,6 +529,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 403 | [Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./C++/frog-jump.cpp) [Python](./Python/frog-jump.py) | _O(n)_ | _O(n) ~ O(n^2)_ | Hard || 416 | [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) | [C++](./C++/partition-equal-subset-sum.cpp) [Python](./Python/partition-equal-subset-sum.py) | _O(n * s)_ | _O(s)_ | Medium || 418 | [Sentence Screen Fitting](https://leetcode.com/problems/sentence-screen-fitting/) | [C++](./C++/sentence-screen-fitting.cpp) [Python](./Python/sentence-screen-fitting.py) | _O(r + n * c)_ | _O(n)_ | Medium |📖| +446 | [Arithmetic Slices II - Subsequence](https://leetcode.com/problems/arithmetic-slices-ii-subsequence/) | [C++](./C++/arithmetic-slices-ii-subsequence.cpp) [Python](./Python/arithmetic-slices-ii-subsequence.py) | _O(n^2)_ | _O(n * d)_ | Hard || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -541,6 +550,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 397| [Integer Replacement](https://leetcode.com/problems/integer-replacement/)| [C++](./C++/integer-replacement.cpp) [Python](./Python/integer-replacement.py) | _O(n)_ | _O(1)_ | Medium || Math 402 | [Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./C++/remove-k-digits.cpp) [Python](./Python/remove-k-digits.py) | _O(n)_ | _O(n)_ | Medium | LintCode | 435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | +452 | [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(nlogn)_ | _O(1)_ | Medium | | +455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/) | [C++](./C++/assign-cookies.cpp) [Python](./Python/assign-cookies.py) | _O(nlogn)_ | _O(1)_ | Easy | | --- ## Design From 8f79929269e65b898b9e3c08cb4601d831b4ff22 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Dec 2016 22:47:10 +0800 Subject: [PATCH 3088/4971] Update README.md --- README.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4ce030260..db6b90f1c 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 401 | [Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./C++/binary-watch.cpp) [Python](./Python/binary-watch.py) | _O(1)_ | _O(1)_ | Easy | | 411 | [Minimum Unique Word Abbreviation](https://leetcode.com/problems/minimum-unique-word-abbreviation/) | [C++](./C++/minimum-unique-word-abbreviation.cpp) [Python](./Python/minimum-unique-word-abbreviation.py) | _O(2^n)_ | _O(n)_ | Hard | 📖 | 421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [C++](./C++/maximum-xor-of-two-numbers-in-an-array.cpp) [Python](./Python/maximum-xor-of-two-numbers-in-an-array.py) | _O(n)_ | _O(1)_ | Medium || +461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [C++](./C++/hamming-distance.cpp) [Python](./Python/hamming-distance.py) | _O(1)_ | _O(1)_ | Easy || +462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/minimum-moves-to-equal-array-elements-ii.py) | _O(n)_ on average | _O(1)_ | Medium || ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -142,7 +144,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 415| [Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./C++/add-strings.cpp) [Python](./Python/add-strings.py) | _O(n)_ | _O(1)_ | Easy | | 420| [Strong Password Checker](https://leetcode.com/problems/strong-password-checker/) | [C++](./C++/strong-password-checker.cpp) [Python](./Python/strong-password-checker.py) | _O(n)_ | _O(1)_ | Hard | | 434| [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/) | [C++](./C++/number-of-segments-in-a-string.cpp) [Python](./Python/number-of-segments-in-a-string.py) | _O(n)_ | _O(1)_ | Easy | | -459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy | `KMP Algorithm` | +459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | +468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | ## Linked List # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -309,6 +312,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [C++](./C++/arranging-coins.cpp) [Python](./Python/arranging-coins.py) | _O(nlogn)_ | _O(1)_ | Easy || Binary Search| 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| +469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| ## Sort # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -456,6 +460,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 399| [Evaluate Division](https://leetcode.com/problems/evaluate-division/) | [C++](./C++/evaluate-division.cpp) [Python](./Python/evaluate-division.py) | _O(q * \|V\|!)_ | _O(e)_ | Medium ||| 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || 440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn)_ | _O(logn)_ | Hard || +464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || ## Backtracking # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -530,6 +535,11 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 416 | [Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) | [C++](./C++/partition-equal-subset-sum.cpp) [Python](./Python/partition-equal-subset-sum.py) | _O(n * s)_ | _O(s)_ | Medium || 418 | [Sentence Screen Fitting](https://leetcode.com/problems/sentence-screen-fitting/) | [C++](./C++/sentence-screen-fitting.cpp) [Python](./Python/sentence-screen-fitting.py) | _O(r + n * c)_ | _O(n)_ | Medium |📖| 446 | [Arithmetic Slices II - Subsequence](https://leetcode.com/problems/arithmetic-slices-ii-subsequence/) | [C++](./C++/arithmetic-slices-ii-subsequence.cpp) [Python](./Python/arithmetic-slices-ii-subsequence.py) | _O(n^2)_ | _O(n * d)_ | Hard || +465 | [Optimal Account Balancing](https://leetcode.com/problems/optimal-account-balancing/) | [C++](./C++/optimal-account-balancing.cpp) [Python](./Python/optimal-account-balancing.py) | _O(n * 2^n)_ | _O(n * 2^n)_ | Hard |📖| +466 | [Count The Repetitions](https://leetcode.com/problems/count-the-repetitions/) | [C++](./C++/count-the-repetitions.cpp) [Python](./Python/count-the-repetitions.py) | _O(s1 * min(s2, n1))_ | _O(s2)_ | Hard || +467 | [Unique Substrings in Wraparound String](https://leetcode.com/problems/unique-substrings-in-wraparound-string/) | [C++](./C++/unique-substrings-in-wraparound-string.cpp) [Python](./Python/unique-substrings-in-wraparound-string.py) | _O(n)_ | _O(1)_ | Medium || +471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| +472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -567,6 +577,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 380| [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./C++/insert-delete-getrandom-o1.cpp) [Python](./Python/insert-delete-getrandom-o1.py) | _O(1)_ | _O(n)_| Hard || | 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_| Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | +460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(n)_| Hard || | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From 941b5720daa1537b400241d96f0a75ef3e2bf5af Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Dec 2016 22:54:17 +0800 Subject: [PATCH 3089/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index db6b90f1c..3f0a6df0f 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 421 | [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | [C++](./C++/maximum-xor-of-two-numbers-in-an-array.cpp) [Python](./Python/maximum-xor-of-two-numbers-in-an-array.py) | _O(n)_ | _O(1)_ | Medium || 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [C++](./C++/hamming-distance.cpp) [Python](./Python/hamming-distance.py) | _O(1)_ | _O(1)_ | Easy || 462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/minimum-moves-to-equal-array-elements-ii.py) | _O(n)_ on average | _O(1)_ | Medium || +477 | [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./C++/total-hamming-distance.cpp) [Python](./Python/total-hamming-distance.py) | _O(n)_ | _O(1)_ | Medium || ## Array # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -265,6 +266,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 438| [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) | [C++](./C++/find-all-anagrams-in-a-string.cpp) [Python](./Python/find-all-anagrams-in-a-string.py) | _O(n)_ | _O(1)_ | Easy || 447| [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/) | [C++](./C++/number-of-boomerangs.cpp) [Python](./Python/number-of-boomerangs.py) | _O(n^2)_ | _O(n)_ | Easy || 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || +473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || ## Data Structure # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -406,6 +408,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 374| [Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/)| [C++](./C++/guess-number-higher-or-lower.cpp) [Python](./Python/guess-number-higher-or-lower.py) | _O(logn)_ | _O(1)_ | Easy | | 410| [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/)| [C++](./C++/split-array-largest-sum.cpp) [Python](./Python/split-array-largest-sum.py) | _O(nlogs)_ | _O(1)_ | Hard | | 436 | [Find Right Interval](https://leetcode.com/problems/find-right-interval/) | [C++](./C++/find-right-interval.cpp) [Python](./Python/find-right-interval.py) | _O(nlogn)_ | _O(n)_ | Medium | | +475 | [Heaters](https://leetcode.com/problems/heaters/) | [C++](./C++/heaters.cpp) [Python](./Python/heaters.py) | _O((m + n) * logn)_ | _O(1)_ | Easy | | ## Binary Search Tree # | Title | Solution | Time | Space | Difficulty | Tag | Note @@ -540,6 +543,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 467 | [Unique Substrings in Wraparound String](https://leetcode.com/problems/unique-substrings-in-wraparound-string/) | [C++](./C++/unique-substrings-in-wraparound-string.cpp) [Python](./Python/unique-substrings-in-wraparound-string.py) | _O(n)_ | _O(1)_ | Medium || 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || +474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || ## Greedy # | Title | Solution | Time | Space | Difficulty | Tag | Note From 5e0d4d0c2eb00edfaf8ea4c902977ab0df7efc5b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Dec 2016 22:58:07 +0800 Subject: [PATCH 3090/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3f0a6df0f..b30af869c 100644 --- a/README.md +++ b/README.md @@ -581,7 +581,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 380| [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./C++/insert-delete-getrandom-o1.cpp) [Python](./Python/insert-delete-getrandom-o1.py) | _O(1)_ | _O(n)_| Hard || | 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_| Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | -460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(n)_| Hard || | +460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_| Hard || | ## SQL # | Title | Solution | Time | Space | Difficulty | Tag | Note From a65d8b76a0223f9d72fa831422319b13317b3570 Mon Sep 17 00:00:00 2001 From: Jack Date: Mon, 2 Jan 2017 00:37:26 +0800 Subject: [PATCH 3091/4971] edit 4 solutions --- .gitignore | 91 +++++++++++++++++++++++++++++++ Python/compare-version-numbers.py | 29 ++++++++++ Python/reverse-integer.py | 23 +++++++- Python/single-number.py | 9 ++- Python/two-sum.py | 17 +++++- 5 files changed, 164 insertions(+), 5 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..4042179a6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,91 @@ +.idea/ + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# IPython Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# dotenv +.env + +# virtualenv +venv/ +ENV/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject diff --git a/Python/compare-version-numbers.py b/Python/compare-version-numbers.py index bc4f909ef..4b67b70e4 100644 --- a/Python/compare-version-numbers.py +++ b/Python/compare-version-numbers.py @@ -17,6 +17,8 @@ # # 0.1 < 1.1 < 1.2 < 13.37 # +import itertools + class Solution(object): def compareVersion(self, version1, version2): @@ -44,6 +46,8 @@ def compareVersion(self, version1, version2): # Time: O(n) # Space: O(n) + + class Solution2(object): def compareVersion(self, version1, version2): """ @@ -69,6 +73,31 @@ def compareVersion(self, version1, version2): return 0 + def compareVersion2(self, version1, version2): + """ + :type version1: str + :type version2: str + :rtype: int + """ + v1 = [int(x) for x in version1.split('.')] + v2 = [int(x) for x in version2.split('.')] + while len(v1) != len(v2): + if len(v1) > len(v2): + v2.append(0) + else: + v1.append(0) + return cmp(v1, v2) + + def compareVersion3(self, version1, version2): + splits = (map(int, v.split('.')) for v in (version1, version2)) + return cmp(*zip(*itertools.izip_longest(*splits, fillvalue=0))) + + def compareVersion4(self, version1, version2): + main1, _, rest1 = ('0' + version1).partition('.') + main2, _, rest2 = ('0' + version2).partition('.') + return cmp(int(main1), int(main2)) or len(rest1 + rest2) and self.compareVersion4(rest1, rest2) + + if __name__ == "__main__": print Solution().compareVersion("21.0", "121.1.0") print Solution().compareVersion("01", "1") diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py index 8ec6f985a..450dac764 100644 --- a/Python/reverse-integer.py +++ b/Python/reverse-integer.py @@ -35,7 +35,28 @@ def reverse(self, x): x /= 10 return result if result <= 0x7fffffff else 0 # Handle overflow. - + def reverse2(self, x): + """ + :type x: int + :rtype: int + """ + if x < 0: + x = int(str(x)[::-1][-1] + str(x)[::-1][:-1]) + else: + x = int(str(x)[::-1]) + x = 0 if abs(x) > 0x7FFFFFFF else x + return x + + def reverse3(self, x): + """ + :type x: int + :rtype: int + """ + s = cmp(x, 0) + r = int(`s * x`[::-1]) + return s * r * (r < 2 ** 31) + + if __name__ == "__main__": print Solution().reverse(123) print Solution().reverse(-321) diff --git a/Python/single-number.py b/Python/single-number.py index adcb1cba6..88047ae25 100644 --- a/Python/single-number.py +++ b/Python/single-number.py @@ -9,11 +9,14 @@ import operator + class Solution: - # @param A, a list of integer - # @return an integer + """ + :type nums: List[int] + :rtype: int + """ def singleNumber(self, A): return reduce(operator.xor, A) if __name__ == '__main__': - print Solution().singleNumber([1, 1, 2, 2, 3]) \ No newline at end of file + print Solution().singleNumber([1, 1, 2, 2, 3]) diff --git a/Python/two-sum.py b/Python/two-sum.py index 7b7aeaf48..d7f27f0f1 100644 --- a/Python/two-sum.py +++ b/Python/two-sum.py @@ -12,6 +12,7 @@ # Because nums[0] + nums[1] = 2 + 7 = 9, # return [0, 1]. + class Solution(object): def twoSum(self, nums, target): """ @@ -26,6 +27,20 @@ def twoSum(self, nums, target): lookup[num] = i return [] + def twoSum2(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: List[int] + """ + k = 0 + for i in nums: + j = target - i + k += 1 + tmp_nums = nums[k:] + if j in tmp_nums: + return [k - 1, tmp_nums.index(j) + k] + if __name__ == '__main__': - print "index1=%d, index2=%d" % Solution().twoSum((2, 7, 11, 15), 9) + print Solution().twoSum((2, 7, 11, 15), 9) From 5ed5a1d06e5e77de754e26c13759a4ea1167e847 Mon Sep 17 00:00:00 2001 From: Jack Date: Mon, 2 Jan 2017 15:59:10 +0800 Subject: [PATCH 3092/4971] edit some solutions --- Python/add-digits.py | 15 ++++-- Python/battleships-in-a-board.py | 1 + Python/counting-bits.py | 17 +++++++ ...nd-all-numbers-disappeared-in-an-array.py} | 21 +++++++++ Python/find-the-difference.py | 34 +++++++++++++- Python/fizz-buzz.py | 23 +++++++++ Python/move-zeroes.py | 14 ++++++ Python/nim-game.py | 1 + Python/reverse-integer.py | 2 +- Python/rotate-array.py | 41 +++++++++++----- Python/sum-of-two-integers.py | 47 +++++++++++++++++++ 11 files changed, 198 insertions(+), 18 deletions(-) rename Python/{find-all-numbers-disappeared-in-an-array. => find-all-numbers-disappeared-in-an-array.py} (62%) diff --git a/Python/add-digits.py b/Python/add-digits.py index baaa5cde5..5d28264e6 100644 --- a/Python/add-digits.py +++ b/Python/add-digits.py @@ -17,9 +17,18 @@ # # A naive implementation of the above process is trivial. # Could you come up with other methods? -# + + class Solution: - # @param {integer} num - # @return {integer} + """ + :type num: int + :rtype: int + """ def addDigits(self, num): return (num - 1) % 9 + 1 if num > 0 else 0 + + +if __name__ == '__main__': + s = Solution() + r = s.addDigits(12345) + print r diff --git a/Python/battleships-in-a-board.py b/Python/battleships-in-a-board.py index 69a62369a..9f9c49944 100644 --- a/Python/battleships-in-a-board.py +++ b/Python/battleships-in-a-board.py @@ -24,6 +24,7 @@ # This is not a valid board - as battleships will always have a cell separating between them. # Your algorithm should not modify the value of the board. + class Solution(object): def countBattleships(self, board): """ diff --git a/Python/counting-bits.py b/Python/counting-bits.py index 27a762944..6ef845380 100644 --- a/Python/counting-bits.py +++ b/Python/counting-bits.py @@ -25,6 +25,7 @@ # 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): """ @@ -36,3 +37,19 @@ def countBits(self, num): # Number of 1's in i = (i & 1) + number of 1's in (i / 2). res.append((i & 1) + res[i >> 1]) return res + + def countBits2(self, num): + """ + :type num: int + :rtype: List[int] + """ + s = [0] + while len(s) <= num: + s.extend(map(lambda x: x + 1, s)) + return s[:num + 1] + + +if __name__ == '__main__': + s = Solution() + r = s.countBits2(5) + print r diff --git a/Python/find-all-numbers-disappeared-in-an-array. b/Python/find-all-numbers-disappeared-in-an-array.py similarity index 62% rename from Python/find-all-numbers-disappeared-in-an-array. rename to Python/find-all-numbers-disappeared-in-an-array.py index 9a56a4370..cde02ffa0 100644 --- a/Python/find-all-numbers-disappeared-in-an-array. +++ b/Python/find-all-numbers-disappeared-in-an-array.py @@ -17,6 +17,7 @@ # Output: # [5,6] + class Solution(object): def findDisappearedNumbers(self, nums): """ @@ -34,3 +35,23 @@ def findDisappearedNumbers(self, nums): else: nums[i] *= -1 return result + + def findDisappearedNumbers2(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + return list(set(range(1, len(nums) + 1)) - set(nums)) + + def findDisappearedNumbers3(self, nums): + for i in range(len(nums)): + index = abs(nums[i]) - 1 + nums[index] = - abs(nums[index]) + + return [i + 1 for i in range(len(nums)) if nums[i] > 0] + + +if __name__ == '__main__': + s = Solution() + r = s.findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1]) + print r diff --git a/Python/find-the-difference.py b/Python/find-the-difference.py index 73948c1ac..d661e7967 100644 --- a/Python/find-the-difference.py +++ b/Python/find-the-difference.py @@ -20,7 +20,9 @@ # Explanation: # 'e' is the letter that was added. -from operator import xor +import operator +import collections + class Solution(object): def findTheDifference(self, s, t): @@ -29,4 +31,32 @@ def findTheDifference(self, s, t): :type t: str :rtype: str """ - return chr(reduce(xor, map(ord, s), 0) ^ reduce(xor, map(ord, t), 0)) + return chr(reduce(operator.xor, map(ord, s), 0) ^ reduce(operator.xor, map(ord, t), 0)) + + def findTheDifference2(self, s, t): + """ + :type s: str + :type t: str + :rtype: str + """ + t = list(t) + s = list(s) + for i in s: + t.remove(i) + return t[0] + + def findTheDifference3(self, s, t): + return chr(reduce(operator.xor, map(ord, s + t))) + + def findTheDifference4(self, s, t): + return list((collections.Counter(t) - collections.Counter(s)))[0] + + def findTheDifference5(self, s, t): + s, t = sorted(s), sorted(t) + return t[-1] if s == t[:-1] else [x[1] for x in zip(s, t) if x[0] != x[1]][0] + + +if __name__ == '__main__': + s = Solution() + r = s.findTheDifference2('abcd', 'abcde') + print r diff --git a/Python/fizz-buzz.py b/Python/fizz-buzz.py index a1937869a..0e46b90e1 100644 --- a/Python/fizz-buzz.py +++ b/Python/fizz-buzz.py @@ -49,3 +49,26 @@ def fizzBuzz(self, n): result.append(str(i)) return result + + def fizzBuzz2(self, n): + """ + :type n: int + :rtype: List[str] + """ + l = [str(x) for x in range(n + 1)] + l3 = range(0, n + 1, 3) + l5 = range(0, n + 1, 5) + for i in l3: + l[i] = 'Fizz' + for i in l5: + if l[i] == 'Fizz': + l[i] += 'Buzz' + else: + l[i] = 'Buzz' + return l[1:] + + def fizzBuzz3(self, n): + return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n + 1)] + + def fizzBuzz4(self, n): + return ['FizzBuzz'[i % -3 & -4:i % -5 & 8 ^ 12] or `i` for i in range(1, n + 1)] diff --git a/Python/move-zeroes.py b/Python/move-zeroes.py index 40a30aa16..fb121754c 100644 --- a/Python/move-zeroes.py +++ b/Python/move-zeroes.py @@ -12,6 +12,7 @@ # 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): """ @@ -24,6 +25,13 @@ def moveZeroes(self, nums): nums[i], nums[pos] = nums[pos], nums[i] pos += 1 + def moveZeroes2(self, nums): + """ + :type nums: List[int] + :rtype: void Do not return anything, modify nums in-place instead. + """ + nums.sort(cmp=lambda a, b: 0 if b else -1) + class Solution2(object): def moveZeroes(self, nums): @@ -39,3 +47,9 @@ def moveZeroes(self, nums): for i in xrange(pos, len(nums)): nums[i] = 0 + + +if __name__ == '__main__': + s = Solution() + r = s.moveZeroes([0, 1, 0, 3, 12]) + print r diff --git a/Python/nim-game.py b/Python/nim-game.py index 619248d22..f1eadb01a 100644 --- a/Python/nim-game.py +++ b/Python/nim-game.py @@ -16,6 +16,7 @@ # the last stone will always be removed by your friend. # + class Solution(object): def canWinNim(self, n): """ diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py index 450dac764..014a66fee 100644 --- a/Python/reverse-integer.py +++ b/Python/reverse-integer.py @@ -18,7 +18,7 @@ # # Throw an exception? Good, but what if throwing an exception is not an option? # You would then have to re-design the function (ie, add an extra parameter). -# + class Solution(object): def reverse(self, x): diff --git a/Python/rotate-array.py b/Python/rotate-array.py index 2041672a9..f4df62d44 100644 --- a/Python/rotate-array.py +++ b/Python/rotate-array.py @@ -10,41 +10,58 @@ # class Solution: - # @param nums, a list of integer - # @param k, num of steps - # @return nothing, please modify the nums list in-place. + """ + :type nums: List[int] + :type k: int + :rtype: void Do not return anything, modify nums in-place instead. + """ + 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] + nums[start], nums[end - 1] = nums[end - 1], nums[start] start += 1 end -= 1 + def rotate2(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: void Do not return anything, modify nums in-place instead. + """ + nums[:] = nums[len(nums) - k:] + nums[:len(nums) - k] + + 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. + """ + :type nums: List[int] + :type k: int + :rtype: void Do not return anything, modify nums in-place instead. + """ + 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 + 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] + nums = [1, 2, 3, 4, 5, 6, 7] Solution().rotate(nums, 3) print nums diff --git a/Python/sum-of-two-integers.py b/Python/sum-of-two-integers.py index 8b1bc8153..1990ef06b 100644 --- a/Python/sum-of-two-integers.py +++ b/Python/sum-of-two-integers.py @@ -7,6 +7,7 @@ # Example: # Given a = 1 and b = 2, return 3. + class Solution(object): def getSum(self, a, b): """ @@ -28,3 +29,49 @@ def getSum(self, a, b): b = (b | ~mask) if (b & neg_bit) else (b & mask) return a + + def getSum2(self, a, b): + """ + :type a: int + :type b: int + :rtype: int + """ + # 32 bits integer max + MAX = 0x7FFFFFFF + # 32 bits interger min + MIN = 0x80000000 + # mask to get last 32 bits + mask = 0xFFFFFFFF + while b: + # ^ get different bits and & gets double 1s, << moves carry + a, b = (a ^ b) & mask, ((a & b) << 1) & mask + # if a is negative, get a's 32 bits complement positive first + # then get 32-bit positive's Python complement negative + return a if a <= MAX else ~(a ^ mask) + + def minus(self, a, b): + b = self.getSum(~b, 1) + return self.getSum(a, b) + + def multiply(self, a, b): + isNeg = (a > 0) ^ (b > 0) + x = a if a > 0 else self.getSum(~a, 1) + y = b if b > 0 else self.getSum(~b, 1) + ans = 0 + while y & 0x01: + ans = self.getSum(ans, x) + y >>= 1 + x <<= 1 + return self.getSum(~ans, 1) if isNeg else ans + + def divide(self, a, b): + isNeg = (a > 0) ^ (b > 0) + x = a if a > 0 else self.getSum(~a, 1) + y = b if b > 0 else self.getSum(~b, 1) + ans = 0 + for i in range(31, -1, -1): + if (x >> i) >= y: + x = self.minus(x, y << i) + ans = self.getSum(ans, 1 << i) + return self.getSum(~ans, 1) if isNeg else ans + From 9b6e30549dc0fcc05878787d7e865a3ef8f40af3 Mon Sep 17 00:00:00 2001 From: Jack Date: Tue, 3 Jan 2017 00:29:49 +0800 Subject: [PATCH 3093/4971] add some solutions --- Python/binary-watch.py | 7 +++++++ Python/climbing-stairs.py | 15 ++++++++++++--- Python/hamming-distance.py | 12 ++++++++++-- Python/island-perimeter.py | 7 +++++++ Python/remove-duplicates-from-sorted-list.py | 20 ++++++++++++++++++-- 5 files changed, 54 insertions(+), 7 deletions(-) diff --git a/Python/binary-watch.py b/Python/binary-watch.py index 5a048487c..eab47e94b 100644 --- a/Python/binary-watch.py +++ b/Python/binary-watch.py @@ -36,3 +36,10 @@ def bit_count(bits): return ['%d:%02d' % (h, m) for h in xrange(12) for m in xrange(60) if bit_count(h) + bit_count(m) == num] + + def readBinaryWatch2(self, num): + """ + :type num: int + :rtype: List[str] + """ + return ['{0}:{1}'.format(str(h), str(m).zfill(2)) for h in range(12) for m in range(60) if (bin(h) + bin(m)).count('1') == num] diff --git a/Python/climbing-stairs.py b/Python/climbing-stairs.py index 1c8df918d..7901fa1cb 100644 --- a/Python/climbing-stairs.py +++ b/Python/climbing-stairs.py @@ -5,17 +5,26 @@ # # Each time you can either climb 1 or 2 steps. # In how many distinct ways can you climb to the top? -# + class Solution: - # @param n, an integer - # @return an integer + """ + :type n: int + :rtype: int + """ def climbStairs(self, n): prev, current = 0, 1 for i in xrange(n): prev, current = current, prev + current, return current + def climbStairs1(self, n): + if n == 1: + return 1 + if n == 2: + return 2 + return self.climbStairs(n - 1) + self.climbStairs(n - 2) + if __name__ == "__main__": result = Solution().climbStairs(2) print result diff --git a/Python/hamming-distance.py b/Python/hamming-distance.py index 1c0b7ad52..31d0c6ce7 100644 --- a/Python/hamming-distance.py +++ b/Python/hamming-distance.py @@ -30,8 +30,16 @@ def hammingDistance(self, x, y): :rtype: int """ distance = 0 - z = x^y + z = x ^ y while z: distance += 1 - z &= z-1 + z &= z - 1 return distance + + def hammingDistance2(self, x, y): + """ + :type x: int + :type y: int + :rtype: int + """ + return bin(x ^ y).count('1') diff --git a/Python/island-perimeter.py b/Python/island-perimeter.py index bf402961d..fc6c9017a 100644 --- a/Python/island-perimeter.py +++ b/Python/island-perimeter.py @@ -19,6 +19,7 @@ # [1,1,0,0]] # # Answer: 16 +import operator class Solution(object): @@ -39,3 +40,9 @@ def islandPerimeter(self, grid): repeat += 1 return 4*count - 2*repeat + +# Since there are no lakes, every pair of neighbour cells with different values is part of the perimeter +# (more precisely, the edge between them is). So just count the differing pairs, both horizontally and vertically +# (for the latter I simply transpose the grid). + def islandPerimeter2(self, grid): + return sum(sum(map(operator.ne, [0] + row, row + [0])) for row in grid + map(list, zip(*grid))) diff --git a/Python/remove-duplicates-from-sorted-list.py b/Python/remove-duplicates-from-sorted-list.py index cb3f9fb59..1eda2ef1c 100644 --- a/Python/remove-duplicates-from-sorted-list.py +++ b/Python/remove-duplicates-from-sorted-list.py @@ -2,18 +2,21 @@ # Space: O(1) # # Given a sorted linked list, delete all duplicates such that each element appear only once. -# +# # For example, # Given 1->1->2, return 1->2. # Given 1->1->2->3->3, return 1->2->3. # # Definition for singly-linked list. + + class ListNode(object): def __init__(self, x): self.val = x self.next = None + class Solution(object): def deleteDuplicates(self, head): """ @@ -29,8 +32,21 @@ def deleteDuplicates(self, head): cur = runner return head + def deleteDuplicates2(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ + if not head: return head + if head.next: + if head.val == head.next.val: + head = self.deleteDuplicates(head.next) + else: + head.next = self.deleteDuplicates(head.next) + 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) - From 7dcf298a66b1ee869e108055e13a23d9c218ef5c Mon Sep 17 00:00:00 2001 From: Jack Date: Tue, 3 Jan 2017 19:23:33 +0800 Subject: [PATCH 3094/4971] add some solutions --- Python/first-unique-character-in-a-string.py | 33 ++++++++++++++++---- Python/intersection-of-two-arrays.py | 10 ++++++ Python/power-of-three.py | 3 +- Python/power-of-two.py | 3 +- Python/repeated-substring-pattern.py | 14 +++++++++ 5 files changed, 55 insertions(+), 8 deletions(-) diff --git a/Python/first-unique-character-in-a-string.py b/Python/first-unique-character-in-a-string.py index 9dbbff04e..3994a8649 100644 --- a/Python/first-unique-character-in-a-string.py +++ b/Python/first-unique-character-in-a-string.py @@ -12,23 +12,44 @@ # s = "loveleetcode", # return 2. # Note: You may assume the string contain only lowercase letters. +import collections +import string -from collections import defaultdict - class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ - lookup = defaultdict(int) + lookup = collections.defaultdict(int) candidtates = set() for i, c in enumerate(s): if lookup[c]: candidtates.discard(lookup[c]) else: - lookup[c] = i+1 - candidtates.add(i+1) + lookup[c] = i + 1 + candidtates.add(i + 1) + + return min(candidtates) - 1 if candidtates else -1 - return min(candidtates)-1 if candidtates else -1 + def firstUniqChar2(self, s): + """ + :type s: str + :rtype: int + """ + return min([s.find(c) for c in string.ascii_lowercase if s.count(c) == 1] or [-1]) + + def firstUniqChar3(self, s): + """ + :type s: str + :rtype: int + """ + cnt = collections.Counter(s) + if cnt: + for i in cnt.keys(): + if cnt[i] == 1: + return s.index(i) + return -1 + else: + return -1 diff --git a/Python/intersection-of-two-arrays.py b/Python/intersection-of-two-arrays.py index 9388a45b1..e04ff0c40 100644 --- a/Python/intersection-of-two-arrays.py +++ b/Python/intersection-of-two-arrays.py @@ -11,6 +11,8 @@ # The result can be in any order. # Hash solution. + + class Solution(object): def intersection(self, nums1, nums2): """ @@ -33,6 +35,14 @@ def intersection(self, nums1, nums2): return res + def intersection2(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: List[int] + """ + return list(set(nums1) & set(nums2)) + # Time: O(max(m, n) * log(max(m, n))) # Space: O(1) diff --git a/Python/power-of-three.py b/Python/power-of-three.py index 182c44b9f..7398d4bf5 100644 --- a/Python/power-of-three.py +++ b/Python/power-of-three.py @@ -6,7 +6,8 @@ # # Follow up: # Could you do it without using any loop / recursion? -# +import math + class Solution(object): def __init__(self): diff --git a/Python/power-of-two.py b/Python/power-of-two.py index f0eaac76d..55e5bbf92 100644 --- a/Python/power-of-two.py +++ b/Python/power-of-two.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given an integer, write a function to determine if it is a power of two. -# + class Solution: # @param {integer} n @@ -10,6 +10,7 @@ class Solution: def isPowerOfTwo(self, n): return n > 0 and (n & (n - 1)) == 0 + class Solution2: # @param {integer} n # @return {boolean} diff --git a/Python/repeated-substring-pattern.py b/Python/repeated-substring-pattern.py index 1247843f8..b7925f67b 100644 --- a/Python/repeated-substring-pattern.py +++ b/Python/repeated-substring-pattern.py @@ -23,6 +23,8 @@ # Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.) # KMP solution. + + class Solution(object): def repeatedSubstringPattern(self, str): """ @@ -43,3 +45,15 @@ def getPrefix(pattern): prefix = getPrefix(str) return prefix[-1] != -1 and \ (prefix[-1] + 1) % (len(str) - prefix[-1] - 1) == 0 + + def repeatedSubstringPattern2(self, str): + """ + :type str: str + :rtype: bool + """ + if not str: + return False + + ss = (str + str)[1:-1] + print ss + return ss.find(str) != -1 From f9681ee53085b9aad34d24083d552f4ca5c3f48f Mon Sep 17 00:00:00 2001 From: Jack Date: Wed, 4 Jan 2017 16:45:22 +0800 Subject: [PATCH 3095/4971] add some solutions --- Python/best-time-to-buy-and-sell-stock-ii.py | 7 +++++-- Python/count-primes.py | 15 +++++++++++++++ Python/intersection-of-two-arrays-ii.py | 15 +++++++++++++++ Python/longest-palindrome.py | 10 ++++++++++ 4 files changed, 45 insertions(+), 2 deletions(-) diff --git a/Python/best-time-to-buy-and-sell-stock-ii.py b/Python/best-time-to-buy-and-sell-stock-ii.py index 5cbdc9a23..133ed078a 100644 --- a/Python/best-time-to-buy-and-sell-stock-ii.py +++ b/Python/best-time-to-buy-and-sell-stock-ii.py @@ -9,7 +9,7 @@ # (ie, buy one and sell one share of the stock multiple times). # However, you may not engage in multiple transactions at the same time # (ie, you must sell the stock before you buy again). -# + class Solution: # @param prices, a list of integer @@ -20,7 +20,10 @@ def maxProfit(self, prices): profit += max(0, prices[i + 1] - prices[i]) return profit + def maxProfit2(self, prices): + return sum(map(lambda x: max(prices[x + 1] - prices[x], 0), range(len(prices[:-1])))) + + if __name__ == "__main__": result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6]) print result - diff --git a/Python/count-primes.py b/Python/count-primes.py index 525d960e1..46ad88ddf 100644 --- a/Python/count-primes.py +++ b/Python/count-primes.py @@ -7,6 +7,7 @@ # # Hint: The number n could be in the order of 100,000 to 5,000,000. + class Solution: # @param {integer} n # @return {integer} @@ -31,3 +32,17 @@ def countPrimes(self, n): is_prime[j] = False return num + + def countPrimes2(self, n): + """ + :type n: int + :rtype: int + """ + if n < 3: + return 0 + primes = [True] * n + primes[0] = primes[1] = False + for i in range(2, int(n ** 0.5) + 1): + if primes[i]: + primes[i * i: n: i] = [False] * len(primes[i * i: n: i]) + return sum(primes) diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index 5dcaad0dc..9e3f626c6 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -32,6 +32,9 @@ # Time: O(m + n) # Space: O(min(m, n)) # Hash solution. +import collections + + class Solution(object): def intersect(self, nums1, nums2): """ @@ -54,6 +57,18 @@ def intersect(self, nums1, nums2): return res + def intersect2(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: List[int] + """ + c = collections.Counter(nums1) & collections.Counter(nums2) + intersect = [] + for i in c: + intersect.extend([i] * c[i]) + return intersect + # If the given array is already sorted, and the memory is limited, and (m << n or m >> n). # Time: O(min(m, n) * log(max(m, n))) diff --git a/Python/longest-palindrome.py b/Python/longest-palindrome.py index 562f9abdd..9f672acf5 100644 --- a/Python/longest-palindrome.py +++ b/Python/longest-palindrome.py @@ -19,6 +19,8 @@ # # Explanation: # One longest palindrome that can be built is "dccaccd", whose length is 7. +import collections + class Solution(object): def longestPalindrome(self, s): @@ -30,3 +32,11 @@ def longestPalindrome(self, s): for k, v in collections.Counter(s).iteritems(): odds += v & 1 return len(s) - odds + int(odds > 0) + + def longestPalindrome2(self, s): + """ + :type s: str + :rtype: int + """ + odd = sum(map(lambda x: x & 1, collections.Counter(s).values())) + return len(s) - odd + int(odd > 0) From f93043903f5467d0935ed1ea5101e0cb2725be2a Mon Sep 17 00:00:00 2001 From: Jack Date: Thu, 5 Jan 2017 00:07:03 +0800 Subject: [PATCH 3096/4971] add some solutions --- Python/divide-two-integers.py | 28 +++++++++++++++++-- ...inimum-moves-to-equal-array-elements-ii.py | 8 ++++++ Python/number-of-boomerangs.py | 17 +++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/Python/divide-two-integers.py b/Python/divide-two-integers.py index 258184bcd..b024170f6 100644 --- a/Python/divide-two-integers.py +++ b/Python/divide-two-integers.py @@ -2,11 +2,15 @@ # Space: O(1) # # Divide two integers without using multiplication, division and mod operator. -# + class Solution: - # @return an integer def divide(self, dividend, divisor): + """ + :type dividend: int + :type divisor: int + :rtype: int + """ result, dvd, dvs = 0, abs(dividend), abs(divisor) while dvd >= dvs: inc = dvs @@ -20,6 +24,26 @@ def divide(self, dividend, divisor): return -result else: return result + + def divide2(self, dividend, divisor): + """ + :type dividend: int + :type divisor: int + :rtype: int + """ + positive = (dividend < 0) is (divisor < 0) + dividend, divisor = abs(dividend), abs(divisor) + res = 0 + while dividend >= divisor: + temp, i = divisor, 1 + while dividend >= temp: + dividend -= temp + res += i + i <<= 1 + temp <<= 1 + if not positive: + res = -res + return min(max(-2147483648, res), 2147483647) if __name__ == "__main__": print Solution().divide(123, 12) diff --git a/Python/minimum-moves-to-equal-array-elements-ii.py b/Python/minimum-moves-to-equal-array-elements-ii.py index 1902794a8..ee447cd6f 100644 --- a/Python/minimum-moves-to-equal-array-elements-ii.py +++ b/Python/minimum-moves-to-equal-array-elements-ii.py @@ -36,3 +36,11 @@ def PartitionAroundPivot(left, right, pivot_idx, nums): median = kthElement(nums, len(nums)/2 + 1) return sum(abs(num - median) for num in nums) + + def minMoves22(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + median = sorted(nums)[len(nums) / 2] + return sum(abs(num - median) for num in nums) diff --git a/Python/number-of-boomerangs.py b/Python/number-of-boomerangs.py index 6ef7f4b28..e31756e0f 100644 --- a/Python/number-of-boomerangs.py +++ b/Python/number-of-boomerangs.py @@ -17,6 +17,8 @@ # # Explanation: # The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]] +import collections + class Solution(object): def numberOfBoomerangs(self, points): @@ -39,3 +41,18 @@ def numberOfBoomerangs(self, points): result += v * (v-1) return result + + def numberOfBoomerangs2(self, points): + """ + :type points: List[List[int]] + :rtype: int + """ + cnt = 0 + for a, i in enumerate(points): + dis_list = [] + for b, k in enumerate(points[:a] + points[a + 1:]): + dis_list.append((k[0] - i[0]) ** 2 + (k[1] - i[1]) ** 2) + for z in collections.Counter(dis_list).values(): + if z > 1: + cnt += z * (z - 1) + return cnt From 00d783edce312f2537c8e970d2c17249a302db1a Mon Sep 17 00:00:00 2001 From: Jack Date: Sat, 7 Jan 2017 23:27:26 +0800 Subject: [PATCH 3097/4971] add some solutions --- Python/add-strings.py | 22 +++++++++++++++++ Python/increasing-triplet-subsequence.py | 1 + Python/pascals-triangle-ii.py | 30 ++++++++++++++++++++++++ Python/pascals-triangle.py | 28 ++++++++++++++++++++++ Python/plus-one.py | 17 +++++++++++--- Python/reverse-bits.py | 8 +++++++ 6 files changed, 103 insertions(+), 3 deletions(-) diff --git a/Python/add-strings.py b/Python/add-strings.py index 4c13bc69a..b70851700 100644 --- a/Python/add-strings.py +++ b/Python/add-strings.py @@ -12,6 +12,7 @@ # You must not use any built-in BigInteger library or # convert the inputs to integer directly. + class Solution(object): def addStrings(self, num1, num2): """ @@ -34,3 +35,24 @@ def addStrings(self, num1, num2): result.reverse() return "".join(result) + + def addStrings2(self, num1, num2): + """ + :type num1: str + :type num2: str + :rtype: str + """ + length = max(len(num1), len(num2)) + num1 = num1.zfill(length)[::-1] + num2 = num2.zfill(length)[::-1] + res, plus = '', 0 + for index, num in enumerate(num1): + tmp = str(int(num) + int(num2[index]) + plus) + res += tmp[-1] + if int(tmp) > 9: + plus = 1 + else: + plus = 0 + if plus: + res += '1' + return res[::-1] diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index a9e76c280..da1e27ccb 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -17,6 +17,7 @@ # Given [5, 4, 3, 2, 1], # return false. + class Solution(object): def increasingTriplet(self, nums): """ diff --git a/Python/pascals-triangle-ii.py b/Python/pascals-triangle-ii.py index 390a804cb..9f7cfd63d 100644 --- a/Python/pascals-triangle-ii.py +++ b/Python/pascals-triangle-ii.py @@ -20,6 +20,36 @@ def getRow(self, rowIndex): old, result[j] = result[j], old + result[j] return result + def getRow2(self, rowIndex): + """ + :type rowIndex: int + :rtype: List[int] + """ + row = [1] + for _ in range(rowIndex): + row = [x + y for x, y in zip([0] + row, row + [0])] + return row + + def getRow3(self, rowIndex): + """ + :type rowIndex: int + :rtype: List[int] + """ + if rowIndex == 0: return [1] + res = [1, 1] + + def add(nums): + res = nums[:1] + for i, j in enumerate(nums): + if i < len(nums) - 1: + res += [nums[i] + nums[i + 1]] + res += nums[:1] + return res + + while res[1] < rowIndex: + res = add(res) + return res + # Time: O(n^2) # Space: O(n) diff --git a/Python/pascals-triangle.py b/Python/pascals-triangle.py index 822acab84..19b03a607 100644 --- a/Python/pascals-triangle.py +++ b/Python/pascals-triangle.py @@ -28,5 +28,33 @@ def generate(self, numRows): result[i].append(result[i - 1][j - 1] + result[i - 1][j]) return result + def generate2(self, numRows): + if not numRows: return [] + res = [[1]] + for i in range(1, numRows): + res += [map(lambda x, y: x + y, res[-1] + [0], [0] + res[-1])] + return res[:numRows] + + def generate3(self, numRows): + """ + :type numRows: int + :rtype: List[List[int]] + """ + if numRows == 0: return [] + if numRows == 1: return [[1]] + res = [[1], [1, 1]] + + def add(nums): + res = nums[:1] + for i, j in enumerate(nums): + if i < len(nums) - 1: + res += [nums[i] + nums[i + 1]] + res += nums[:1] + return res + + while len(res) < numRows: + res.extend([add(res[-1])]) + return res + if __name__ == "__main__": print Solution().generate(5) diff --git a/Python/plus-one.py b/Python/plus-one.py index e704900ef..c708ff120 100644 --- a/Python/plus-one.py +++ b/Python/plus-one.py @@ -4,11 +4,13 @@ # Given a non-negative number represented as an array of digits, plus one to the number. # # The digits are stored such that the most significant digit is at the head of the list. -# + class Solution: - # @param digits, a list of integer digits - # @return a list of integer digits + """ + :type digits: List[int] + :rtype: List[int] + """ def plusOne(self, digits): carry = 1 for i in reversed(xrange(len(digits))): @@ -21,5 +23,14 @@ def plusOne(self, digits): return digits + def plusOne2(self, digits): + """ + :type digits: List[int] + :rtype: List[int] + """ + digits = [str(x) for x in digits] + num = int(''.join(digits)) + 1 + return [int(x) for x in str(num)] + if __name__ == "__main__": print Solution().plusOne([9, 9, 9, 9]) \ No newline at end of file diff --git a/Python/reverse-bits.py b/Python/reverse-bits.py index 4dc5252b9..636684e0e 100644 --- a/Python/reverse-bits.py +++ b/Python/reverse-bits.py @@ -21,6 +21,14 @@ def reverseBits(self, n): result |= n & 1 n >>= 1 return result + + def reverseBits2(self, n): + string = bin(n) + if '-' in string: + string = string[:3] + string[3:].zfill(32)[::-1] + else: + string = string[:2] + string[2:].zfill(32)[::-1] + return int(string, 2) if __name__ == '__main__': print Solution().reverseBits(1) From dc6a2ea29c2b7bb350a6f91eae8915dd42301cf5 Mon Sep 17 00:00:00 2001 From: Jack Date: Sun, 8 Jan 2017 20:48:27 +0800 Subject: [PATCH 3098/4971] add some solutions --- Python/implement-strstr.py | 11 +++++++++++ Python/jump-game-ii.py | 27 +++++++++++++++++++++++++++ Python/majority-element-ii.py | 9 +++++++++ Python/majority-element.py | 24 +++++++++++++++++------- Python/repeated-dna-sequences.py | 14 +++++++++++++- 5 files changed, 77 insertions(+), 8 deletions(-) diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index 97042a17f..6af9a5ec2 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -43,6 +43,17 @@ def getPrefix(self, pattern): j += 1 prefix[i] = j return prefix + + def strStr2(self, haystack, needle): + """ + :type haystack: str + :type needle: str + :rtype: int + """ + try: + return haystack.index(needle) + except: + return -1 # Time: O(n * k) # Space: O(k) diff --git a/Python/jump-game-ii.py b/Python/jump-game-ii.py index bd771dabf..c3b405c0b 100644 --- a/Python/jump-game-ii.py +++ b/Python/jump-game-ii.py @@ -13,6 +13,7 @@ # The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) # +# not pass on leetcode because of time limit class Solution: # @param A, a list of integers # @return an integer @@ -29,6 +30,7 @@ def jump(self, A): reachable = max(reachable, i + length) return jump_count +# not pass on leetcode because of time limit # Time: O(n^2) # Space: O(1) class Solution2: @@ -44,6 +46,31 @@ def jump(self, A): for i, length in enumerate(A[:reachable + 1]): reachable = max(reachable, i + length) return -1 + +# when you on an index of nums, move to next index which can move farthest in range of this index reachable +# Time: O(log(n)) +# Space: O(1) +class Solution3(object): + def jump(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums2, l = [i + j for i, j in enumerate(nums)], len(nums) - 1 + if not l: return 0 + + def find_max_index(index): + if index + nums[index] >= l: return l + tmp = nums2[index + 1:index + nums[index] + 1] + return index + tmp.index(max(tmp)) + 1 + + index, steps = 0, 0 + while True: + index = find_max_index(index) + steps += 1 + if index == l: + break + return steps if __name__ == "__main__": print Solution().jump([2,3,1,1,4]) diff --git a/Python/majority-element-ii.py b/Python/majority-element-ii.py index 4efbe7e76..849bde6cb 100644 --- a/Python/majority-element-ii.py +++ b/Python/majority-element-ii.py @@ -4,6 +4,8 @@ # 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. +import collections + class Solution(object): def majorityElement(self, nums): @@ -41,3 +43,10 @@ def majorityElement(self, nums): result.append(i) return result + + def majorityElement2(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + return [i[0] for i in collections.Counter(nums).items() if i[1] > len(nums) / 3] diff --git a/Python/majority-element.py b/Python/majority-element.py index bfd6f0dc0..f39f2c0d7 100644 --- a/Python/majority-element.py +++ b/Python/majority-element.py @@ -5,16 +5,19 @@ # The majority element is the element that appears more than [n/2] times. # # You may assume that the array is non-empty and the majority element always exist in the array. -# +import collections + class Solution: - # @param num, a list of integers - # @return an integer - def majorityElement(self, num): + def majorityElement(self, nums): + """ + :type nums: List[int] + :rtype: int + """ idx, cnt = 0, 1 - for i in xrange(1, len(num)): - if num[idx] == num[i]: + for i in xrange(1, len(nums)): + if nums[idx] == nums[i]: cnt += 1 else: cnt -= 1 @@ -22,7 +25,14 @@ def majorityElement(self, num): idx = i cnt = 1 - return num[idx] + return nums[idx] + + def majorityElement2(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + return sorted(collections.Counter(nums).items(), key=lambda a: a[1], reverse=True)[0][0] if __name__ == "__main__": print Solution().majorityElement([1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6]) \ No newline at end of file diff --git a/Python/repeated-dna-sequences.py b/Python/repeated-dna-sequences.py index e2727b908..a4c72fc78 100644 --- a/Python/repeated-dna-sequences.py +++ b/Python/repeated-dna-sequences.py @@ -12,7 +12,8 @@ # # Return: # ["AAAAACCCCC", "CCCCCAAAAA"]. -# +import collections + class Solution: # @param s, a string @@ -29,6 +30,17 @@ def findRepeatedDnaSequences(self, s): dict[rolling_hash] = False return res + def findRepeatedDnaSequences2(self, s): + """ + :type s: str + :rtype: List[str] + """ + l, r = [], [] + if len(s) < 10: return [] + for i in range(len(s) - 9): + l.extend([s[i:i + 10]]) + return [k for k, v in collections.Counter(l).items() if v > 1] + if __name__ == "__main__": print Solution().findRepeatedDnaSequences("AAAAAAAAAA") print Solution().findRepeatedDnaSequences("") From 493994dd2d40a6d6de736ffc74f2834194488267 Mon Sep 17 00:00:00 2001 From: Jack Date: Mon, 9 Jan 2017 01:00:02 +0800 Subject: [PATCH 3099/4971] edit jump-game-ii.py --- Python/jump-game-ii.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/jump-game-ii.py b/Python/jump-game-ii.py index c3b405c0b..28895f016 100644 --- a/Python/jump-game-ii.py +++ b/Python/jump-game-ii.py @@ -56,18 +56,18 @@ def jump(self, nums): :type nums: List[int] :rtype: int """ + nums[-1] = 2 ** 31 nums2, l = [i + j for i, j in enumerate(nums)], len(nums) - 1 - if not l: return 0 def find_max_index(index): - if index + nums[index] >= l: return l - tmp = nums2[index + 1:index + nums[index] + 1] - return index + tmp.index(max(tmp)) + 1 + tmp = nums2[index:index + nums[index] + 1] + return index + tmp.index(max(tmp)) index, steps = 0, 0 while True: index = find_max_index(index) - steps += 1 + if index: + steps += 1 if index == l: break return steps From 89fb7f3d61928354d8c3940f98bb76e3caf43c5e Mon Sep 17 00:00:00 2001 From: Jack Date: Tue, 10 Jan 2017 15:37:16 +0800 Subject: [PATCH 3100/4971] add some solutions --- Python/3sum-closest.py | 2 +- Python/3sum.py | 24 +++++++++++++++++++++++- Python/jump-game-ii.py | 1 - Python/ugly-number-ii.py | 31 +++++++++++++++++++++++++++++++ 4 files changed, 55 insertions(+), 3 deletions(-) diff --git a/Python/3sum-closest.py b/Python/3sum-closest.py index 35301b24a..742e1fa57 100644 --- a/Python/3sum-closest.py +++ b/Python/3sum-closest.py @@ -9,7 +9,7 @@ # For example, given array S = {-1 2 1 -4}, and target = 1. # # The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). -# + class Solution(object): def threeSumClosest(self, nums, target): diff --git a/Python/3sum.py b/Python/3sum.py index a622d76bf..404c19099 100644 --- a/Python/3sum.py +++ b/Python/3sum.py @@ -13,7 +13,8 @@ # A solution set is: # (-1, 0, 1) # (-1, -1, 2) -# +import collections + class Solution(object): def threeSum(self, nums): @@ -40,6 +41,27 @@ def threeSum(self, nums): i += 1 return result + def threeSum2(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + d = collections.Counter(nums) + nums_2 = [x[0] for x in d.items() if x[1] > 1] + nums_new = sorted([x[0] for x in d.items()]) + rtn = [[0, 0, 0]] if d[0] >= 3 else [] + for i, j in enumerate(nums_new): + if j <= 0: + numss2 = nums_new[i + 1:] + for x, y in enumerate(numss2): + if 0 - j - y in [j, y] and 0 - j - y in nums_2: + if sorted([j, y, 0 - j - y]) not in rtn: + rtn.append(sorted([j, y, 0 - j - y])) + if 0 - j - y not in [j, y] and 0 - j - y in nums_new: + if sorted([j, y, 0 - j - y]) not in rtn: + rtn.append(sorted([j, y, 0 - j - y])) + return rtn + if __name__ == '__main__': result = Solution().threeSum([-1, 0, 1, 2, -1, -4]) print result diff --git a/Python/jump-game-ii.py b/Python/jump-game-ii.py index 28895f016..61223b114 100644 --- a/Python/jump-game-ii.py +++ b/Python/jump-game-ii.py @@ -30,7 +30,6 @@ def jump(self, A): reachable = max(reachable, i + length) return jump_count -# not pass on leetcode because of time limit # Time: O(n^2) # Space: O(1) class Solution2: diff --git a/Python/ugly-number-ii.py b/Python/ugly-number-ii.py index 7afc95156..f2eff1e9b 100644 --- a/Python/ugly-number-ii.py +++ b/Python/ugly-number-ii.py @@ -40,3 +40,34 @@ def nthUglyNumber(self, n): heapq.heappush(heap, ugly_number * 5) return ugly_number + + def nthUglyNumber2(self, n): + ugly = [1] + i2 = i3 = i5 = 0 + while len(ugly) < n: + while ugly[i2] * 2 <= ugly[-1]: i2 += 1 + while ugly[i3] * 3 <= ugly[-1]: i3 += 1 + while ugly[i5] * 5 <= ugly[-1]: i5 += 1 + ugly.append(min(ugly[i2] * 2, ugly[i3] * 3, ugly[i5] * 5)) + return ugly[-1] + + def nthUglyNumber3(self, n): + q2, q3, q5 = [2], [3], [5] + ugly = 1 + for u in heapq.merge(q2, q3, q5): + if n == 1: + return ugly + if u > ugly: + ugly = u + n -= 1 + q2 += 2 * u, + q3 += 3 * u, + q5 += 5 * u, + + +class Solution2: + ugly = sorted(2**a * 3**b * 5**c + for a in range(32) for b in range(20) for c in range(14)) + + def nthUglyNumber(self, n): + return self.ugly[n-1] From 6d6d9306c91ae67ca6c6b90c5121cb74d936a1de Mon Sep 17 00:00:00 2001 From: Jack Date: Wed, 11 Jan 2017 16:27:21 +0800 Subject: [PATCH 3101/4971] add some solutions --- Python/house-robber.py | 11 ++++++++ Python/number-complement.py | 32 ++++++++++++++++++++++++ Python/number-of-segments-in-a-string.py | 8 ++++++ Python/power-of-four.py | 10 ++++++++ Python/ransom-note.py | 4 +-- 5 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 Python/number-complement.py diff --git a/Python/house-robber.py b/Python/house-robber.py index db2379811..3efd6e8a0 100644 --- a/Python/house-robber.py +++ b/Python/house-robber.py @@ -26,5 +26,16 @@ def rob(self, num): return num_i + def rob2(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + last, now = 0, 0 + for i in nums: + last, now = now, max(last + i, now) + return now + + if __name__ == '__main__': print Solution().rob([8,4,8,5,9,6,5,4,4,10]) diff --git a/Python/number-complement.py b/Python/number-complement.py new file mode 100644 index 000000000..0adb83481 --- /dev/null +++ b/Python/number-complement.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. +# +# Note: +# The given integer is guaranteed to fit within the range of a 32-bit signed integer. +# You could assume no leading zero bit in the integer’s binary representation. +# Example 1: +# Input: 5 +# Output: 2 +# Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. +# Example 2: +# Input: 1 +# Output: 0 +# Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. + + +class Solution(object): + def findComplement(self, num): + """ + :type num: int + :rtype: int + """ + return 2 ** (len(bin(num)) - 2) - 1 - num + + +class Solution2(object): + def findComplement(self, num): + i = 1 + while i <= num: + i <<= 1 + return (i - 1) ^ num diff --git a/Python/number-of-segments-in-a-string.py b/Python/number-of-segments-in-a-string.py index 066b98208..1a5c0086f 100644 --- a/Python/number-of-segments-in-a-string.py +++ b/Python/number-of-segments-in-a-string.py @@ -13,6 +13,7 @@ # Input: "Hello, my name is John" # Output: 5 + class Solution(object): def countSegments(self, s): """ @@ -24,3 +25,10 @@ def countSegments(self, s): if s[i] == ' ' and s[i-1] != ' ': result += 1 return result + + def countSegments2(self, s): + """ + :type s: str + :rtype: int + """ + return len([i for i in s.strip().split(' ') if i]) diff --git a/Python/power-of-four.py b/Python/power-of-four.py index b8da27b99..74ca8217a 100644 --- a/Python/power-of-four.py +++ b/Python/power-of-four.py @@ -29,3 +29,13 @@ def isPowerOfFour(self, num): while num and not (num & 0b11): num >>= 2 return (num == 1) + + +class Solution3(object): + def isPowerOfFour(self, num): + """ + :type num: int + :rtype: bool + """ + num = bin(num) + return True if num[2:].startswith('1') and len(num[2:]) == num.count('0') and num.count('0') % 2 and '-' not in num else False diff --git a/Python/ransom-note.py b/Python/ransom-note.py index 347cc0548..917334555 100644 --- a/Python/ransom-note.py +++ b/Python/ransom-note.py @@ -41,7 +41,7 @@ def canConstruct(self, ransomNote, magazine): # Time: O(n) # Space: O(1) -from collections import Counter +import collections class Solution2(object): def canConstruct(self, ransomNote, magazine): @@ -50,4 +50,4 @@ def canConstruct(self, ransomNote, magazine): :type magazine: str :rtype: bool """ - return not Counter(ransomNote) - Counter(magazine) + return not collections.Counter(ransomNote) - collections.Counter(magazine) From b7f1e6e37b695a033b57a14c1e12ddc5dbfd397e Mon Sep 17 00:00:00 2001 From: Jack Date: Wed, 11 Jan 2017 23:46:49 +0800 Subject: [PATCH 3102/4971] add some solutions --- Python/single-number-ii.py | 28 ++++++++++++++++++++++++---- Python/single-number-iii.py | 16 ++++++++++++++-- Shell/valid-phone-numbers.sh | 1 + 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/Python/single-number-ii.py b/Python/single-number-ii.py index 0e97ce970..e87276c96 100644 --- a/Python/single-number-ii.py +++ b/Python/single-number-ii.py @@ -5,9 +5,10 @@ # # Note: # Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? -# +import collections -class Solution: + +class Solution(object): # @param A, a list of integer # @return an integer def singleNumber(self, A): @@ -16,7 +17,7 @@ def singleNumber(self, A): one, two = (~x & one) | (x & ~one & ~two), (~x & two) | (x & one) return one -class Solution2: +class Solution2(object): # @param A, a list of integer # @return an integer def singleNumber(self, A): @@ -29,8 +30,27 @@ def singleNumber(self, A): two &= ~carry return one + +class Solution3(object): + def singleNumber(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + return (collections.Counter(list(set(nums)) * 3) - collections.Counter(nums)).keys()[0] + + +class Solution4(object): + def singleNumber(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + return (sum(set(nums)) * 3 - sum(nums)) / 2 + + # every element appears 4 times except for one with 2 times -class SolutionEX: +class SolutionEX(object): # @param A, a list of integer # @return an integer # [1, 1, 1, 1, 2, 2, 2, 2, 3, 3] diff --git a/Python/single-number-iii.py b/Python/single-number-iii.py index c90e79bd2..49d0e53ba 100644 --- a/Python/single-number-iii.py +++ b/Python/single-number-iii.py @@ -14,7 +14,9 @@ # above example, [5, 3] is also correct. # Your algorithm should run in linear runtime complexity. # Could you implement it using only constant space complexity? -# +import operator +import collections + class Solution: # @param {integer[]} nums @@ -26,7 +28,8 @@ def singleNumber(self, nums): for i in nums: result[bool(i & bit)] ^= i return result - + + class Solution2: # @param {integer[]} nums # @return {integer[]} @@ -43,3 +46,12 @@ def singleNumber(self, nums): x ^= i return [x, x ^ x_xor_y] + + +class Solution3(object): + def singleNumber(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + return [x[0] for x in sorted(collections.Counter(nums).items(), key=lambda i: i[1], reverse=False)[:2]] diff --git a/Shell/valid-phone-numbers.sh b/Shell/valid-phone-numbers.sh index 561fde3a0..ca2e85fbf 100644 --- a/Shell/valid-phone-numbers.sh +++ b/Shell/valid-phone-numbers.sh @@ -1,3 +1,4 @@ +#!/usr/bin/env bash # Time: O(n) # Space: O(1) # From b5c46b8a24c625d2bc2f7899e0dd5db146a53c87 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jan 2017 17:29:42 +0800 Subject: [PATCH 3103/4971] Create sliding-window-median.cpp --- C++/sliding-window-median.cpp | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/sliding-window-median.cpp diff --git a/C++/sliding-window-median.cpp b/C++/sliding-window-median.cpp new file mode 100644 index 000000000..1aaf28d84 --- /dev/null +++ b/C++/sliding-window-median.cpp @@ -0,0 +1,42 @@ +// Time: O(nlogw) +// Space: O(w) + +class Solution { +public: +vector medianSlidingWindow(vector& nums, int k) { + multiset> min_bst; + multiset> max_bst; + + vector result; + for (int i = 0; i < nums.size(); ++i) { + if (i >= k) { + if (max_bst.find(nums[i - k]) != max_bst.cend()) { + max_bst.erase(max_bst.find(nums[i - k])); + } else { + min_bst.erase(min_bst.find(nums[i - k])); + } + } + + if (max_bst.empty() || nums[i] > *max_bst.cbegin()) { + min_bst.emplace(nums[i]); + if (min_bst.size() > max_bst.size() + 1) { + max_bst.emplace(*min_bst.cbegin()); + min_bst.erase(min_bst.cbegin()); + } + } else { + max_bst.emplace(nums[i]); + if (max_bst.size() > min_bst.size()) { + min_bst.emplace(*max_bst.cbegin()); + max_bst.erase(max_bst.cbegin()); + } + } + + if (i >= k - 1) { + result.emplace_back(min_bst.size() == max_bst.size() ? + *max_bst.cbegin() / 2.0 + *min_bst.cbegin() / 2.0 : *min_bst.cbegin()); + } + } + + return result; + } +}; From 7eb30ff4fb9a19517d5a4472478288d692975593 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jan 2017 17:30:53 +0800 Subject: [PATCH 3104/4971] Update sliding-window-median.cpp --- C++/sliding-window-median.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/sliding-window-median.cpp b/C++/sliding-window-median.cpp index 1aaf28d84..984721150 100644 --- a/C++/sliding-window-median.cpp +++ b/C++/sliding-window-median.cpp @@ -1,5 +1,5 @@ -// Time: O(nlogw) -// Space: O(w) +// Time: O(nlogk) +// Space: O(k) class Solution { public: From 07c84ad0e9cae245eafa6b6365c9b8eca6cfa5e0 Mon Sep 17 00:00:00 2001 From: Chih-Yao Ma Date: Sun, 15 Jan 2017 15:52:25 -0500 Subject: [PATCH 3105/4971] add an if constrain when the input is [] to avoid the "index out of range" error --- Python/search-a-2d-matrix.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/search-a-2d-matrix.py b/Python/search-a-2d-matrix.py index 46f85d228..39a3f98a6 100644 --- a/Python/search-a-2d-matrix.py +++ b/Python/search-a-2d-matrix.py @@ -24,6 +24,9 @@ def searchMatrix(self, matrix, target): :type target: int :rtype: bool """ + if matrix == []: + return False + m, n = len(matrix), len(matrix[0]) left, right = 0, m * n while left < right: From 8726fe3836342705d879afbd67a24b4c5b67ab27 Mon Sep 17 00:00:00 2001 From: Chih-Yao Ma Date: Sun, 15 Jan 2017 23:24:55 -0500 Subject: [PATCH 3106/4971] Use floor division instead of regular division print Solution().sqrt(9) gave me 2.75, which should be 3. --- Python/sqrtx.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/sqrtx.py b/Python/sqrtx.py index 9fd3679f8..6429b9180 100644 --- a/Python/sqrtx.py +++ b/Python/sqrtx.py @@ -14,9 +14,9 @@ def mySqrt(self, x): if x < 2: return x - left, right = 1, x / 2 + left, right = 1, x // 2 while left <= right: - mid = left + (right - left) / 2 + mid = left + (right - left) // 2 if mid > x / mid: right = mid - 1 else: From 9f9a4fca2d50b8ae969d96fefabc13bf85f8aa24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Feb 2017 15:22:51 +0800 Subject: [PATCH 3107/4971] Create number-complement.cpp --- C++/number-complement.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/number-complement.cpp diff --git a/C++/number-complement.cpp b/C++/number-complement.cpp new file mode 100644 index 000000000..d07a6b8e1 --- /dev/null +++ b/C++/number-complement.cpp @@ -0,0 +1,13 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int findComplement(int num) { + unsigned int i = 1; + while (i <= num) { + i <<= 1; + } + return (i - 1) ^ num; + } +}; From 9804f4e3ed733440e9d738cfb021bda2322aeeea Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Feb 2017 15:24:31 +0800 Subject: [PATCH 3108/4971] Update number-complement.py --- Python/number-complement.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Python/number-complement.py b/Python/number-complement.py index 0adb83481..5e628b8e6 100644 --- a/Python/number-complement.py +++ b/Python/number-complement.py @@ -1,6 +1,8 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. +# Time: O(1) +# Space: O(1) + +# Given a positive integer, output its complement number. +# The complement strategy is to flip the bits of its binary representation. # # Note: # The given integer is guaranteed to fit within the range of a 32-bit signed integer. From 9a1bb7d66d847e5614b7f42bbf40be9cedb4efbe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Feb 2017 15:56:53 +0800 Subject: [PATCH 3109/4971] Create magical-string.cpp --- C++/magical-string.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/magical-string.cpp diff --git a/C++/magical-string.cpp b/C++/magical-string.cpp new file mode 100644 index 000000000..90b95c430 --- /dev/null +++ b/C++/magical-string.cpp @@ -0,0 +1,13 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int magicalString(int n) { + string S = "122"; + for (int i = 2; S.length() < n; ++i) { + S += string(S[i] - '0', S.back() ^ 3); + } + return count(S.begin(), S.begin() + n, '1'); + } +}; From 2ebc93f6c6723f9414415cb005510af0abf528e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Feb 2017 16:44:16 +0800 Subject: [PATCH 3110/4971] Create magical-string.py --- Python/magical-string.py | 45 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/magical-string.py diff --git a/Python/magical-string.py b/Python/magical-string.py new file mode 100644 index 000000000..299d6b842 --- /dev/null +++ b/Python/magical-string.py @@ -0,0 +1,45 @@ +# Time: O(n) +# Space: O(logn) + +# A magical string S consists of only '1' and '2' and obeys the following rules: +# +# The string S is magical because concatenating +# the number of contiguous occurrences of characters '1' and '2' generates the string S itself. +# +# The first few elements of string S is the following: S = "1221121221221121122……" +# +# If we group the consecutive '1's and '2's in S, it will be: +# +# 1 22 11 2 1 22 1 22 11 2 11 22 ...... +# +# and the occurrences of '1's or '2's in each group are: +# +# 1 2 2 1 1 2 1 2 2 1 2 2 ...... +# +# You can see that the occurrence sequence above is the S itself. +# +# Given an integer N as input, return the number of '1's in the first N number in the magical string S. +# +# Note: N will not exceed 100,000. +# +# Example 1: +# Input: 6 +# Output: 3 +# Explanation: The first 6 elements of magical string S is "12211" and it contains three 1's, so return 3. + +# the solution comes from https://discuss.leetcode.com/topic/75242/o-log-n-space-using-recursive-generators +class Solution(object): + def magicalString(self, n): + """ + :type n: int + :rtype: int + """ + def gen(): # see figure 1 on page 3 of http://www.emis.ams.org/journals/JIS/VOL15/Nilsson/nilsson5.pdf + for c in 1, 2, 2: + yield c + for i, c in enumerate(gen()): + if i > 1: + for _ in xrange(c): + yield i % 2 + 1 + + return sum(c & 1 for c in itertools.islice(gen(), n)) From ca906ff055a6e72caed1419db11d0b3c9edc60f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Feb 2017 19:17:35 +0800 Subject: [PATCH 3111/4971] Create license-key-formatting.cpp --- C++/license-key-formatting.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/license-key-formatting.cpp diff --git a/C++/license-key-formatting.cpp b/C++/license-key-formatting.cpp new file mode 100644 index 000000000..f365c7b27 --- /dev/null +++ b/C++/license-key-formatting.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string licenseKeyFormatting(string S, int K) { + string result; + for (auto it = S.rbegin(); it < S.rend(); ++it) { + if (*it == '-') { + continue; + } + if (result.length() % (K + 1) == K) { + result += '-'; + } + result += toupper(*it); + } + reverse(result.begin(), result.end()); + return result; + } +}; From 5bb7ee663bf8cef07bd87c5db0a26f0e7b825702 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Feb 2017 19:23:53 +0800 Subject: [PATCH 3112/4971] Create icense-key-formatting.py --- Python/icense-key-formatting.py | 51 +++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/icense-key-formatting.py diff --git a/Python/icense-key-formatting.py b/Python/icense-key-formatting.py new file mode 100644 index 000000000..9c729793b --- /dev/null +++ b/Python/icense-key-formatting.py @@ -0,0 +1,51 @@ +# Time: O(n) +# Space: O(1) + +# Now you are given a string S, which represents a software license key which we would like to format. +# The string S is composed of alphanumerical characters and dashes. +# The dashes split the alphanumerical characters within the string into groups. +# (i.e. if there are M dashes, the string is split into M+1 groups). +# The dashes in the given string are possibly misplaced. +# +# We want each group of characters to be of length K +# (except for possibly the first group, which could be shorter, +# but still must contain at least one character). +# To satisfy this requirement, we will reinsert dashes. +# Additionally, all the lower case letters in the string must be converted to upper case. +# +# So, you are given a non-empty string S, representing a license key to format, +# and an integer K. And you need to return the license key formatted according to the description above. +# +# Example 1: +# Input: S = "2-4A0r7-4k", K = 4 +# +# Output: "24A0-R74K" +# +# Explanation: The string S has been split into two parts, each part has 4 characters. +# Example 2: +# Input: S = "2-4A0r7-4k", K = 3 +# +# Output: "24-A0R-74K" +# +# Explanation: The string S has been split into three parts, each part has 3 characters +# except the first part as it could be shorter as said above. +# Note: +# The length of string S will not exceed 12,000, and K is a positive integer. +# String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-). +# String S is non-empty. + +class Solution(object): + def licenseKeyFormatting(self, S, K): + """ + :type S: str + :type K: int + :rtype: str + """ + result = [] + for i in reversed(xrange(len(S))): + if S[i] == '-': + continue + if len(result) % (K + 1) == K: + result += '-' + result += S[i].upper() + return "".join(reversed(result)) From 3ac5c55189900c2663df967903cf7b7b5d34c2e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Feb 2017 22:56:51 +0800 Subject: [PATCH 3113/4971] Rename icense-key-formatting.py to license-key-formatting.py --- Python/{icense-key-formatting.py => license-key-formatting.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{icense-key-formatting.py => license-key-formatting.py} (100%) diff --git a/Python/icense-key-formatting.py b/Python/license-key-formatting.py similarity index 100% rename from Python/icense-key-formatting.py rename to Python/license-key-formatting.py From 95276aec73540b6884e61db670b22df876519ee5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Feb 2017 22:57:38 +0800 Subject: [PATCH 3114/4971] Create smallest-good-base.py --- Python/smallest-good-base.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/smallest-good-base.py diff --git a/Python/smallest-good-base.py b/Python/smallest-good-base.py new file mode 100644 index 000000000..c63d418b6 --- /dev/null +++ b/Python/smallest-good-base.py @@ -0,0 +1,36 @@ +# Time: O(logn * log(logn)) +# Space: O(1) + +# For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1. +# +# Now given a string representing n, you should return the smallest good base of n in string format. +# +# Example 1: +# Input: "13" +# Output: "3" +# Explanation: 13 base 3 is 111. +# Example 2: +# Input: "4681" +# Output: "8" +# Explanation: 4681 base 8 is 11111. +# Example 3: +# Input: "1000000000000000000" +# Output: "999999999999999999" +# Explanation: 1000000000000000000 base 999999999999999999 is 11. +# Note: +# The range of n is [3, 10^18]. +# The string representing n is always valid and will not have leading zeros. + +class Solution(object): + def smallestGoodBase(self, n): + """ + :type n: str + :rtype: str + """ + num = int(n) + max_len = int(math.log(num,2)) + for l in xrange(max_len, 1, -1): + b = int(num ** (l**-1)) + if (b**(l+1)-1) // (b-1) == num: + return str(b) + return str(num-1) From 59c09349d6a3d957bfab783e658cacbb16ca3183 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Feb 2017 22:58:10 +0800 Subject: [PATCH 3115/4971] Create smallest-good-base.cpp --- C++/smallest-good-base.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/smallest-good-base.cpp diff --git a/C++/smallest-good-base.cpp b/C++/smallest-good-base.cpp new file mode 100644 index 000000000..e3a435ab1 --- /dev/null +++ b/C++/smallest-good-base.cpp @@ -0,0 +1,19 @@ +// Time: O((logn)^2) +// Space: O(1) + +class Solution { +public: + string smallestGoodBase(string n) { + unsigned long long num = stoll(n); + for (int l = log(num) / log(2); l >= 2; --l) { + unsigned long long b = pow(num, 1.0 / l), sum = 0, curr = 1; + for (int i = 0; i <= l; ++i, curr *= b) { + sum += curr; + } + if (sum == num) { + return to_string(b); + } + } + return to_string(num - 1); + } +}; From 5d50569da9db98b530b02e5380314b788b3f7579 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Feb 2017 23:20:44 +0800 Subject: [PATCH 3116/4971] Create find-permutation.py --- Python/find-permutation.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Python/find-permutation.py diff --git a/Python/find-permutation.py b/Python/find-permutation.py new file mode 100644 index 000000000..4a9710abf --- /dev/null +++ b/Python/find-permutation.py @@ -0,0 +1,14 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def findPermutation(self, s): + """ + :type s: str + :rtype: List[int] + """ + result = [] + for i in xrange(len(s)+1): + if i == len(s) or s[i] == 'I': + result += range(i+1, len(result), -1) + return result From 96d060a95d9bdd84221b2f96f0e19b3f7d6cf6bd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Feb 2017 23:21:57 +0800 Subject: [PATCH 3117/4971] Create find-permutation.cpp --- C++/find-permutation.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/find-permutation.cpp diff --git a/C++/find-permutation.cpp b/C++/find-permutation.cpp new file mode 100644 index 000000000..31c295061 --- /dev/null +++ b/C++/find-permutation.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector findPermutation(string s) { + vector result; + for (int i = 0; i <= s.length(); ++i) { + if (i == s.length() || s[i] == 'I') { + const int k = result.size(); + for (int j = i + 1; j > k; --j) { + result.emplace_back(j); + } + } + } + return result; + } +}; From 05b301b5fe28437f7efe8e3a4f8c76571894abe3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Feb 2017 00:06:12 +0800 Subject: [PATCH 3118/4971] Create max-consecutive-ones.py --- Python/max-consecutive-ones.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/max-consecutive-ones.py diff --git a/Python/max-consecutive-ones.py b/Python/max-consecutive-ones.py new file mode 100644 index 000000000..88f26e1f2 --- /dev/null +++ b/Python/max-consecutive-ones.py @@ -0,0 +1,26 @@ +# Time: O(n) +# Space: O(1) + +# Given a binary array, find the maximum number of consecutive 1s in this array. +# +# Example 1: +# Input: [1,1,0,1,1,1] +# Output: 3 +# Explanation: The first two digits or the last three digits are consecutive 1s. +# The maximum number of consecutive 1s is 3. +# Note: +# +# The input array will only contain 0 and 1. +# The length of input array is a positive integer and will not exceed 10,000 + +class Solution(object): + def findMaxConsecutiveOnes(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + result, local_max = 0, 0 + for n in nums: + local_max = (local_max + 1 if n else 0) + result = max(result, local_max) + return result From b25bfc2e42f1af9b234808804fc44b696995e977 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Feb 2017 00:06:47 +0800 Subject: [PATCH 3119/4971] Create max-consecutive-ones.cpp --- C++/max-consecutive-ones.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/max-consecutive-ones.cpp diff --git a/C++/max-consecutive-ones.cpp b/C++/max-consecutive-ones.cpp new file mode 100644 index 000000000..5510733e3 --- /dev/null +++ b/C++/max-consecutive-ones.cpp @@ -0,0 +1,14 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int result = 0, local_max = 0; + for (const auto& n : nums) { + local_max = n ? local_max + 1 : 0; + result = max(result, local_max); + } + return result; + } +}; From 3787d58cd7c1625474f3285025eee1ec98d7d4b0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Feb 2017 00:25:40 +0800 Subject: [PATCH 3120/4971] Create max-consecutive-ones-ii.py --- Python/max-consecutive-ones-ii.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/max-consecutive-ones-ii.py diff --git a/Python/max-consecutive-ones-ii.py b/Python/max-consecutive-ones-ii.py new file mode 100644 index 000000000..a674080fd --- /dev/null +++ b/Python/max-consecutive-ones-ii.py @@ -0,0 +1,17 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def findMaxConsecutiveOnes(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + result, prev, curr = 0, 0, 0 + for n in nums: + if n == 0: + result = max(result, prev+curr+1) + prev, curr = curr, 0 + else: + curr += 1 + return min(max(result, prev+curr+1), len(nums)) From f0cf11fee2f01b8d166a5d210c5006154e0cde2e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Feb 2017 00:28:28 +0800 Subject: [PATCH 3121/4971] Create max-consecutive-ones-ii.cpp --- C++/max-consecutive-ones-ii.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/max-consecutive-ones-ii.cpp diff --git a/C++/max-consecutive-ones-ii.cpp b/C++/max-consecutive-ones-ii.cpp new file mode 100644 index 000000000..289e662d5 --- /dev/null +++ b/C++/max-consecutive-ones-ii.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findMaxConsecutiveOnes(vector& nums) { + int result = 0, prev = 0, curr = 0; + for (const auto& n : nums) { + if (n == 0) { + result = max(result, prev + curr + 1); + prev = curr; + curr = 0; + } else { + ++curr; + } + } + return min(max(result, prev + curr + 1), static_cast(nums.size())); + } +}; From 4fbede8552434b4df6acaec8cdfad0a32243ba0e Mon Sep 17 00:00:00 2001 From: Hongyi Shen Date: Fri, 17 Feb 2017 10:39:28 -0800 Subject: [PATCH 3122/4971] fix minor error --- Python/unique-word-abbreviation.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/unique-word-abbreviation.py b/Python/unique-word-abbreviation.py index b6e84e88d..f734f40c8 100644 --- a/Python/unique-word-abbreviation.py +++ b/Python/unique-word-abbreviation.py @@ -20,13 +20,14 @@ def isUnique(self, word): :type word: str :rtype: bool """ - l = len(word) abbr = self.abbreviation(word) return self.lookup_[abbr] <= {word} def abbreviation(self, word): - return word[0] + str(len(word)) + word[-1] + if len(word) <= 2: + return word + return word[0] + str(len(word)-2) + word[-1] # Your ValidWordAbbr object will be instantiated and called as such: From 18aaddc6ecbac8a66e67a75b62cf2421610a2fb0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 15:53:26 +0800 Subject: [PATCH 3123/4971] Create predict-the-winner.cpp --- C++/predict-the-winner.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/predict-the-winner.cpp diff --git a/C++/predict-the-winner.cpp b/C++/predict-the-winner.cpp new file mode 100644 index 000000000..4cda5afd5 --- /dev/null +++ b/C++/predict-the-winner.cpp @@ -0,0 +1,21 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + bool PredictTheWinner(vector& nums) { + if (nums.size() % 2 == 0 || nums.size() == 1) { + return true; + } + + vector dp(nums.size()); + for (int i = nums.size() - 1; i >= 0; --i) { + dp[i] = nums[i]; + for (int j = i + 1; j < nums.size(); ++j) { + dp[j] = max(nums[i] - dp[j], nums[j] - dp[j - 1]); + } + } + + return dp.back() >= 0; + } +}; From 555f4c1040e93a291ed0b8649c4651cb866aa574 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 15:58:15 +0800 Subject: [PATCH 3124/4971] Create predict-the-winner.py --- Python/predict-the-winner.py | 48 ++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/predict-the-winner.py diff --git a/Python/predict-the-winner.py b/Python/predict-the-winner.py new file mode 100644 index 000000000..b64a44cf3 --- /dev/null +++ b/Python/predict-the-winner.py @@ -0,0 +1,48 @@ +# Time: O(n^2) +# Space: O(n) + +# Given an array of scores that are non-negative integers. +# Player 1 picks one of the numbers from either end of the array +# followed by the player 2 and then player 1 and so on. +# Each time a player picks a number, that number will not be available for the next player. +# This continues until all the scores have been chosen. The player with the maximum score wins. +# +# Given an array of scores, predict whether player 1 is the winner. +# You can assume each player plays to maximize his score. +# +# Example 1: +# Input: [1, 5, 2] +# Output: False +# Explanation: Initially, player 1 can choose between 1 and 2. +# If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. +# If player 2 chooses 5, then player 1 will be left with 1 (or 2). +# So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. +# Hence, player 1 will never be the winner and you need to return False. +# Example 2: +# Input: [1, 5, 233, 7] +# Output: True +# Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. +# No matter which number player 2 choose, player 1 can choose 233. +# Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win. +# Note: +# 1 <= length of the array <= 20. +# Any scores in the given array are non-negative integers and will not exceed 10,000,000. +# If the scores of both players are equal, then player 1 is still the winner. + +class Solution(object): + def PredictTheWinner(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + if len(nums) % 2 == 0 or len(nums) == 1: + return True + + dp = [0] * len(nums); + for i in reversed(xrange(len(nums))): + dp[i] = nums[i] + for j in xrange(i+1, len(nums)): + dp[j] = max(nums[i] - dp[j], nums[j] - dp[j - 1]) + + return dp[-1] >= 0 + From 7a982534a6d067001cf10a83ed5c79c7f4279e89 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 18:32:44 +0800 Subject: [PATCH 3125/4971] Create zuma-game.cpp --- C++/zuma-game.cpp | 76 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 C++/zuma-game.cpp diff --git a/C++/zuma-game.cpp b/C++/zuma-game.cpp new file mode 100644 index 000000000..784b96f05 --- /dev/null +++ b/C++/zuma-game.cpp @@ -0,0 +1,76 @@ +// Time: O(b * b! * h!) +// Space: O(b * b! * h!) + +class Solution { +public: + int findMinStep(string board, string hand) { + unordered_map> lookup; + sort(hand.begin(), hand.end()); + int res = findMinStepHelper(board, hand, &lookup); + return res > hand.size() ? -1 : res; + } + +private: + int findMinStepHelper(const string& board, const string& hand, + unordered_map> *lookup) { + if (board.empty()) { + return 0; + } + if (hand.empty()) { + return MAX_STEP; + } + if ((*lookup)[board][hand]) { + return (*lookup)[board][hand]; + } + + int res = MAX_STEP; + for (int i = 0; i < hand.size(); ++i) { + int j = 0; + int n = board.size(); + while (j < n) { + int k = board.find(hand[i], j); + if (k == string::npos) { + break; + } + if (k < n - 1 && board[k] == board[k + 1]) { + string next_board = shrink(board.substr(0, k) + board.substr(k + 2)); + string next_hand = hand.substr(0, i) + hand.substr(i + 1); + res = min(res, findMinStepHelper(next_board, next_hand, lookup) + 1); + ++k; + } else if (i > 0 && hand[i] == hand[i - 1]) { + string next_board = shrink(board.substr(0, k) + board.substr(k + 1)); + string next_hand = hand.substr(0, i - 1) + hand.substr(i + 1); + res = min(res, findMinStepHelper(next_board, next_hand, lookup) + 2); + } + j = k + 1; + } + } + + (*lookup)[board][hand] = res; + return res; + } + + string shrink(const string& s) { // Time: O(n), Space: O(n) + vector> stack; + for (int i = 0, start = 0; i <= s.size(); ++i) { + if (i == s.size() || s[i] != s[start]) { + if (!stack.empty() && stack.back().first == s[start]) { + stack.back().second += i - start; + if (stack.back().second >= 3) { + stack.pop_back(); + } + } else if (i - start < 3) { + stack.emplace_back(s[start], i - start); + } + start = i; + } + } + string result; + for (const auto& p : stack) { + result += string(p.second, p.first); + } + return result; + } + + static const int MAX_STEP = 6; +}; From 893f28d627cf8bc2b6a9138d541423fdd8dd19a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 18:37:12 +0800 Subject: [PATCH 3126/4971] Update zuma-game.cpp --- C++/zuma-game.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/C++/zuma-game.cpp b/C++/zuma-game.cpp index 784b96f05..514ae368f 100644 --- a/C++/zuma-game.cpp +++ b/C++/zuma-game.cpp @@ -6,8 +6,8 @@ class Solution { int findMinStep(string board, string hand) { unordered_map> lookup; sort(hand.begin(), hand.end()); - int res = findMinStepHelper(board, hand, &lookup); - return res > hand.size() ? -1 : res; + int result = findMinStepHelper(board, hand, &lookup); + return result > hand.size() ? -1 : result; } private: @@ -23,7 +23,7 @@ class Solution { return (*lookup)[board][hand]; } - int res = MAX_STEP; + int result = MAX_STEP; for (int i = 0; i < hand.size(); ++i) { int j = 0; int n = board.size(); @@ -35,19 +35,18 @@ class Solution { if (k < n - 1 && board[k] == board[k + 1]) { string next_board = shrink(board.substr(0, k) + board.substr(k + 2)); string next_hand = hand.substr(0, i) + hand.substr(i + 1); - res = min(res, findMinStepHelper(next_board, next_hand, lookup) + 1); + result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 1); ++k; } else if (i > 0 && hand[i] == hand[i - 1]) { string next_board = shrink(board.substr(0, k) + board.substr(k + 1)); string next_hand = hand.substr(0, i - 1) + hand.substr(i + 1); - res = min(res, findMinStepHelper(next_board, next_hand, lookup) + 2); + result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 2); } j = k + 1; } } - (*lookup)[board][hand] = res; - return res; + return (*lookup)[board][hand] = result; } string shrink(const string& s) { // Time: O(n), Space: O(n) From 81e2e0e813613e07da1a1f26673882f708d1dd2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 18:52:45 +0800 Subject: [PATCH 3127/4971] Update zuma-game.cpp --- C++/zuma-game.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/zuma-game.cpp b/C++/zuma-game.cpp index 514ae368f..8c8b6715a 100644 --- a/C++/zuma-game.cpp +++ b/C++/zuma-game.cpp @@ -26,13 +26,12 @@ class Solution { int result = MAX_STEP; for (int i = 0; i < hand.size(); ++i) { int j = 0; - int n = board.size(); - while (j < n) { + while (j < board.size()) { int k = board.find(hand[i], j); if (k == string::npos) { break; } - if (k < n - 1 && board[k] == board[k + 1]) { + if (k < board.size() - 1 && board[k] == board[k + 1]) { string next_board = shrink(board.substr(0, k) + board.substr(k + 2)); string next_hand = hand.substr(0, i) + hand.substr(i + 1); result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 1); From ed27fd5b9af377c143fced6936e4b84c2782813e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 19:14:52 +0800 Subject: [PATCH 3128/4971] Update zuma-game.cpp --- C++/zuma-game.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/zuma-game.cpp b/C++/zuma-game.cpp index 8c8b6715a..c038098ba 100644 --- a/C++/zuma-game.cpp +++ b/C++/zuma-game.cpp @@ -57,8 +57,8 @@ class Solution { if (stack.back().second >= 3) { stack.pop_back(); } - } else if (i - start < 3) { - stack.emplace_back(s[start], i - start); + } else if (!s.empty() && i - start < 3) { + stack.emplace_back(s[start], i - start); } start = i; } From e8efc78d53d1077837065359169ee805b04ca237 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 19:34:23 +0800 Subject: [PATCH 3129/4971] Create zuma-game.py --- Python/zuma-game.py | 104 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 Python/zuma-game.py diff --git a/Python/zuma-game.py b/Python/zuma-game.py new file mode 100644 index 000000000..5ff1c5f61 --- /dev/null +++ b/Python/zuma-game.py @@ -0,0 +1,104 @@ +# Time: O(b * b! * h!) +# Space: O(b * b! * h!) + +# Think about Zuma Game. You have a row of balls on the table, +# colored red(R), yellow(Y), blue(B), green(G), and white(W). +# You also have several balls in your hand. +# +# Each time, you may choose a ball in your hand, and insert it into the row +# (including the leftmost place and rightmost place). +# Then, if there is a group of 3 or more balls in the same color touching, +# remove these balls. Keep doing this until no more balls can be removed. +# +# Find the minimal balls you have to insert to remove all the balls on the table. +# If you cannot remove all the balls, output -1. +# +# Examples: +# +# Input: "WRRBBW", "RB" +# Output: -1 +# Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW +# +# Input: "WWRRBBWW", "WRBRW" +# Output: 2 +# Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty +# +# Input:"G", "GGGGG" +# Output: 2 +# Explanation: G -> G[G] -> GG[G] -> empty +# +# Input: "RBYYBBRRB", "YRBGB" +# Output: 3 +# Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty +# +# Note: +# You may assume that the initial row of balls on the table won’t have any 3 or +# more consecutive balls with the same color. +# The number of balls on the table won't exceed 20, and the string represents these balls +# is called "board" in the input. +# The number of balls in your hand won't exceed 5, and the string represents these balls +# is called "hand" in the input. +# Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'. + +class Solution(object): + def findMinStep(self, board, hand): + """ + :type board: str + :type hand: str + :rtype: int + """ + def shrink(s): # Time: O(n), Space: O(n) + stack = [] + start = 0 + for i in xrange(len(s)+1): + if i == len(s) or s[i] != s[start]: + if stack and stack[-1][0] == s[start]: + stack[-1][1] += i - start + if stack[-1][1] >= 3: + stack.pop() + elif s and i - start < 3: + stack += [s[start], i - start], + start = i + result = [] + for p in stack: + result += [p[0]] * p[1] + return result + + def find(board, c, j): + for i in xrange(j, len(board)): + if board[i] == c: + return i + return -1 + + def findMinStepHelper(board, hand, lookup): + if not board: return 0 + if not hand: return float("inf") + if tuple(hand) in lookup[tuple(board)]: return lookup[tuple(board)][tuple(hand)] + + result = float("inf") + for i in xrange(len(hand)): + j = 0 + while j < len(board): + k = find(board, hand[i], j) + if k == -1: + break + + if k < len(board) - 1 and board[k] == board[k+1]: + next_board = shrink(board[0:k] + board[k+2:]) + next_hand = hand[0:i] + hand[i+1:] + result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 1) + k += 1 + elif i > 0 and hand[i] == hand[i-1]: + next_board = shrink(board[0:k] + board[k+1:]) + next_hand = hand[0:i-1] + hand[i+1:] + result = min(result, findMinStepHelper(next_board, next_hand, lookup) + 2) + j = k+1 + + lookup[tuple(board)][tuple(hand)] = result + return result + + lookup = collections.defaultdict(dict) + board, hand = list(board), list(hand) + hand.sort() + result = findMinStepHelper(board, hand, lookup) + return -1 if result == float("inf") else result From de8501c90e049b98d1069dd09a589173a6dc8458 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 19:35:56 +0800 Subject: [PATCH 3130/4971] Update zuma-game.py --- Python/zuma-game.py | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/Python/zuma-game.py b/Python/zuma-game.py index 5ff1c5f61..1af644c93 100644 --- a/Python/zuma-game.py +++ b/Python/zuma-game.py @@ -48,21 +48,21 @@ def findMinStep(self, board, hand): :rtype: int """ def shrink(s): # Time: O(n), Space: O(n) - stack = [] - start = 0 - for i in xrange(len(s)+1): - if i == len(s) or s[i] != s[start]: - if stack and stack[-1][0] == s[start]: - stack[-1][1] += i - start - if stack[-1][1] >= 3: - stack.pop() - elif s and i - start < 3: - stack += [s[start], i - start], - start = i - result = [] - for p in stack: - result += [p[0]] * p[1] - return result + stack = [] + start = 0 + for i in xrange(len(s)+1): + if i == len(s) or s[i] != s[start]: + if stack and stack[-1][0] == s[start]: + stack[-1][1] += i - start + if stack[-1][1] >= 3: + stack.pop() + elif s and i - start < 3: + stack += [s[start], i - start], + start = i + result = [] + for p in stack: + result += [p[0]] * p[1] + return result def find(board, c, j): for i in xrange(j, len(board)): From 74fb9786f9a69126ca37949fc1aac3080d28c511 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 19:48:19 +0800 Subject: [PATCH 3131/4971] Create reverse-pairs.cpp --- C++/reverse-pairs.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/reverse-pairs.cpp diff --git a/C++/reverse-pairs.cpp b/C++/reverse-pairs.cpp new file mode 100644 index 000000000..3977c701a --- /dev/null +++ b/C++/reverse-pairs.cpp @@ -0,0 +1,26 @@ +// Time: O(nlogn) +// Space: O(logn) + +class Solution { +public: + int reversePairs(vector& nums) { + return sortAndCount(nums.begin(), nums.end()); + } + +private: + int sortAndCount(vector::iterator begin, vector::iterator end) { + if (end - begin <= 1) { + return 0; + } + auto mid = begin + (end - begin) / 2; + int count = sortAndCount(begin, mid) + sortAndCount(mid, end); + for (auto i = begin, j = mid; i != mid; ++i) { + while (j != end && *i > 2L * *j) { + ++j; + } + count += j - mid; + } + inplace_merge(begin, mid, end); + return count; + } +}; From 951da1ebe25474614f4d3512f89e58df6bbd1f76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 19:51:24 +0800 Subject: [PATCH 3132/4971] Update reverse-pairs.cpp --- C++/reverse-pairs.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/reverse-pairs.cpp b/C++/reverse-pairs.cpp index 3977c701a..4dcc941d3 100644 --- a/C++/reverse-pairs.cpp +++ b/C++/reverse-pairs.cpp @@ -4,16 +4,16 @@ class Solution { public: int reversePairs(vector& nums) { - return sortAndCount(nums.begin(), nums.end()); + return countAndMergeSort(nums.begin(), nums.end()); } private: - int sortAndCount(vector::iterator begin, vector::iterator end) { + int countAndMergeSort(vector::iterator begin, vector::iterator end) { if (end - begin <= 1) { return 0; } auto mid = begin + (end - begin) / 2; - int count = sortAndCount(begin, mid) + sortAndCount(mid, end); + int count = countAndMergeSort(begin, mid) + countAndMergeSort(mid, end); for (auto i = begin, j = mid; i != mid; ++i) { while (j != end && *i > 2L * *j) { ++j; From ecbdce766850d6344ebea9ea9d5ee518bfcd9827 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 20:52:08 +0800 Subject: [PATCH 3133/4971] Create reverse-pairs.py --- Python/reverse-pairs.py | 53 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/reverse-pairs.py diff --git a/Python/reverse-pairs.py b/Python/reverse-pairs.py new file mode 100644 index 000000000..54b338a7e --- /dev/null +++ b/Python/reverse-pairs.py @@ -0,0 +1,53 @@ +# Time: O(nlogn) +# Space: O(logn) + +# Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j]. +# +# You need to return the number of important reverse pairs in the given array. +# +# Example1: +# +# Input: [1,3,2,3,1] +# Output: 2 +# Example2: +# +# Input: [2,4,3,5,1] +# Output: 3 +# Note: +# The length of the given array will not exceed 50,000. +# All the numbers in the input array are in the range of 32-bit integer. +# Show Company Tags +# Show Tags +# Hide Similar Problems + +class Solution(object): + def reversePairs(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + def merge(nums, start, mid, end): + r = mid + 1 + tmp = [] + for i in xrange(start, mid + 1): + while r <= end and nums[i] > nums[r]: + tmp.append(nums[r]) + r += 1 + tmp.append(nums[i]) + nums[start:start+len(tmp)] = tmp + + def countAndMergeSort(nums, start, end): + if end - start <= 0: + return 0 + + mid = start + (end - start) / 2 + count = countAndMergeSort(nums, start, mid) + countAndMergeSort(nums, mid + 1, end) + r = mid + 1 + for i in xrange(start, mid + 1): + while r <= end and nums[i] > nums[r] * 2: + r += 1 + count += r - (mid + 1) + merge(nums, start, mid, end) + return count + + return countAndMergeSort(nums, 0, len(nums) - 1) From 8f854c57be04b01ccdee21cc4b5d8c1e94df3f46 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 20:53:34 +0800 Subject: [PATCH 3134/4971] Update reverse-pairs.py --- Python/reverse-pairs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/reverse-pairs.py b/Python/reverse-pairs.py index 54b338a7e..17a430162 100644 --- a/Python/reverse-pairs.py +++ b/Python/reverse-pairs.py @@ -1,5 +1,5 @@ # Time: O(nlogn) -# Space: O(logn) +# Space: O(n) # Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j]. # From 85d2d9fae18565b4ec9b25f96c7d0291cef55667 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 21:36:42 +0800 Subject: [PATCH 3135/4971] Create ipo.cpp --- C++/ipo.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/ipo.cpp diff --git a/C++/ipo.cpp b/C++/ipo.cpp new file mode 100644 index 000000000..d0d1d19cf --- /dev/null +++ b/C++/ipo.cpp @@ -0,0 +1,26 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + int findMaximizedCapital(int k, int W, vector& Profits, vector& Capital) { + vector> future; + for (int i = 0; i < Profits.size(); ++i) { + future.emplace_back(Capital[i], Profits[i]); + } + sort(future.begin(), future.end(), greater>()); + + priority_queue curr; + while (k--) { + while (!future.empty() && future.back().first <= W) { + curr.emplace(future.back().second); + future.pop_back(); + } + if (!curr.empty()) { + W += curr.top(); + curr.pop(); + } + } + return W; + } +}; From 42fc99430bc63600d14ce1235c7edf25a35f67c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 21:38:12 +0800 Subject: [PATCH 3136/4971] Create ipo.py --- Python/ipo.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/ipo.py diff --git a/Python/ipo.py b/Python/ipo.py new file mode 100644 index 000000000..ef1b99102 --- /dev/null +++ b/Python/ipo.py @@ -0,0 +1,47 @@ +# Time: O(nlogn) +# Space: O(n) + +# Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, +# LeetCode would like to work on some projects to increase its capital before the IPO. +# Since it has limited resources, it can only finish at most k distinct projects before the IPO. +# Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects. +# +# You are given several projects. For each project i, it has a pure profit Pi and a minimum capital +# of Ci is needed to start the corresponding project. Initially, you have W capital. +# When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. +# +# To sum up, pick a list of at most k distinct projects from given projects to maximize +# your final capital, and output your final maximized capital. +# +# Example 1: +# Input: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1]. +# +# Output: 4 +# +# Explanation: Since your initial capital is 0, you can only start the project indexed 0. +# After finishing it you will obtain profit 1 and your capital becomes 1. +# With capital 1, you can either start the project indexed 1 or the project indexed 2. +# Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. +# Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. +# Note: +# You may assume all numbers in the input are non-negative integers. +# The length of Profits array and Capital array will not exceed 50,000. +# The answer is guaranteed to fit in a 32-bit signed integer. + +class Solution(object): + def findMaximizedCapital(self, k, W, Profits, Capital): + """ + :type k: int + :type W: int + :type Profits: List[int] + :type Capital: List[int] + :rtype: int + """ + curr = [] + future = sorted(zip(Capital, Profits), reverse=True) + for _ in xrange(k): + while future and future[-1][0] <= W: + heapq.heappush(curr, -future.pop()[1]) + if curr: + W -= heapq.heappop(curr) + return W From eb7be3b8b2c69ff6e9eea046adb88d411ec2cc6c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 23:10:56 +0800 Subject: [PATCH 3137/4971] Create super-washing-machines.cpp --- C++/super-washing-machines.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/super-washing-machines.cpp diff --git a/C++/super-washing-machines.cpp b/C++/super-washing-machines.cpp new file mode 100644 index 000000000..bb10a9353 --- /dev/null +++ b/C++/super-washing-machines.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findMinMoves(vector& machines) { + int sum = accumulate(machines.begin(), machines.end(), 0); + if (sum % machines.size() != 0) { + return -1; + } + + int result = 0, target = sum / machines.size(), curr = 0; + for (auto i = 0; i < machines.size(); ++i) { + curr += machines[i] - target; + result = max(result, max(machines[i] - target, abs(curr))); + } + return result; + } +}; From 48f037725c054e125b4af8cde0e3a3a679924167 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 23:17:43 +0800 Subject: [PATCH 3138/4971] Create super-washing-machines.py --- Python/super-washing-machines.py | 61 ++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/super-washing-machines.py diff --git a/Python/super-washing-machines.py b/Python/super-washing-machines.py new file mode 100644 index 000000000..1db926366 --- /dev/null +++ b/Python/super-washing-machines.py @@ -0,0 +1,61 @@ +# Time: O(n) +# Space: O(1) + +# You have n super washing machines on a line. +# Initially, each washing machine has some dresses or is empty. +# +# For each move, you could choose any m (1 <= m <= n) washing machines, +# and pass one dress of each washing machine to one of +# its adjacent washing machines at the same time . +# +# Given an integer array representing the number of dresses +# in each washing machine from left to right on the line, +# you should find the minimum number of moves to make +# all the washing machines have the same number of dresses. +# If it is not possible to do it, return -1. +# +# Example1 +# +# Input: [1,0,5] +# +# Output: 3 +# +# Explanation: +# 1st move: 1 0 <-- 5 => 1 1 4 +# 2nd move: 1 <-- 1 <-- 4 => 2 1 3 +# 3rd move: 2 1 <-- 3 => 2 2 2 +# Example2 +# +# Input: [0,3,0] +# +# Output: 2 +# +# Explanation: +# 1st move: 0 <-- 3 0 => 1 2 0 +# 2nd move: 1 2 --> 0 => 1 1 1 +# Example3 +# +# Input: [0,2,0] +# +# Output: -1 +# +# Explanation: +# It's impossible to make all the three washing machines have the same number of dresses. +# Note: +# The range of n is [1, 10000]. +# The range of dresses number in a super washing machine is [0, 1e5]. + +class Solution(object): + def findMinMoves(self, machines): + """ + :type machines: List[int] + :rtype: int + """ + total = sum(machines) + if total % len(machines): return -1 + + result, target, curr = 0, total / len(machines), 0 + for n in machines: + curr += n - target + result = max(result, max(n - target, abs(curr))) + return result From a76a099ac6a0690c3010a1a9389e2d674bbdf607 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 23:18:20 +0800 Subject: [PATCH 3139/4971] Update super-washing-machines.cpp --- C++/super-washing-machines.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/super-washing-machines.cpp b/C++/super-washing-machines.cpp index bb10a9353..e2f0ff82e 100644 --- a/C++/super-washing-machines.cpp +++ b/C++/super-washing-machines.cpp @@ -10,9 +10,9 @@ class Solution { } int result = 0, target = sum / machines.size(), curr = 0; - for (auto i = 0; i < machines.size(); ++i) { - curr += machines[i] - target; - result = max(result, max(machines[i] - target, abs(curr))); + for (const auto& n : machines) { + curr += n - target; + result = max(result, max(n - target, abs(curr))); } return result; } From 1829b3d1162f4f8d63f07e61d22947fd4368f234 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Feb 2017 23:52:46 +0800 Subject: [PATCH 3140/4971] Create target-sum.cpp --- C++/target-sum.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/target-sum.cpp diff --git a/C++/target-sum.cpp b/C++/target-sum.cpp new file mode 100644 index 000000000..a3a7f01d7 --- /dev/null +++ b/C++/target-sum.cpp @@ -0,0 +1,28 @@ +// Time: O(n * S) +// Space: O(S) + +class Solution { +public: + int findTargetSumWays(vector& nums, int S) { + // sum(P) - sum(N) = S + // <=> + // 2 * sum(P) = S + sum(nums) + int sum = accumulate(nums.begin(), nums.end(), 0); + if (sum < S || (S + sum) % 2) { + return 0; + } + return subsetSum(nums, (S + sum) / 2); + } + +private: + int subsetSum(vector& nums, int S) { + vector dp(S + 1); + dp[0] = 1; + for (const auto& n : nums) { + for (int i = S; i >= n; --i) { + dp[i] += dp[i - n]; + } + } + return dp.back(); + } +}; From 88e84ef09787b78f15d1e68a3b8cece8acc54bc1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Feb 2017 00:23:13 +0800 Subject: [PATCH 3141/4971] Create target-sum.py --- Python/target-sum.py | 46 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/target-sum.py diff --git a/Python/target-sum.py b/Python/target-sum.py new file mode 100644 index 000000000..602767865 --- /dev/null +++ b/Python/target-sum.py @@ -0,0 +1,46 @@ +# Time: O(n * S) +# Space: O(S) + +# You are given a list of non-negative integers, a1, a2, ..., an, +# and a target, S. Now you have 2 symbols + and -. +# For each integer, you should choose one from + and - as its new symbol. +# +# Find out how many ways to assign symbols to make sum of integers equal to target S. +# +# Example 1: +# Input: nums is [1, 1, 1, 1, 1], S is 3. +# Output: 5 +# Explanation: +# +# -1+1+1+1+1 = 3 +# +1-1+1+1+1 = 3 +# +1+1-1+1+1 = 3 +# +1+1+1-1+1 = 3 +# +1+1+1+1-1 = 3 +# +# There are 5 ways to assign symbols to make the sum of nums be target 3. +# Note: +# The length of the given array is positive and will not exceed 20. +# The sum of elements in the given array will not exceed 1000. +# Your output answer is guaranteed to be fitted in a 32-bit integer. + +class Solution(object): + def findTargetSumWays(self, nums, S): + """ + :type nums: List[int] + :type S: int + :rtype: int + """ + def subsetSum(nums, S): + dp = collections.defaultdict(int) + dp[0] = 1 + for n in nums: + for i in reversed(xrange(n, S+1)): + if i-n in dp: + dp[i] += dp[i-n] + return dp[S] + + total = sum(nums) + if total < S or (S + total) % 2: return 0 + P = (S + total) // 2 + return subsetSum(nums, P) From 6227bed2a33de8a9c6a43091ea9ae59aa0d45ef3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Feb 2017 00:44:58 +0800 Subject: [PATCH 3142/4971] Create contiguous-array.cpp --- C++/contiguous-array.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/contiguous-array.cpp diff --git a/C++/contiguous-array.cpp b/C++/contiguous-array.cpp new file mode 100644 index 000000000..d18cb0ece --- /dev/null +++ b/C++/contiguous-array.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int findMaxLength(vector& nums) { + int result = 0, count = 0; + unordered_map lookup; + lookup[0] = 0; + for (int i = 0; i < nums.size(); ++i) { + count += nums[i] == 1 ? 1 : -1; + if (lookup.count(count)) { + result = max(result, i + 1 - lookup[count]); + } else { + lookup[count] = i + 1; + } + } + return result; + } +}; From fdefe6bb2eba1b4e9ca62fa746ee779a50d45055 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Feb 2017 00:46:34 +0800 Subject: [PATCH 3143/4971] Create contiguous-array.py --- Python/contiguous-array.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/contiguous-array.py diff --git a/Python/contiguous-array.py b/Python/contiguous-array.py new file mode 100644 index 000000000..c52b9b992 --- /dev/null +++ b/Python/contiguous-array.py @@ -0,0 +1,32 @@ +# Time: O(n) +# Space: O(n) + +# Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. +# +# Example 1: +# Input: [0,1] +# Output: 2 +# Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. +# Example 2: +# Input: [0,1,0] +# Output: 2 +# Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. +# Note: The length of the given binary array will not exceed 50,000. + +class Solution(object): + def findMaxLength(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + result, count = 0, 0 + lookup = {0: 0} + + for i, num in enumerate(nums): + count += 1 if num == 1 else -1 + if count in lookup: + result = max(result, i+1 - lookup[count]) + else: + lookup[count] = i+1 + + return result From bae959490d8b5c6bedb9e18b8ad7a99aa3c58092 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Feb 2017 18:23:52 +0800 Subject: [PATCH 3144/4971] Update contiguous-array.cpp --- C++/contiguous-array.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/contiguous-array.cpp b/C++/contiguous-array.cpp index d18cb0ece..cd067f052 100644 --- a/C++/contiguous-array.cpp +++ b/C++/contiguous-array.cpp @@ -6,13 +6,13 @@ class Solution { int findMaxLength(vector& nums) { int result = 0, count = 0; unordered_map lookup; - lookup[0] = 0; + lookup[0] = -1; for (int i = 0; i < nums.size(); ++i) { count += nums[i] == 1 ? 1 : -1; if (lookup.count(count)) { - result = max(result, i + 1 - lookup[count]); + result = max(result, i - lookup[count]); } else { - lookup[count] = i + 1; + lookup[count] = i; } } return result; From a098e33684e1e5b579bd7732d72e7c14051f8786 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Feb 2017 18:24:36 +0800 Subject: [PATCH 3145/4971] Update contiguous-array.py --- Python/contiguous-array.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Python/contiguous-array.py b/Python/contiguous-array.py index c52b9b992..f16e9147d 100644 --- a/Python/contiguous-array.py +++ b/Python/contiguous-array.py @@ -20,13 +20,12 @@ def findMaxLength(self, nums): :rtype: int """ result, count = 0, 0 - lookup = {0: 0} - + lookup = {0: -1} for i, num in enumerate(nums): count += 1 if num == 1 else -1 if count in lookup: - result = max(result, i+1 - lookup[count]) + result = max(result, i - lookup[count]) else: - lookup[count] = i+1 + lookup[count] = i return result From f28a3c6dc8f83a0915491e39db265e3368c47b2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Feb 2017 18:27:20 +0800 Subject: [PATCH 3146/4971] Create continuous-subarray-sum.cpp --- C++/continuous-subarray-sum.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/continuous-subarray-sum.cpp diff --git a/C++/continuous-subarray-sum.cpp b/C++/continuous-subarray-sum.cpp new file mode 100644 index 000000000..9b0155131 --- /dev/null +++ b/C++/continuous-subarray-sum.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(k) + +class Solution { +public: + bool checkSubarraySum(vector& nums, int k) { + int count = 0; + unordered_map lookup; + lookup[0] = -1; + for (int i = 0; i < nums.size(); ++i) { + count += nums[i]; + if (k != 0) { + count %= k; + } + if (lookup.count(count)) { + if (i - lookup[count] > 1) { + return true; + } + } else { + lookup[count] = i; + } + } + return false; + } +}; From 0ac3b0e01182f341973e3d31ad20fad457c7fcc5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Feb 2017 18:29:50 +0800 Subject: [PATCH 3147/4971] Create continuous-subarray-sum.py --- Python/continuous-subarray-sum.py | 40 +++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/continuous-subarray-sum.py diff --git a/Python/continuous-subarray-sum.py b/Python/continuous-subarray-sum.py new file mode 100644 index 000000000..b9991538f --- /dev/null +++ b/Python/continuous-subarray-sum.py @@ -0,0 +1,40 @@ +# Time: O(n) +# Space: O(k) + +# Given a list of non-negative numbers and a target integer k, +# write a function to check if the array has a continuous subarray +# of size at least 2 that sums up to the multiple of k, that is, +# sums up to n*k where n is also an integer. +# +# Example 1: +# Input: [23, 2, 4, 6, 7], k=6 +# Output: True +# Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6. +# Example 2: +# Input: [23, 2, 6, 4, 7], k=6 +# Output: True +# Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42. +# Note: +# The length of the array won't exceed 10,000. +# You may assume the sum of all the numbers is in the range of a signed 32-bit integer. + +class Solution(object): + def checkSubarraySum(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: bool + """ + count = 0 + lookup = {0: -1} + for i, num in enumerate(nums): + count += num + if k: + count %= k + if count in lookup: + if i - lookup[count] > 1: + return True + else: + lookup[count] = i + + return False From 6d4b371db52c672a1f60e6c055c472684e73b5ef Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Feb 2017 18:43:39 +0800 Subject: [PATCH 3148/4971] Create minimum-absolute-difference-in-bst.cpp --- C++/minimum-absolute-difference-in-bst.cpp | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/minimum-absolute-difference-in-bst.cpp diff --git a/C++/minimum-absolute-difference-in-bst.cpp b/C++/minimum-absolute-difference-in-bst.cpp new file mode 100644 index 000000000..038991bd2 --- /dev/null +++ b/C++/minimum-absolute-difference-in-bst.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 getMinimumDifference(TreeNode* root) { + int result = numeric_limits::max(); + TreeNode *prev = nullptr; + + inorderTraversal(root, &prev, &result); + + return result; + } + +private: + void inorderTraversal(TreeNode *root, TreeNode **prev, int *result) { + if (!root) { + return; + } + + inorderTraversal(root->left, prev, result); + + if (*prev) { + *result = min(*result, root->val - (*prev)->val); + } + *prev = root; + + inorderTraversal(root->right, prev, result); + } +}; From 1241de1b9a775f7ce0e056ca0f551ac19a89e671 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Feb 2017 18:51:44 +0800 Subject: [PATCH 3149/4971] Create minimum-absolute-difference-in-bst.py --- Python/minimum-absolute-difference-in-bst.py | 46 ++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/minimum-absolute-difference-in-bst.py diff --git a/Python/minimum-absolute-difference-in-bst.py b/Python/minimum-absolute-difference-in-bst.py new file mode 100644 index 000000000..daaafe6df --- /dev/null +++ b/Python/minimum-absolute-difference-in-bst.py @@ -0,0 +1,46 @@ +# Time: O(n) +# Space: O(h) + +# Given a binary search tree with non-negative values, +# find the minimum absolute difference between values of any two nodes. +# +# Example: +# +# Input: +# +# 1 +# \ +# 3 +# / +# 2 +# +# Output: +# 1 +# +# Explanation: +# The minimum absolute difference is 1, +# which is the difference between 2 and 1 (or between 2 and 3). +# Note: There are at least two nodes in this BST. +# +# 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 getMinimumDifference(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def inorderTraversal(root, prev, result): + if not root: + return (result, prev) + + result, prev = inorderTraversal(root.left, prev, result) + if prev: result = min(result, root.val - prev.val) + return inorderTraversal(root.right, root, result) + + return inorderTraversal(root, None, float("inf"))[0] From 9353a18fefbbf29b73564a2b820bce48e87c0ba7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Mar 2017 00:07:53 +0800 Subject: [PATCH 3150/4971] Create the-maze-iii.cpp --- C++/the-maze-iii.cpp | 75 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 C++/the-maze-iii.cpp diff --git a/C++/the-maze-iii.cpp b/C++/the-maze-iii.cpp new file mode 100644 index 000000000..6eacd3221 --- /dev/null +++ b/C++/the-maze-iii.cpp @@ -0,0 +1,75 @@ +// Time: O(max(r, c) * wlogw) +// Space: O(w^2) + +class Solution { +public: + string findShortestWay(vector>& maze, vector& ball, vector& hole) { + static const unordered_map> dirs = {{"u", {-1, 0}}, {"r", {0, 1}}, + {"l", {0, -1}}, {"d", {1, 0}}}; + queue heap; + unordered_set visited; + heap.emplace(0, make_pair("", ball)); + + while (!heap.empty()) { + int dist = 0; + string path; + vector node; + tie(dist, lvalue(tie(path, node))) = heap.front(); + heap.pop(); + if (visited.count(hash(maze, node))) { + continue; + } + + if (node[0] == hole[0] && + node[1] == hole[1]) { + return path; + } + + visited.emplace(hash(maze, node)); + for (const auto& kvp : dirs) { + int neighbor_dist = 0; + string dir; + vector neighbor; + tie(neighbor_dist, lvalue(tie(dir, neighbor))) = findNeighbor(maze, hole, node, kvp); + heap.emplace(dist + neighbor_dist, make_pair(path + dir, neighbor)); + } + } + + return "impossible"; + } + +private: + using node = pair>>; + + node findNeighbor(const vector>& maze, const vector& hole, + const vector& node, const pair>& kvp) { + string dir; + vector vec; + tie(dir, vec) = kvp; + vector cur_node = node; + int dist = 0; + + while (0 <= cur_node[0] + vec[0] && cur_node[0] + vec[0] < maze.size() && + 0 <= cur_node[1] + vec[1] && cur_node[1] + vec[1] < maze[0].size() && + !maze[cur_node[0] + vec[0]][cur_node[1] + vec[1]]) { + + cur_node[0] += vec[0]; + cur_node[1] += vec[1]; + ++dist; + if (cur_node[0] == hole[0] && + cur_node[1] == hole[1]) { + break; + } + } + return {dist, {dir, cur_node}}; + } + + int hash(const vector>& maze, const vector& node) { + return node[0] * maze[0].size() + node[1]; + } + + template + constexpr T &lvalue(T &&v) { + return v; + } +}; From 0f6ff7a4c1bbe655833649c5e70bc3ba42d682e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Mar 2017 00:08:58 +0800 Subject: [PATCH 3151/4971] Create the-maze-iii.py --- Python/the-maze-iii.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/the-maze-iii.py diff --git a/Python/the-maze-iii.py b/Python/the-maze-iii.py new file mode 100644 index 000000000..17e8d9792 --- /dev/null +++ b/Python/the-maze-iii.py @@ -0,0 +1,39 @@ +# Time: O(max(r, c) * wlogw) +# Space: O(w^2) + +class Solution(object): + def findShortestWay(self, maze, ball, hole): + """ + :type maze: List[List[int]] + :type ball: List[int] + :type hole: List[int] + :rtype: str + """ + ball, hole = tuple(ball), tuple(hole) + dirs = {'u' : (-1, 0), 'r' : (0, 1), 'l' : (0, -1), 'd': (1, 0)} + + def neighbors(maze, node): + for dir, vec in dirs.iteritems(): + cur_node, dist = list(node), 0 + while 0 <= cur_node[0]+vec[0] < len(maze) and \ + 0 <= cur_node[1]+vec[1] < len(maze[0]) and \ + not maze[cur_node[0]+vec[0]][cur_node[1]+vec[1]]: + cur_node[0] += vec[0] + cur_node[1] += vec[1] + dist += 1 + if tuple(cur_node) == hole: + break + yield tuple(cur_node), dir, dist + + heap = [(0, '', ball)] + visited = set() + while heap: + dist, path, node = heapq.heappop(heap) + if node == hole: return path + if node in visited: continue + visited.add(node) + print node + for neighbor, dir, neighbor_dist in neighbors(maze, node): + heapq.heappush(heap, (dist+neighbor_dist, path+dir, neighbor)) + + return "impossible" From 432ace8619e77440ea4c817c1ccfc1163fabebac Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Mar 2017 00:09:20 +0800 Subject: [PATCH 3152/4971] Update the-maze-iii.py --- Python/the-maze-iii.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/the-maze-iii.py b/Python/the-maze-iii.py index 17e8d9792..390bccf9b 100644 --- a/Python/the-maze-iii.py +++ b/Python/the-maze-iii.py @@ -32,7 +32,6 @@ def neighbors(maze, node): if node == hole: return path if node in visited: continue visited.add(node) - print node for neighbor, dir, neighbor_dist in neighbors(maze, node): heapq.heappush(heap, (dist+neighbor_dist, path+dir, neighbor)) From 85f8429a4ccaf5efab9a0089005d9bdb7e20ea43 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Mar 2017 00:10:22 +0800 Subject: [PATCH 3153/4971] Update the-maze-iii.py --- Python/the-maze-iii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/the-maze-iii.py b/Python/the-maze-iii.py index 390bccf9b..02be0681a 100644 --- a/Python/the-maze-iii.py +++ b/Python/the-maze-iii.py @@ -29,8 +29,8 @@ def neighbors(maze, node): visited = set() while heap: dist, path, node = heapq.heappop(heap) - if node == hole: return path if node in visited: continue + if node == hole: return path visited.add(node) for neighbor, dir, neighbor_dist in neighbors(maze, node): heapq.heappush(heap, (dist+neighbor_dist, path+dir, neighbor)) From 779a50905e45d6ab17f66999d7b96b143dc0e21c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Mar 2017 22:02:47 +0800 Subject: [PATCH 3154/4971] Create the-maze-ii.py --- Python/the-maze-ii.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/the-maze-ii.py diff --git a/Python/the-maze-ii.py b/Python/the-maze-ii.py new file mode 100644 index 000000000..421e44335 --- /dev/null +++ b/Python/the-maze-ii.py @@ -0,0 +1,37 @@ +# Time: O(max(r, c) * wlogw) +# Space: O(w^2) + +class Solution(object): + def shortestDistance(self, maze, start, destination): + """ + :type maze: List[List[int]] + :type start: List[int] + :type destination: List[int] + :rtype: int + """ + start, destination = tuple(start), tuple(destination) + + def neighbors(maze, node): + for dir in [(-1, 0), (0, 1), (0, -1), (1, 0)]: + cur_node, dist = list(node), 0 + while 0 <= cur_node[0]+dir[0] < len(maze) and \ + 0 <= cur_node[1]+dir[1] < len(maze[0]) and \ + not maze[cur_node[0]+dir[0]][cur_node[1]+dir[1]]: + cur_node[0] += dir[0] + cur_node[1] += dir[1] + dist += 1 + yield dist, tuple(cur_node) + + result = None + heap = [(0, start)] + visited = set() + while heap: + dist, node = heapq.heappop(heap) + if node in visited: continue + if node == destination: + result = min(result, dist) if result else dist + visited.add(node) + for neighbor_dist, neighbor in neighbors(maze, node): + heapq.heappush(heap, (dist+neighbor_dist, neighbor)) + + return result if result else -1 From a47fd2a8c681658821c355454730928168fe8abf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Mar 2017 22:41:16 +0800 Subject: [PATCH 3155/4971] Update the-maze-iii.cpp --- C++/the-maze-iii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/the-maze-iii.cpp b/C++/the-maze-iii.cpp index 6eacd3221..cf2739527 100644 --- a/C++/the-maze-iii.cpp +++ b/C++/the-maze-iii.cpp @@ -6,7 +6,7 @@ class Solution { string findShortestWay(vector>& maze, vector& ball, vector& hole) { static const unordered_map> dirs = {{"u", {-1, 0}}, {"r", {0, 1}}, {"l", {0, -1}}, {"d", {1, 0}}}; - queue heap; + priority_queue, greater> heap; unordered_set visited; heap.emplace(0, make_pair("", ball)); @@ -14,7 +14,7 @@ class Solution { int dist = 0; string path; vector node; - tie(dist, lvalue(tie(path, node))) = heap.front(); + tie(dist, lvalue(tie(path, node))) = heap.top(); heap.pop(); if (visited.count(hash(maze, node))) { continue; From f2319e3f2b2fa025f1f0b53e094d20a570ef3cc2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Mar 2017 22:47:01 +0800 Subject: [PATCH 3156/4971] Create the-maze-ii.cpp --- C++/the-maze-ii.cpp | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 C++/the-maze-ii.cpp diff --git a/C++/the-maze-ii.cpp b/C++/the-maze-ii.cpp new file mode 100644 index 000000000..0d7a55eea --- /dev/null +++ b/C++/the-maze-ii.cpp @@ -0,0 +1,59 @@ +// Time: O(max(r, c) * wlogw) +// Space: O(w^2) + +class Solution { +public: + int shortestDistance(vector>& maze, vector& start, vector& destination) { + static const vector> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}}; + int result = -1; + priority_queue, greater> heap; + unordered_set visited; + heap.emplace(0, start); + + while (!heap.empty()) { + int dist = 0; + vector node; + tie(dist, node) = heap.top(); + heap.pop(); + if (visited.count(hash(maze, node))) { + continue; + } + if (node[0] == destination[0] && + node[1] == destination[1]) { + result = result != -1 ? min(result, dist) : dist; + } + + visited.emplace(hash(maze, node)); + for (const auto& dir : dirs) { + int neighbor_dist = 0; + vector neighbor; + tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir); + heap.emplace(dist + neighbor_dist, neighbor); + } + } + + return result; + } + +private: + using node = pair>; + + node findNeighbor(const vector>& maze, + const vector& node, const vector& dir) { + vector cur_node = node; + int dist = 0; + + while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() && + 0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() && + !maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) { + cur_node[0] += dir[0]; + cur_node[1] += dir[1]; + ++dist; + } + return {dist, cur_node}; + } + + int hash(const vector>& maze, const vector& node) { + return node[0] * maze[0].size() + node[1]; + } +}; From aac0373c4b57fda54ba687627e4597fdbc9176fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Mar 2017 22:55:27 +0800 Subject: [PATCH 3157/4971] Update the-maze-ii.cpp --- C++/the-maze-ii.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/the-maze-ii.cpp b/C++/the-maze-ii.cpp index 0d7a55eea..cc401bbb9 100644 --- a/C++/the-maze-ii.cpp +++ b/C++/the-maze-ii.cpp @@ -5,7 +5,6 @@ class Solution { public: int shortestDistance(vector>& maze, vector& start, vector& destination) { static const vector> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}}; - int result = -1; priority_queue, greater> heap; unordered_set visited; heap.emplace(0, start); @@ -20,7 +19,7 @@ class Solution { } if (node[0] == destination[0] && node[1] == destination[1]) { - result = result != -1 ? min(result, dist) : dist; + return dist; } visited.emplace(hash(maze, node)); @@ -32,7 +31,7 @@ class Solution { } } - return result; + return -1; } private: From d317fd778f9f3476efa5e8634d80f4aeb8b7fe0a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Mar 2017 22:57:06 +0800 Subject: [PATCH 3158/4971] Update the-maze-ii.py --- Python/the-maze-ii.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Python/the-maze-ii.py b/Python/the-maze-ii.py index 421e44335..9c9f4d362 100644 --- a/Python/the-maze-ii.py +++ b/Python/the-maze-ii.py @@ -22,16 +22,15 @@ def neighbors(maze, node): dist += 1 yield dist, tuple(cur_node) - result = None heap = [(0, start)] visited = set() while heap: dist, node = heapq.heappop(heap) if node in visited: continue if node == destination: - result = min(result, dist) if result else dist + return dist visited.add(node) for neighbor_dist, neighbor in neighbors(maze, node): heapq.heappush(heap, (dist+neighbor_dist, neighbor)) - return result if result else -1 + return -1 From e60291d086b65ff9589013095ddc1f748b1f4413 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Mar 2017 23:03:01 +0800 Subject: [PATCH 3159/4971] Update the-maze-ii.cpp --- C++/the-maze-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/the-maze-ii.cpp b/C++/the-maze-ii.cpp index cc401bbb9..1256ced9b 100644 --- a/C++/the-maze-ii.cpp +++ b/C++/the-maze-ii.cpp @@ -1,5 +1,5 @@ // Time: O(max(r, c) * wlogw) -// Space: O(w^2) +// Space: O(w) class Solution { public: From 7c5f9d6dead73c09298e6c53384f2fd3713108aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Mar 2017 23:03:21 +0800 Subject: [PATCH 3160/4971] Update the-maze-ii.py --- Python/the-maze-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/the-maze-ii.py b/Python/the-maze-ii.py index 9c9f4d362..534ad0925 100644 --- a/Python/the-maze-ii.py +++ b/Python/the-maze-ii.py @@ -1,5 +1,5 @@ # Time: O(max(r, c) * wlogw) -# Space: O(w^2) +# Space: O(w) class Solution(object): def shortestDistance(self, maze, start, destination): From a3a5ca2646672e9718f0a0d69b4bab5c6f915cb0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Mar 2017 23:04:17 +0800 Subject: [PATCH 3161/4971] Create the-maze.py --- Python/the-maze.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/the-maze.py diff --git a/Python/the-maze.py b/Python/the-maze.py new file mode 100644 index 000000000..573eeebd4 --- /dev/null +++ b/Python/the-maze.py @@ -0,0 +1,36 @@ +# Time: O(max(r, c) * w) +# Space: O(w) + +class Solution(object): + def hasPath(self, maze, start, destination): + """ + :type maze: List[List[int]] + :type start: List[int] + :type destination: List[int] + :rtype: bool + """ + start, destination = tuple(start), tuple(destination) + + def neighbors(maze, node): + for dir in [(-1, 0), (0, 1), (0, -1), (1, 0)]: + cur_node, dist = list(node), 0 + while 0 <= cur_node[0]+dir[0] < len(maze) and \ + 0 <= cur_node[1]+dir[1] < len(maze[0]) and \ + not maze[cur_node[0]+dir[0]][cur_node[1]+dir[1]]: + cur_node[0] += dir[0] + cur_node[1] += dir[1] + dist += 1 + yield dist, tuple(cur_node) + + queue = collections.deque([(0, start)]) + visited = set() + while queue: + dist, node = queue.popleft() + if node in visited: continue + if node == destination: + return True + visited.add(node) + for neighbor_dist, neighbor in neighbors(maze, node): + queue.append((dist+neighbor_dist, neighbor)) + + return False From 0bce6e74be3e9977b8518e0f3f9aa9b6fcbd3e04 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Mar 2017 23:07:45 +0800 Subject: [PATCH 3162/4971] Create the-maze.cpp --- C++/the-maze.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 C++/the-maze.cpp diff --git a/C++/the-maze.cpp b/C++/the-maze.cpp new file mode 100644 index 000000000..6a80e40e6 --- /dev/null +++ b/C++/the-maze.cpp @@ -0,0 +1,58 @@ +// Time: O(max(r, c) * w) +// Space: O(w) + +class Solution { +public: + bool hasPath(vector>& maze, vector& start, vector& destination) { + static const vector> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}}; + queue q; + unordered_set visited; + q.emplace(0, start); + + while (!q.empty()) { + int dist = 0; + vector node; + tie(dist, node) = q.front(); + q.pop(); + if (visited.count(hash(maze, node))) { + continue; + } + if (node[0] == destination[0] && + node[1] == destination[1]) { + return true; + } + + visited.emplace(hash(maze, node)); + for (const auto& dir : dirs) { + int neighbor_dist = 0; + vector neighbor; + tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir); + q.emplace(dist + neighbor_dist, neighbor); + } + } + + return false; + } + +private: + using node = pair>; + + node findNeighbor(const vector>& maze, + const vector& node, const vector& dir) { + vector cur_node = node; + int dist = 0; + + while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() && + 0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() && + !maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) { + cur_node[0] += dir[0]; + cur_node[1] += dir[1]; + ++dist; + } + return {dist, cur_node}; + } + + int hash(const vector>& maze, const vector& node) { + return node[0] * maze[0].size() + node[1]; + } +}; From e8af44791a917557f62fb6cc92c62e22c13f06a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Mar 2017 00:14:37 +0800 Subject: [PATCH 3163/4971] Create increasing-subsequences.cpp --- C++/increasing-subsequences.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/increasing-subsequences.cpp diff --git a/C++/increasing-subsequences.cpp b/C++/increasing-subsequences.cpp new file mode 100644 index 000000000..50cd7c944 --- /dev/null +++ b/C++/increasing-subsequences.cpp @@ -0,0 +1,30 @@ +// Time: O(n * 2^n) +// Space: O(n^2) + +class Solution { +public: + vector> findSubsequences(vector& nums) { + vector> result; + vector seq; + findSubsequencesHelper(nums, 0, &seq, &result); + return result; + } + + void findSubsequencesHelper(const vector& nums, int i, + vector *seq, + vector> *result) { + if (seq->size() >= 2) { + result->emplace_back(*seq); + } + unordered_set lookup; + for (; i < nums.size(); ++i) { + if ((seq->empty() || nums[i] >= seq->back()) && + lookup.find(nums[i]) == lookup.end()) { + lookup.emplace(nums[i]); + seq->emplace_back(nums[i]); + findSubsequencesHelper(nums, i + 1, seq, result); + seq->pop_back(); + } + } + } +}; From 00c9213c4754801ee6a74755031adede5cc565f4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Mar 2017 00:22:42 +0800 Subject: [PATCH 3164/4971] Create increasing-subsequences.py --- Python/increasing-subsequences.py | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/increasing-subsequences.py diff --git a/Python/increasing-subsequences.py b/Python/increasing-subsequences.py new file mode 100644 index 000000000..e246be299 --- /dev/null +++ b/Python/increasing-subsequences.py @@ -0,0 +1,38 @@ +# Time: O(n * 2^n) +# Space: O(n^2) + +# Given an integer array, your task is +# to find all the different possible increasing +# subsequences of the given array, +# and the length of an increasing subsequence should be at least 2 . +# +# Example: +# Input: [4, 6, 7, 7] +# Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]] +# Note: +# The length of the given array will not exceed 15. +# The range of integer in the given array is [-100,100]. +# The given array may contain duplicates, +# and two equal integers should also be considered as a special case of increasing sequence. + +class Solution(object): + def findSubsequences(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + def findSubsequencesHelper(nums, pos, seq, result): + if len(seq) >= 2: + result.append(list(seq)) + lookup = set() + for i in xrange(pos, len(nums)): + if (not seq or nums[i] >= seq[-1]) and \ + nums[i] not in lookup: + lookup.add(nums[i]) + seq.append(nums[i]) + findSubsequencesHelper(nums, i+1, seq, result) + seq.pop() + + result, seq = [], [] + findSubsequencesHelper(nums, 0, seq, result) + return result From 8b0935251953c66b08cd6d19c9f126363210e996 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Mar 2017 01:24:22 +0800 Subject: [PATCH 3165/4971] Create longest-word-in-dictionary-through-deleting.cpp --- ...st-word-in-dictionary-through-deleting.cpp | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/longest-word-in-dictionary-through-deleting.cpp diff --git a/C++/longest-word-in-dictionary-through-deleting.cpp b/C++/longest-word-in-dictionary-through-deleting.cpp new file mode 100644 index 000000000..f2e3f438d --- /dev/null +++ b/C++/longest-word-in-dictionary-through-deleting.cpp @@ -0,0 +1,25 @@ +// Time: O(dlogd) +// Space: O(1) + +class Solution { +public: + string findLongestWord(string s, vector& d) { + sort(d.begin(), d.end(), + [](const string& a, const string&b) { + return a.length() != b.length() ? a.length() > b.length() : a < b; + }); + + for (const auto& word : d) { + int i = 0; + for (const auto& c : s) { + if (i < word.length() && word[i] == c) { + ++i; + } + } + if (i == word.length()) { + return word; + } + } + return ""; + } +}; From 468dc8599377c0a3c4b1a33c45fedaa92a82db92 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Mar 2017 01:26:07 +0800 Subject: [PATCH 3166/4971] Create longest-word-in-dictionary-through-deleting.py --- ...est-word-in-dictionary-through-deleting.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/longest-word-in-dictionary-through-deleting.py diff --git a/Python/longest-word-in-dictionary-through-deleting.py b/Python/longest-word-in-dictionary-through-deleting.py new file mode 100644 index 000000000..7b69a39d0 --- /dev/null +++ b/Python/longest-word-in-dictionary-through-deleting.py @@ -0,0 +1,43 @@ +# Time: O(dlogd) +# Space: O(1) + +# Given a string and a string dictionary, +# find the longest string in the dictionary +# that can be formed by deleting some characters of the given string. +# If there are more than one possible results, +# return the longest word with the smallest lexicographical order. +# If there is no possible result, return the empty string. +# +# Example 1: +# Input: +# s = "abpcplea", d = ["ale","apple","monkey","plea"] +# +# Output: +# "apple" +# Example 2: +# Input: +# s = "abpcplea", d = ["a","b","c"] +# +# Output: +# "a" +# Note: +# All the strings in the input will only contain lower-case letters. +# The size of the dictionary won't exceed 1,000. +# The length of all the strings in the input won't exceed 1,000. + +class Solution(object): + def findLongestWord(self, s, d): + """ + :type s: str + :type d: List[str] + :rtype: str + """ + d.sort(key = lambda x: (-len(x), x)) + for word in d: + i = 0 + for c in s: + if i < len(word) and word[i] == c: + i += 1 + if i == len(word): + return word + return "" From a58403fdd0c6d5be62acedc7b6fa4f1f907b3c96 Mon Sep 17 00:00:00 2001 From: Piyush Sharma Date: Wed, 15 Mar 2017 10:57:53 -0700 Subject: [PATCH 3167/4971] Fix to create a complete BST Given a list [1,2,3,4,5], the previous solution will create this: 3 / \ 2 4 / / 1 5 But a complete perfect BST should look like this: 4 / \ 3 5 / \ 1 2 There are two cases: Either case 1: the left subtree of the root is perfect and the right subtree has less nodes or case 2: the left subtree of the root has more nodes and the right subtree is perfect. In both cases the number of nodes in the perfect subtree is some 2**d - 1 so the root is the 2**dth node counting from the left (case 1) or the right (case 2) --- ...vert-sorted-array-to-binary-search-tree.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 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..ca9e1314d 100644 --- a/Python/convert-sorted-array-to-binary-search-tree.py +++ b/Python/convert-sorted-array-to-binary-search-tree.py @@ -17,10 +17,27 @@ class Solution: def sortedArrayToBST(self, num): return self.sortedArrayToBSTRecu(num, 0, len(num)) + @staticmethod + def perfect_tree_pivot(n): + """ + Find the point to partition n keys for a perfect binary search tree + """ + x = 1 + # find a power of 2 <= n//2 + # while x <= n//2: # this loop could probably be written more elegantly :) + # x *= 2 + x = 1 << (n.bit_length() - 1) # use the left bit shift, same as multiplying x by 2**n-1 + + if x // 2 - 1 <= (n - x): + return x - 1 # case 1: the left subtree of the root is perfect and the right subtree has less nodes + else: + return n - x // 2 # case 2 == n - (x//2 - 1) - 1 : the left subtree of the root + # has more nodes and the right subtree is perfect. + def sortedArrayToBSTRecu(self, num, start, end): if start == end: return None - mid = start + (end - start) / 2 + mid = start + self.perfect_tree_pivot(end - start) node = TreeNode(num[mid]) node.left = self.sortedArrayToBSTRecu(num, start, mid) node.right = self.sortedArrayToBSTRecu(num, mid + 1, end) From be708adb771392c7443788ff1cdc88afd1ed0743 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Mar 2017 18:32:50 +0800 Subject: [PATCH 3168/4971] Create k-diff-pairs-in-an-array.cpp --- C++/k-diff-pairs-in-an-array.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/k-diff-pairs-in-an-array.cpp diff --git a/C++/k-diff-pairs-in-an-array.cpp b/C++/k-diff-pairs-in-an-array.cpp new file mode 100644 index 000000000..0d1d32fd5 --- /dev/null +++ b/C++/k-diff-pairs-in-an-array.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int findPairs(vector& nums, int k) { + if (k < 0) { + return 0; + } + unordered_set result, lookup; + for (const auto& num : nums) { + if (lookup.count(num - k)) { + result.emplace(num - k); + } + if (lookup.count(num + k)) { + result.emplace(num); + } + lookup.emplace(num); + } + return result.size(); + } +}; From 9e090675765a2c0c6412ee51d1e0e007404a30fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Mar 2017 18:36:28 +0800 Subject: [PATCH 3169/4971] Create k-diff-pairs-in-an-array.py --- Python/k-diff-pairs-in-an-array.py | 46 ++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/k-diff-pairs-in-an-array.py diff --git a/Python/k-diff-pairs-in-an-array.py b/Python/k-diff-pairs-in-an-array.py new file mode 100644 index 000000000..58a4b29b5 --- /dev/null +++ b/Python/k-diff-pairs-in-an-array.py @@ -0,0 +1,46 @@ +# Time: O(n) +# Space: O(n) + +# Total Accepted: 5671 +# Total Submissions: 20941 +# Difficulty: Easy +# Contributors: murali.kf370 +# Given an array of integers and an integer k, +# you need to find the number of unique k-diff pairs in the array. +# Here a k-diff pair is defined as an integer pair (i, j), +# where i and j are both numbers in the array and their absolute difference is k. +# +# Example 1: +# Input: [3, 1, 4, 1, 5], k = 2 +# Output: 2 +# Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). +# Although we have two 1s in the input, we should only return the number of unique pairs. +# Example 2: +# Input:[1, 2, 3, 4, 5], k = 1 +# Output: 4 +# Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). +# Example 3: +# Input: [1, 3, 1, 5, 4], k = 0 +# Output: 1 +# Explanation: There is one 0-diff pair in the array, (1, 1). +# Note: +# The pairs (i, j) and (j, i) count as the same pair. +# The length of the array won't exceed 10,000. +# All the integers in the given input belong to the range: [-1e7, 1e7]. + +class Solution(object): + def findPairs(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + if k < 0: return 0 + result, lookup = set(), set() + for num in nums: + if num-k in lookup: + result.add(num-k) + if num+k in lookup: + result.add(num) + lookup.add(num) + return len(result) From 992f1043f4f838f4ba179ffe69670c3b17ee7dbf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Mar 2017 19:18:55 +0800 Subject: [PATCH 3170/4971] Create keyboard-row.cpp --- C++/keyboard-row.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/keyboard-row.cpp diff --git a/C++/keyboard-row.cpp b/C++/keyboard-row.cpp new file mode 100644 index 000000000..d6820da13 --- /dev/null +++ b/C++/keyboard-row.cpp @@ -0,0 +1,30 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector findWords(vector& words) { + static const vector> rows{{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'}, + {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'}, + {'z', 'x', 'c', 'v', 'b' ,'n', 'm'}}; + + vector result; + for (const auto& word : words) { + int k = 0; + for (int i = 0; i < rows.size(); ++i) { + if (rows[i].count(tolower(word[0]))) { + k = i; + break; + } + } + result.emplace_back(word); + for (const auto& c: word) { + if (!rows[k].count(tolower(c))) { + result.pop_back(); + break; + } + } + } + return result; + } +}; From 3e985b0e7696f575faafa7c211e138b139b9a2ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Mar 2017 19:25:34 +0800 Subject: [PATCH 3171/4971] Create keyboard-row.py --- Python/keyboard-row.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/keyboard-row.py diff --git a/Python/keyboard-row.py b/Python/keyboard-row.py new file mode 100644 index 000000000..13314b621 --- /dev/null +++ b/Python/keyboard-row.py @@ -0,0 +1,36 @@ +# Time: O(n) +# Space: O(1) + +# Given a List of words, return the words that can be typed +# using letters of alphabet on only one row's of American keyboard like the image below. +# +# Example 1: +# Input: ["Hello", "Alaska", "Dad", "Peace"] +# Output: ["Alaska", "Dad"] +# Note: +# You may use one character in the keyboard more than once. +# You may assume the input string will only contain letters of alphabet. + +class Solution(object): + def findWords(self, words): + """ + :type words: List[str] + :rtype: List[str] + """ + rows = [set(['q', 'w', 'e', 'r', 't', 'y','u', 'i', 'o', 'p']), + set(['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']), + set(['z', 'x', 'c', 'v', 'b' ,'n', 'm'])] + + result = [] + for word in words: + k = 0 + for i in xrange(len(rows)): + if word[0].lower() in rows[i]: + k = i + break + for c in word: + if c.lower() not in rows[k]: + break + else: + result.append(word) + return result From fac315560ba121844930cd4521497258805eac60 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 00:50:09 +0800 Subject: [PATCH 3172/4971] Create freedom-trail.cpp --- C++/freedom-trail.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/freedom-trail.cpp diff --git a/C++/freedom-trail.cpp b/C++/freedom-trail.cpp new file mode 100644 index 000000000..0efa4a994 --- /dev/null +++ b/C++/freedom-trail.cpp @@ -0,0 +1,30 @@ +// Time: O(k) ~ O(k * r^2) +// Space: O(r) + +class Solution { +public: + int findRotateSteps(string ring, string key) { + unordered_map> lookup; + for (int i = 0; i < ring.size(); ++i) { + lookup[ring[i]].emplace_back(i); + } + int cnt = 0; + + vector> dp(2, vector (ring.size())); + vector tmp(1, 0); + vector *prev = &tmp; + for (int i = 1; i <= key.size(); ++i) { + fill(dp[i % 2].begin(), dp[i % 2].end(), numeric_limits::max()); + for (const auto& j : lookup[key[i - 1]]) { + for (const auto& k : *prev) { + int min_dist = min((k + ring.size() - j) % ring.size(), + (j + ring.size() - k) % ring.size()) + + dp[(i - 1) % 2][k]; + dp[i % 2][j] = min(dp[i % 2][j], min_dist); + } + } + prev = &lookup[key[i - 1]]; + } + return *min_element(dp[key.size() % 2].begin(), dp[key.size() % 2].end()) + key.size(); + } +}; From 9bb58d8f53dd216e248bbfff79e60aface55ee1f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 00:50:45 +0800 Subject: [PATCH 3173/4971] Update freedom-trail.cpp --- C++/freedom-trail.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/freedom-trail.cpp b/C++/freedom-trail.cpp index 0efa4a994..856c10cae 100644 --- a/C++/freedom-trail.cpp +++ b/C++/freedom-trail.cpp @@ -8,8 +8,7 @@ class Solution { for (int i = 0; i < ring.size(); ++i) { lookup[ring[i]].emplace_back(i); } - int cnt = 0; - + vector> dp(2, vector (ring.size())); vector tmp(1, 0); vector *prev = &tmp; From e2112a87659d7090d23b12159a45727524ceae84 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 00:52:51 +0800 Subject: [PATCH 3174/4971] Update freedom-trail.cpp --- C++/freedom-trail.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/freedom-trail.cpp b/C++/freedom-trail.cpp index 856c10cae..2e97a2482 100644 --- a/C++/freedom-trail.cpp +++ b/C++/freedom-trail.cpp @@ -4,7 +4,7 @@ class Solution { public: int findRotateSteps(string ring, string key) { - unordered_map> lookup; + unordered_map> lookup; for (int i = 0; i < ring.size(); ++i) { lookup[ring[i]].emplace_back(i); } From 42dbd256abdbaf7d5c18a6f776ca1a76da4375c6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 01:09:05 +0800 Subject: [PATCH 3175/4971] Create freedom-trail.py --- Python/freedom-trail.py | 61 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/freedom-trail.py diff --git a/Python/freedom-trail.py b/Python/freedom-trail.py new file mode 100644 index 000000000..227b48c74 --- /dev/null +++ b/Python/freedom-trail.py @@ -0,0 +1,61 @@ +# Time: O(k) ~ O(k * r^2) +# Space: O(r) + +# In the video game Fallout 4, the quest "Road to Freedom" +# requires players to reach a metal dial called the "Freedom Trail Ring", +# and use the dial to spell a specific keyword in order to open the door. +# +# Given a string ring, which represents the code engraved on the outer ring +# and another string key, which represents the keyword needs to be spelled. +# You need to find the minimum number of steps in order to spell all the characters in the keyword. +# +# Initially, the first character of the ring is aligned at 12:00 direction. +# You need to spell all the characters in the string key one by one +# by rotating the ring clockwise or anticlockwise to make each character of +# the string key aligned at 12:00 direction and then by pressing the center button. +# At the stage of rotating the ring to spell the key character key[i]: +# You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. +# The final purpose of the rotation is to align one of the string ring's +# characters at the 12:00 direction, where this character must equal to the character key[i]. +# If the character key[i] has been aligned at the 12:00 direction, +# you need to press the center button to spell, which also counts as 1 step. +# After the pressing, you could begin to spell the next character in the key (next stage), +# otherwise, you've finished all the spelling. +# Example: +# +# Input: ring = "godding", key = "gd" +# Output: 4 +# Explanation: +# For the first key character 'g', since it is already in place, we just need 1 step to spell this character. +# For the second key character 'd', +# we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo". +# Also, we need 1 more step for spelling. +# So the final output is 4. +# Note: +# Length of both ring and key will be in range 1 to 100. +# There are only lowercase letters in both strings and might be some duplcate characters in both strings. +# It's guaranteed that string key could always be spelled by rotating the string ring. + +class Solution(object): + def findRotateSteps(self, ring, key): + """ + :type ring: str + :type key: str + :rtype: int + """ + lookup = collections.defaultdict(list) + for i in xrange(len(ring)): + lookup[ring[i]].append(i) + + dp = [[0] * len(ring) for _ in xrange(2)] + prev = [0] + for i in xrange(1, len(key)+1): + dp[i%2] = [float("inf")] * len(ring) + for j in lookup[key[i-1]]: + for k in prev: + dp[i%2][j] = min(dp[i%2][j], + min((k+len(ring)-j) % len(ring), \ + (j+len(ring)-k) % len(ring)) + \ + dp[(i-1) % 2][k]) + prev = lookup[key[i-1]] + return min(dp[len(key)%2]) + len(key) From 3dc9091dc398fca92ca9a498153a0ef9f82392f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 01:14:39 +0800 Subject: [PATCH 3176/4971] Update freedom-trail.cpp --- C++/freedom-trail.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/C++/freedom-trail.cpp b/C++/freedom-trail.cpp index 2e97a2482..8387cee40 100644 --- a/C++/freedom-trail.cpp +++ b/C++/freedom-trail.cpp @@ -8,21 +8,18 @@ class Solution { for (int i = 0; i < ring.size(); ++i) { lookup[ring[i]].emplace_back(i); } - + vector> dp(2, vector (ring.size())); - vector tmp(1, 0); - vector *prev = &tmp; for (int i = 1; i <= key.size(); ++i) { fill(dp[i % 2].begin(), dp[i % 2].end(), numeric_limits::max()); for (const auto& j : lookup[key[i - 1]]) { - for (const auto& k : *prev) { + for (const auto& k : (i > 1 ? lookup[key[i - 2]] : vector(1))) { int min_dist = min((k + ring.size() - j) % ring.size(), (j + ring.size() - k) % ring.size()) + dp[(i - 1) % 2][k]; dp[i % 2][j] = min(dp[i % 2][j], min_dist); } } - prev = &lookup[key[i - 1]]; } return *min_element(dp[key.size() % 2].begin(), dp[key.size() % 2].end()) + key.size(); } From bd0dd63a9c38579ca9596e8024e752dc1b8a1109 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 17:15:44 +0800 Subject: [PATCH 3177/4971] Create word-abbreviation.py --- Python/word-abbreviation.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/word-abbreviation.py diff --git a/Python/word-abbreviation.py b/Python/word-abbreviation.py new file mode 100644 index 000000000..ef666f0a3 --- /dev/null +++ b/Python/word-abbreviation.py @@ -0,0 +1,35 @@ +# Time: O(n * l) ~ O(n^2 * l^2) +# Space: O(n * l) + +class Solution(object): + def wordsAbbreviation(self, dict): + """ + :type dict: List[str] + :rtype: List[str] + """ + def isUnique(prefix, words): + return sum(word.startswith(prefix) for word in words) == 1 + + def toAbbr(prefix, word): + abbr = prefix + str(len(word) - 1 - len(prefix)) + word[-1] + return abbr if len(abbr) < len(word) else word + + abbr_to_word = collections.defaultdict(set) + word_to_abbr = {} + + for word in dict: + prefix = word[:1] + abbr_to_word[toAbbr(prefix, word)].add(word) + + for abbr, conflicts in abbr_to_word.iteritems(): + if len(conflicts) > 1: + for word in conflicts: + for i in xrange(2, len(word)): + prefix = word[:i] + if isUnique(prefix, conflicts): + word_to_abbr[word] = toAbbr(prefix, word) + break + else: + word_to_abbr[conflicts.pop()] = abbr + + return [word_to_abbr[word] for word in dict] From 0259de25b39ee37962b1f3803e3e7bddaea5b4ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 17:49:36 +0800 Subject: [PATCH 3178/4971] Create word-abbreviation.cpp --- C++/word-abbreviation.cpp | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 C++/word-abbreviation.cpp diff --git a/C++/word-abbreviation.cpp b/C++/word-abbreviation.cpp new file mode 100644 index 000000000..2303f6a1c --- /dev/null +++ b/C++/word-abbreviation.cpp @@ -0,0 +1,57 @@ +// Time: O(n * l) ~ O(n^2 * l^2) +// Space: O(n * l) + +class Solution { +public: + vector wordsAbbreviation(vector& dict) { + unordered_map> abbr_to_word; + unordered_map word_to_abbr; + + for (const auto& word : dict) { + const auto prefix = word.substr(0, 1); + abbr_to_word[toAbbr(prefix, word)].emplace(word); + } + + for (const auto& kvp : abbr_to_word) { + if (kvp.second.size() > 1) { + for (const auto& word : kvp.second) { + for (int i = 2; i < word.length(); ++i) { + const auto prefix = word.substr(0, i); + if (isUnique(prefix, kvp.second)) { + word_to_abbr[word] = toAbbr(prefix, word); + break; + } + } + } + } else { + word_to_abbr[*kvp.second.begin()] = kvp.first; + } + } + + vector result; + for (const auto& word : dict) { + result.emplace_back(word_to_abbr[word]); + } + return result; + } + +private: + bool isUnique(const string& prefix, const unordered_set& words) { + int count = 0; + for (const auto& word : words) { + if (!word.compare(0, prefix.length(), prefix)) { + if (++count > 1) { + return false; + } + } + } + return true; + } + + string toAbbr(const string& prefix, const string& word) { + string abbr = prefix; + abbr += to_string(word.length() - 1 - prefix.length()); + abbr += word.back(); + return abbr.length() < word.length() ? abbr : word; + } +}; From f89e967d110289944dc8875ffa011d496b36a88e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 18:20:56 +0800 Subject: [PATCH 3179/4971] Create encode-and-decode-tinyurl.cpp --- C++/encode-and-decode-tinyurl.cpp | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/encode-and-decode-tinyurl.cpp diff --git a/C++/encode-and-decode-tinyurl.cpp b/C++/encode-and-decode-tinyurl.cpp new file mode 100644 index 000000000..8a5cb1d12 --- /dev/null +++ b/C++/encode-and-decode-tinyurl.cpp @@ -0,0 +1,42 @@ +// Time: O(1) +// Space: O(n) + +class Solution { +public: + Solution() : gen_((random_device())()) { + } + + // Encodes a URL to a shortened URL. + string encode(string longUrl) { + string key = getRand(); + while (lookup_.count(key)) { + key = getRand(); + } + lookup_[key] = longUrl; + return "http://tinyurl.com/" + key; + } + + // Decodes a shortened URL to its original URL. + string decode(string shortUrl) { + return lookup_[shortUrl.substr(tiny_url.length())]; + } + +private: + string getRand() { + string random; + for (int i = 0; i < random_length; ++i) { + random += alphabet_[uniform_int_distribution{0, alphabet_.length() - 1}(gen_)]; + } + return random; + } + + const int random_length = 6; + const string tiny_url = "http://tinyurl.com/"; + const string alphabet_ = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + default_random_engine gen_; + unordered_map lookup_; +}; + +// Your Solution object will be instantiated and called as such: +// Solution solution; +// solution.decode(solution.encode(url)); From b84c7c7b7e95589997ddb64bf56c8d47c2143862 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 18:37:03 +0800 Subject: [PATCH 3180/4971] Create encode-and-decode-tinyurl.py --- Python/encode-and-decode-tinyurl.py | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/encode-and-decode-tinyurl.py diff --git a/Python/encode-and-decode-tinyurl.py b/Python/encode-and-decode-tinyurl.py new file mode 100644 index 000000000..b112e211f --- /dev/null +++ b/Python/encode-and-decode-tinyurl.py @@ -0,0 +1,51 @@ +# Time: O(1) +# Space: O(n) + +# TinyURL is a URL shortening service where you enter a URL +# such as https://leetcode.com/problems/design-tinyurl and +# it returns a short URL such as http://tinyurl.com/4e9iAk. +# +# Design the encode and decode methods for the TinyURL service. +# There is no restriction on how your encode/decode algorithm should work. +# You just need to ensure that a URL can be encoded to a tiny URL +# and the tiny URL can be decoded to the original URL. + +class Codec: + def __init__(self): + self.__random_length = 6 + self.__tiny_url = "http://tinyurl.com/" + self.__alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + self.__lookup = {} + + + def encode(self, longUrl): + """Encodes a URL to a shortened URL. + + :type longUrl: str + :rtype: str + """ + def getRand(): + rand = [] + for _ in xrange(self.__random_length): + rand += self.__alphabet[random.randint(0, len(self.__alphabet)-1)] + return "".join(rand) + + key = getRand() + while key in self.__lookup: + key = getRand() + self.__lookup[key] = longUrl + return self.__tiny_url + key + + + def decode(self, shortUrl): + """Decodes a shortened URL to its original URL. + + :type shortUrl: str + :rtype: str + """ + return self.__lookup[shortUrl[len(self.__tiny_url):]] + + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.decode(codec.encode(url)) From 5bf89ae725fb2cd906e795b5145a1f167bacb07c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 18:45:38 +0800 Subject: [PATCH 3181/4971] Create detect-capital.cpp --- C++/detect-capital.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 C++/detect-capital.cpp diff --git a/C++/detect-capital.cpp b/C++/detect-capital.cpp new file mode 100644 index 000000000..59f287a8f --- /dev/null +++ b/C++/detect-capital.cpp @@ -0,0 +1,10 @@ +// Time: O(l) +// Space: O(1) + +class Solution { +public: + bool detectCapitalUse(string word) { + int count = count_if(word.begin(), word.end(), [](char c){ return isupper(c); }); + return count == word.length() || count == 0 || (count == 1 && isupper(word[0])); + } +}; From 3a22723c35da806e42d078e86d78c6d285ce42c8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 18:47:19 +0800 Subject: [PATCH 3182/4971] Create detect-capital.py --- Python/detect-capital.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/detect-capital.py diff --git a/Python/detect-capital.py b/Python/detect-capital.py new file mode 100644 index 000000000..c0949a7e5 --- /dev/null +++ b/Python/detect-capital.py @@ -0,0 +1,24 @@ +# Time: O(l) +# Space: O(1) + +# We define the usage of capitals in a word to be right when one of the following cases holds: +# +# All letters in this word are capitals, like "USA". +# All letters in this word are not capitals, like "leetcode". +# Only the first letter in this word is capital if it has more than one letter, like "Google". +# Otherwise, we define that this word doesn't use capitals in a right way. +# Example 1: +# Input: "USA" +# Output: True +# Example 2: +# Input: "FlaG" +# Output: False +# Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters. + +class Solution(object): + def detectCapitalUse(self, word): + """ + :type word: str + :rtype: bool + """ + return word.isupper() or word.islower() or word.istitle() From de82dadb411431dd2511060de65b4d68e6f88aa1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 18:50:42 +0800 Subject: [PATCH 3183/4971] Update word-abbreviation.cpp --- C++/word-abbreviation.cpp | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/C++/word-abbreviation.cpp b/C++/word-abbreviation.cpp index 2303f6a1c..ef4e94bbf 100644 --- a/C++/word-abbreviation.cpp +++ b/C++/word-abbreviation.cpp @@ -37,15 +37,10 @@ class Solution { private: bool isUnique(const string& prefix, const unordered_set& words) { - int count = 0; - for (const auto& word : words) { - if (!word.compare(0, prefix.length(), prefix)) { - if (++count > 1) { - return false; - } - } - } - return true; + return 1 == count_if(words.begin(), words.end(), + [&prefix](const string& word) { + return !word.compare(0, prefix.length(), prefix); + }); } string toAbbr(const string& prefix, const string& word) { From d24c5c8f1d173a58dffbb6c0861866a19ed505e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 19:49:50 +0800 Subject: [PATCH 3184/4971] Create construct-binary-tree-from-string.cpp --- C++/construct-binary-tree-from-string.cpp | 43 +++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 C++/construct-binary-tree-from-string.cpp diff --git a/C++/construct-binary-tree-from-string.cpp b/C++/construct-binary-tree-from-string.cpp new file mode 100644 index 000000000..1d86f1f81 --- /dev/null +++ b/C++/construct-binary-tree-from-string.cpp @@ -0,0 +1,43 @@ +// 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: + TreeNode* str2tree(string s) { + int i = 0; + return s.empty() ? nullptr : str2treeHelper(s, &i); + } + +private: + TreeNode* str2treeHelper(const string& s, int *i) { + auto start = *i; + if (s[*i] == '-') { + ++(*i); + } + while (isdigit(s[*i])) { + ++(*i); + } + + auto node = new TreeNode(stoi(s.substr(start, *i - start))); + if (s[*i] == '(') { + ++(*i); + node->left = str2treeHelper(s, i); + ++(*i); + } + if (s[*i] == '(') { + ++(*i); + node->right = str2treeHelper(s, i); + ++(*i); + } + return node; + } +}; From f23da49e3293f130d1404e68d37554eb6b736618 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 20:01:34 +0800 Subject: [PATCH 3185/4971] Update construct-binary-tree-from-string.cpp --- C++/construct-binary-tree-from-string.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/construct-binary-tree-from-string.cpp b/C++/construct-binary-tree-from-string.cpp index 1d86f1f81..0f2d1ce36 100644 --- a/C++/construct-binary-tree-from-string.cpp +++ b/C++/construct-binary-tree-from-string.cpp @@ -23,17 +23,17 @@ class Solution { if (s[*i] == '-') { ++(*i); } - while (isdigit(s[*i])) { + while (*i < s.length() && isdigit(s[*i])) { ++(*i); } auto node = new TreeNode(stoi(s.substr(start, *i - start))); - if (s[*i] == '(') { + if (*i < s.length() && s[*i] == '(') { ++(*i); node->left = str2treeHelper(s, i); ++(*i); } - if (s[*i] == '(') { + if (*i < s.length() && s[*i] == '(') { ++(*i); node->right = str2treeHelper(s, i); ++(*i); From 64bfcf8e87ef8186a446bce0ec73502e48b3b9a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 20:02:16 +0800 Subject: [PATCH 3186/4971] Create construct-binary-tree-from-string.py --- Python/construct-binary-tree-from-string.py | 32 +++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/construct-binary-tree-from-string.py diff --git a/Python/construct-binary-tree-from-string.py b/Python/construct-binary-tree-from-string.py new file mode 100644 index 000000000..c7bcaafab --- /dev/null +++ b/Python/construct-binary-tree-from-string.py @@ -0,0 +1,32 @@ +# 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 str2tree(self, s): + """ + :type s: str + :rtype: TreeNode + """ + def str2treeHelper(s, i): + start = i + if s[i] == '-': i += 1 + while i < len(s) and s[i].isdigit(): i += 1 + node = TreeNode(int(s[start:i])) + if i < len(s) and s[i] == '(': + i += 1 + node.left, i = str2treeHelper(s, i) + i += 1 + if i < len(s) and s[i] == '(': + i += 1 + node.right, i = str2treeHelper(s, i) + i += 1 + return node, i + + return str2treeHelper(s, 0)[0] if s else None From 39f6fe412d47be872f78c786b074bbddc35f1a7a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 21:34:23 +0800 Subject: [PATCH 3187/4971] Create next-greater-element-i.cpp --- C++/next-greater-element-i.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/next-greater-element-i.cpp diff --git a/C++/next-greater-element-i.cpp b/C++/next-greater-element-i.cpp new file mode 100644 index 000000000..28bdc2623 --- /dev/null +++ b/C++/next-greater-element-i.cpp @@ -0,0 +1,27 @@ +// Time: O(m + n) +// Space: O(m + n) + +class Solution { +public: + vector nextGreaterElement(vector& findNums, vector& nums) { + stack stk; + unordered_map lookup; + for (const auto& num : nums) { + while (!stk.empty() && num > stk.top()) { + lookup[stk.top()] = num; + stk.pop(); + } + stk.emplace(num); + } + while (!stk.empty()) { + lookup[stk.top()] = -1; + stk.pop(); + } + + vector result; + for (const auto& num : findNums) { + result.emplace_back(lookup[num]); + } + return result; + } +}; From 555dc74ad29b99fd4cf4c3ba97b7edfdaf8e485f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 21:39:46 +0800 Subject: [PATCH 3188/4971] Create next-greater-element-i.py --- Python/next-greater-element-i.py | 41 ++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/next-greater-element-i.py diff --git a/Python/next-greater-element-i.py b/Python/next-greater-element-i.py new file mode 100644 index 000000000..10463b33a --- /dev/null +++ b/Python/next-greater-element-i.py @@ -0,0 +1,41 @@ +# Time: O(m + n) +# Space: O(m + n) + +# You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. +# Find all the next greater numbers for nums1's elements in the corresponding places of nums2. +# +# The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. +# If it does not exist, output -1 for this number. +# +# Example 1: +# Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. +# Output: [-1,3,-1] +# Explanation: +# For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. +# For number 1 in the first array, the next greater number for it in the second array is 3. +# For number 2 in the first array, there is no next greater number for it in the second array, so output -1. +# Example 2: +# Input: nums1 = [2,4], nums2 = [1,2,3,4]. +# Output: [3,-1] +# Explanation: +# For number 2 in the first array, the next greater number for it in the second array is 3. +# For number 4 in the first array, there is no next greater number for it in the second array, so output -1. +# Note: +# All elements in nums1 and nums2 are unique. +# The length of both nums1 and nums2 would not exceed 1000. + +class Solution(object): + def nextGreaterElement(self, findNums, nums): + """ + :type findNums: List[int] + :type nums: List[int] + :rtype: List[int] + """ + stk, lookup = [], {} + for num in nums: + while stk and num > stk[-1]: + lookup[stk.pop()] = num + stk.append(num) + while stk: + lookup[stk.pop()] = -1 + return map(lambda x : lookup[x], findNums) From 3a371b40388f542e34fb98d4a3e0283da27e1733 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 21:55:32 +0800 Subject: [PATCH 3189/4971] Create next-greater-element-ii.cpp --- C++/next-greater-element-ii.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/next-greater-element-ii.cpp diff --git a/C++/next-greater-element-ii.cpp b/C++/next-greater-element-ii.cpp new file mode 100644 index 000000000..04c6440bf --- /dev/null +++ b/C++/next-greater-element-ii.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector nextGreaterElements(vector& nums) { + vector result(nums.size()); + stack stk; + for (int i = 2 * nums.size() - 1; i >= 0; --i) { + while (!stk.empty() && stk.top() <= nums[i % nums.size()]) { + stk.pop(); + } + result[i % nums.size()] = stk.empty() ? -1 : stk.top(); + stk.emplace(nums[i % nums.size()]); + } + return result; + } +}; From f16667cb81907f0370cbb4f070b2dbf56593379d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 21:59:53 +0800 Subject: [PATCH 3190/4971] Create next-greater-element-ii.py --- Python/next-greater-element-ii.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/next-greater-element-ii.py diff --git a/Python/next-greater-element-ii.py b/Python/next-greater-element-ii.py new file mode 100644 index 000000000..03ee1c106 --- /dev/null +++ b/Python/next-greater-element-ii.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(n) + +# Given a circular array (the next element of the last element is the first element of the array), +# print the Next Greater Number for every element. +# The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, +# which means you could search circularly to find its next greater number. +# If it doesn't exist, output -1 for this number. +# +# Example 1: +# Input: [1,2,1] +# Output: [2,-1,2] +# Explanation: The first 1's next greater number is 2; +# The number 2 can't find next greater number; +# The second 1's next greater number needs to search circularly, which is also 2. +# Note: The length of given array won't exceed 10000. + +class Solution(object): + def nextGreaterElements(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + result, stk = [0] * len(nums), [] + for i in reversed(xrange(2*len(nums))): + while stk and stk[-1] <= nums[i % len(nums)]: + stk.pop() + result[i % len(nums)] = stk[-1] if stk else -1 + stk.append(nums[i % len(nums)]) + return result From e40af5c1ce2d2f770150e9629d81b21187800a12 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 22:13:12 +0800 Subject: [PATCH 3191/4971] Create base-7.cpp --- C++/base-7.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/base-7.cpp diff --git a/C++/base-7.cpp b/C++/base-7.cpp new file mode 100644 index 000000000..0895eb6b3 --- /dev/null +++ b/C++/base-7.cpp @@ -0,0 +1,32 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + string convertToBase7(int num) { + if (num == 0) { + return "0"; + } + string result; + int n = abs(num); + while (n) { + result.append(to_string(n % 7)); + n /= 7; + } + reverse(result.begin(), result.end()); + return num >= 0 ? result : "-" + result; + } +}; + +class Solution2 { +public: + string convertToBase7(int num) { + if (num < 0) { + return string("-").append(convertToBase7(-num)); + } + if (num < 7) { + return to_string(num); + } + return convertToBase7(num / 7).append(to_string(num % 7)); + } +}; From 9b355f51f6aa4b352c9216027781494bc349fc46 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 22:16:19 +0800 Subject: [PATCH 3192/4971] Update base-7.cpp --- C++/base-7.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/C++/base-7.cpp b/C++/base-7.cpp index 0895eb6b3..e568211c3 100644 --- a/C++/base-7.cpp +++ b/C++/base-7.cpp @@ -4,17 +4,16 @@ class Solution { public: string convertToBase7(int num) { - if (num == 0) { - return "0"; + if (num < 0) { + return string("-").append(convertToBase7(-num)); } string result; - int n = abs(num); - while (n) { - result.append(to_string(n % 7)); - n /= 7; + while (num) { + result.append(to_string(num % 7)); + num /= 7; } reverse(result.begin(), result.end()); - return num >= 0 ? result : "-" + result; + return result.empty() ? "0" : result; } }; From 198b54c9ff796cc98cccfdc530f0111739901b0d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 22:17:31 +0800 Subject: [PATCH 3193/4971] Create base-7.py --- Python/base-7.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/base-7.py diff --git a/Python/base-7.py b/Python/base-7.py new file mode 100644 index 000000000..b6544bd02 --- /dev/null +++ b/Python/base-7.py @@ -0,0 +1,32 @@ +# Time: O(1) +# Space: O(1) + +# Given an integer, return its base 7 string representation. +# +# Example 1: +# Input: 100 +# Output: "202" +# Example 2: +# Input: -7 +# Output: "-10" +# Note: The input will be in range of [-1e7, 1e7]. + +class Solution(object): + def convertToBase7(self, num): + if num < 0: return '-' + self.convertToBase7(-num) + result = '' + while num: + result = str(num % 7) + result + num //= 7 + return result if result else '0' + + +class Solution2(object): + def convertToBase7(self, num): + """ + :type num: int + :rtype: str + """ + if num < 0: return '-' + self.convertToBase7(-num) + if num < 7: return str(num) + return self.convertToBase7(num // 7) + str(num % 7) From bfa24f3c6fde634792378d138f3b2680b75631de Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 22:39:09 +0800 Subject: [PATCH 3194/4971] Create teemo-attacking.cpp --- C++/teemo-attacking.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/teemo-attacking.cpp diff --git a/C++/teemo-attacking.cpp b/C++/teemo-attacking.cpp new file mode 100644 index 000000000..294abfb79 --- /dev/null +++ b/C++/teemo-attacking.cpp @@ -0,0 +1,13 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findPoisonedDuration(vector& timeSeries, int duration) { + int result = duration * timeSeries.size(); + for (int i = 1; i < timeSeries.size(); ++i){ + result -= max(0, duration - (timeSeries[i] - timeSeries[i - 1])); + } + return result; + } +}; From b3537e315549f5b71a5d43bdc6208c81a94396d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 22:40:42 +0800 Subject: [PATCH 3195/4971] Create teemo-attacking.py --- Python/teemo-attacking.py | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/teemo-attacking.py diff --git a/Python/teemo-attacking.py b/Python/teemo-attacking.py new file mode 100644 index 000000000..4ae1d8435 --- /dev/null +++ b/Python/teemo-attacking.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(1) + +# In LLP world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. +# Now, given the Teemo's attacking ascending time series towards Ashe and +# the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition. +# +# You may assume that Teemo attacks at the very beginning of a specific time point, +# and makes Ashe be in poisoned condition immediately. +# +# Example 1: +# Input: [1,4], 2 +# Output: 4 +# Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. +# This poisoned status will last 2 seconds until the end of time point 2. +# And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds. +# So you finally need to output 4. +# Example 2: +# Input: [1,2], 2 +# Output: 3 +# Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned. +# This poisoned status will last 2 seconds until the end of time point 2. +# However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status. +# Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, +# it will stop at the end of time point 3. +# So you finally need to output 3. +# Note: +# You may assume the length of given time series array won't exceed 10000. +# You may assume the numbers in the Teemo's attacking time series and his poisoning time +# duration per attacking are non-negative integers, which won't exceed 10,000,000. + +class Solution(object): + def findPoisonedDuration(self, timeSeries, duration): + """ + :type timeSeries: List[int] + :type duration: int + :rtype: int + """ + result = duration * len(timeSeries) + for i in xrange(1, len(timeSeries)): + result -= max(0, duration - (timeSeries[i] - timeSeries[i-1])) + return result From 240fda8bff333dc2e9ba1e29a06cfcf5ed21a5ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 22:50:40 +0800 Subject: [PATCH 3196/4971] Create construct-the-rectangle.cpp --- C++/construct-the-rectangle.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/construct-the-rectangle.cpp diff --git a/C++/construct-the-rectangle.cpp b/C++/construct-the-rectangle.cpp new file mode 100644 index 000000000..0940be3de --- /dev/null +++ b/C++/construct-the-rectangle.cpp @@ -0,0 +1,13 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + vector constructRectangle(int area) { + int w = sqrt(area); + while (area % w) { + --w; + } + return {area / w, w}; + } +}; From 2324548f6c40b16e102c1c93b15d49586b7d3aa0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 22:52:07 +0800 Subject: [PATCH 3197/4971] Create construct-the-rectangle.py --- Python/construct-the-rectangle.py | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/construct-the-rectangle.py diff --git a/Python/construct-the-rectangle.py b/Python/construct-the-rectangle.py new file mode 100644 index 000000000..54a412741 --- /dev/null +++ b/Python/construct-the-rectangle.py @@ -0,0 +1,34 @@ +# Time: O(1) +# Space: O(1) + +# For a web developer, it is very important to know how to design a web page's size. +# So, given a specific rectangular web page’s area, +# your job by now is to design a rectangular web page, whose length L +# and width W satisfy the following requirements: +# +# 1. The area of the rectangular web page you designed must equal to the given target area. +# +# 2. The width W should not be larger than the length L, which means L >= W. +# +# 3. The difference between length L and width W should be as small as possible. +# You need to output the length L and the width W of the web page you designed in sequence. +# Example: +# Input: 4 +# Output: [2, 2] +# Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. +# But according to requirement 2, [1,4] is illegal; according to requirement 3, +# [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2. +# Note: +# The given area won't exceed 10,000,000 and is a positive integer +# The web page's width and length you designed must be positive integers. + +class Solution(object): + def constructRectangle(self, area): + """ + :type area: int + :rtype: List[int] + """ + w = int(math.sqrt(area)) + while area % w: + w -= 1 + return [area // w, w] From 072f772af9ec6e7595bf92d407d45d9b5969437c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 23:49:56 +0800 Subject: [PATCH 3198/4971] Create reverse-string-ii.cpp --- C++/reverse-string-ii.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/reverse-string-ii.cpp diff --git a/C++/reverse-string-ii.cpp b/C++/reverse-string-ii.cpp new file mode 100644 index 000000000..590c24fd1 --- /dev/null +++ b/C++/reverse-string-ii.cpp @@ -0,0 +1,15 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string reverseStr(string s, int k) { + for (int left = 0; left < s.size(); left += 2 * k) { + for (int i = left, j = min(left + k - 1, static_cast(s.size()) - 1); + i < j; ++i, --j) { + swap(s[i], s[j]); + } + } + return s; + } +}; From 964c38b8f7be21f839d20c08cf81aae45d0e9268 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Mar 2017 23:55:02 +0800 Subject: [PATCH 3199/4971] Create reverse-string-ii.py --- Python/reverse-string-ii.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/reverse-string-ii.py diff --git a/Python/reverse-string-ii.py b/Python/reverse-string-ii.py new file mode 100644 index 000000000..e9958cae9 --- /dev/null +++ b/Python/reverse-string-ii.py @@ -0,0 +1,26 @@ +# Time: O(n) +# Space: O(1) + +# Given a string and an integer k, you need to reverse the first k characters +# for every 2k characters counting from the start of the string. +# If there are less than k characters left, reverse all of them. +# If there are less than 2k but greater than or equal to k characters, +# then reverse the first k characters and left the other as original. +# Example: +# Input: s = "abcdefg", k = 2 +# Output: "bacdfeg" +# Restrictions: +# The string consists of lower English letters only. +# Length of the given string and k will in the range [1, 10000] + +class Solution(object): + def reverseStr(self, s, k): + """ + :type s: str + :type k: int + :rtype: str + """ + s = list(s) + for i in xrange(0, len(s), 2*k): + s[i:i+k] = reversed(s[i:i+k]) + return "".join(s) From bb8cdd17d6144a8f63c2eada3cdab79fc00d4649 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Mar 2017 00:23:30 +0800 Subject: [PATCH 3200/4971] Create diagonal-traverse.cpp --- C++/diagonal-traverse.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/diagonal-traverse.cpp diff --git a/C++/diagonal-traverse.cpp b/C++/diagonal-traverse.cpp new file mode 100644 index 000000000..989cc0aa6 --- /dev/null +++ b/C++/diagonal-traverse.cpp @@ -0,0 +1,39 @@ +// Time: O(m * n) +// Space: O(1) + +class Solution { +public: + vector findDiagonalOrder(vector>& matrix) { + if (matrix.empty() || matrix[0].empty()) { + return {}; + } + + vector result; + int row = 0, col = 0, d = 0; + vector> dirs = {{-1, 1}, {1, -1}}; + + for (int i = 0; i < matrix.size() * matrix[0].size(); ++i) { + result.emplace_back(matrix[row][col]); + row += dirs[d][0]; + col += dirs[d][1]; + + if (row >= static_cast(matrix.size())) { + row = matrix.size() - 1; + col += 2; + d = 1 - d; + } else if (col >= static_cast(matrix[0].size())) { + col = matrix[0].size() - 1; + row += 2; + d = 1 - d; + } else if (row < 0) { + row = 0; + d = 1 - d; + } else if (col < 0) { + col = 0; + d = 1 - d; + } + } + + return result; + } +}; From 86cbe7d74d4f19bb0df937ebcda04511f58511a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Mar 2017 00:27:43 +0800 Subject: [PATCH 3201/4971] Create diagonal-traverse.py --- Python/diagonal-traverse.py | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/diagonal-traverse.py diff --git a/Python/diagonal-traverse.py b/Python/diagonal-traverse.py new file mode 100644 index 000000000..8410476a4 --- /dev/null +++ b/Python/diagonal-traverse.py @@ -0,0 +1,55 @@ +# Time: O(m * n) +# Space: O(1) + +# Given a matrix of M x N elements (M rows, N columns), +# return all elements of the matrix in diagonal order as shown in the below image. +# +# Example: +# Input: +# [ +# [ 1, 2, 3 ], +# [ 4, 5, 6 ], +# [ 7, 8, 9 ] +# ] +# Output: [1,2,4,7,5,3,6,8,9] +# Explanation: +# +# Note: +# The total number of elements of the given matrix will not exceed 10,000. +# Show Company Tags + +class Solution(object): + def findDiagonalOrder(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[int] + """ + if not matrix or not matrix[0]: + return [] + + result = [] + row, col, d = 0, 0, 0 + dirs = [(-1, 1), (1, -1)] + + for i in xrange(len(matrix) * len(matrix[0])): + result.append(matrix[row][col]) + row += dirs[d][0] + col += dirs[d][1] + + if row >= len(matrix): + row = len(matrix) - 1 + col += 2 + d = 1 - d + elif col >= len(matrix[0]): + col = len(matrix[0]) - 1 + row += 2 + d = 1 - d + elif row < 0: + row = 0 + d = 1 - d + elif col < 0: + col = 0 + d = 1 - d + + return result + From 009af8783451e2b18ac0f1c52253691df92e66c6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Mar 2017 23:06:20 +0800 Subject: [PATCH 3202/4971] Update README.md --- README.md | 104 +++++++++++++++++++++++++++--------------------------- 1 file changed, 52 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index b30af869c..4a9aa8df1 100644 --- a/README.md +++ b/README.md @@ -43,12 +43,12 @@ 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 - # | 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)_ | Easy || -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 || +| # | 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)_ | Easy ||| +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 || @@ -66,8 +66,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 477 | [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./C++/total-hamming-distance.cpp) [Python](./Python/total-hamming-distance.py) | _O(n)_ | _O(1)_ | Medium || ## Array - # | Title | 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 || Two Pointers 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 || Two Pointers 18| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(1)_ | Medium || Two Pointers @@ -117,8 +117,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## String - # | Title | Solution | Time | Space | Difficulty | Tag | Note ------|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +| # | 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/) | [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 || @@ -149,8 +149,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | ## Linked List - # | Title | Solution | Time | Space | Difficulty | Tag | Note ------|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +| # | 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 || 21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./C++/merge-two-sorted-lists.cpp) [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || 23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | | Heap, Divide and Conquer @@ -171,8 +171,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 445| [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/)| [C++](./C++/add-two-numbers-ii.cpp) [Python](./Python/add-two-numbers-ii.py) | _O(m + n)_ | _O(m + n)_ | Medium ||| ## Stack - # | Title | Solution | Time | Space | Difficulty | Tag | Note ------|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +| # | Title | Solution | Time | Space | Difficulty | Tag | Note| +|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || 32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./C++/longest-valid-parentheses.cpp) [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || 71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./C++/simplify-path.cpp) [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || @@ -195,15 +195,15 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 456| [132 Pattern](https://leetcode.com/problems/132-pattern/) | [C++](./C++/132-pattern.cpp) [Python](./Python/132-pattern.py) | _O(n)_ | _O(n)_ | Medium || ## Queue - # | Title | 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 |📖|| 346| [Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/)| [C++](./C++/moving-average-from-data-stream.cpp) [Python](./Python/moving-average-from-data-stream.py) | _O(1)_ | _O(w)_ | Easy |📖|| ## Heap - # | Title | Solution | Time | Space | Difficulty | Tag | Note ------|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +| # | Title | Solution | Time | Space | Difficulty | Tag | Note| +|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 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 | @@ -213,8 +213,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 407 | [Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/) | [C++](./C++/trapping-rain-water-ii.cpp) [Python](./Python/trapping-rain-water-ii.py) | _O(m * n * (logm + logn))_ | _O(m * n)_ | Hard | LintCode || ## Tree - # | Title | 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/) | [C++](./C++/binary-tree-inorder-traversal.cpp) [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/) | [C++](./C++/recover-binary-search-tree.cpp) [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/) | [C++](./C++/binary-tree-preorder-traversal.cpp) [Python](./Python/binary-tree-preorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` @@ -228,8 +228,8 @@ 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 - # | Title | Solution | Time | Space | Difficulty | Tag | Note ------|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +| # | Title | Solution | Time | Space | Difficulty | Tag | Note| +|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Easy || 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || @@ -269,14 +269,14 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || ## Data Structure - # | Title | Solution | Time | Space | Difficulty | Tag | Note ------|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +| # | Title | Solution | Time | Space | Difficulty | Tag | Note| +|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [C++](./C++/lru-cache.cpp) [Python](./Python/lru-cache.py) | _O(1)_ | _O(k)_ | 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)_ | Easy || ## Math - # | Title | Solution | Time | Space | Difficulty | Tag | Note ------|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +| # | Title | Solution | Time | Space | Difficulty | Tag | Note| +|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [Python](./Python/reverse-integer.py) | _O(1)_ | _O(1)_ | Easy || 9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C++](./C++/palindrome-number.cpp) [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || 12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [C++](./C++/integer-to-roman.cpp) [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || @@ -317,8 +317,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| ## Sort - # | Title | Solution | Time | Space | Difficulty | Tag | Note ------|---------------- | --------------- | --------------- | --------------- | ------------- |--------------| ----- +| # | Title | Solution | Time | Space | Difficulty | Tag | Note| +|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [C++](./C++/merge-intervals.cpp) [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || 57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [C++](./C++/insert-interval.cpp) [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || 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 @@ -339,8 +339,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Two Pointers - # | Title | 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/)| [C++](./C++/remove-nth-node-from-end-of-list.cpp) [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || 86| [Partition List](https://leetcode.com/problems/partition-list/)| [C++](./C++/partition-list.cpp) [Python](./Python/partition-list.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)_ | Easy || @@ -358,8 +358,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 457| [Circular Array Loop](https://leetcode.com/problems/circular-array-loop/) | [C++](./C++/circular-array-loop.cpp) [Python](./Python/circular-array-loop.py) | _O(n)_ | _O(1)_ | Medium || ## Recursion - # | Title | 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/) | [C++](./C++/unique-binary-search-trees-ii.cpp) [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/)|[C++](./C++/validate-binary-search-tree.cpp) [Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || 100| [Same Tree](https://leetcode.com/problems/same-tree/) |[C+](./C++/same-tree.cpp) [Python](./Python/same-tree.py) | _O(n)_ | _O(h)_ | Easy || @@ -385,8 +385,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n^2)_ | _O(h)_ | Easy || ## Binary Search - # | Title | 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/) | [C++](./C++/search-in-rotated-sorted-array.cpp) [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/) | [C++](./C++/search-for-a-range.cpp) [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || @@ -411,8 +411,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 475 | [Heaters](https://leetcode.com/problems/heaters/) | [C++](./C++/heaters.cpp) [Python](./Python/heaters.py) | _O((m + n) * logn)_ | _O(1)_ | Easy | | ## Binary Search Tree - # | Title | 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 || 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 | @@ -423,8 +423,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 450|[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/)| [C++](./C++/delete-node-in-a-bst.cpp) [Python](./Python/delete-node-in-a-bst.py)| _O(h)_ | _O(h)_ | Medium | | | ## Breadth-First Search - # | Title | 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/)| [C++](./C++/binary-tree-level-order-traversal.cpp) [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 || @@ -443,8 +443,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 444| [Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction/)| [C++](./C++/sequence-reconstruction.cpp) [Python](./Python/sequence-reconstruction.py) | _O(n * s)_ | _O(n)_ | Medium |📖| Topological Sort | ## Depth-First Search - # | Title | 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 || 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 || @@ -466,8 +466,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || ## Backtracking - # | Title | 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 || 37| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || @@ -495,8 +495,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 425| [Word Squares](https://leetcode.com/problems/word-squares/) | [C++](./C++/word-squares.cpp) [Python](./Python/word-squares.py) | _O(n^2 * n!)_ | _O(n^2)_ | Hard |📖|| ## Dynamic Programming - # | Title | 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 || 62| [Unique Paths](https://leetcode.com/problems/unique-paths/) | [Python](./Python/unique-paths.py)| _O(m * n)_ | _O(m + n)_ | Medium || @@ -546,8 +546,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || ## Greedy - # | Title | 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/)| [C++](./C++/container-with-most-water.cpp) [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || 42| [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [C++](./C++/trapping-rain-water.cpp) [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 @@ -569,8 +569,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates --- ## Design - # | Title | 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 || 348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_| _O(n^2)_| Medium |📖|| 353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(1)_| _O(s)_| Medium |📖| Deque | @@ -584,8 +584,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_| Hard || | ## SQL - # | Title | 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 || 177| [Nth Highest Salary](https://leetcode.com/problems/nth-highest-salary/) | [MySQL](./MySQL/nth-highest-salary.sql) | _O(n^2)_ | _O(n)_ | Medium || @@ -601,8 +601,8 @@ 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 - # | Title | 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 || 194 | [Transpose File](https://leetcode.com/problems/transpose-file/) | [Shell](./Shell/transpose-file.sh) | _O(n^2)_ | _O(n^2)_ | Medium || From cb38e90b3e27f3bd0adacbcb6653abc3ba30832f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Mar 2017 23:10:22 +0800 Subject: [PATCH 3203/4971] Create 01-matrix.cpp --- C++/01-matrix.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/01-matrix.cpp diff --git a/C++/01-matrix.cpp b/C++/01-matrix.cpp new file mode 100644 index 000000000..db2c6d5cf --- /dev/null +++ b/C++/01-matrix.cpp @@ -0,0 +1,37 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector> updateMatrix(vector>& matrix) { + queue> queue; + for (int i = 0; i < matrix.size(); ++i) { + for (int j = 0; j < matrix[0].size(); ++j) { + if (matrix[i][j] == 0) { + queue.emplace(i, j); + } + else { + matrix[i][j] = numeric_limits::max(); + } + } + } + + const vector> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + while (!queue.empty()) { + auto cell = queue.front(); + queue.pop(); + for (const auto& dir : dirs) { + auto i = cell.first + dir.first; + auto j = cell.second + dir.second; + if (i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() || + matrix[i][j] <= matrix[cell.first][cell.second] + 1) { + continue; + } + queue.emplace(i, j); + matrix[i][j] = matrix[cell.first][cell.second] + 1; + } + } + + return matrix; + } +}; From 51a974c5c9da08406baa81b4800970a997625b6c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Mar 2017 23:14:56 +0800 Subject: [PATCH 3204/4971] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4a9aa8df1..932f75cc2 100644 --- a/README.md +++ b/README.md @@ -90,9 +90,9 @@ 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/) | [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)_ | Medium | | +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)_ | 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 | 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 b9b76a9316f2de4e95eb5d0a70ee5aec02df800c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Mar 2017 23:36:17 +0800 Subject: [PATCH 3205/4971] Create 01-matrix.py --- Python/01-matrix.py | 61 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/01-matrix.py diff --git a/Python/01-matrix.py b/Python/01-matrix.py new file mode 100644 index 000000000..5a5413a48 --- /dev/null +++ b/Python/01-matrix.py @@ -0,0 +1,61 @@ +# Time: O(n) +# Space: O(n) + +# Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. +# The distance between two adjacent cells is 1. +# +# Example 1: +# +# Input: +# 0 0 0 +# 0 1 0 +# 0 0 0 +# +# Output: +# 0 0 0 +# 0 1 0 +# 0 0 0 +# +# Example 2: +# +# Input: +# 0 0 0 +# 0 1 0 +# 1 1 1 +# +# Output: +# 0 0 0 +# 0 1 0 +# 1 2 1 +# +# Note: +# The number of elements of the given matrix will not exceed 10,000. +# There are at least one 0 in the given matrix. +# The cells are adjacent in only four directions: up, down, left and right. + +class Solution(object): + def updateMatrix(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[List[int]] + """ + queue = collections.deque([]) + for i in xrange(len(matrix)): + for j in xrange(len(matrix[0])): + if matrix[i][j] == 0: + queue.append((i, j)) + else: + matrix[i][j] = float("inf") + + dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)] + while queue: + cell = queue.popleft() + for dir in dirs: + i, j = cell[0]+dir[0], cell[1]+dir[1] + if not (0 <= i < len(matrix)) or not (0 <= j < len(matrix[0])) or \ + matrix[i][j] <= matrix[cell[0]][cell[1]]+1: + continue + queue.append((i, j)) + matrix[i][j] = matrix[cell[0]][cell[1]]+1 + + return matrix From c3dba3cfdd52732e648934c0183dc4a2734fee64 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Mar 2017 23:36:41 +0800 Subject: [PATCH 3206/4971] Update 01-matrix.py --- Python/01-matrix.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/01-matrix.py b/Python/01-matrix.py index 5a5413a48..16934096d 100644 --- a/Python/01-matrix.py +++ b/Python/01-matrix.py @@ -1,5 +1,5 @@ -# Time: O(n) -# Space: O(n) +# Time: O(m * n) +# Space: O(m * n) # Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. # The distance between two adjacent cells is 1. From 3919ba03d67e76ab7891d20c1880471d9781e562 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Mar 2017 23:37:04 +0800 Subject: [PATCH 3207/4971] Update 01-matrix.cpp --- C++/01-matrix.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/01-matrix.cpp b/C++/01-matrix.cpp index db2c6d5cf..bb7c65b70 100644 --- a/C++/01-matrix.cpp +++ b/C++/01-matrix.cpp @@ -1,5 +1,5 @@ -// Time: O(n) -// Space: O(n) +// Time: O(m * n) +// Space: O(m * n) class Solution { public: From 0d8ffea595977cb6befd7d4b16b3ab5f5f80ca4b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Mar 2017 00:12:29 +0800 Subject: [PATCH 3208/4971] Update unique-word-abbreviation.cpp --- C++/unique-word-abbreviation.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/unique-word-abbreviation.cpp b/C++/unique-word-abbreviation.cpp index 646c46d1d..e07743b9f 100644 --- a/C++/unique-word-abbreviation.cpp +++ b/C++/unique-word-abbreviation.cpp @@ -21,6 +21,9 @@ class ValidWordAbbr { unordered_map> lookup_; string abbreviation(const string& word) { + if (word.length() <= 2) { + return word; + } return word.front() + to_string(word.length()) + word.back(); } }; From 04758529588e276d15d5ecee95b8cebd6252254e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Mar 2017 00:21:02 +0800 Subject: [PATCH 3209/4971] Update search-a-2d-matrix.py --- Python/search-a-2d-matrix.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/search-a-2d-matrix.py b/Python/search-a-2d-matrix.py index 39a3f98a6..cc0e67e95 100644 --- a/Python/search-a-2d-matrix.py +++ b/Python/search-a-2d-matrix.py @@ -24,7 +24,7 @@ def searchMatrix(self, matrix, target): :type target: int :rtype: bool """ - if matrix == []: + if not matrix: return False m, n = len(matrix), len(matrix[0]) From 746df5cff523361145a74d9d429dc541a7b99910 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 22 Mar 2017 15:56:02 +0800 Subject: [PATCH 3210/4971] Update climbing-stairs.py --- Python/climbing-stairs.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Python/climbing-stairs.py b/Python/climbing-stairs.py index 7901fa1cb..6511a1dee 100644 --- a/Python/climbing-stairs.py +++ b/Python/climbing-stairs.py @@ -18,6 +18,8 @@ def climbStairs(self, n): prev, current = current, prev + current, return current + # Time: O(2^n) + # Space: O(n) def climbStairs1(self, n): if n == 1: return 1 From 4cde1f2fcc21ff83daabdb5221c462f44991c73f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 13:54:43 +0800 Subject: [PATCH 3211/4971] Create remove-boxes.py --- Python/remove-boxes.py | 46 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/remove-boxes.py diff --git a/Python/remove-boxes.py b/Python/remove-boxes.py new file mode 100644 index 000000000..a34b96d6a --- /dev/null +++ b/Python/remove-boxes.py @@ -0,0 +1,46 @@ +# Time: O(n^3) ~ O(n^4) +# Space: O(n^3) + +# Given several boxes with different colors represented by different positive numbers. +# You may experience several rounds to remove boxes until there is no box left. +# Each time you can choose some continuous boxes with the same color (composed of k boxes, k >= 1), +# remove them and get k*k points. +# Find the maximum points you can get. +# +# Example 1: +# Input: +# +# [1, 3, 2, 2, 2, 3, 4, 3, 1] +# Output: +# 23 +# Explanation: +# [1, 3, 2, 2, 2, 3, 4, 3, 1] +# ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) +# ----> [1, 3, 3, 3, 1] (1*1=1 points) +# ----> [1, 1] (3*3=9 points) +# ----> [] (2*2=4 points) +# Note: The number of boxes n would not exceed 100. + +class Solution(object): + def removeBoxes(self, boxes): + """ + :type boxes: List[int] + :rtype: int + """ + def dfs(boxes, l, r, k, lookup): + if l > r: return 0 + if lookup[l][r][k]: return lookup[l][r][k] + + ll, kk = l, k + while l < r and boxes[l+1] == boxes[l]: + l += 1 + k += 1 + result = dfs(boxes, l+1, r, 0, lookup) + (k+1) ** 2 + for i in xrange(l+1, r+1): + if boxes[i] == boxes[l]: + result = max(result, dfs(boxes, l+1, i-1, 0, lookup) + dfs(boxes, i, r, k+1, lookup)) + lookup[ll][r][kk] = result + return result + + lookup = [[[0]*len(boxes) for _ in xrange(len(boxes)) ] for _ in xrange(len(boxes)) ] + return dfs(boxes, 0, len(boxes)-1, 0, lookup) From d3156394d3357e71875d91b0baa0a6269ca4b9b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 13:55:29 +0800 Subject: [PATCH 3212/4971] Create remote-boxes.cpp --- C++/remote-boxes.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/remote-boxes.cpp diff --git a/C++/remote-boxes.cpp b/C++/remote-boxes.cpp new file mode 100644 index 000000000..b23789130 --- /dev/null +++ b/C++/remote-boxes.cpp @@ -0,0 +1,34 @@ +// Time: O(n^3) ~ O(n^4) +// Space: O(n^3) + +class Solution { +public: + int removeBoxes(vector& boxes) { + int lookup[100][100][100] = {0}; + return removeBoxesHelper(boxes, 0, boxes.size() - 1, 0, lookup); + } + +private: + int removeBoxesHelper(const vector& boxes, int l, int r, int k, int lookup[100][100][100]) { + if (l > r) { + return 0; + } + if (lookup[l][r][k]) { + return lookup[l][r][k]; + } + + auto& result = lookup[l][r][k]; + while (l < r && boxes[l + 1] == boxes[l]) { + ++l, ++k; + } + result = removeBoxesHelper(boxes, l + 1, r, 0, lookup) + (k + 1) * (k + 1); + for (int i = l + 1; i <= r; ++i) { + if (boxes[i] == boxes[l]) { + result = max(result, + removeBoxesHelper(boxes, l + 1, i - 1, 0, lookup) + + removeBoxesHelper(boxes, i, r, k + 1, lookup)); + } + } + return result; + } +}; From 49490937053f37091fa45810e9cc2e9f4cb5e6f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 13:55:55 +0800 Subject: [PATCH 3213/4971] Rename remote-boxes.cpp to remove-boxes.cpp --- C++/{remote-boxes.cpp => remove-boxes.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{remote-boxes.cpp => remove-boxes.cpp} (100%) diff --git a/C++/remote-boxes.cpp b/C++/remove-boxes.cpp similarity index 100% rename from C++/remote-boxes.cpp rename to C++/remove-boxes.cpp From c253074114f6958f3180169db7fefcb878759a66 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 17:32:52 +0800 Subject: [PATCH 3214/4971] Create boundary-of-binary-tree.cpp --- C++/boundary-of-binary-tree.cpp | 65 +++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 C++/boundary-of-binary-tree.cpp diff --git a/C++/boundary-of-binary-tree.cpp b/C++/boundary-of-binary-tree.cpp new file mode 100644 index 000000000..a372556b4 --- /dev/null +++ b/C++/boundary-of-binary-tree.cpp @@ -0,0 +1,65 @@ +// 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: + vector boundaryOfBinaryTree(TreeNode* root) { + if (!root) { + return {}; + } + + vector nodes; + nodes.emplace_back(root->val); + leftBoundary(root->left, &nodes); + leaves(root->left, &nodes); + leaves(root->right, &nodes); + rightBoundary(root->right, &nodes); + return nodes; + } + +private: + void leftBoundary(TreeNode *root, vector *nodes) { + if (!root || (!root->left && !root->right)) { + return; + } + nodes->emplace_back(root->val); + if (!root->left) { + leftBoundary(root->right, nodes); + } else { + leftBoundary(root->left, nodes); + } + } + + void rightBoundary(TreeNode *root, vector *nodes) { + if (!root || (!root->right && !root->left)) { + return; + } + if (!root->right) { + rightBoundary(root->left, nodes); + } else { + rightBoundary(root->right, nodes); + } + nodes->emplace_back(root->val); + } + + void leaves(TreeNode *root, vector *nodes) { + if (!root) { + return; + } + if (!root->left && !root->right) { + nodes->emplace_back(root->val); + return; + } + leaves(root->left, nodes); + leaves(root->right, nodes); + } +}; From 7e5cf15607221db831c9a1e7fa3576078c6f58a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 17:45:31 +0800 Subject: [PATCH 3215/4971] Create boundary-of-binary-tree.py --- Python/boundary-of-binary-tree.py | 52 +++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/boundary-of-binary-tree.py diff --git a/Python/boundary-of-binary-tree.py b/Python/boundary-of-binary-tree.py new file mode 100644 index 000000000..ad7a6a6b3 --- /dev/null +++ b/Python/boundary-of-binary-tree.py @@ -0,0 +1,52 @@ +# 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 boundaryOfBinaryTree(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ + def leftBoundary(root, nodes): + if not root or (not root.left and not root.right): + return + nodes.append(root.val) + if not root.left: + leftBoundary(root.right, nodes) + else: + leftBoundary(root.left, nodes) + + def rightBoundary(root, nodes): + if not root or (not root.left and not root.right): + return + if not root.right: + rightBoundary(root.left, nodes) + else: + rightBoundary(root.right, nodes) + nodes.append(root.val) + + def leaves(root, nodes): + if not root: + return + if not root.left and not root.right: + nodes.append(root.val) + return + leaves(root.left, nodes) + leaves(root.right, nodes) + + if not root: + return [] + + nodes = [root.val] + leftBoundary(root.left, nodes) + leaves(root.left, nodes) + leaves(root.right, nodes) + rightBoundary(root.right, nodes) + return nodes From eac588229bd82c00de9c652c9c1aaf6e5491f46b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 18:08:25 +0800 Subject: [PATCH 3216/4971] Create perfect-number.cpp --- C++/perfect-number.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/perfect-number.cpp diff --git a/C++/perfect-number.cpp b/C++/perfect-number.cpp new file mode 100644 index 000000000..c3516c4ca --- /dev/null +++ b/C++/perfect-number.cpp @@ -0,0 +1,21 @@ +// Time: O(sqrt(n)) +// Space: O(1) + +class Solution { +public: + bool checkPerfectNumber(int num) { + if (num <= 0) { + return false; + } + int sum = 0; + for (int i = 1; i * i <= num; ++i) { + if (num % i == 0) { + sum += i; + if (i * i != num) { + sum += num / i; + } + } + } + return sum - num == num; + } +}; From b92147d7a960a35e1da83d135e0de4b82a17b260 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 18:10:35 +0800 Subject: [PATCH 3217/4971] Create perfect-number.py --- Python/perfect-number.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Python/perfect-number.py diff --git a/Python/perfect-number.py b/Python/perfect-number.py new file mode 100644 index 000000000..a3fefe5b5 --- /dev/null +++ b/Python/perfect-number.py @@ -0,0 +1,28 @@ +# Time: O(sqrt(n)) +# Space: O(1) + +# We define the Perfect Number is a positive integer that is equal +# to the sum of all its positive divisors except itself. +# +# Now, given an integer n, write a function that returns true +# when it is a perfect number and false when it is not. +# Example: +# Input: 28 +# Output: True +# Explanation: 28 = 1 + 2 + 4 + 7 + 14 +# Note: The input number n will not exceed 100,000,000. (1e8) + +class Solution(object): + def checkPerfectNumber(self, num): + """ + :type num: int + :rtype: bool + """ + if num <= 0: + return False + + sqrt_num = int(num ** 0.5) + total = sum(i+num//i for i in xrange(1, sqrt_num+1) if num%i == 0) + if sqrt_num ** 2 == num: + total -= sqrt_num + return total - num == num From bdd65b35a8083d68b54277cc7c9d742e1a751d0b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 18:38:47 +0800 Subject: [PATCH 3218/4971] Create find-mode-in-binary-search-tree.cpp --- C++/find-mode-in-binary-search-tree.cpp | 51 +++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 C++/find-mode-in-binary-search-tree.cpp diff --git a/C++/find-mode-in-binary-search-tree.cpp b/C++/find-mode-in-binary-search-tree.cpp new file mode 100644 index 000000000..087a5579d --- /dev/null +++ b/C++/find-mode-in-binary-search-tree.cpp @@ -0,0 +1,51 @@ +// 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: + vector findMode(TreeNode* root) { + if (!root) { + return {}; + } + + vector result; + TreeNode *prev = nullptr; + int cnt = 1, max_cnt = 0; + inorder(root, &prev, &cnt, &max_cnt, &result); + return result; + } + +private: + void inorder(TreeNode *root, TreeNode **prev, int *cnt, int *max_cnt, vector *result) { + if (root == nullptr) { + return; + } + + inorder(root->left, prev, cnt, max_cnt, result); + if (*prev) { + if (root->val == (*prev)->val) { + ++(*cnt); + } else { + *cnt = 1; + } + } + if (*cnt > *max_cnt) { + *max_cnt = *cnt; + result->clear(); + result->emplace_back(root->val); + } else if (*cnt == *max_cnt) { + result->emplace_back(root->val); + } + *prev = root; + inorder(root->right, prev, cnt, max_cnt, result); + } +}; From d581f2f95ab924e846c0e9e6f73bf32ec32cc28c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 18:53:38 +0800 Subject: [PATCH 3219/4971] Create find-mode-in-binary-search-tree.py --- Python/find-mode-in-binary-search-tree.py | 61 +++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/find-mode-in-binary-search-tree.py diff --git a/Python/find-mode-in-binary-search-tree.py b/Python/find-mode-in-binary-search-tree.py new file mode 100644 index 000000000..60a53fa65 --- /dev/null +++ b/Python/find-mode-in-binary-search-tree.py @@ -0,0 +1,61 @@ +# Time: O(n) +# Space: O(1) + +# Given a binary search tree (BST) with duplicates, +# find all the mode(s) (the most frequently occurred element) in the given BST. +# +# Assume a BST is defined as follows: +# +# The left subtree of a node contains only nodes with keys less than or equal to the node's key. +# The right subtree of a node contains only nodes with keys greater than or equal to the node's key. +# Both the left and right subtrees must also be binary search trees. +# For example: +# Given BST [1,null,2,2], +# 1 +# \ +# 2 +# / +# 2 +# return [2]. +# +# Note: If a tree has more than one mode, you can return them in any order. +# +# Follow up: Could you do that without using any extra space? +# (Assume that the implicit stack space incurred due to recursion does not count). + +# 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 findMode(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ + def inorder(root, prev, cnt, max_cnt, result): + if not root: + return prev, cnt, max_cnt + + prev, cnt, max_cnt = inorder(root.left, prev, cnt, max_cnt, result) + if prev: + if root.val == prev.val: + cnt += 1 + else: + cnt = 1 + if cnt > max_cnt: + max_cnt = cnt; + del result[:] + result.append(root.val) + elif cnt == max_cnt: + result.append(root.val) + return inorder(root.right, root, cnt, max_cnt, result) + + if not root: + return [] + result = [] + inorder(root, None, 1, 0, result); + return result From 35cf2424be4adf7ec9c6002fa0bd73b9fd258158 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 18:54:26 +0800 Subject: [PATCH 3220/4971] Update find-mode-in-binary-search-tree.cpp --- C++/find-mode-in-binary-search-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/find-mode-in-binary-search-tree.cpp b/C++/find-mode-in-binary-search-tree.cpp index 087a5579d..6f7961e69 100644 --- a/C++/find-mode-in-binary-search-tree.cpp +++ b/C++/find-mode-in-binary-search-tree.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(h) +// Space: O(1) /** * Definition for a binary tree node. From ad5f358520f04f7335f7a5ea61ac9b7bca790fd3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 21:46:00 +0800 Subject: [PATCH 3221/4971] Create lonely-pixel-ii.cpp --- C++/lonely-pixel-ii.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/lonely-pixel-ii.cpp diff --git a/C++/lonely-pixel-ii.cpp b/C++/lonely-pixel-ii.cpp new file mode 100644 index 000000000..d78e87774 --- /dev/null +++ b/C++/lonely-pixel-ii.cpp @@ -0,0 +1,35 @@ +// Time: O(m * n) +// Space: O(m * n) + +class Solution { +public: + int findBlackPixel(vector>& picture, int N) { + vector rows = vector(picture.size()); + vector cols = vector(picture[0].size()); + + unordered_map lookup; + vector srows; + for (int i = 0; i < picture.size(); ++i) { + string s; + for (int j = 0; j < picture[0].size(); ++j) { + if (picture[i][j] == 'B') { + ++rows[i]; + ++cols[j]; + } + s.push_back(picture[i][j]); + } + ++lookup[s]; + srows.emplace_back(move(s)); + } + + int result = 0; + for (int i = 0; i < picture.size(); ++i) { + if (rows[i] == N && lookup[srows[i]] == N) { + for (int j = 0; j < picture[0].size(); ++j) { + result += picture[i][j] == 'B' && cols[j] == N; + } + } + } + return result; + } +}; From be02f11451182be00fa938c32cf25ac9ea92e95d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 21:46:34 +0800 Subject: [PATCH 3222/4971] Create lonely-pixel-i.cpp --- C++/lonely-pixel-i.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/lonely-pixel-i.cpp diff --git a/C++/lonely-pixel-i.cpp b/C++/lonely-pixel-i.cpp new file mode 100644 index 000000000..709853593 --- /dev/null +++ b/C++/lonely-pixel-i.cpp @@ -0,0 +1,27 @@ +// Time: O(m * n) +// Space: O(m + n) + +class Solution { +public: + int findLonelyPixel(vector>& picture) { + vector rows = vector(picture.size()); + vector cols = vector(picture[0].size()); + + for (int i = 0; i < picture.size(); ++i) { + for (int j = 0; j < picture[0].size(); ++j) { + rows[i] += picture[i][j] == 'B'; + cols[j] += picture[i][j] == 'B'; + } + } + + int result = 0; + for (int i = 0; i < picture.size(); ++i) { + if (rows[i] == 1) { + for (int j = 0; j < picture[0].size() && rows[i] > 0; ++j) { + result += picture[i][j] == 'B' && cols[j] == 1; + } + } + } + return result; + } +}; From ba017d42d0320c314452a7e2727504a30667b559 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 21:47:57 +0800 Subject: [PATCH 3223/4971] Update lonely-pixel-ii.cpp --- C++/lonely-pixel-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/lonely-pixel-ii.cpp b/C++/lonely-pixel-ii.cpp index d78e87774..98ae8aeef 100644 --- a/C++/lonely-pixel-ii.cpp +++ b/C++/lonely-pixel-ii.cpp @@ -1,5 +1,5 @@ // Time: O(m * n) -// Space: O(m * n) +// Space: O(m + n) class Solution { public: From 2db48d20f410026612b7df2550e6424728f49bc2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 21:49:37 +0800 Subject: [PATCH 3224/4971] Update lonely-pixel-ii.cpp --- C++/lonely-pixel-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/lonely-pixel-ii.cpp b/C++/lonely-pixel-ii.cpp index 98ae8aeef..dd024083d 100644 --- a/C++/lonely-pixel-ii.cpp +++ b/C++/lonely-pixel-ii.cpp @@ -7,7 +7,7 @@ class Solution { vector rows = vector(picture.size()); vector cols = vector(picture[0].size()); - unordered_map lookup; + unordered_map lookup; vector srows; for (int i = 0; i < picture.size(); ++i) { string s; From a0e34de93f2312775203a41a28f63ec3c0a5fbe5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 22:11:07 +0800 Subject: [PATCH 3225/4971] Update lonely-pixel-ii.cpp --- C++/lonely-pixel-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/lonely-pixel-ii.cpp b/C++/lonely-pixel-ii.cpp index dd024083d..08c23dd68 100644 --- a/C++/lonely-pixel-ii.cpp +++ b/C++/lonely-pixel-ii.cpp @@ -1,5 +1,5 @@ // Time: O(m * n) -// Space: O(m + n) +// Space: O(m * n) class Solution { public: From df8ddd56ad51f0a644696cb0ff12c2e7a17c5913 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 22:34:12 +0800 Subject: [PATCH 3226/4971] Create lonely-pixel-i.py --- Python/lonely-pixel-i.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Python/lonely-pixel-i.py diff --git a/Python/lonely-pixel-i.py b/Python/lonely-pixel-i.py new file mode 100644 index 000000000..28f8ba9a1 --- /dev/null +++ b/Python/lonely-pixel-i.py @@ -0,0 +1,33 @@ +# Time: O(m * n) +# Space: O(m + n) + +class Solution(object): + def findLonelyPixel(self, picture): + """ + :type picture: List[List[str]] + :rtype: int + """ + rows, cols = [0] * len(picture), [0] * len(picture[0]) + for i in xrange(len(picture)): + for j in xrange(len(picture[0])): + if picture[i][j] == 'B': + rows[i] += 1 + cols[j] += 1 + + result = 0 + for i in xrange(len(picture)): + if rows[i] == 1: + for j in xrange(len(picture[0])): + result += picture[i][j] == 'B' and cols[j] == 1 + return result + + +class Solution2(object): + def findLonelyPixel(self, picture): + """ + :type picture: List[List[str]] + :type N: int + :rtype: int + """ + return sum(col.count('B') == 1 == picture[col.index('B')].count('B') \ + for col in zip(*picture)) From 8e422d4343c897d89809a59285fb8ac5dffc4257 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Apr 2017 22:35:30 +0800 Subject: [PATCH 3227/4971] Create lonely-pixel-ii.py --- Python/lonely-pixel-ii.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/lonely-pixel-ii.py diff --git a/Python/lonely-pixel-ii.py b/Python/lonely-pixel-ii.py new file mode 100644 index 000000000..25bb4c408 --- /dev/null +++ b/Python/lonely-pixel-ii.py @@ -0,0 +1,39 @@ +# Time: O(m * n) +# Space: O(m * n) + +class Solution(object): + def findBlackPixel(self, picture, N): + """ + :type picture: List[List[str]] + :type N: int + :rtype: int + """ + rows, cols = [0] * len(picture), [0] * len(picture[0]) + lookup = collections.defaultdict(int) + for i in xrange(len(picture)): + for j in xrange(len(picture[0])): + if picture[i][j] == 'B': + rows[i] += 1 + cols[j] += 1 + lookup[tuple(picture[i])] += 1 + + result = 0 + for i in xrange(len(picture)): + if rows[i] == N and lookup[tuple(picture[i])] == N: + for j in xrange(len(picture[0])): + result += picture[i][j] == 'B' and cols[j] == N + return result + + +class Solution2(object): + def findBlackPixel(self, picture, N): + """ + :type picture: List[List[str]] + :type N: int + :rtype: int + """ + lookup = collections.Counter(map(tuple, picture)) + cols = [col.count('B') for col in zip(*picture)] + return sum(N * zip(row, cols).count(('B', N)) \ + for row, cnt in lookup.iteritems() \ + if cnt == N == row.count('B')) From c00f86594a9c705d03f2b587be9cea9c271ac6d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 2 Apr 2017 19:58:05 +0800 Subject: [PATCH 3228/4971] Create relative-ranks.cpp --- C++/relative-ranks.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/relative-ranks.cpp diff --git a/C++/relative-ranks.cpp b/C++/relative-ranks.cpp new file mode 100644 index 000000000..835aaf44b --- /dev/null +++ b/C++/relative-ranks.cpp @@ -0,0 +1,21 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + vector findRelativeRanks(vector& nums) { + vector indices(nums.size()); + iota(indices.begin(), indices.end(), 0); + sort(indices.begin(), indices.end(), + [&nums](int a, int b) { + return nums[a] > nums[b]; + }); + + const vector ranks = {"Gold Medal", "Silver Medal", "Bronze Medal"}; + vector result(nums.size()); + for (int i = 0; i < nums.size(); ++i) { + result[indices[i]] = i > 2 ? to_string(i + 1) : ranks[i]; + } + return result; + } +}; From a6a9f182c6c46aec1145838db6f4024d669ed60e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 2 Apr 2017 20:10:29 +0800 Subject: [PATCH 3229/4971] Create relative-ranks.py --- Python/relative-ranks.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/relative-ranks.py diff --git a/Python/relative-ranks.py b/Python/relative-ranks.py new file mode 100644 index 000000000..3b32dd9a4 --- /dev/null +++ b/Python/relative-ranks.py @@ -0,0 +1,27 @@ +# Time: O(nlogn) +# Space: O(n) + +# Given scores of N athletes, find their relative ranks and +# the people with the top three highest scores, who will be +# awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal". +# +# Example 1: +# Input: [5, 4, 3, 2, 1] +# Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] +# Explanation: The first three athletes got the top three highest scores, +# so they got "Gold Medal", "Silver Medal" and "Bronze Medal". +# For the left two athletes, you just need to output +# their relative ranks according to their scores. +# Note: +# N is a positive integer and won't exceed 10,000. +# All the scores of athletes are guaranteed to be unique. + +class Solution(object): + def findRelativeRanks(self, nums): + """ + :type nums: List[int] + :rtype: List[str] + """ + sorted_nums = sorted(nums)[::-1] + ranks = ["Gold Medal", "Silver Medal", "Bronze Medal"] + map(str, range(4, len(nums) + 1)) + return map(dict(zip(sorted_nums, ranks)).get, nums) From d31bb209ab57be84f1b810734b0a03cabc2882ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 2 Apr 2017 20:23:14 +0800 Subject: [PATCH 3230/4971] Create most-frequent-subtree-sum.cpp --- C++/most-frequent-subtree-sum.cpp | 41 +++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 C++/most-frequent-subtree-sum.cpp diff --git a/C++/most-frequent-subtree-sum.cpp b/C++/most-frequent-subtree-sum.cpp new file mode 100644 index 000000000..cb3ff6f6c --- /dev/null +++ b/C++/most-frequent-subtree-sum.cpp @@ -0,0 +1,41 @@ +// 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 findFrequentTreeSum(TreeNode* root) { + unordered_map counts; + int max_count = 0; + countSubtreeSumsHelper(root, &counts, &max_count); + + vector result; + for (const auto& kvp : counts){ + if (kvp.second == max_count) { + result.emplace_back(kvp.first); + } + } + return result; + } + +private: + int countSubtreeSumsHelper(TreeNode *root, unordered_map *counts, int *max_count) { + if (!root) { + return 0; + } + auto sum = root->val + + countSubtreeSumsHelper(root->left, counts, max_count) + + countSubtreeSumsHelper(root->right, counts, max_count); + ++(*counts)[sum]; + (*max_count) = max((*max_count), (*counts)[sum]); + return sum; + } +}; From c52ef6d9fdc0fc992b6f80893e4a83a024c65465 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 2 Apr 2017 20:37:26 +0800 Subject: [PATCH 3231/4971] Create most-frequent-subtree-sum.py --- Python/most-frequent-subtree-sum.py | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/most-frequent-subtree-sum.py diff --git a/Python/most-frequent-subtree-sum.py b/Python/most-frequent-subtree-sum.py new file mode 100644 index 000000000..ca261a1b5 --- /dev/null +++ b/Python/most-frequent-subtree-sum.py @@ -0,0 +1,51 @@ +# Time: O(n) +# Space: O(n) + +# Given the root of a tree, you are asked to find the most frequent subtree sum. +# The subtree sum of a node is defined as the sum of all the node values formed by +# the subtree rooted at that node (including the node itself). +# So what is the most frequent subtree sum value? If there is a tie, +# return all the values with the highest frequency in any order. +# +# Examples 1 +# Input: +# +# 5 +# / \ +# 2 -3 +# return [2, -3, 4], since all the values happen only once, return all of them in any order. +# Examples 2 +# Input: +# +# 5 +# / \ +# 2 -5 +# return [2], since 2 happens twice, however -5 only occur once. +# Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer. + +# 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 findFrequentTreeSum(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ + def countSubtreeSumHelper(root, counts): + if not root: + return 0 + total = root.val + \ + countSubtreeSumHelper(root.left, counts) + \ + countSubtreeSumHelper(root.right, counts) + counts[total] += 1 + return total + + counts = collections.defaultdict(int) + countSubtreeSumHelper(root, counts) + max_count = max(counts.values()) if counts else 0 + return [total for total, count in counts.iteritems() if count == max_count] From 932268433b4131ad926cdb7ca19b424c037e04cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 00:15:33 +0800 Subject: [PATCH 3232/4971] Create split-array-with-equal-sum.cpp --- C++/split-array-with-equal-sum.cpp | 32 ++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/split-array-with-equal-sum.cpp diff --git a/C++/split-array-with-equal-sum.cpp b/C++/split-array-with-equal-sum.cpp new file mode 100644 index 000000000..5f4c336de --- /dev/null +++ b/C++/split-array-with-equal-sum.cpp @@ -0,0 +1,32 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + bool splitArray(vector& nums) { + if (nums.size() < 7) { + return false; + } + + vector sum(nums.size()); + sum[0] = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + sum[i] = sum[i - 1] + nums[i]; + } + for (int j = 3; j < nums.size() - 3; ++j) { + unordered_set lookup; + for (int i = 1; i < j - 1; ++i) { + if (sum[i - 1] == sum[j - 1] - sum[i]) { + lookup.emplace(sum[i - 1]); + } + } + for (int k = j + 2; k < nums.size() - 1; ++k) { + if (sum[nums.size() - 1] - sum[k] == sum[k - 1] - sum[j] && + lookup.count(sum[k - 1] - sum[j])) { + return true; + } + } + } + return false; + } +}; From 275adbea5477bbc6938e59edab23e1df182435ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 00:25:57 +0800 Subject: [PATCH 3233/4971] Create split-array-with-equal-sum.py --- Python/split-array-with-equal-sum.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/split-array-with-equal-sum.py diff --git a/Python/split-array-with-equal-sum.py b/Python/split-array-with-equal-sum.py new file mode 100644 index 000000000..036df2334 --- /dev/null +++ b/Python/split-array-with-equal-sum.py @@ -0,0 +1,26 @@ +# Time: O(n^2) +# Space: O(n) + +class Solution(object): + def splitArray(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + if len(nums) < 7: + return False + + accumulated_sum = [0] * len(nums) + accumulated_sum[0] = nums[0] + for i in xrange(1, len(nums)): + accumulated_sum[i] = accumulated_sum[i-1] + nums[i] + for j in xrange(3, len(nums)-3): + lookup = set() + for i in xrange(1, j-1): + if accumulated_sum[i-1] == accumulated_sum[j-1] - accumulated_sum[i]: + lookup.add(accumulated_sum[i-1]) + for k in xrange(j+2, len(nums)-1): + if accumulated_sum[-1] - accumulated_sum[k] == accumulated_sum[k-1] - accumulated_sum[j] and \ + accumulated_sum[k - 1] - accumulated_sum[j] in lookup: + return True + return False From 84a4f5ccb8a0764d6a0376c912d5b0e0b296a219 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 00:39:31 +0800 Subject: [PATCH 3234/4971] Create friend-circles.cpp --- C++/friend-circles.cpp | 48 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 C++/friend-circles.cpp diff --git a/C++/friend-circles.cpp b/C++/friend-circles.cpp new file mode 100644 index 000000000..3a58b0c26 --- /dev/null +++ b/C++/friend-circles.cpp @@ -0,0 +1,48 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + int findCircleNum(vector>& M) { + UnionFind circles(M.size()); + for (int i = 0; i < M.size(); ++i) { + for (int j = 0; j < M[i].size(); ++j) { + if (M[i][j] && i != j) { + circles.union_set(i, j); + } + } + } + return circles.size(); + } + +private: + class UnionFind { + public: + UnionFind(const int n) : set_(n), count_(n) { + iota(set_.begin(), set_.end(), 0); + } + + int find_set(const 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 size() const { + return count_; + } + + private: + vector set_; + int count_; + }; +}; From 5480a46c70bce9d9406c76e9a27f3915e53868f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 00:43:48 +0800 Subject: [PATCH 3235/4971] Create friend-circles.py --- Python/friend-circles.py | 66 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Python/friend-circles.py diff --git a/Python/friend-circles.py b/Python/friend-circles.py new file mode 100644 index 000000000..19ee1f376 --- /dev/null +++ b/Python/friend-circles.py @@ -0,0 +1,66 @@ +# Time: O(n^2) +# Space: O(n) + +# There are N students in a class. Some of them are friends, while some are not. +# Their friendship is transitive in nature. +# For example, if A is a direct friend of B, and B is a direct friend of C, +# then A is an indirect friend of C. +# And we defined a friend circle is a group of students who are direct or indirect friends. +# +# Given a N*N matrix M representing the friend relationship between students in the class. +# If M[i][j] = 1, then the ith and jth students are direct friends with each other, +# otherwise not. And you have to output the total number of friend circles among all the students. +# +# Example 1: +# Input: +# [[1,1,0], +# [1,1,0], +# [0,0,1]] +# Output: 2 +# Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. +# The 2nd student himself is in a friend circle. So return 2. +# +# Example 2: +# Input: +# [[1,1,0], +# [1,1,1], +# [0,1,1]] +# Output: 1 +# Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, +# so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1. +# +# Note: +# N is in range [1,200]. +# M[i][i] = 1 for all students. +# If M[i][j] = 1, then M[j][i] = 1. + +class Solution(object): + def findCircleNum(self, M): + """ + :type M: List[List[int]] + :rtype: int + """ + + 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 + + circles = UnionFind(len(M)) + for i in xrange(len(M)): + for j in xrange(len(M)): + if M[i][j] and i != j: + circles.union_set(i, j) + return circles.count + From 849f7dab375c393b9d3028b0deaa57958708bf17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 01:33:27 +0800 Subject: [PATCH 3236/4971] Create find-bottom-left-tree-value.cpp --- C++/find-bottom-left-tree-value.cpp | 59 +++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 C++/find-bottom-left-tree-value.cpp diff --git a/C++/find-bottom-left-tree-value.cpp b/C++/find-bottom-left-tree-value.cpp new file mode 100644 index 000000000..b30755d7b --- /dev/null +++ b/C++/find-bottom-left-tree-value.cpp @@ -0,0 +1,59 @@ +// 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 findBottomLeftValue(TreeNode* root) { + int result = 0, max_depth = 0; + findBottomLeftValueHelper(root, 0, &max_depth, &result); + return result; + } + +private: + void findBottomLeftValueHelper(TreeNode *root, int curr_depth, int *max_depth, int *bottom_left_value) { + if (!root) { + return; + } + if (!root->left && !root->right && + curr_depth + 1 > *max_depth) { + *max_depth = curr_depth + 1; + *bottom_left_value = root->val; + return; + } + + findBottomLeftValueHelper(root->left, curr_depth + 1, max_depth, bottom_left_value); + findBottomLeftValueHelper(root->right, curr_depth + 1, max_depth, bottom_left_value); + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { +public: + int findBottomLeftValue(TreeNode* root) { + queue q; + q.emplace(root); + TreeNode *node = nullptr; + while (!q.empty()) { + node = q.front(); + q.pop(); + if (node->right) { + q.emplace(node->right); + } + if (node->left) { + q.emplace(node->left); + } + } + return node->val; + } +}; From 88d5cde769af5e2e5509c7c229b35ec990b95c64 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 01:44:34 +0800 Subject: [PATCH 3237/4971] Create find-bottom-left-tree-value.py --- Python/find-bottom-left-tree-value.py | 67 +++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Python/find-bottom-left-tree-value.py diff --git a/Python/find-bottom-left-tree-value.py b/Python/find-bottom-left-tree-value.py new file mode 100644 index 000000000..bda1f8710 --- /dev/null +++ b/Python/find-bottom-left-tree-value.py @@ -0,0 +1,67 @@ +# Time: O(n) +# Space: O(h) + +# Given a binary tree, find the leftmost value in the last row of the tree. +# +# Example 1: +# Input: +# +# 2 +# / \ +# 1 3 +# +# Output: +# 1 +# Example 2: +# Input: +# +# 1 +# / \ +# 2 3 +# / / \ +# 4 5 6 +# / +# 7 +# +# Output: +# 7 +# Note: You may assume the tree (i.e., the given root node) is not NULL. + +# 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 findBottomLeftValue(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def findBottomLeftValueHelper(root, curr_depth, max_depth, bottom_left_value): + if not root: + return max_depth, bottom_left_value + if not root.left and not root.right and curr_depth+1 > max_depth: + return curr_depth+1, root.val + max_depth, bottom_left_value = findBottomLeftValueHelper(root.left, curr_depth+1, max_depth, bottom_left_value) + max_depth, bottom_left_value = findBottomLeftValueHelper(root.right, curr_depth+1, max_depth, bottom_left_value) + return max_depth, bottom_left_value + + result, max_depth = 0, 0 + return findBottomLeftValueHelper(root, 0, max_depth, result)[1] + + +# Time: O(n) +# Space: O(n) +class Solution2(object): + def findBottomLeftValue(self, root): + """ + :type root: TreeNode + :rtype: int + """ + queue = [root] + for node in queue: + queue += filter(None, (node.right, node.left)) + return node.val From dee1290e891620d16beb6ace29020437164f11cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 02:24:56 +0800 Subject: [PATCH 3238/4971] Create find-largest-value-in-each-tree-row.cpp --- C++/find-largest-value-in-each-tree-row.cpp | 64 +++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 C++/find-largest-value-in-each-tree-row.cpp diff --git a/C++/find-largest-value-in-each-tree-row.cpp b/C++/find-largest-value-in-each-tree-row.cpp new file mode 100644 index 000000000..396ad8e3d --- /dev/null +++ b/C++/find-largest-value-in-each-tree-row.cpp @@ -0,0 +1,64 @@ +// 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: + vector largestValues(TreeNode* root) { + vector result; + largestValuesHelper(root, 0, &result); + return result; + } +private: + void largestValuesHelper(TreeNode* root, int depth, vector *result) { + if (!root) { + return; + } + if (depth == result->size()) { + result->emplace_back(root->val); + } else { + (*result)[depth] = max((*result)[depth], root->val); + } + largestValuesHelper(root->left, depth + 1, result); + largestValuesHelper(root->right, depth + 1, result); + } + }; + +// Time: O(n) +// Space: O(n) +class Solution2 { +public: + vector largestValues(TreeNode* root) { + if (!root) { + return {}; + } + vector result; + vector curr, next; + curr.emplace_back(root); + while (!curr.empty()) { + int max_val = numeric_limits::min(); + next.clear(); + for (const auto& node : curr) { + max_val = max(max_val, node->val); + if (node->left) { + next.emplace_back(node->left); + } + if (node->right) { + next.emplace_back(node->right); + } + } + result.emplace_back(max_val); + swap(curr, next); + } + return result; + } +}; From b5ee59c1e33516288dfeeb7e0e3132c376f48096 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 02:30:42 +0800 Subject: [PATCH 3239/4971] Create find-largest-value-in-each-tree-row.py --- Python/find-largest-value-in-each-tree-row.py | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/find-largest-value-in-each-tree-row.py diff --git a/Python/find-largest-value-in-each-tree-row.py b/Python/find-largest-value-in-each-tree-row.py new file mode 100644 index 000000000..0ddc4af54 --- /dev/null +++ b/Python/find-largest-value-in-each-tree-row.py @@ -0,0 +1,59 @@ +# Time: O(n) +# Space: O(h) + +# You need to find the largest value in each row of a binary tree. +# +# Example: +# Input: +# +# 1 +# / \ +# 3 2 +# / \ \ +# 5 3 9 +# +# Output: [1, 3, 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 largestValues(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ + def largestValuesHelper(root, depth, result): + if not root: + return + if depth == len(result): + result.append(root.val) + else: + result[depth] = max(result[depth], root.val) + largestValuesHelper(root.left, depth+1, result) + largestValuesHelper(root.right, depth+1, result) + + result = [] + largestValuesHelper(root, 0, result) + return result + + +# Time: O(n) +# Space: O(n) +class Solution2(object): + def largestValues(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ + result = [] + curr = [root] + while any(curr): + result.append(max(node.val for node in curr)) + curr = [child for node in curr for child in (node.left, node.right) if child] + return result + From 3b7e9afa9600a1ed3f976efe63c0685edbdea302 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 12:25:04 +0800 Subject: [PATCH 3240/4971] Create longest-uncommon-subsequence-ii.cpp --- C++/longest-uncommon-subsequence-ii.cpp | 34 +++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/longest-uncommon-subsequence-ii.cpp diff --git a/C++/longest-uncommon-subsequence-ii.cpp b/C++/longest-uncommon-subsequence-ii.cpp new file mode 100644 index 000000000..1641f6074 --- /dev/null +++ b/C++/longest-uncommon-subsequence-ii.cpp @@ -0,0 +1,34 @@ +// Time: O(l * n^2) +// Space: O(1) + +class Solution { +public: + int findLUSlength(vector& strs) { + sort(strs.begin(), strs.end(), + [](const string& a, const string& b) { return a.length() > b.length(); }); + for (int i = 0; i < strs.size(); ++i) { + bool all_of = true; + for (int j = 0; strs[j].length() >= strs[i].length() && j < strs.size(); ++j) { + if (i != j && isSubsequence(strs[i], strs[j])) { + all_of = false; + break; + } + } + if (all_of) { + return strs[i].length(); + } + } + return -1; + } + +private: + bool isSubsequence(const string& a, const string& b) { + int i = 0; + for (int j = 0; j < b.length() && i < a.length(); ++j) { + if (a[i] == b[j]) { + ++i; + } + } + return i == a.length(); + } +}; From 88cdc42bb4c7a66209ccd4b5d38844472f302f8b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 12:27:18 +0800 Subject: [PATCH 3241/4971] Create longest-uncommon-subsequence-i.cpp --- C++/longest-uncommon-subsequence-i.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 C++/longest-uncommon-subsequence-i.cpp diff --git a/C++/longest-uncommon-subsequence-i.cpp b/C++/longest-uncommon-subsequence-i.cpp new file mode 100644 index 000000000..24b695e99 --- /dev/null +++ b/C++/longest-uncommon-subsequence-i.cpp @@ -0,0 +1,12 @@ +// Time: O(min(a, b)) +// Space: O(1) + +class Solution { +public: + int findLUSlength(string a, string b) { + if (a == b) { + return -1; + } + return max(a.length(), b.length()); + } +}; From 31b205337d9535ffbba7f3b897f7ec2798a1c1e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 12:37:52 +0800 Subject: [PATCH 3242/4971] Create ongest-uncommon-subsequence-ii.py --- Python/ongest-uncommon-subsequence-ii.py | 49 ++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/ongest-uncommon-subsequence-ii.py diff --git a/Python/ongest-uncommon-subsequence-ii.py b/Python/ongest-uncommon-subsequence-ii.py new file mode 100644 index 000000000..c73d74a3f --- /dev/null +++ b/Python/ongest-uncommon-subsequence-ii.py @@ -0,0 +1,49 @@ +# Time: O(l * n^2) +# Space: O(1) + +# Given a list of strings, you need to find the longest uncommon subsequence among them. +# The longest uncommon subsequence is defined as the longest subsequence of one of these strings +# and this subsequence should not be any subsequence of the other strings. +# +# A subsequence is a sequence that can be derived from one sequence +# by deleting some characters without changing the order of the remaining elements. +# Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string. +# +# The input will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. +# If the longest uncommon subsequence doesn't exist, return -1. +# +# Example 1: +# Input: "aba", "cdc", "eae" +# Output: 3 +# Note: +# +# All the given strings' lengths will not exceed 10. +# The length of the given list will be in the range of [2, 50]. + +class Solution(object): + def findLUSlength(self, strs): + """ + :type strs: List[str] + :rtype: int + """ + def isSubsequence(a, b): + i = 0 + for j in xrange(len(b)): + if i >= len(a): + break + if a[i] == b[j]: + i += 1 + return i == len(a) + + strs.sort(key=len, reverse=True) + for i in xrange(len(strs)): + all_of = True + for j in xrange(len(strs)): + if len(strs[j]) < len(strs[i]): + break + if i != j and isSubsequence(strs[i], strs[j]): + all_of = False + break + if all_of: + return len(strs[i]) + return -1 From 4c419865002d6f057074f5bd605746e870a3e856 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 12:38:09 +0800 Subject: [PATCH 3243/4971] Rename ongest-uncommon-subsequence-ii.py to longest-uncommon-subsequence-ii.py --- ...ommon-subsequence-ii.py => longest-uncommon-subsequence-ii.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{ongest-uncommon-subsequence-ii.py => longest-uncommon-subsequence-ii.py} (100%) diff --git a/Python/ongest-uncommon-subsequence-ii.py b/Python/longest-uncommon-subsequence-ii.py similarity index 100% rename from Python/ongest-uncommon-subsequence-ii.py rename to Python/longest-uncommon-subsequence-ii.py From fa855ae48a15cfd9b1e01227952a29249faa55d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 12:39:59 +0800 Subject: [PATCH 3244/4971] Create longest-uncommon-subsequence-i.py --- Python/longest-uncommon-subsequence-i.py | 35 ++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/longest-uncommon-subsequence-i.py diff --git a/Python/longest-uncommon-subsequence-i.py b/Python/longest-uncommon-subsequence-i.py new file mode 100644 index 000000000..007cee665 --- /dev/null +++ b/Python/longest-uncommon-subsequence-i.py @@ -0,0 +1,35 @@ +# Time: O(min(a, b)) +# Space: O(1) + +# Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. +# The longest uncommon subsequence is defined as the longest subsequence of one of these strings +# and this subsequence should not be any subsequence of the other strings. +# +# A subsequence is a sequence that can be derived from one sequence +# by deleting some characters without changing the order of the remaining elements. +# Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string. +# +# The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. +# If the longest uncommon subsequence doesn't exist, return -1. +# +# Example 1: +# Input: "aba", "cdc" +# Output: 3 +# Explanation: The longest uncommon subsequence is "aba" (or "cdc"), +# because "aba" is a subsequence of "aba", +# but not a subsequence of any other strings in the group of two strings. +# Note: +# +# Both strings' lengths will not exceed 100. +# Only letters from a ~ z will appear in input strings. + +class Solution(object): + def findLUSlength(self, a, b): + """ + :type a: str + :type b: str + :rtype: int + """ + if a == b: + return -1 + return max(len(a), len(b)) From 49ed646e9b94442908d92b561ffa874aca9d4fa9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 15:00:51 +0800 Subject: [PATCH 3245/4971] Create longest-palindromic-subsequence.cpp --- C++/longest-palindromic-subsequence.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/longest-palindromic-subsequence.cpp diff --git a/C++/longest-palindromic-subsequence.cpp b/C++/longest-palindromic-subsequence.cpp new file mode 100644 index 000000000..852f3ff0c --- /dev/null +++ b/C++/longest-palindromic-subsequence.cpp @@ -0,0 +1,19 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + int longestPalindromeSubseq(string s) { + vector> dp(2, vector(s.size(), 1)); + for (int i = s.length() - 2; i >= 0; --i) { + for (int j = i + 1; j < s.length(); ++j) { + if (s[i] == s[j]) { + dp[i % 2][j] = (i + 1 <= j - 1) ? 2 + dp[(i + 1) % 2][j - 1] : 2; + } else { + dp[i % 2][j] = max(dp[(i + 1) % 2][j], dp[i % 2][j - 1]); + } + } + } + return dp[0][s.length() - 1]; + } +}; From c4c83833fe6a2b3d35e38b4afe5773b6d3a5200f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 15:08:19 +0800 Subject: [PATCH 3246/4971] Create longest-palindromic-subsequence.py --- Python/longest-palindromic-subsequence.py | 37 +++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/longest-palindromic-subsequence.py diff --git a/Python/longest-palindromic-subsequence.py b/Python/longest-palindromic-subsequence.py new file mode 100644 index 000000000..2c0cd5f5c --- /dev/null +++ b/Python/longest-palindromic-subsequence.py @@ -0,0 +1,37 @@ +# Time: O(n^2) +# Space: O(n) + +# Given a string s, find the longest palindromic subsequence's length in s. +# You may assume that the maximum length of s is 1000. +# +# Example 1: +# Input: +# +# "bbbab" +# Output: +# 4 +# One possible longest palindromic subsequence is "bbbb". +# Example 2: +# Input: +# +# "cbbd" +# Output: +# 2 + +class Solution(object): + def longestPalindromeSubseq(self, s): + """ + :type s: str + :rtype: int + """ + if s == s[::-1]: + return len(s) + + dp = [[1] * len(s) for _ in xrange(2)] + for i in reversed(xrange(len(s))): + for j in xrange(i+1, len(s)): + if s[i] == s[j]: + dp[i%2][j] = 2 + dp[(i+1)%2][j-1] if i+1 <= j-1 else 2 + else: + dp[i%2][j] = max(dp[(i+1)%2][j], dp[i%2][j-1]) + return dp[0][-1] From 6ad6855aea48a079b32ffec33a93c9efd1f730d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 15:18:43 +0800 Subject: [PATCH 3247/4971] Create beautiful-arrangement.cpp --- C++/beautiful-arrangement.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/beautiful-arrangement.cpp diff --git a/C++/beautiful-arrangement.cpp b/C++/beautiful-arrangement.cpp new file mode 100644 index 000000000..b2ca85574 --- /dev/null +++ b/C++/beautiful-arrangement.cpp @@ -0,0 +1,27 @@ +// Time: O(n!) +// Space: O(n) + +class Solution { +public: + int countArrangement(int N) { + vector arrangement(N); + iota(arrangement.begin(), arrangement.end(), 1); + return countArrangementHelper(N, &arrangement); + } + +private: + int countArrangementHelper(int n, vector *arrangement) { + if (n <= 0) { + return 1; + } + int count = 0; + for (int i = 0; i < n; ++i) { + if ((*arrangement)[i] % n == 0 || n % (*arrangement)[i] == 0) { + swap((*arrangement)[i], (*arrangement)[n - 1]); + count += countArrangementHelper(n - 1, arrangement); + swap((*arrangement)[i], (*arrangement)[n - 1]); + } + } + return count; + } +}; From 98961aee03a0d311ef082b2219d79d527187785d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 15:27:55 +0800 Subject: [PATCH 3248/4971] Create beautiful-arrangement.py --- Python/beautiful-arrangement.py | 48 +++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/beautiful-arrangement.py diff --git a/Python/beautiful-arrangement.py b/Python/beautiful-arrangement.py new file mode 100644 index 000000000..383209c20 --- /dev/null +++ b/Python/beautiful-arrangement.py @@ -0,0 +1,48 @@ +# Time: O(n!) +# Space: O(n) + +# Suppose you have N integers from 1 to N. +# We define a beautiful arrangement as an array that is constructed by these N numbers successfully +# if one of the following is true for the ith position (1 <= i <= N) in this array: +# +# The number at the ith position is divisible by i. +# i is divisible by the number at the ith position. +# Now given N, how many beautiful arrangements can you construct? +# +# Example 1: +# Input: 2 +# Output: 2 +# Explanation: +# +# The first beautiful arrangement is [1, 2]: +# +# Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1). +# +# Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2). +# +# The second beautiful arrangement is [2, 1]: +# +# Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1). +# +# Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1. +# Note: +# N is a positive integer and will not exceed 15. + +class Solution(object): + def countArrangement(self, N): + """ + :type N: int + :rtype: int + """ + def countArrangementHelper(n, arrangement): + if n <= 0: + return 1 + count = 0 + for i in xrange(n): + if arrangement[i] % n == 0 or n % arrangement[i] == 0: + arrangement[i], arrangement[n-1] = arrangement[n-1], arrangement[i] + count += countArrangementHelper(n - 1, arrangement) + arrangement[i], arrangement[n-1] = arrangement[n-1], arrangement[i] + return count + + return countArrangementHelper(N, range(1, N+1)) From fbacbb719b701a51851d874595376d6fb9e19707 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 16:05:48 +0800 Subject: [PATCH 3249/4971] Create minesweeper.cpp --- C++/minesweeper.cpp | 108 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 C++/minesweeper.cpp diff --git a/C++/minesweeper.cpp b/C++/minesweeper.cpp new file mode 100644 index 000000000..4f344c139 --- /dev/null +++ b/C++/minesweeper.cpp @@ -0,0 +1,108 @@ +// Time: O(m * n) +// Space: O(m + n) + +class Solution { +public: + vector> updateBoard(vector>& board, vector& click) { + queue> q; + q.emplace(click); + while (!q.empty()) { + int row = q.front()[0], col = q.front()[1]; + q.pop(); + if (board[row][col] == 'M') { + board[row][col] = 'X'; + } else { + int count = 0; + for (int i = -1; i < 2; ++i) { + for (int j = -1; j < 2; ++j) { + if (i == 0 && j == 0) { + continue; + } + int r = row + i, c = col + j; + if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) { + continue; + } + if (board[r][c] == 'M' || board[r][c] == 'X') { + ++count; + } + } + } + + if (count > 0) { + board[row][col] = count + '0'; + } else { + board[row][col] = 'B'; + for (int i = -1; i < 2; ++i) { + for (int j = -1; j < 2; ++j) { + if (i == 0 && j == 0) { + continue; + } + int r = row + i, c = col + j; + if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) { + continue; + } + if (board[r][c] == 'E') { + vector next_click = {r, c}; + q.emplace(next_click); + board[r][c] = 'B'; + } + } + } + } + } + } + + return board; + } +}; + +// Time: O(m * n) +// Space: O(m * n) +class Solution2 { +public: + vector> updateBoard(vector>& board, vector& click) { + int row = click[0], col = click[1]; + if (board[row][col] == 'M') { + board[row][col] = 'X'; + } else { + int count = 0; + for (int i = -1; i < 2; ++i) { + for (int j = -1; j < 2; ++j) { + if (i == 0 && j == 0) { + continue; + } + int r = row + i, c = col + j; + if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) { + continue; + } + if (board[r][c] == 'M' || board[r][c] == 'X') { + ++count; + } + } + } + + if (count > 0) { + board[row][col] = count + '0'; + } else { + board[row][col] = 'B'; + for (int i = -1; i < 2; ++i) { + for (int j = -1; j < 2; ++j) { + if (i == 0 && j == 0) { + continue; + } + int r = row + i, c = col + j; + if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) { + continue; + } + vector next_click = {r, c}; + if (board[r][c] == 'E') { + updateBoard(board, next_click); + } + } + } + } + } + + return board; + } +}; From d302614909cdf57be6fbb46eb7937a314c58a446 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 16:19:48 +0800 Subject: [PATCH 3250/4971] Update minesweeper.cpp --- C++/minesweeper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/minesweeper.cpp b/C++/minesweeper.cpp index 4f344c139..88fbb15f4 100644 --- a/C++/minesweeper.cpp +++ b/C++/minesweeper.cpp @@ -94,8 +94,8 @@ class Solution2 { if (r < 0 || r >= board.size() || c < 0 || c < 0 || c >= board[r].size()) { continue; } - vector next_click = {r, c}; if (board[r][c] == 'E') { + vector next_click = {r, c}; updateBoard(board, next_click); } } From 71b77e95162bc7edcd9b205d270dab6f266c4d92 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 16:35:12 +0800 Subject: [PATCH 3251/4971] Create minesweeper.py --- Python/minesweeper.py | 138 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 Python/minesweeper.py diff --git a/Python/minesweeper.py b/Python/minesweeper.py new file mode 100644 index 000000000..a3a9fe712 --- /dev/null +++ b/Python/minesweeper.py @@ -0,0 +1,138 @@ +# Time: O(m * n) +# Space: O(m + n) + +# Let's play the minesweeper game (Wikipedia, online game)! +# +# You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, +# 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent +# (above, below, left, right, and all 4 diagonals) mines, digit ('1' to '8') represents +# how many mines are adjacent to this revealed square, and finally 'X' represents a revealed mine. +# +# Now given the next click position (row and column indices) among all the unrevealed squares ('M' or 'E'), +# return the board after revealing this position according to the following rules: +# +# If a mine ('M') is revealed, then the game is over - change it to 'X'. +# If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') +# and all of its adjacent unrevealed squares should be revealed recursively. +# If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') +# representing the number of adjacent mines. +# Return the board when no more squares will be revealed. +# +# Example 1: +# Input: +# [['E', 'E', 'E', 'E', 'E'], +# ['E', 'E', 'M', 'E', 'E'], +# ['E', 'E', 'E', 'E', 'E'], +# ['E', 'E', 'E', 'E', 'E']] +# Click : [3,0] +# Output: +# [['B', '1', 'E', '1', 'B'], +# ['B', '1', 'M', '1', 'B'], +# ['B', '1', '1', '1', 'B'], +# ['B', 'B', 'B', 'B', 'B']] +# +# Example 2: +# Input: +# [['B', '1', 'E', '1', 'B'], +# ['B', '1', 'M', '1', 'B'], +# ['B', '1', '1', '1', 'B'], +# ['B', 'B', 'B', 'B', 'B']] +# +# Click : [1,2] +# Output: +# [['B', '1', 'E', '1', 'B'], +# ['B', '1', 'X', '1', 'B'], +# ['B', '1', '1', '1', 'B'], +# ['B', 'B', 'B', 'B', 'B']] +# +# Note: +# The range of the input matrix's height and width is [1,50]. +# The click position will only be an unrevealed square ('M' or 'E'), +# which also means the input board contains at least one clickable square. +# The input board won't be a stage when game is over (some mines have been revealed). +# For simplicity, not mentioned rules should be ignored in this problem. +# For example, you don't need to reveal all the unrevealed mines when the game is over, +# consider any cases that you will win the game or flag any squares. + +class Solution(object): + def updateBoard(self, board, click): + """ + :type board: List[List[str]] + :type click: List[int] + :rtype: List[List[str]] + """ + q = collections.deque([click]) + while q: + row, col = q.popleft() + if board[row][col] == 'M': + board[row][col] = 'X' + else: + count = 0 + for i in xrange(-1, 2): + for j in xrange(-1, 2): + if i == 0 and j == 0: + continue + r, c = row + i, col + j + if not (0 <= r < len(board)) or not (0 <= c < len(board[r])): + continue + if board[r][c] == 'M' or board[r][c] == 'X': + count += 1 + + if count: + board[row][col] = chr(count + ord('0')) + else: + board[row][col] = 'B' + for i in xrange(-1, 2): + for j in xrange(-1, 2): + if i == 0 and j == 0: + continue + r, c = row + i, col + j + if not (0 <= r < len(board)) or not (0 <= c < len(board[r])): + continue + if board[r][c] == 'E': + q.append((r, c)) + board[r][c] = ' ' + + return board + + +# Time: O(m * n) +# Space: O(m * n) +class Solution2(object): + def updateBoard(self, board, click): + """ + :type board: List[List[str]] + :type click: List[int] + :rtype: List[List[str]] + """ + row, col = click[0], click[1] + if board[row][col] == 'M': + board[row][col] = 'X' + else: + count = 0 + for i in xrange(-1, 2): + for j in xrange(-1, 2): + if i == 0 and j == 0: + continue + r, c = row + i, col + j + if not (0 <= r < len(board)) or not (0 <= c < len(board[r])): + continue + if board[r][c] == 'M' or board[r][c] == 'X': + count += 1 + + if count: + board[row][col] = chr(count + ord('0')) + else: + board[row][col] = 'B' + for i in xrange(-1, 2): + for j in xrange(-1, 2): + if i == 0 and j == 0: + continue + r, c = row + i, col + j + if not (0 <= r < len(board)) or not (0 <= c < len(board[r])): + continue + if board[r][c] == 'E': + self.updateBoard(board, (r, c)) + + return board + From 8f7d3b7b212e77dcb49045b32ef20b89bf61b8d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 16:50:05 +0800 Subject: [PATCH 3252/4971] Create diameter-of-binary-tree.py --- Python/diameter-of-binary-tree.py | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/diameter-of-binary-tree.py diff --git a/Python/diameter-of-binary-tree.py b/Python/diameter-of-binary-tree.py new file mode 100644 index 000000000..736e93b3b --- /dev/null +++ b/Python/diameter-of-binary-tree.py @@ -0,0 +1,38 @@ +# Time: O(n) +# Space: O(h) + +# Given a binary tree, you need to compute the length of the diameter of the tree. +# The diameter of a binary tree is the length of the longest path between +# any two nodes in a tree. This path may or may not pass through the root. +# +# Example: +# Given a binary tree +# 1 +# / \ +# 2 3 +# / \ +# 4 5 +# Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. +# +# Note: The length of path between two nodes is represented by the number of edges between them. + +# 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 diameterOfBinaryTree(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def depth(root, diameter): + if not root: return 0, diameter + left, diameter = depth(root.left, diameter) + right, diameter = depth(root.right, diameter) + return 1 + max(left, right), max(diameter, 1 + left + right) + + return depth(root, 1)[1] - 1 From 0a4ae0e2f70afccb60c584f6f04837e3c6258d5c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 17:00:12 +0800 Subject: [PATCH 3253/4971] Create diameter-of-binary-tree.cpp --- C++/diameter-of-binary-tree.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/diameter-of-binary-tree.cpp diff --git a/C++/diameter-of-binary-tree.cpp b/C++/diameter-of-binary-tree.cpp new file mode 100644 index 000000000..c7c46d0f3 --- /dev/null +++ b/C++/diameter-of-binary-tree.cpp @@ -0,0 +1,31 @@ +// 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 diameterOfBinaryTree(TreeNode* root) { + int diameter = 1; + depth(root, &diameter); + return diameter - 1; + } + +private: + int depth(TreeNode *root, int *diameter) { + if (!root) { + return 0; + } + auto left = depth(root->left, diameter); + auto right = depth(root->right, diameter); + *diameter = max(*diameter, 1 + left + right); + return 1 + max(left, right); + } +}; From 55c6624fefde058e73ce704c795bcf800ed3c25f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 17:12:23 +0800 Subject: [PATCH 3254/4971] Create minimum-time-difference.cpp --- C++/minimum-time-difference.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/minimum-time-difference.cpp diff --git a/C++/minimum-time-difference.cpp b/C++/minimum-time-difference.cpp new file mode 100644 index 000000000..145cf6dce --- /dev/null +++ b/C++/minimum-time-difference.cpp @@ -0,0 +1,19 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + int findMinDifference(vector& timePoints) { + static const int N = 60 * 24; + vector minutes; + for (const auto& t : timePoints) { + minutes.emplace_back(stoi(t.substr(0, 2)) * 60 + stoi(t.substr(3))); + } + sort(minutes.begin(), minutes.end()); + int result = numeric_limits::max(); + for (int i = 0; i < timePoints.size(); ++i) { + result = min(result, (N + minutes[(i + 1) % timePoints.size()] - minutes[i]) % N); + } + return result; + } +}; From 75689f79f5eeb9e3927195c2505e6e9c185c1605 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 17:18:34 +0800 Subject: [PATCH 3255/4971] Create minimum-time-difference.py --- Python/minimum-time-difference.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Python/minimum-time-difference.py diff --git a/Python/minimum-time-difference.py b/Python/minimum-time-difference.py new file mode 100644 index 000000000..1366a336a --- /dev/null +++ b/Python/minimum-time-difference.py @@ -0,0 +1,23 @@ +# Time: O(nlogn) +# Space: O(n) + +# Given a list of 24-hour clock time points in "Hour:Minutes" format, +# find the minimum minutes difference between any two time points in the list. +# +# Example 1: +# Input: ["23:59","00:00"] +# Output: 1 +# Note: +# The number of time points in the given list is at least 2 and won't exceed 20000. +# The input time is legal and ranges from 00:00 to 23:59. + +class Solution(object): + def findMinDifference(self, timePoints): + """ + :type timePoints: List[str] + :rtype: int + """ + minutes = map(lambda x: int(x[:2]) * 60 + int(x[3:]), timePoints) + minutes.sort() + return min((y - x) % (24 * 60) \ + for x, y in zip(minutes, minutes[1:] + minutes[:1])) From 550c3f00d28852c593af5809bc68561cc18ae753 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 17:23:34 +0800 Subject: [PATCH 3256/4971] Create convert-bst-to-greater-tree.cpp --- C++/convert-bst-to-greater-tree.cpp | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/convert-bst-to-greater-tree.cpp diff --git a/C++/convert-bst-to-greater-tree.cpp b/C++/convert-bst-to-greater-tree.cpp new file mode 100644 index 000000000..162989479 --- /dev/null +++ b/C++/convert-bst-to-greater-tree.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: + TreeNode* convertBST(TreeNode* root) { + int cur_sum = 0; + convertBSTHelper(root, &cur_sum); + return root; + } + +private: + void convertBSTHelper(TreeNode* root, int *cur_sum){ + if (!root) { + return; + } + + if (root->right) { + convertBSTHelper(root->right, cur_sum); + } + root->val = (*cur_sum += root->val); + if (root->left) { + convertBSTHelper(root->left, cur_sum); + } + } +}; From 6357256ab80f86461fa7294b7899d83f2cd4ccd4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 17:24:48 +0800 Subject: [PATCH 3257/4971] Update convert-bst-to-greater-tree.cpp --- C++/convert-bst-to-greater-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/convert-bst-to-greater-tree.cpp b/C++/convert-bst-to-greater-tree.cpp index 162989479..c66042d2a 100644 --- a/C++/convert-bst-to-greater-tree.cpp +++ b/C++/convert-bst-to-greater-tree.cpp @@ -19,7 +19,7 @@ class Solution { } private: - void convertBSTHelper(TreeNode* root, int *cur_sum){ + void convertBSTHelper(TreeNode* root, int *cur_sum) { if (!root) { return; } From d5cb11e3d5d91d9c18b12cccbc806e1cf3bd0697 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 17:30:18 +0800 Subject: [PATCH 3258/4971] Create convert-bst-to-greater-tree.py --- Python/convert-bst-to-greater-tree.py | 47 +++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/convert-bst-to-greater-tree.py diff --git a/Python/convert-bst-to-greater-tree.py b/Python/convert-bst-to-greater-tree.py new file mode 100644 index 000000000..c0ff15309 --- /dev/null +++ b/Python/convert-bst-to-greater-tree.py @@ -0,0 +1,47 @@ +# Time: O(n) +# Space: O(h) + +# Given a Binary Search Tree (BST), +# convert it to a Greater Tree such that every key of +# the original BST is changed to the original key plus sum of +# all keys greater than the original key in BST. +# +# Example: +# +# Input: The root of a Binary Search Tree like this: +# 5 +# / \ +# 2 13 +# +# Output: The root of a Greater Tree like this: +# 18 +# / \ +# 20 13 + +# 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 convertBST(self, root): + """ + :type root: TreeNode + :rtype: TreeNode + """ + def convertBSTHelper(root, cur_sum): + if not root: + return cur_sum + + if root.right: + cur_sum = convertBSTHelper(root.right, cur_sum) + cur_sum += root.val + root.val = cur_sum; + if root.left: + cur_sum = convertBSTHelper(root.left, cur_sum) + return cur_sum + + convertBSTHelper(root, 0) + return root From 448200dc5c962d6b1ebf3aeb6c22a530bf495f8f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 17:39:02 +0800 Subject: [PATCH 3259/4971] Create complex-number-multiplication.py --- Python/complex-number-multiplication.py | 32 +++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/complex-number-multiplication.py diff --git a/Python/complex-number-multiplication.py b/Python/complex-number-multiplication.py new file mode 100644 index 000000000..63fc97772 --- /dev/null +++ b/Python/complex-number-multiplication.py @@ -0,0 +1,32 @@ +# Time: O(1) +# Space: O(1) + +# Given two strings representing two complex numbers. +# +# You need to return a string representing their multiplication. Note i2 = -1 according to the definition. +# +# Example 1: +# Input: "1+1i", "1+1i" +# Output: "0+2i" +# Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i. +# Example 2: +# Input: "1+-1i", "1+-1i" +# Output: "0+-2i" +# Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i. +# Note: +# +# The input strings will not have extra blank. +# The input strings will be given in the form of a+bi, +# where the integer a and b will both belong to the range of [-100, 100]. +# And the output should be also in this form. + +class Solution(object): + def complexNumberMultiply(self, a, b): + """ + :type a: str + :type b: str + :rtype: str + """ + ra, ia = map(int, a[:-1].split('+')) + rb, ib = map(int, b[:-1].split('+')) + return '%d+%di' % (ra * rb - ia * ib, ra * ib + ia * rb) From 237e863f713fa986a205b4551535f22b727ac5d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 17:40:05 +0800 Subject: [PATCH 3260/4971] Create complex-number-multiplication.cpp --- C++/complex-number-multiplication.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/complex-number-multiplication.cpp diff --git a/C++/complex-number-multiplication.cpp b/C++/complex-number-multiplication.cpp new file mode 100644 index 000000000..d3127e59b --- /dev/null +++ b/C++/complex-number-multiplication.cpp @@ -0,0 +1,18 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + string complexNumberMultiply(string a, string b) { + int ra, ia, rb, ib; + char op; + stringstream ssa(a), ssb(b); + ssa >> ra >> op >> ia; + ssb >> rb >> op >> ib; + string result = to_string(ra * rb - ia * ib); + result += "+"; + result += to_string(ra * ib + rb * ia); + result += "i"; + return result; + } +}; From 73efe81b872f57565881448ff52942751bb9816c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 18:09:14 +0800 Subject: [PATCH 3261/4971] Create output-contest-matches.cpp --- C++/output-contest-matches.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/output-contest-matches.cpp diff --git a/C++/output-contest-matches.cpp b/C++/output-contest-matches.cpp new file mode 100644 index 000000000..b97d47a3e --- /dev/null +++ b/C++/output-contest-matches.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + string findContestMatch(int n) { + vector matches(n); + for (int i = 0; i < n; ++i) { + matches[i] = to_string(i + 1); + } + while (matches.size() / 2) { + vector next_matches; + for (int i = 0; i < matches.size() / 2; ++i) { + next_matches.emplace_back("(" + matches[i] + "," + matches[matches.size() - 1 - i] + ")"); + } + swap(matches, next_matches); + } + return matches[0]; + } +}; From 292370e182e2a5df650ccc5cb48812458054a227 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Apr 2017 18:10:33 +0800 Subject: [PATCH 3262/4971] Create output-contest-matches.py --- Python/output-contest-matches.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Python/output-contest-matches.py diff --git a/Python/output-contest-matches.py b/Python/output-contest-matches.py new file mode 100644 index 000000000..1606a031e --- /dev/null +++ b/Python/output-contest-matches.py @@ -0,0 +1,14 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def findContestMatch(self, n): + """ + :type n: int + :rtype: str + """ + matches = map(str, range(1, n+1)) + while len(matches)/2: + matches = ["({},{})".format(matches[i], matches[-i-1]) for i in xrange(len(matches)/2)] + return matches[0] + From 21ac079214b01bcba39935d16663092f66cf3549 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Apr 2017 21:40:31 +0800 Subject: [PATCH 3263/4971] Create next-greater-element-iii.cpp --- C++/next-greater-element-iii.cpp | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/next-greater-element-iii.cpp diff --git a/C++/next-greater-element-iii.cpp b/C++/next-greater-element-iii.cpp new file mode 100644 index 000000000..a6e9ac3e7 --- /dev/null +++ b/C++/next-greater-element-iii.cpp @@ -0,0 +1,39 @@ +// Time: O(logn) +// Space: O(logn) + +class Solution { +public: + int nextGreaterElement(int n) { + auto digits = to_string(n); + nextPermutation(begin(digits), end(digits)); // self-implemented next_permutattion() + auto result = stoll(digits); + return (result > numeric_limits::max() || result <= n) ? -1 : result; + } + +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; + } + + 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 is_greater; + } +}; From 457de6791c41d0643a85e601db940671fa12c7af Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Apr 2017 21:42:16 +0800 Subject: [PATCH 3264/4971] Create next-greater-element-iii.py --- Python/next-greater-element-iii.py | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/next-greater-element-iii.py diff --git a/Python/next-greater-element-iii.py b/Python/next-greater-element-iii.py new file mode 100644 index 000000000..4f93b7946 --- /dev/null +++ b/Python/next-greater-element-iii.py @@ -0,0 +1,38 @@ +# Time: O(logn) +# Space: O(logn) + +# Given a positive 32-bit integer n, you need to find the smallest 32-bit integer +# which has exactly the same digits existing in the integer n and is greater in value than n. +# If no such positive 32-bit integer exists, you need to return -1. +@ +# Example 1: +# Input: 12 +# Output: 21 +# Example 2: +# Input: 21 +# Output: -1 + +class Solution(object): + def nextGreaterElement(self, n): + """ + :type n: int + :rtype: int + """ + digits = map(int, list(str(n))) + k, l = -1, 0 + for i in xrange(len(digits) - 1): + if digits[i] < digits[i + 1]: + k = i + + if k == -1: + digits.reverse() + return -1 + + for i in xrange(k + 1, len(digits)): + if digits[i] > digits[k]: + l = i + + digits[k], digits[l] = digits[l], digits[k] + digits[k + 1:] = digits[:k:-1] + result = int("".join(map(str, digits))) + return -1 if result >= 0x7FFFFFFF else result From 535dae19e68a5169569073e1ed801f4e47116ff8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Apr 2017 21:45:16 +0800 Subject: [PATCH 3265/4971] Create reverse-words-in-a-string-iii.cpp --- C++/reverse-words-in-a-string-iii.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/reverse-words-in-a-string-iii.cpp diff --git a/C++/reverse-words-in-a-string-iii.cpp b/C++/reverse-words-in-a-string-iii.cpp new file mode 100644 index 000000000..8edc11bbc --- /dev/null +++ b/C++/reverse-words-in-a-string-iii.cpp @@ -0,0 +1,15 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string reverseWords(string s) { + 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; + } + } + return s; + } +}; From 896fcd8ed390e6395cc903b2a65a562ec2870594 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Apr 2017 21:49:40 +0800 Subject: [PATCH 3266/4971] Create reverse-words-in-a-string-iii.py --- Python/reverse-words-in-a-string-iii.py | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Python/reverse-words-in-a-string-iii.py diff --git a/Python/reverse-words-in-a-string-iii.py b/Python/reverse-words-in-a-string-iii.py new file mode 100644 index 000000000..31947e6ae --- /dev/null +++ b/Python/reverse-words-in-a-string-iii.py @@ -0,0 +1,28 @@ +# Time: O(n) +# Space: O(1) + +# Given a string, you need to reverse the order of characters in each word within a sentence +# while still preserving whitespace and initial word order. +# +# Example 1: +# Input: "Let's take LeetCode contest" +# Output: "s'teL ekat edoCteeL tsetnoc" +# Note: In the string, each word is separated by single space and +# there will not be any extra space in the string. + +class Solution(object): + def reverseWords(self, s): + """ + :type s: str + :rtype: str + """ + 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] + + s, i = list(s), 0 + for j in xrange(len(s) + 1): + if j == len(s) or s[j] == ' ': + reverse(s, i, j) + i = j + 1 + return "".join(s) From cd89d42376a28afe5017580b1489b21f8b7e2022 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Apr 2017 21:59:47 +0800 Subject: [PATCH 3267/4971] Create brick-wall.cpp --- C++/brick-wall.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 C++/brick-wall.cpp diff --git a/C++/brick-wall.cpp b/C++/brick-wall.cpp new file mode 100644 index 000000000..55a8d5e83 --- /dev/null +++ b/C++/brick-wall.cpp @@ -0,0 +1,16 @@ +// Time: O(n), n is the total number of the bricks +// Space: O(m), m is the total number different widths + +class Solution { +public: + int leastBricks(vector>& wall) { + unordered_map widths; + auto result = wall.size(); + for (const auto& row : wall) { + for (auto i = 0, width = 0; i < row.size() - 1; ++i) { + result = min(result, wall.size() - (++widths[width += row[i]])); + } + } + return result; + } +}; From e58fe43d032a98849acc9c0ca041432bea0dbdba Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Apr 2017 22:04:17 +0800 Subject: [PATCH 3268/4971] Create brick-wall.py --- Python/brick-wall.py | 47 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/brick-wall.py diff --git a/Python/brick-wall.py b/Python/brick-wall.py new file mode 100644 index 000000000..47ea1c230 --- /dev/null +++ b/Python/brick-wall.py @@ -0,0 +1,47 @@ +# Time: O(n), n is the total number of the bricks +# Space: O(m), m is the total number different widths + +# There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. +# The bricks have the same height but different width. You want to draw a vertical line from +# the top to the bottom and cross the least bricks. +# +# The brick wall is represented by a list of rows. Each row is a list of integers representing the +# width of each brick in this row from left to right. +# +# If your line go through the edge of a brick, then the brick is not considered as crossed. +# You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks. +# +# You cannot draw a line just along one of the two vertical edges of the wall, +# in which case the line will obviously cross no bricks. +# +# Example: +# Input: +# [[1,2,2,1], +# [3,1,2], +# [1,3,2], +# [2,4], +# [3,1,2], +# [1,3,1,1]] +# Output: 2 +# +# Note: +# The width sum of bricks in different rows are the same and won't exceed INT_MAX. +# The number of bricks in each row is in range [1,10,000]. +# The height of wall is in range [1,10,000]. +# Total number of bricks of the wall won't exceed 20,000. + +class Solution(object): + def leastBricks(self, wall): + """ + :type wall: List[List[int]] + :rtype: int + """ + widths = collections.defaultdict(int) + result = len(wall) + for row in wall: + width = 0 + for i in xrange(len(row)-1): + width += row[i] + widths[width] += 1 + result = min(result, len(wall) - widths[width]); + return result From a1f2515de2f46c8b378c33b52fb6423868a136dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Apr 2017 22:38:50 +0800 Subject: [PATCH 3269/4971] Create binary-tree-longest-consecutive-sequence-ii.cpp --- ...y-tree-longest-consecutive-sequence-ii.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/binary-tree-longest-consecutive-sequence-ii.cpp diff --git a/C++/binary-tree-longest-consecutive-sequence-ii.cpp b/C++/binary-tree-longest-consecutive-sequence-ii.cpp new file mode 100644 index 000000000..a1b18a229 --- /dev/null +++ b/C++/binary-tree-longest-consecutive-sequence-ii.cpp @@ -0,0 +1,46 @@ +// 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; + } + + pair longestConsecutiveHelper(TreeNode *root, int *max_len) { + if (!root) { + return {0, 0}; + } + const pair left_len = longestConsecutiveHelper(root->left, max_len); + const pair right_len = longestConsecutiveHelper(root->right, max_len); + + int cur_inc_len = 1, cur_dec_len = 1; + if (root->left) { + if (root->left->val == root->val + 1) { + cur_inc_len = max(cur_inc_len, left_len.first + 1); + } else if (root->left->val == root->val - 1){ + cur_dec_len = max(cur_dec_len, left_len.second + 1); + } + } + if (root->right) { + if (root->right->val == root->val + 1) { + cur_inc_len = max(cur_inc_len, right_len.first + 1); + } else if (root->right->val == root->val - 1) { + cur_dec_len = max(cur_dec_len, right_len.second + 1); + } + } + *max_len = max(*max_len, cur_dec_len + cur_inc_len - 1); + return {cur_inc_len, cur_dec_len}; + } +}; From 35590f52452249e5bbac480a797f651af58adbaf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Apr 2017 22:45:23 +0800 Subject: [PATCH 3270/4971] Create binary-tree-longest-consecutive-sequence-ii.py --- ...ry-tree-longest-consecutive-sequence-ii.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/binary-tree-longest-consecutive-sequence-ii.py diff --git a/Python/binary-tree-longest-consecutive-sequence-ii.py b/Python/binary-tree-longest-consecutive-sequence-ii.py new file mode 100644 index 000000000..70b68368c --- /dev/null +++ b/Python/binary-tree-longest-consecutive-sequence-ii.py @@ -0,0 +1,39 @@ +# 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 + """ + def longestConsecutiveHelper(root): + if not root: + return 0 + left_len = longestConsecutiveHelper(root.left) + right_len = longestConsecutiveHelper(root.right) + cur_inc_len, cur_dec_len = 1, 1 + if root.left: + if root.left.val == root.val + 1: + cur_inc_len = max(cur_inc_len, left_len[0] + 1) + elif root.left.val == root.val - 1: + cur_dec_len = max(cur_dec_len, left_len[1] + 1) + if root.right: + if root.right.val == root.val + 1: + cur_inc_len = max(cur_inc_len, right_len[0] + 1) + elif root.right.val == root.val - 1: + cur_dec_len = max(cur_dec_len, right_len[1] + 1) + self.max_len = max(self.max_len, cur_dec_len + cur_inc_len - 1) + return cur_inc_len, cur_dec_len + + self.max_len = 0 + longestConsecutiveHelper(root) + return self.max_len + From 46b76c96309cdeb435502a7ee96c672edc2abee7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Apr 2017 22:46:08 +0800 Subject: [PATCH 3271/4971] Update binary-tree-longest-consecutive-sequence-ii.py --- Python/binary-tree-longest-consecutive-sequence-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/binary-tree-longest-consecutive-sequence-ii.py b/Python/binary-tree-longest-consecutive-sequence-ii.py index 70b68368c..99c88f13c 100644 --- a/Python/binary-tree-longest-consecutive-sequence-ii.py +++ b/Python/binary-tree-longest-consecutive-sequence-ii.py @@ -16,7 +16,7 @@ def longestConsecutive(self, root): """ def longestConsecutiveHelper(root): if not root: - return 0 + return 0, 0 left_len = longestConsecutiveHelper(root.left) right_len = longestConsecutiveHelper(root.right) cur_inc_len, cur_dec_len = 1, 1 From a24f3161a1c3980bdb9a3b3b4017adb42b48abbc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Apr 2017 21:58:55 +0800 Subject: [PATCH 3272/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 932f75cc2..e03ceda74 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 434| [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/) | [C++](./C++/number-of-segments-in-a-string.cpp) [Python](./Python/number-of-segments-in-a-string.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | +556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | +557| [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) |[C++](./C++/reverse-words-in-a-string-iii.cpp) [Python](./Python/reverse-words-in-a-string-iii.py) | _O(n)_ | _O(1)_ | Easy | | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -267,6 +269,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 447| [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/) | [C++](./C++/number-of-boomerangs.cpp) [Python](./Python/number-of-boomerangs.py) | _O(n^2)_ | _O(n)_ | Easy || 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || +554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | ## Data Structure | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -383,6 +386,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 395| [Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./C++/longest-substring-with-at-least-k-repeating-characters.cpp) [Python](./Python/longest-substring-with-at-least-k-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 404| [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./C++/sum-of-left-leaves.cpp) [Python](./Python/sum-of-left-leaves.py) | _O(n)_ | _O(h)_ | Easy || 437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n^2)_ | _O(h)_ | Easy || +574 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| ## Binary Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 3211afeb4b84ddfccc315bcda12bedef13d8b04e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Apr 2017 22:00:03 +0800 Subject: [PATCH 3273/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e03ceda74..c56c382b1 100644 --- a/README.md +++ b/README.md @@ -386,7 +386,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 395| [Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./C++/longest-substring-with-at-least-k-repeating-characters.cpp) [Python](./Python/longest-substring-with-at-least-k-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 404| [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./C++/sum-of-left-leaves.cpp) [Python](./Python/sum-of-left-leaves.py) | _O(n)_ | _O(h)_ | Easy || 437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n^2)_ | _O(h)_ | Easy || -574 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| +549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| ## Binary Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From b4d82c21995fb2b9e2afd93eea8849ded8b7d489 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Apr 2017 22:00:28 +0800 Subject: [PATCH 3274/4971] Update next-greater-element-iii.py --- Python/next-greater-element-iii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/next-greater-element-iii.py b/Python/next-greater-element-iii.py index 4f93b7946..9a4f344ea 100644 --- a/Python/next-greater-element-iii.py +++ b/Python/next-greater-element-iii.py @@ -1,5 +1,5 @@ -# Time: O(logn) -# Space: O(logn) +# Time: O(logn) = O(1) +# Space: O(logn) = O(1) # Given a positive 32-bit integer n, you need to find the smallest 32-bit integer # which has exactly the same digits existing in the integer n and is greater in value than n. From 3abc5cddcca6c18b086860b02a0f5a0cd3c8b846 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 10 Apr 2017 22:00:45 +0800 Subject: [PATCH 3275/4971] Update next-greater-element-iii.cpp --- C++/next-greater-element-iii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/next-greater-element-iii.cpp b/C++/next-greater-element-iii.cpp index a6e9ac3e7..2f086500c 100644 --- a/C++/next-greater-element-iii.cpp +++ b/C++/next-greater-element-iii.cpp @@ -1,5 +1,5 @@ -// Time: O(logn) -// Space: O(logn) +// Time: O(logn) = O(1) +// Space: O(logn) = O(1) class Solution { public: From 1c76dc4e085c5b87f0d7b92bb8f83bed99591512 Mon Sep 17 00:00:00 2001 From: Peng Xiao Date: Sun, 16 Apr 2017 13:18:39 +0800 Subject: [PATCH 3276/4971] fix word ladder issue for python Signed-off-by: Peng Xiao --- Python/word-ladder.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/Python/word-ladder.py b/Python/word-ladder.py index 17cdb9a77..61e80abdf 100644 --- a/Python/word-ladder.py +++ b/Python/word-ladder.py @@ -26,25 +26,26 @@ class Solution: # @param end, a string # @param dict, a set of string # @return an integer - def ladderLength(self, start, end, dict): + def ladderLength(self, start, end, word_list): distance, cur, visited = 0, [start], set([start]) - dict.add(end) - + while cur: - next = [] + _next = [] + for word in cur: if word == end: return distance + 1 for i in xrange(len(word)): for j in 'abcdefghijklmnopqrstuvwxyz': candidate = word[:i] + j + word[i + 1:] - if candidate not in visited and candidate in dict: - next.append(candidate) + if candidate not in visited and candidate in word_list: + _next.append(candidate) visited.add(candidate) distance += 1 - cur = next - + cur = _next + return 0 - + if __name__ == "__main__": - print Solution().ladderLength("hit", "cog", set(["hot","dot","dog","lot","log"])) + print Solution().ladderLength("hit", "cog", set(["hot", "dot", "dog", "lot", "log"])) + print Solution().ladderLength("hit", "cog", set(["hot", "dot", "dog", "lot", "log", "cog"])) From f5862be7782b4d705fd52083aaedd78649737e83 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 May 2017 19:56:09 +0800 Subject: [PATCH 3277/4971] Create student-attendance-record-i.cpp --- C++/student-attendance-record-i.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/student-attendance-record-i.cpp diff --git a/C++/student-attendance-record-i.cpp b/C++/student-attendance-record-i.cpp new file mode 100644 index 000000000..fc17a325b --- /dev/null +++ b/C++/student-attendance-record-i.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool checkRecord(string s) { + int count_A = 0; + for (int i = 0; i < s.length(); ++i) { + if (s[i] == 'A') { + if (++count_A == 2) { + return false; + } + } + if (i + 3 <= s.length() && s[i] == 'L' && s[i + 1] == 'L' && s[i + 2] == 'L') { + return false; + } + } + return true; + } +}; From 585967ff3093bd6cc2982288907657ecd94a4618 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 May 2017 19:58:53 +0800 Subject: [PATCH 3278/4971] Update student-attendance-record-i.cpp --- C++/student-attendance-record-i.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/student-attendance-record-i.cpp b/C++/student-attendance-record-i.cpp index fc17a325b..bf7eb9aa2 100644 --- a/C++/student-attendance-record-i.cpp +++ b/C++/student-attendance-record-i.cpp @@ -11,7 +11,7 @@ class Solution { return false; } } - if (i + 3 <= s.length() && s[i] == 'L' && s[i + 1] == 'L' && s[i + 2] == 'L') { + if (i + 2 < s.length() && s[i] == 'L' && s[i + 1] == 'L' && s[i + 2] == 'L') { return false; } } From 5b37aab11b718e7fac06a3d7b1aad3d003a2f9d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 May 2017 20:00:46 +0800 Subject: [PATCH 3279/4971] Create student-attendance-record-ii.py --- Python/student-attendance-record-ii.py | 37 ++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/student-attendance-record-ii.py diff --git a/Python/student-attendance-record-ii.py b/Python/student-attendance-record-ii.py new file mode 100644 index 000000000..07c836558 --- /dev/null +++ b/Python/student-attendance-record-ii.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(1) + +# You are given a string representing an attendance record for a student. +# The record only contains the following three characters: +# +# 'A' : Absent. +# 'L' : Late. +# 'P' : Present. +# A student could be rewarded if his attendance record +# doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). +# +# You need to return whether the student could be rewarded according to his attendance record. +# +# Example 1: +# Input: "PPALLP" +# Output: True +# Example 2: +# Input: "PPALLL" +# Output: False + +class Solution(object): + def checkRecord(self, s): + """ + :type s: str + :rtype: bool + """ + count_A = 0 + for i in xrange(len(s)): + if s[i] == 'A': + count_A += 1 + if count_A == 2: + return False + if i < len(s) - 2 and s[i] == s[i+1] == s[i+2] == 'L': + return False + return True + From 085fcf5953e8af2c6b87714c053dd9be365b37cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 May 2017 20:27:37 +0800 Subject: [PATCH 3280/4971] Rename student-attendance-record-ii.py to student-attendance-record-i.py --- ...ent-attendance-record-ii.py => student-attendance-record-i.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{student-attendance-record-ii.py => student-attendance-record-i.py} (100%) diff --git a/Python/student-attendance-record-ii.py b/Python/student-attendance-record-i.py similarity index 100% rename from Python/student-attendance-record-ii.py rename to Python/student-attendance-record-i.py From ec05121e42d53f826e9894f80a2c9e8ed70709fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 May 2017 20:28:09 +0800 Subject: [PATCH 3281/4971] Create student-attendance-record-ii.py --- Python/student-attendance-record-ii.py | 35 ++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/student-attendance-record-ii.py diff --git a/Python/student-attendance-record-ii.py b/Python/student-attendance-record-ii.py new file mode 100644 index 000000000..2b1cc99b6 --- /dev/null +++ b/Python/student-attendance-record-ii.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(1) + +# Given a positive integer n, return the number of all possible attendance records with length n, +# which will be regarded as rewardable. The answer may be very large, return it after mod 10^9 + 7. +# +# A student attendance record is a string that only contains the following three characters: +# +# 'A' : Absent. +# 'L' : Late. +# 'P' : Present. +# A record is regarded as rewardable if it doesn't +# contain more than one 'A' (absent) or more than two continuous 'L' (late). +# +# Example 1: +# Input: n = 2 +# Output: 8 +# Explanation: +# There are 8 records with length 2 will be regarded as rewardable: +# "PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL" +# Only "AA" won't be regarded as rewardable owing to more than one absent times. +# Note: The value of n won't exceed 100,000. + +class Solution(object): + def checkRecord(self, n): + """ + :type n: int + :rtype: int + """ + M = 1000000007 + a0l0, a0l1, a0l2, a1l0, a1l1, a1l2 = 1, 0, 0, 0, 0, 0 + for i in xrange(n+1): + a0l2, a0l1, a0l0 = a0l1, a0l0, (a0l0 + a0l1 + a0l2) % M + a1l2, a1l1, a1l0 = a1l1, a1l0, (a0l0 + a1l0 + a1l1 + a1l2) % M; + return a1l0 From c4a51c31f67181bb6a8ca380c8b880256a0834a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 May 2017 20:29:30 +0800 Subject: [PATCH 3282/4971] Create student-attendance-record-ii.cpp --- C++/student-attendance-record-ii.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/student-attendance-record-ii.cpp diff --git a/C++/student-attendance-record-ii.cpp b/C++/student-attendance-record-ii.cpp new file mode 100644 index 000000000..819c954da --- /dev/null +++ b/C++/student-attendance-record-ii.cpp @@ -0,0 +1,21 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int checkRecord(int n) { + static const long long M = 1000000007; + long long a0l0 = 1, a0l1 = 0, a0l2 = 0, a1l0 = 0, a1l1 = 0, a1l2 = 0; + for (int i = 0; i <= n; ++i) { + auto new_a0l0 = (a0l0 + a0l1 + a0l2) % M; + a0l2 = a0l1; + a0l1 = a0l0; + a0l0 = new_a0l0; + auto new_a1l0 = (a0l0 + a1l0 + a1l1 + a1l2) % M; + a1l2 = a1l1; + a1l1 = a1l0; + a1l0 = new_a1l0; + } + return static_cast(a1l0); + } +}; From b8668d032281b0e541d5b58292568824237e2f2a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 May 2017 21:07:22 +0800 Subject: [PATCH 3283/4971] Create maximum-vacation-days.cpp --- C++/maximum-vacation-days.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/maximum-vacation-days.cpp diff --git a/C++/maximum-vacation-days.cpp b/C++/maximum-vacation-days.cpp new file mode 100644 index 000000000..ed61426a7 --- /dev/null +++ b/C++/maximum-vacation-days.cpp @@ -0,0 +1,24 @@ +// Time: O(n^2 * k) +// Space: O(k) + +class Solution { +public: + int maxVacationDays(vector>& flights, vector>& days) { + if (days.empty() || flights.empty()) { + return 0; + } + vector> dp(2, vector(days.size())); + for (int week = days[0].size() - 1; week >= 0; --week) { + for (int cur_city = 0; cur_city < days.size(); ++cur_city) { + dp[week % 2][cur_city] = days[cur_city][week] + dp[(week + 1) % 2][cur_city]; + for (int dest_city = 0; dest_city < days.size(); ++dest_city) { + if (flights[cur_city][dest_city] == 1) { + dp[week % 2][cur_city] = max(dp[week % 2][cur_city], + days[dest_city][week] + dp[(week + 1) % 2][dest_city]); + } + } + } + } + return dp[0][0]; + } +}; From 97c149057bf68ef8063316acad2b4c86f6579452 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 May 2017 21:12:10 +0800 Subject: [PATCH 3284/4971] Create maximum-vacation-days.py --- Python/maximum-vacation-days.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/maximum-vacation-days.py diff --git a/Python/maximum-vacation-days.py b/Python/maximum-vacation-days.py new file mode 100644 index 000000000..ad87e5d9c --- /dev/null +++ b/Python/maximum-vacation-days.py @@ -0,0 +1,21 @@ +# Time: O(n^2 * k) +# Space: O(k) + +class Solution(object): + def maxVacationDays(self, flights, days): + """ + :type flights: List[List[int]] + :type days: List[List[int]] + :rtype: int + """ + if not days or not flights: + return 0 + dp = [[0] * len(days) for _ in xrange(2)] + for week in reversed(xrange(len(days[0]))): + for cur_city in xrange(len(days)): + dp[week % 2][cur_city] = days[cur_city][week] + dp[(week+1) % 2][cur_city] + for dest_city in xrange(len(days)): + if flights[cur_city][dest_city] == 1: + dp[week % 2][cur_city] = max(dp[week % 2][cur_city], \ + days[dest_city][week] + dp[(week+1) % 2][dest_city]) + return dp[0][0] From 450f895769d8f0222a0dd172260a11ef762f3a5a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 May 2017 23:45:49 +0800 Subject: [PATCH 3285/4971] Create find-the-closest-palindrome.cpp --- C++/find-the-closest-palindrome.cpp | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/find-the-closest-palindrome.cpp diff --git a/C++/find-the-closest-palindrome.cpp b/C++/find-the-closest-palindrome.cpp new file mode 100644 index 000000000..502a98729 --- /dev/null +++ b/C++/find-the-closest-palindrome.cpp @@ -0,0 +1,30 @@ +// Time: O(l) +// Space: O(l) + +class Solution { +public: + string nearestPalindromic(string n) { + const auto l = n.size(); + vector candidates; + candidates.emplace_back(static_cast(pow(10, l)) + 1); + candidates.emplace_back(static_cast(pow(10, l - 1)) - 1); + auto prefix = stol(n.substr(0, (l + 1) / 2)); + for (long long i = -1; i <= 1; ++i) { + auto p = to_string(prefix + i); + auto pp = p + string(p.rbegin() + (l % 2), p.rend()); + candidates.emplace_back(stol(pp)); + } + long long num = stol(n), closest_val = numeric_limits::max(); + for (const auto& val : candidates) { + if (val == num) { + continue; + } + if (abs(val - num) < abs(closest_val - num)) { + closest_val = val; + } else if (abs(val - num) == abs(closest_val - num)) { + closest_val = min(closest_val, val); + } + } + return to_string(closest_val); + } +}; From 3880973117ebcf911ab2fa48f4c693ef9730181a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 00:00:33 +0800 Subject: [PATCH 3286/4971] Create find-the-closest-palindrome.py --- Python/find-the-closest-palindrome.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/find-the-closest-palindrome.py diff --git a/Python/find-the-closest-palindrome.py b/Python/find-the-closest-palindrome.py new file mode 100644 index 000000000..f4b9bae21 --- /dev/null +++ b/Python/find-the-closest-palindrome.py @@ -0,0 +1,27 @@ +# Time: O(l) +# Space: O(l) + +# Given an integer n, find the closest integer (not including itself), which is a palindrome. +# +# The 'closest' is defined as absolute difference minimized between two integers. +# +# Example 1: +# Input: "123" +# Output: "121" +# Note: +# The input n is a positive integer represented by string, whose length will not exceed 18. +# If there is a tie, return the smaller one as answer. + +class Solution(object): + def nearestPalindromic(self, n): + """ + :type n: str + :rtype: str + """ + l = len(n) + candidates = set((str(10**l + 1), str(10**(l - 1) - 1))) + prefix = int(n[:(l + 1)/2]) + for i in map(str, (prefix-1, prefix, prefix+1)): + candidates.add(i + [i, i[:-1]][l%2][::-1]) + candidates.discard(n) + return min(candidates, key=lambda x: (abs(int(x) - int(n)), int(x))) From 7e99067a156b9c20f4b6bee88c3f1ee091ddba38 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 00:03:38 +0800 Subject: [PATCH 3287/4971] Update find-the-closest-palindrome.cpp --- C++/find-the-closest-palindrome.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/C++/find-the-closest-palindrome.cpp b/C++/find-the-closest-palindrome.cpp index 502a98729..0e4f79f59 100644 --- a/C++/find-the-closest-palindrome.cpp +++ b/C++/find-the-closest-palindrome.cpp @@ -5,20 +5,18 @@ class Solution { public: string nearestPalindromic(string n) { const auto l = n.size(); - vector candidates; - candidates.emplace_back(static_cast(pow(10, l)) + 1); - candidates.emplace_back(static_cast(pow(10, l - 1)) - 1); + unordered_set candidates; + candidates.emplace(static_cast(pow(10, l)) + 1); + candidates.emplace(static_cast(pow(10, l - 1)) - 1); auto prefix = stol(n.substr(0, (l + 1) / 2)); for (long long i = -1; i <= 1; ++i) { auto p = to_string(prefix + i); auto pp = p + string(p.rbegin() + (l % 2), p.rend()); - candidates.emplace_back(stol(pp)); + candidates.emplace(stol(pp)); } long long num = stol(n), closest_val = numeric_limits::max(); + candidates.erase(num); for (const auto& val : candidates) { - if (val == num) { - continue; - } if (abs(val - num) < abs(closest_val - num)) { closest_val = val; } else if (abs(val - num) == abs(closest_val - num)) { From 19d64afe4c168f2d7a3d1d67b06da2fa966c9d28 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 00:21:30 +0800 Subject: [PATCH 3288/4971] Rename find-the-closest-palindrome.py to optimal-division.py --- Python/optimal-division.py | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/optimal-division.py diff --git a/Python/optimal-division.py b/Python/optimal-division.py new file mode 100644 index 000000000..0435f174f --- /dev/null +++ b/Python/optimal-division.py @@ -0,0 +1,44 @@ +# Time: O(n) +# Space: O(1) + +# Given a list of positive integers, the adjacent integers will perform the float division. +# For example, [2,3,4] -> 2 / 3 / 4. +# +# However, you can add any number of parenthesis at any position to change the priority of operations. +# You should find out how to add parenthesis to get the maximum result, +# and return the corresponding expression in string format. Your expression should NOT contain redundant parenthesis. +# +# Example: +# Input: [1000,100,10,2] +# Output: "1000/(100/10/2)" +# Explanation: +# 1000/(100/10/2) = 1000/((100/10)/2) = 200 +# However, the bold parenthesis in "1000/((100/10)/2)" are redundant, +# since they don't influence the operation priority. So you should return "1000/(100/10/2)". +# +# Other cases: +# 1000/(100/10)/2 = 50 +# 1000/(100/(10/2)) = 50 +# 1000/100/10/2 = 0.5 +# 1000/100/(10/2) = 2 +# Note: +# +# The length of the input array is [1, 10]. +# Elements in the given array will be in range [2, 1000]. +# There is only one optimal division for each test case. + +class Solution(object): + def optimalDivision(self, nums): + """ + :type nums: List[int] + :rtype: str + """ + if len(nums) == 1: + return str(nums[0]) + if len(nums) == 2: + return str(nums[0]) + "/" + str(nums[1]) + result = [str(nums[0]) + "/(" + str(nums[1])] + for i in xrange(2, len(nums)): + result += "/" + str(nums[i]) + result += ")" + return "".join(result) From e9ec4cd6d30f59ce288718c4e224faf1023df520 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 00:22:04 +0800 Subject: [PATCH 3289/4971] Create optimal-division.cpp --- C++/optimal-division.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/optimal-division.cpp diff --git a/C++/optimal-division.cpp b/C++/optimal-division.cpp new file mode 100644 index 000000000..899ab0fa3 --- /dev/null +++ b/C++/optimal-division.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string optimalDivision(vector& nums) { + if (nums.size() == 1) { + return to_string(nums[0]); + } + if (nums.size() == 2) { + return to_string(nums[0]) + "/" + to_string(nums[1]); + } + string result = to_string(nums[0]) + "/(" + to_string(nums[1]); + for (int i = 2; i < nums.size(); ++i) { + result += "/" + to_string(nums[i]); + } + result.push_back(')'); + return result; + } +}; From 4e55b043b64ee8d21a9f07ba7a3a9998cf3c1766 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 00:55:58 +0800 Subject: [PATCH 3290/4971] Create split-concatenated-strings.cpp --- C++/split-concatenated-strings.cpp | 31 ++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/split-concatenated-strings.cpp diff --git a/C++/split-concatenated-strings.cpp b/C++/split-concatenated-strings.cpp new file mode 100644 index 000000000..66bdd7805 --- /dev/null +++ b/C++/split-concatenated-strings.cpp @@ -0,0 +1,31 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + string splitLoopedString(vector& strs) { + string s = ""; + for (auto& str : strs) { + auto rev{str}; + reverse(rev.begin(), rev.end()); + s += max(str, rev); + } + string result = "a"; + for (auto i = 0, st = 0; i < strs.size(); st += strs[i++].size()) { + auto rev{strs[i]}, body{s.substr(st + strs[i].length())}; + body += s.substr(0, st); + reverse(rev.begin(), rev.end()); + for (const auto& p : {strs[i], rev}) { + for (auto j = 0; j < strs[i].size(); ++j) { + if (p[j] >= result[0]) { + string tmp{p.substr(j)}; + tmp += body; + tmp += p.substr(0, j); + result = max(result, tmp); + } + } + } + } + return result; + } +}; From 7330688a9e132d7d078417730a23bd9f440742aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 00:57:28 +0800 Subject: [PATCH 3291/4971] Update split-concatenated-strings.cpp --- C++/split-concatenated-strings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/split-concatenated-strings.cpp b/C++/split-concatenated-strings.cpp index 66bdd7805..650d747bb 100644 --- a/C++/split-concatenated-strings.cpp +++ b/C++/split-concatenated-strings.cpp @@ -4,7 +4,7 @@ class Solution { public: string splitLoopedString(vector& strs) { - string s = ""; + string s; for (auto& str : strs) { auto rev{str}; reverse(rev.begin(), rev.end()); From ed02fa32a87eb820d393b4b56b034248e38e2563 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 00:57:44 +0800 Subject: [PATCH 3292/4971] Update split-concatenated-strings.cpp --- C++/split-concatenated-strings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/split-concatenated-strings.cpp b/C++/split-concatenated-strings.cpp index 650d747bb..01726db76 100644 --- a/C++/split-concatenated-strings.cpp +++ b/C++/split-concatenated-strings.cpp @@ -10,7 +10,7 @@ class Solution { reverse(rev.begin(), rev.end()); s += max(str, rev); } - string result = "a"; + string result{a}; for (auto i = 0, st = 0; i < strs.size(); st += strs[i++].size()) { auto rev{strs[i]}, body{s.substr(st + strs[i].length())}; body += s.substr(0, st); From 43838a3f94905e07d38bf2edf79e0006cd0587a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 00:57:58 +0800 Subject: [PATCH 3293/4971] Update split-concatenated-strings.cpp --- C++/split-concatenated-strings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/split-concatenated-strings.cpp b/C++/split-concatenated-strings.cpp index 01726db76..064f6217a 100644 --- a/C++/split-concatenated-strings.cpp +++ b/C++/split-concatenated-strings.cpp @@ -10,7 +10,7 @@ class Solution { reverse(rev.begin(), rev.end()); s += max(str, rev); } - string result{a}; + string result{"a"}; for (auto i = 0, st = 0; i < strs.size(); st += strs[i++].size()) { auto rev{strs[i]}, body{s.substr(st + strs[i].length())}; body += s.substr(0, st); From db30fd6caf5e3a2b3258c99b49ab4ea04bfe1c65 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 00:58:55 +0800 Subject: [PATCH 3294/4971] Update split-concatenated-strings.cpp --- C++/split-concatenated-strings.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/split-concatenated-strings.cpp b/C++/split-concatenated-strings.cpp index 064f6217a..0c2578f43 100644 --- a/C++/split-concatenated-strings.cpp +++ b/C++/split-concatenated-strings.cpp @@ -5,7 +5,7 @@ class Solution { public: string splitLoopedString(vector& strs) { string s; - for (auto& str : strs) { + for (const auto& str : strs) { auto rev{str}; reverse(rev.begin(), rev.end()); s += max(str, rev); From f6664e16fbbf36e31227f8da7ad4f6f0ea4befeb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 01:08:58 +0800 Subject: [PATCH 3295/4971] Create split-concatenated-strings.py --- Python/split-concatenated-strings.py | 50 ++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/split-concatenated-strings.py diff --git a/Python/split-concatenated-strings.py b/Python/split-concatenated-strings.py new file mode 100644 index 000000000..555595037 --- /dev/null +++ b/Python/split-concatenated-strings.py @@ -0,0 +1,50 @@ +# Time: O(n^2) +# Space: O(n) + +# Given a list of strings, you could concatenate these strings together into a loop, +# where for each string you could choose to reverse it or not. +# Among all the possible loops, you need to find the lexicographically +# biggest string after cutting the loop, which will make the looped string into a regular one. +# +# Specifically, to find the lexicographically biggest string, you need to experience two phases: +# +# Concatenate all the strings into a loop, where you can reverse some strings or +# not and connect them in the same order as given. +# Cut and make one breakpoint in any place of the loop, which will make the looped string +# into a regular one starting from the character at the cutpoint. +# And your job is to find the lexicographically biggest one among all the possible regular strings. +# +# Example: +# Input: "abc", "xyz" +# Output: "zyxcba" +# Explanation: You can get the looped string "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-", +# where '-' represents the looped status. +# The answer string came from the fourth looped one, +# where you could cut from the middle character 'a' and get "zyxcba". +# Note: +# The input strings will only contain lowercase letters. +# The total length of all the strings will not over 1,000. + +class Solution(object): + def splitLoopedString(self, strs): + """ + :type strs: List[str] + :rtype: str + """ + tmp = [] + for s in strs: + tmp += max(s, s[::-1]) + s = "".join(tmp) + + result, st = "a", 0 + for i in xrange(len(strs)): + body = s[st + len(strs[i]):] + s[0:st] + for p in strs[i], strs[i][::-1]: + for j in xrange(len(strs[i])): + if p[j] >= result[0]: + tmp = [p[j:]] + tmp += body + tmp += p[:j] + result = max(result, "".join(tmp)) + st += len(strs[i]) + return result From fa54472bab97b276bde9041ee7f85caa6d736ee7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 01:13:23 +0800 Subject: [PATCH 3296/4971] Update split-concatenated-strings.py --- Python/split-concatenated-strings.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Python/split-concatenated-strings.py b/Python/split-concatenated-strings.py index 555595037..4693b532e 100644 --- a/Python/split-concatenated-strings.py +++ b/Python/split-concatenated-strings.py @@ -38,13 +38,10 @@ def splitLoopedString(self, strs): result, st = "a", 0 for i in xrange(len(strs)): - body = s[st + len(strs[i]):] + s[0:st] + body = "".join([s[st + len(strs[i]):], s[0:st]]) for p in strs[i], strs[i][::-1]: for j in xrange(len(strs[i])): if p[j] >= result[0]: - tmp = [p[j:]] - tmp += body - tmp += p[:j] - result = max(result, "".join(tmp)) + result = max(result, "".join([p[j:], body, p[:j]])) st += len(strs[i]) return result From 162d98ea6e55477dd1017e803007a64d2c303342 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 11:50:07 +0800 Subject: [PATCH 3297/4971] Create permutation-in-string.cpp --- C++/permutation-in-string.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/permutation-in-string.cpp diff --git a/C++/permutation-in-string.cpp b/C++/permutation-in-string.cpp new file mode 100644 index 000000000..daaf56889 --- /dev/null +++ b/C++/permutation-in-string.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool checkInclusion(string s1, string s2) { + vector counts(256); + for (const auto& c : s1) { + ++counts[c]; + } + for (int i = 0, l = s1.length(); i < s2.length(); ++i) { + if (counts[s2[i]]-- > 0) { + --l; + } + if (l == 0) { + return true; + } + int start = i + 1 - s1.length(); + if (start >= 0 && ++counts[s2[start]] > 0) { + ++l; + } + } + return false; + } +}; From 0f31db66a38073e1549d977909c5f4c5d3eab280 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 11:59:25 +0800 Subject: [PATCH 3298/4971] Create permutation-in-string.py --- Python/permutation-in-string.py | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/permutation-in-string.py diff --git a/Python/permutation-in-string.py b/Python/permutation-in-string.py new file mode 100644 index 000000000..171502725 --- /dev/null +++ b/Python/permutation-in-string.py @@ -0,0 +1,39 @@ +# Time: O(n) +# Space: O(1) + +# Given two strings s1 and s2, write a function to return true +# if s2 contains the permutation of s1. In other words, +# one of the first string's permutations is the substring of the second string. +# +# Example 1: +# Input:s1 = "ab" s2 = "eidbaooo" +# Output:True +# Explanation: s2 contains one permutation of s1 ("ba"). +# Example 2: +# Input:s1= "ab" s2 = "eidboaoo" +# Output: False +# Note: +# The input strings only contain lower case letters. +# The length of both given strings is in range [1, 10,000]. + +class Solution(object): + def checkInclusion(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: bool + """ + counts = collections.Counter(s1) + l = len(s1) + for i in xrange(len(s2)): + if counts[s2[i]] > 0: + l -= 1 + counts[s2[i]] -= 1 + if l == 0: + return True + start = i + 1 - len(s1) + if start >= 0: + counts[s2[start]] += 1 + if counts[s2[start]] > 0: + l += 1 + return False From da2a4d3d5b3eada433b762da420c607eed623cc9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 14:26:53 +0800 Subject: [PATCH 3299/4971] Create longest-line-of-consecutive-one-in-matrix.cpp --- ...gest-line-of-consecutive-one-in-matrix.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/longest-line-of-consecutive-one-in-matrix.cpp diff --git a/C++/longest-line-of-consecutive-one-in-matrix.cpp b/C++/longest-line-of-consecutive-one-in-matrix.cpp new file mode 100644 index 000000000..9380a3d74 --- /dev/null +++ b/C++/longest-line-of-consecutive-one-in-matrix.cpp @@ -0,0 +1,26 @@ +// Time: O(m * n) +// Space: O(n) + +class Solution { +public: + int longestLine(vector>& M) { + if (M.empty()) { + return 0; + } + int result = 0; + vector>> dp(2, vector>(M[0].size(), vector(4))); + for (int i = 0; i < M.size(); ++i) { + for (int j = 0; j < M[0].size(); ++j) { + dp[i % 2][j][0] = dp[i % 2][j][1] = dp[i % 2][j][2] = dp[i % 2][j][3] = 0 + if (M[i][j] == 1) { + dp[i % 2][j][0] = j > 0 ? dp[i % 2][j - 1][0] + 1 : 1; + dp[i % 2][j][1] = i > 0 ? dp[(i - 1) % 2][j][1] + 1 : 1; + dp[i % 2][j][2] = (i > 0 && j > 0) ? dp[(i - 1) % 2][j - 1][2] + 1 : 1; + dp[i % 2][j][3] = (i > 0 && j < M[0].size() - 1) ? dp[(i - 1) % 2][j + 1][3] + 1 : 1; + result = max(result, max(dp[i % 2][j][0], max(dp[i % 2][j][1], max(dp[i % 2][j][2], dp[i % 2][j][3])))); + } + } + } + return result; + } +}; From 43947ee7a143579d7a76081c1b086cc8c3115797 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 14:28:02 +0800 Subject: [PATCH 3300/4971] Update longest-line-of-consecutive-one-in-matrix.cpp --- C++/longest-line-of-consecutive-one-in-matrix.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-line-of-consecutive-one-in-matrix.cpp b/C++/longest-line-of-consecutive-one-in-matrix.cpp index 9380a3d74..a59c4c433 100644 --- a/C++/longest-line-of-consecutive-one-in-matrix.cpp +++ b/C++/longest-line-of-consecutive-one-in-matrix.cpp @@ -11,7 +11,7 @@ class Solution { vector>> dp(2, vector>(M[0].size(), vector(4))); for (int i = 0; i < M.size(); ++i) { for (int j = 0; j < M[0].size(); ++j) { - dp[i % 2][j][0] = dp[i % 2][j][1] = dp[i % 2][j][2] = dp[i % 2][j][3] = 0 + dp[i % 2][j][0] = dp[i % 2][j][1] = dp[i % 2][j][2] = dp[i % 2][j][3] = 0; if (M[i][j] == 1) { dp[i % 2][j][0] = j > 0 ? dp[i % 2][j - 1][0] + 1 : 1; dp[i % 2][j][1] = i > 0 ? dp[(i - 1) % 2][j][1] + 1 : 1; From 48b724d7a2163c50be60d98933132b51347940bd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 May 2017 14:36:48 +0800 Subject: [PATCH 3301/4971] Create longest-line-of-consecutive-one-in-a-matrix.py --- ...est-line-of-consecutive-one-in-a-matrix.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Python/longest-line-of-consecutive-one-in-a-matrix.py diff --git a/Python/longest-line-of-consecutive-one-in-a-matrix.py b/Python/longest-line-of-consecutive-one-in-a-matrix.py new file mode 100644 index 000000000..4f6845c00 --- /dev/null +++ b/Python/longest-line-of-consecutive-one-in-a-matrix.py @@ -0,0 +1,22 @@ +# Time: O(m * n) +# Space: O(n) + +class Solution(object): + def longestLine(self, M): + """ + :type M: List[List[int]] + :rtype: int + """ + if not M: return 0 + result = 0 + dp = [[[0] * 4 for _ in xrange(len(M[0]))] for _ in xrange(2)] + for i in xrange(len(M)): + for j in xrange(len(M[0])): + dp[i % 2][j][:] = [0] * 4 + if M[i][j] == 1: + dp[i % 2][j][0] = dp[i % 2][j - 1][0]+1 if j > 0 else 1 + dp[i % 2][j][1] = dp[(i-1) % 2][j][1]+1 if i > 0 else 1 + dp[i % 2][j][2] = dp[(i-1) % 2][j-1][2]+1 if (i > 0 and j > 0) else 1 + dp[i % 2][j][3] = dp[(i-1) % 2][j+1][3]+1 if (i > 0 and j < len(M[0])-1) else 1 + result = max(result, max(dp[i % 2][j])) + return result From da5f81d2567f3515c8ebffc14fd4a687910ed34e Mon Sep 17 00:00:00 2001 From: Diana Holland Date: Wed, 17 May 2017 22:47:42 -0700 Subject: [PATCH 3302/4971] Update requirements --- MySQL/second-highest-salary.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/second-highest-salary.sql b/MySQL/second-highest-salary.sql index 2565e2a61..272ee4713 100644 --- a/MySQL/second-highest-salary.sql +++ b/MySQL/second-highest-salary.sql @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(1) # -# Write a SQL query to get the second highest salary from the Employee table. +# Write a SQL query to get the second highest salary from the Employee table. Alias Salary as SecondHighestSalary. # # +----+--------+ # | Id | Salary | From 430b45c74fa9502985d6b398789ee6d3bbebef11 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Jun 2017 19:36:35 +0800 Subject: [PATCH 3303/4971] Create subarray-sum-equals-k.cpp --- C++/subarray-sum-equals-k.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/subarray-sum-equals-k.cpp diff --git a/C++/subarray-sum-equals-k.cpp b/C++/subarray-sum-equals-k.cpp new file mode 100644 index 000000000..3b0e19401 --- /dev/null +++ b/C++/subarray-sum-equals-k.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int subarraySum(vector& nums, int k) { + auto result{0}; + auto accumulated_sum{0}; + unordered_map lookup; + ++lookup[0]; + for (const auto& num : nums) { + accumulated_sum += num; + result += lookup[accumulated_sum - k]; + ++lookup[accumulated_sum]; + } + return result; + } +}; From ebb797bb7596adc71b1e906cb7d7f94b56e8f535 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Jun 2017 19:41:21 +0800 Subject: [PATCH 3304/4971] Create subarray-sum-equals-k.py --- Python/subarray-sum-equals-k.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/subarray-sum-equals-k.py diff --git a/Python/subarray-sum-equals-k.py b/Python/subarray-sum-equals-k.py new file mode 100644 index 000000000..98e7d8ae0 --- /dev/null +++ b/Python/subarray-sum-equals-k.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(n) + +# Given an array of integers and an integer k, +# you need to find the total number of continuous subarrays whose sum equals to k. +# +# Example 1: +# Input:nums = [1,1,1], k = 2 +# Output: 2 +# +# Note: +# The length of the array is in range [1, 20,000]. +# The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. + +class Solution(object): + def subarraySum(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + result = 0 + accumulated_sum = 0 + lookup = collections.defaultdict(int) + lookup[0] += 1 + for num in nums: + accumulated_sum += num + result += lookup[accumulated_sum - k] + lookup[accumulated_sum] += 1 + return result From 698bc9b0c54f3c36766f4fce43d9164bf5faf551 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Jun 2017 20:26:26 +0800 Subject: [PATCH 3305/4971] Create array-partition-i.cpp --- C++/array-partition-i.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/array-partition-i.cpp diff --git a/C++/array-partition-i.cpp b/C++/array-partition-i.cpp new file mode 100644 index 000000000..d2072e8fb --- /dev/null +++ b/C++/array-partition-i.cpp @@ -0,0 +1,34 @@ +// Time: O(R), R is the range size of the integers +// Space: O(R) + +class Solution { +public: + int arrayPairSum(vector& nums) { + const auto LEFT = -10000; + const auto RIGHT = 10000; + vector lookup(RIGHT - LEFT + 1, 0); + for (const auto& num: nums) { + ++lookup[num - LEFT]; + } + auto r = 0, result = 0; + for (int i = LEFT; i <= RIGHT; ++i) { + result += (lookup[i - LEFT] + 1 - r) / 2 * i; + r = (lookup[i - LEFT] + r) % 2; + } + return result; + } +}; + +// Time: O(nlogn) +// Space: O(1) +class Solution2 { +public: + int arrayPairSum(vector& nums) { + sort(nums.begin(), nums.end()); + auto result = 0; + for (auto i = 0; i < nums.size(); i += 2) { + result += nums[i]; + } + return result; + } +}; From 8d02d82024166966024ab4356d129a9e647134e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Jun 2017 22:21:20 +0800 Subject: [PATCH 3306/4971] Create array-partition-i.py --- Python/array-partition-i.py | 44 +++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/array-partition-i.py diff --git a/Python/array-partition-i.py b/Python/array-partition-i.py new file mode 100644 index 000000000..66bcd87eb --- /dev/null +++ b/Python/array-partition-i.py @@ -0,0 +1,44 @@ +# Time: O(R), R is the range size of the integers +# Space: O(R) + +# Given an array of 2n integers, your task is to group these integers into n pairs of integer, +# say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. +# +# Example 1: +# Input: [1,4,3,2] +# +# Output: 4 +# Explanation: n is 2, and the maximum sum of pairs is 4. +# Note: +# n is a positive integer, which is in the range of [1, 10000]. +# All the integers in the array will be in the range of [-10000, 10000]. + +class Solution(object): + def arrayPairSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + LEFT, RIGHT = -10000, 10000 + lookup = [0] * (RIGHT-LEFT+1) + for num in nums: + lookup[num-LEFT] += 1 + r, result = 0, 0 + for i in xrange(LEFT, RIGHT+1): + result += (lookup[i-LEFT] + 1 - r) / 2 * i + r = (lookup[i-LEFT] + r) % 2 + return result + +# Time: O(nlogn) +# Space: O(1) +class Solution2(object): + def arrayPairSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums.sort() + result = 0 + for i in xrange(0, len(nums), 2): + result += nums[i] + return result From 00323879c955f4a836f0ae7d8ca6503dea48607e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Jun 2017 22:28:39 +0800 Subject: [PATCH 3307/4971] Create binary-tree-tilt.cpp --- C++/binary-tree-tilt.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/binary-tree-tilt.cpp diff --git a/C++/binary-tree-tilt.cpp b/C++/binary-tree-tilt.cpp new file mode 100644 index 000000000..9511fcb34 --- /dev/null +++ b/C++/binary-tree-tilt.cpp @@ -0,0 +1,30 @@ +// 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: + int findTilt(TreeNode* root) { + int tilt = 0; + postOrderTraverse(root, &tilt); + return tilt; + } +private: + int postOrderTraverse(TreeNode* root, int *tilt) { + if (!root) { + return 0; + } + auto left = postOrderTraverse(root->left, tilt); + auto right = postOrderTraverse(root->right, tilt); + *tilt += abs(left - right); + return left + right + root->val; + } +}; From 49a4799c618af9fa427d6f18764ec10c7664352e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Jun 2017 22:33:42 +0800 Subject: [PATCH 3308/4971] Create binary-tree-tilt.py --- Python/binary-tree-tilt.py | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/binary-tree-tilt.py diff --git a/Python/binary-tree-tilt.py b/Python/binary-tree-tilt.py new file mode 100644 index 000000000..e1ed02783 --- /dev/null +++ b/Python/binary-tree-tilt.py @@ -0,0 +1,49 @@ +# Time: O(n) +# Space: O(n) + +# Given a binary tree, return the tilt of the whole tree. +# +# The tilt of a tree node is defined as the absolute difference +# between the sum of all left subtree node values and +# the sum of all right subtree node values. Null node has tilt 0. +# +# The tilt of the whole tree is defined as the sum of all nodes' tilt. +# +# Example: +# Input: +# 1 +# / \ +# 2 3 +# Output: 1 +# Explanation: +# Tilt of node 2 : 0 +# Tilt of node 3 : 0 +# Tilt of node 1 : |2-3| = 1 +# Tilt of binary tree : 0 + 0 + 1 = 1 +# Note: +# +# The sum of node values in any subtree won't exceed the range of 32-bit integer. + + +# 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 findTilt(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def postOrderTraverse(root, tilt): + if not root: + return 0, tilt + left, tilt = postOrderTraverse(root.left, tilt) + right, tilt = postOrderTraverse(root.right, tilt) + tilt += abs(left-right) + return left+right+root.val, tilt + + return postOrderTraverse(root, 0)[1] From 32e56daa6dd8ee64492c659aa8eaf36b429e3ef8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 5 Jun 2017 00:02:27 +0800 Subject: [PATCH 3309/4971] Create array-nesting.cpp --- C++/array-nesting.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/array-nesting.cpp diff --git a/C++/array-nesting.cpp b/C++/array-nesting.cpp new file mode 100644 index 000000000..2dc891643 --- /dev/null +++ b/C++/array-nesting.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int arrayNesting(vector& nums) { + auto result = 0; + for (const auto& num : nums) { + if (num != numeric_limits::max()) { + auto start = num, count = 0; + while (nums[start] != numeric_limits::max()) { + auto temp = start; + start = nums[start]; + nums[temp] = numeric_limits::max(); + ++count; + } + result = max(result, count); + } + } + return result; + } +}; From e0b60d40d9a30c802ce127ba97f22e4b6c881212 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 5 Jun 2017 00:05:45 +0800 Subject: [PATCH 3310/4971] Create array-nesting.py --- Python/array-nesting.py | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/array-nesting.py diff --git a/Python/array-nesting.py b/Python/array-nesting.py new file mode 100644 index 000000000..e2407e9b8 --- /dev/null +++ b/Python/array-nesting.py @@ -0,0 +1,46 @@ +# Time: O(n) +# Space: O(1) + +# A zero-indexed array A consisting of N different integers is given. +# The array contains all integers in the range [0, N - 1]. +# +# Sets S[K] for 0 <= K < N are defined as follows: +# +# S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }. +# +# Sets S[K] are finite for each K and should NOT contain duplicates. +# +# Write a function that given an array A consisting of N integers, +# return the size of the largest set S[K] for this array. +# +# Example 1: +# Input: A = [5,4,0,3,1,6,2] +# Output: 4 +# Explanation: +# A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. +# +# One of the longest S[K]: +# S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0} +# Note: +# N is an integer within the range [1, 20,000]. +# The elements of A are all distinct. +# Each element of array A is an integer within the range [0, N-1]. + +class Solution(object): + def arrayNesting(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + result = 0 + for num in nums: + if num != None: + start, count = num, 0 + while nums[start] != None: + temp = start + start = nums[start] + nums[temp] = None + count += 1 + result = max(result, count) + return result + From 7426a382a2a5f6c5145e4099d2e5d03718de09c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Jun 2017 00:13:08 +0800 Subject: [PATCH 3311/4971] Create reshape-the-matrix.cpp --- C++/reshape-the-matrix.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/reshape-the-matrix.cpp diff --git a/C++/reshape-the-matrix.cpp b/C++/reshape-the-matrix.cpp new file mode 100644 index 000000000..11ac63605 --- /dev/null +++ b/C++/reshape-the-matrix.cpp @@ -0,0 +1,22 @@ +// Time: O(m * n) +// Space: O(m * n) + +class Solution { +public: + vector> matrixReshape(vector>& nums, int r, int c) { + if (nums.empty() || + r * c != nums.size() * nums[0].size()) { + return nums; + } + + vector> result(r, vector(c)); + int count = 0; + for (int i = 0; i < nums.size(); ++i) { + for (int j = 0; j < nums[0].size(); ++j) { + result[count / c][count % c] = nums[i][j]; + ++count; + } + } + return result; + } +}; From e3d5a879459186afe1d0c46577b964b9c6286a13 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Jun 2017 00:17:57 +0800 Subject: [PATCH 3312/4971] Create reshape-the-matrix.py --- Python/reshape-the-matrix.py | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Python/reshape-the-matrix.py diff --git a/Python/reshape-the-matrix.py b/Python/reshape-the-matrix.py new file mode 100644 index 000000000..acbe6bdb2 --- /dev/null +++ b/Python/reshape-the-matrix.py @@ -0,0 +1,63 @@ +# Time: O(m * n) +# Space: O(m * n) + +# In MATLAB, there is a very useful function called 'reshape', +# which can reshape a matrix into a new one with different size but keep its original data. +# +# You're given a matrix represented by a two-dimensional array, +# and two positive integers r and c representing the row number +# and column number of the wanted reshaped matrix, respectively. +# +# The reshaped matrix need to be filled with +# all the elements of the original matrix in the same row-traversing order as they were. +# +# If the 'reshape' operation with given parameters is possible and legal, +# output the new reshaped matrix; Otherwise, output the original matrix. +# +# Example 1: +# Input: +# nums = +# [[1,2], +# [3,4]] +# r = 1, c = 4 +# Output: +# [[1,2,3,4]] +# Explanation: +# The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, +# fill it row by row by using the previous list. +# +# Example 2: +# Input: +# nums = +# [[1,2], +# [3,4]] +# r = 2, c = 4 +# Output: +# [[1,2], +# [3,4]] +# Explanation: +# There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix. +# +# Note: +# The height and width of the given matrix is in range [1, 100]. +# The given r and c are all positive. + +class Solution(object): + def matrixReshape(self, nums, r, c): + """ + :type nums: List[List[int]] + :type r: int + :type c: int + :rtype: List[List[int]] + """ + if not nums or \ + r*c != len(nums) * len(nums[0]): + return nums + + result = [[0 for _ in xrange(c)] for _ in xrange(r)] + count = 0 + for i in xrange(len(nums)): + for j in xrange(len(nums[0])): + result[count/c][count%c] = nums[i][j] + count += 1 + return result From 4867b692f53dc57d2050993482587ef0de2fe12c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Jun 2017 00:37:51 +0800 Subject: [PATCH 3313/4971] Create subtree-of-another-tree.cpp --- C++/subtree-of-another-tree.cpp | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/subtree-of-another-tree.cpp diff --git a/C++/subtree-of-another-tree.cpp b/C++/subtree-of-another-tree.cpp new file mode 100644 index 000000000..c018489fd --- /dev/null +++ b/C++/subtree-of-another-tree.cpp @@ -0,0 +1,37 @@ +// Time: O(m * n), m is the number of nodes of s, n is the number of nodes of t +// Space: O(h), h is the height of s + +/** + * 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: + bool isSubtree(TreeNode* s, TreeNode* t) { + return preOrderTraverse(s, t); + } + +private: + bool preOrderTraverse(TreeNode *s, TreeNode *t) { + return s && (isSame(s, t) || + preOrderTraverse(s->left, t) || + preOrderTraverse(s->right, t)); + } + + bool isSame(TreeNode *x,TreeNode *y) { + if (!x && !y) { + return true; + } + if (!x || !y) { + return false; + } + return x->val == y->val && + isSame(x->left, y->left) && + isSame(x->right, y->right); + } +}; From 9fadd8445f832fd87150a59dbf5d987dcf57f94f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Jun 2017 00:43:36 +0800 Subject: [PATCH 3314/4971] Create subtree-of-another-tree.py --- Python/subtree-of-another-tree.py | 68 +++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Python/subtree-of-another-tree.py diff --git a/Python/subtree-of-another-tree.py b/Python/subtree-of-another-tree.py new file mode 100644 index 000000000..9b0987f33 --- /dev/null +++ b/Python/subtree-of-another-tree.py @@ -0,0 +1,68 @@ +# Time: O(m * n), m is the number of nodes of s, n is the number of nodes of t +# Space: O(h), h is the height of s + +# Given two non-empty binary trees s and t, +# check whether tree t has exactly the same structure and +# node values with a subtree of s. +# A subtree of s is a tree consists of a node in s and all of this node's descendants. +# The tree s could also be considered as a subtree of itself. +# +# Example 1: +# Given tree s: +# +# 3 +# / \ +# 4 5 +# / \ +# 1 2 +# Given tree t: +# 4 +# / \ +# 1 2 +# Return true, because t has the same structure and node values with a subtree of s. +# Example 2: +# Given tree s: +# +# 3 +# / \ +# 4 5 +# / \ +# 1 2 +# / +# 0 +# Given tree t: +# 4 +# / \ +# 1 2 +# Return false. + +# 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 isSubtree(self, s, t): + """ + :type s: TreeNode + :type t: TreeNode + :rtype: bool + """ + def isSame(x, y): + if not x and not y: + return True + if not x or not y: + return False + return x.val == y.val and \ + isSame(x.left, y.left) and \ + isSame(x.right, y.right) + + def preOrderTraverse(s, t): + return s != None and \ + (isSame(s, t) or \ + preOrderTraverse(s.left, t) or \ + preOrderTraverse(s.right, t)) + + return preOrderTraverse(s, t) From cf74979263b2981a4e057d908cd37d8547700667 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Jun 2017 00:17:53 +0800 Subject: [PATCH 3315/4971] Create squirrel-simulation.cpp --- C++/squirrel-simulation.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/squirrel-simulation.cpp diff --git a/C++/squirrel-simulation.cpp b/C++/squirrel-simulation.cpp new file mode 100644 index 000000000..adf3aa525 --- /dev/null +++ b/C++/squirrel-simulation.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int minDistance(int height, int width, vector& tree, vector& squirrel, vector>& nuts) { + int result = 0; + int d = numeric_limits::max(); + for (const auto& nut : nuts) { + result += (distance(nut, tree) * 2); + d = min(d, distance(nut, squirrel) - distance(nut, tree)); + } + return result + d; + } + +private: + int distance(const vector& a, const vector& b) { + return abs(a[0] - b[0]) + abs(a[1] - b[1]); + } +}; From 571452236be15f2f67824007a7646eb9318ec387 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Jun 2017 00:21:34 +0800 Subject: [PATCH 3316/4971] Create squirrel-simulation.py --- Python/squirrel-simulation.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Python/squirrel-simulation.py diff --git a/Python/squirrel-simulation.py b/Python/squirrel-simulation.py new file mode 100644 index 000000000..11935ae5e --- /dev/null +++ b/Python/squirrel-simulation.py @@ -0,0 +1,22 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def minDistance(self, height, width, tree, squirrel, nuts): + """ + :type height: int + :type width: int + :type tree: List[int] + :type squirrel: List[int] + :type nuts: List[List[int]] + :rtype: int + """ + def distance(a, b): + return abs(a[0] - b[0]) + abs(a[1] - b[1]) + + result = 0 + d = float("inf") + for nut in nuts: + result += (distance(nut, tree) * 2) + d = min(d, distance(nut, squirrel) - distance(nut, tree)) + return result + d From dca7ec632befd50f3acece1a9bcc3c7b9aec3356 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Jun 2017 00:27:43 +0800 Subject: [PATCH 3317/4971] Create distribute-candies.cpp --- C++/distribute-candies.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/distribute-candies.cpp diff --git a/C++/distribute-candies.cpp b/C++/distribute-candies.cpp new file mode 100644 index 000000000..ffbda99da --- /dev/null +++ b/C++/distribute-candies.cpp @@ -0,0 +1,13 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int distributeCandies(vector& candies) { + unordered_set lookup; + for (const auto& candy: candies) { + lookup.emplace(candy); + } + return min(lookup.size(), candies.size() / 2); + } +}; From ec8ab5fe43c3b6f2dcd7010c56839c276017d036 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Jun 2017 00:30:10 +0800 Subject: [PATCH 3318/4971] Create distribute-candies.py --- Python/distribute-candies.py | 37 ++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/distribute-candies.py diff --git a/Python/distribute-candies.py b/Python/distribute-candies.py new file mode 100644 index 000000000..922454a98 --- /dev/null +++ b/Python/distribute-candies.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(n) + +# Given an integer array with even length, where different numbers +# in this array represent different kinds of candies. +# Each number means one candy of the corresponding kind. +# You need to distribute these candies equally in number to brother and sister. +# Return the maximum number of kinds of candies the sister could gain. +# +# Example 1: +# Input: candies = [1,1,2,2,3,3] +# Output: 3 +# Explanation: +# There are three different kinds of candies (1, 2 and 3), and two candies for each kind. +# Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. +# The sister has three different kinds of candies. +# +# Example 2: +# Input: candies = [1,1,2,3] +# Output: 2 +# Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. +# The sister has two different kinds of candies, the brother has only one kind of candies. +# +# Note: +# The length of the given array is in range [2, 10,000], and will be even. +# The number in given array is in range [-100,000, 100,000]. + +class Solution(object): + def distributeCandies(self, candies): + """ + :type candies: List[int] + :rtype: int + """ + lookup = set() + for candy in candies: + lookup.add(candy) + return min(len(lookup), len(candies)/2) From b38cc0044db950c1c7b9c01fcb5d82958fa219d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Jun 2017 23:42:13 +0800 Subject: [PATCH 3319/4971] Create out-of-boundary-paths.cpp --- C++/out-of-boundary-paths.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/out-of-boundary-paths.cpp diff --git a/C++/out-of-boundary-paths.cpp b/C++/out-of-boundary-paths.cpp new file mode 100644 index 000000000..48c447c01 --- /dev/null +++ b/C++/out-of-boundary-paths.cpp @@ -0,0 +1,22 @@ +// Time: O(N * m * n) +// Space: O(m * n) + +class Solution { +public: + int findPaths(int m, int n, int N, int i, int j) { + const auto M = 1000000000 + 7; + vector>> dp(2, vector>(m, vector(n))); + int result = 0; + for (int moves = 0; moves < N; ++moves) { + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + dp[(moves + 1) % 2][i][j] = (((i == 0 ? 1 : dp[moves % 2][i - 1][j] ) + + (i == m - 1 ? 1 : dp[moves % 2][i + 1][j])) % M + + ((j == 0 ? 1 : dp[moves % 2][i][j - 1]) + + (j == n - 1 ? 1 : dp[moves % 2][i][j + 1])) % M) % M; + } + } + } + return dp[N % 2][i][j]; + } +}; From 3cf6cb01796258991984d3d51b1895fe6024c036 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Jun 2017 23:45:14 +0800 Subject: [PATCH 3320/4971] Update out-of-boundary-paths.cpp --- C++/out-of-boundary-paths.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/out-of-boundary-paths.cpp b/C++/out-of-boundary-paths.cpp index 48c447c01..df2310e21 100644 --- a/C++/out-of-boundary-paths.cpp +++ b/C++/out-of-boundary-paths.cpp @@ -10,7 +10,7 @@ class Solution { for (int moves = 0; moves < N; ++moves) { for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { - dp[(moves + 1) % 2][i][j] = (((i == 0 ? 1 : dp[moves % 2][i - 1][j] ) + + dp[(moves + 1) % 2][i][j] = (((i == 0 ? 1 : dp[moves % 2][i - 1][j]) + (i == m - 1 ? 1 : dp[moves % 2][i + 1][j])) % M + ((j == 0 ? 1 : dp[moves % 2][i][j - 1]) + (j == n - 1 ? 1 : dp[moves % 2][i][j + 1])) % M) % M; From 944ef57fd7478a53ad28138a4e99bfc635ca03b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Jun 2017 23:52:40 +0800 Subject: [PATCH 3321/4971] Update out-of-boundary-paths.cpp --- C++/out-of-boundary-paths.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/out-of-boundary-paths.cpp b/C++/out-of-boundary-paths.cpp index df2310e21..95ad063f5 100644 --- a/C++/out-of-boundary-paths.cpp +++ b/C++/out-of-boundary-paths.cpp @@ -11,9 +11,9 @@ class Solution { for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { dp[(moves + 1) % 2][i][j] = (((i == 0 ? 1 : dp[moves % 2][i - 1][j]) + - (i == m - 1 ? 1 : dp[moves % 2][i + 1][j])) % M + - ((j == 0 ? 1 : dp[moves % 2][i][j - 1]) + - (j == n - 1 ? 1 : dp[moves % 2][i][j + 1])) % M) % M; + (i == m - 1 ? 1 : dp[moves % 2][i + 1][j])) % M + + ((j == 0 ? 1 : dp[moves % 2][i][j - 1]) + + (j == n - 1 ? 1 : dp[moves % 2][i][j + 1])) % M) % M; } } } From ce5b6119ad3404fb2e347de73e88132a84c7b241 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Jun 2017 23:53:15 +0800 Subject: [PATCH 3322/4971] Update out-of-boundary-paths.cpp --- C++/out-of-boundary-paths.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/out-of-boundary-paths.cpp b/C++/out-of-boundary-paths.cpp index 95ad063f5..dcefa7253 100644 --- a/C++/out-of-boundary-paths.cpp +++ b/C++/out-of-boundary-paths.cpp @@ -6,7 +6,6 @@ class Solution { int findPaths(int m, int n, int N, int i, int j) { const auto M = 1000000000 + 7; vector>> dp(2, vector>(m, vector(n))); - int result = 0; for (int moves = 0; moves < N; ++moves) { for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { From a9970d09fc60d67be4c8d4d2d8cf67802614e3f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Jun 2017 23:59:31 +0800 Subject: [PATCH 3323/4971] Update out-of-boundary-paths.cpp --- C++/out-of-boundary-paths.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/C++/out-of-boundary-paths.cpp b/C++/out-of-boundary-paths.cpp index dcefa7253..a0c829858 100644 --- a/C++/out-of-boundary-paths.cpp +++ b/C++/out-of-boundary-paths.cpp @@ -3,9 +3,10 @@ class Solution { public: - int findPaths(int m, int n, int N, int i, int j) { + int findPaths(int m, int n, int N, int x, int y) { const auto M = 1000000000 + 7; vector>> dp(2, vector>(m, vector(n))); + int result = 0; for (int moves = 0; moves < N; ++moves) { for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { @@ -16,6 +17,6 @@ class Solution { } } } - return dp[N % 2][i][j]; + return dp[N % 2][x][y]; } }; From c0769b303db72ebbdbe5fcc302f4292f526c15c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Jun 2017 00:01:46 +0800 Subject: [PATCH 3324/4971] Create out-of-boundary-paths.py --- Python/out-of-boundary-paths.py | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/out-of-boundary-paths.py diff --git a/Python/out-of-boundary-paths.py b/Python/out-of-boundary-paths.py new file mode 100644 index 000000000..259406840 --- /dev/null +++ b/Python/out-of-boundary-paths.py @@ -0,0 +1,42 @@ +# Time: O(N * m * n) +# Space: O(m * n) + +# There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, +# you can move the ball to adjacent cell or cross the grid boundary in +# four directions (up, down, left, right). However, you can at most move N times. +# Find out the number of paths to move the ball out of grid boundary. +# The answer may be very large, return it after mod 109 + 7. +# +# Example 1: +# Input:m = 2, n = 2, N = 2, i = 0, j = 0 +# Output: 6 +# +# Example 2: +# Input:m = 1, n = 3, N = 3, i = 0, j = 1 +# Output: 12 +# +# Note: +# Once you move the ball out of boundary, you cannot move it back. +# The length and height of the grid is in range [1,50]. +# N is in range [0,50]. + +class Solution(object): + def findPaths(self, m, n, N, x, y): + """ + :type m: int + :type n: int + :type N: int + :type x: int + :type y: int + :rtype: int + """ + M = 1000000000 + 7 + dp = [[[0 for _ in xrange(n)] for _ in xrange(m)] for _ in xrange(2)] + for moves in xrange(N): + for i in xrange(m): + for j in xrange(n): + dp[(moves + 1) % 2][i][j] = (((1 if (i == 0) else dp[moves % 2][i - 1][j]) + \ + (1 if (i == m - 1) else dp[moves % 2][i + 1][j])) % M + \ + ((1 if (j == 0) else dp[moves % 2][i][j - 1]) + \ + (1 if (j == n - 1) else dp[moves % 2][i][j + 1])) % M) % M + return dp[N % 2][x][y] From 37dc4e1cdfe8cf29c6849841517eee78b72d5919 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Jun 2017 00:26:01 +0800 Subject: [PATCH 3325/4971] Create shortest-unsorted-continuous-subarray.cpp --- C++/shortest-unsorted-continuous-subarray.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/shortest-unsorted-continuous-subarray.cpp diff --git a/C++/shortest-unsorted-continuous-subarray.cpp b/C++/shortest-unsorted-continuous-subarray.cpp new file mode 100644 index 000000000..fe45e1ac8 --- /dev/null +++ b/C++/shortest-unsorted-continuous-subarray.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findUnsortedSubarray(vector& nums) { + const auto n = nums.size(); + auto left = -1, right = -2; + auto max_from_left = nums[0], min_from_right = nums.back(); + for (int i = 1; i < n; ++i) { + max_from_left = max(max_from_left, nums[i]); + min_from_right = min(min_from_right, nums[n - 1 - i]); + if (nums[i] < max_from_left) { + right = i; + } + if (nums[n - 1 - i] > min_from_right) { + left = n - 1 - i; + } + } + return right - left + 1; + } +}; From f0adf7c3600f97817f84241057b7274f5f89de64 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Jun 2017 00:27:47 +0800 Subject: [PATCH 3326/4971] Create shortest-unsorted-continuous-subarray.py --- .../shortest-unsorted-continuous-subarray.py | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/shortest-unsorted-continuous-subarray.py diff --git a/Python/shortest-unsorted-continuous-subarray.py b/Python/shortest-unsorted-continuous-subarray.py new file mode 100644 index 000000000..bed6c7a6a --- /dev/null +++ b/Python/shortest-unsorted-continuous-subarray.py @@ -0,0 +1,34 @@ +# Time: O(n) +# Space: O(1) + +# Given an integer array, you need to find one continuous subarray that +# if you only sort this subarray in ascending order, +# then the whole array will be sorted in ascending order, too. +# +# You need to find the shortest such subarray and output its length. +# +# Example 1: +# Input: [2, 6, 4, 8, 10, 9, 15] +# Output: 5 +# Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order +# to make the whole array sorted in ascending order. +# +# Note: +# Then length of the input array is in range [1, 10,000]. +# The input array may contain duplicates, so ascending order here means <=. + +class Solution(object): + def findUnsortedSubarray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n = len(nums) + left, right = -1, -2 + min_from_right, max_from_left = nums[-1], nums[0] + for i in xrange(1, n): + max_from_left = max(max_from_left, nums[i]) + min_from_right = min(min_from_right, nums[n-1-i]) + if nums[i] < max_from_left: right = i + if nums[n-1-i] > min_from_right: left = n-1-i + return right - left + 1 From b055b21b14df1000096cd11af50d23a18ec1f276 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Jun 2017 21:03:48 +0800 Subject: [PATCH 3327/4971] Create kill-process.cpp --- C++/kill-process.cpp | 50 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 C++/kill-process.cpp diff --git a/C++/kill-process.cpp b/C++/kill-process.cpp new file mode 100644 index 000000000..4f4e82766 --- /dev/null +++ b/C++/kill-process.cpp @@ -0,0 +1,50 @@ +// Time: O(n) +// Space: O(n) + +// DFS solution. +class Solution { +public: + vector killProcess(vector& pid, vector& ppid, int kill) { + vector result; + unordered_map> children; + for (int i = 0; i < pid.size(); ++i) { + children[ppid[i]].emplace(pid[i]); + } + killAll(kill, children, &result); + return result; + } + +private: + void killAll(int pid, unordered_map>& children, vector *killed) { + killed->emplace_back(pid); + for (const auto& child : children[pid]) { + killAll(child, children, killed); + } + } +}; + +// Time: O(n) +// Space: O(n) +// BFS solution. +class Solution { +public: + vector killProcess(vector& pid, vector& ppid, int kill) { + vector result; + unordered_map> children; + for (int i = 0; i < pid.size(); ++i) { + children[ppid[i]].emplace(pid[i]); + } + + queue q; + q.emplace(kill); + while (!q.empty()) { + const auto p = q.front(); q.pop(); + result.emplace_back(p); + for (const auto& child : children[p]) { + q.emplace(child); + } + } + + return result; + } +}; From f906bf6c6bff223295aeda8bd75c4e7827c7fbad Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Jun 2017 21:13:30 +0800 Subject: [PATCH 3328/4971] Create kill-process.py --- Python/kill-process.py | 87 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 Python/kill-process.py diff --git a/Python/kill-process.py b/Python/kill-process.py new file mode 100644 index 000000000..daedeab3a --- /dev/null +++ b/Python/kill-process.py @@ -0,0 +1,87 @@ +# Time: O(n) +# Space: O(n) + +# Given n processes, each process has a unique PID (process id) +# and its PPID (parent process id). +# +# Each process only has one parent process, but may have one or more children processes. +# This is just like a tree structure. Only one process has PPID that is 0, +# which means this process has no parent process. All the PIDs will be distinct positive integers. +# +# We use two list of integers to represent a list of processes, +# where the first list contains PID for each process +# and the second list contains the corresponding PPID. +# +# Now given the two lists, and a PID representing a process you want to kill, +# return a list of PIDs of processes that will be killed in the end. +# You should assume that when a process is killed, +# all its children processes will be killed. +# No order is required for the final answer. +# +# Example 1: +# Input: +# pid = [1, 3, 10, 5] +# ppid = [3, 0, 5, 3] +# kill = 5 +# Output: [5,10] +# Explanation: +# 3 +# / \ +# 1 5 +# / +# 10 +# Kill 5 will also kill 10. +# Note: +# The given kill id is guaranteed to be one of the given PIDs. +# n >= 1. + +# DFS solution. +class Solution(object): + def killProcess(self, pid, ppid, kill): + """ + :type pid: List[int] + :type ppid: List[int] + :type kill: int + :rtype: List[int] + """ + def killAll(pid, children, killed): + killed.append(pid) + for child in children[pid]: + killAll(child, children, killed) + + result = [] + children = collections.defaultdict(set) + for i in xrange(len(pid)): + children[ppid[i]].add(pid[i]) + killAll(kill, children, result) + return result + + +# Time: O(n) +# Space: O(n) +# BFS solution. +class Solution2(object): + def killProcess(self, pid, ppid, kill): + """ + :type pid: List[int] + :type ppid: List[int] + :type kill: int + :rtype: List[int] + """ + def killAll(pid, children, killed): + killed.append(pid) + for child in children[pid]: + killAll(child, children, killed) + + result = [] + children = collections.defaultdict(set) + for i in xrange(len(pid)): + children[ppid[i]].add(pid[i]) + q = collections.deque() + q.append(kill) + while q: + p = q.popleft() + result.append(p); + for child in children[p]: + q.append(child) + return result From 9db3cad76e20e1b797dec70c9a74f9aeb66bbbc3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Jun 2017 21:36:38 +0800 Subject: [PATCH 3329/4971] Create delete-operation-for-two-strings.cpp --- C++/delete-operation-for-two-strings.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/delete-operation-for-two-strings.cpp diff --git a/C++/delete-operation-for-two-strings.cpp b/C++/delete-operation-for-two-strings.cpp new file mode 100644 index 000000000..46a33c247 --- /dev/null +++ b/C++/delete-operation-for-two-strings.cpp @@ -0,0 +1,19 @@ +// Time: O(m * n) +// Space: O(n) + +class Solution { +public: + int minDistance(string word1, string word2) { + const auto m = word1.length(); + const auto n = word2.length(); + + vector> dp(2, vector(n + 1)); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + dp[(i + 1) % 2][j + 1] = max(max(dp[i % 2][j + 1], dp[(i + 1) % 2][j]), + dp[i % 2][j] + (word1[i] == word2[j])); + } + } + return m + n - 2 * dp[m % 2][n]; + } +}; From 975220f71692cccbe8c7017ada81a5757e5061b9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Jun 2017 21:38:00 +0800 Subject: [PATCH 3330/4971] Create delete-operation-for-two-strings.py --- Python/delete-operation-for-two-strings.py | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/delete-operation-for-two-strings.py diff --git a/Python/delete-operation-for-two-strings.py b/Python/delete-operation-for-two-strings.py new file mode 100644 index 000000000..557948096 --- /dev/null +++ b/Python/delete-operation-for-two-strings.py @@ -0,0 +1,30 @@ +# Time: O(m * n) +# Space: O(n) + +# Given two words word1 and word2, +# find the minimum number of steps required to make word1 and word2 the same, +# where in each step you can delete one character in either string. +# +# Example 1: +# Input: "sea", "eat" +# Output: 2 +# Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea". +# Note: +# The length of given words won't exceed 500. +# Characters in given words can only be lower-case letters. + +class Solution(object): + def minDistance(self, word1, word2): + """ + :type word1: str + :type word2: str + :rtype: int + """ + m, n = len(word1), len(word2) + dp = [[0] * (n+1) for _ in xrange(2)] + for i in xrange(m): + for j in xrange(n): + dp[(i+1)%2][j+1] = max(dp[i%2][j+1], \ + dp[(i+1)%2][j], \ + dp[i%2][j] + (word1[i] == word2[j])) + return m + n - 2*dp[m%2][n] From 65acaa5d3fae2a51fee5e1d73ec05b55dcd2e905 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Jun 2017 20:56:42 +0800 Subject: [PATCH 3331/4971] Create erect-the-fence.cpp --- C++/erect-the-fence.cpp | 54 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 C++/erect-the-fence.cpp diff --git a/C++/erect-the-fence.cpp b/C++/erect-the-fence.cpp new file mode 100644 index 000000000..409b5eee2 --- /dev/null +++ b/C++/erect-the-fence.cpp @@ -0,0 +1,54 @@ +// Time: O(nlogn) +// Space: O(n) + +/** + * Definition for a point. + * struct Point { + * int x; + * int y; + * Point() : x(0), y(0) {} + * Point(int a, int b) : x(a), y(b) {} + * }; + */ +class Solution { +public: + vector outerTrees(vector& points) { + const auto orientation = [](const Point& p, const Point& q, const Point& r) { + return (q.y - p.y) * (r.x - q.x) - + (q.x - p.x) * (r.y - q.y); + }; + const auto cmp = [](const Point& p, const Point& q) { + return p.x == q.x ? p.y < q.y : p.x < q.x; + }; + const auto eq = [](const Point &p1, const Point &p2) { + return p1.x == p2.x && p1.y == p2.y; + }; + + vector hull; + sort(points.begin(), points.end(), cmp); + + for (int i = 0; i < points.size(); ++i) { + while (hull.size() >= 2 && + orientation(hull[hull.size() - 2], + hull[hull.size() - 1], + points[i]) > 0) { + hull.pop_back(); + } + hull.emplace_back(points[i]); + } + + for (int i = points.size() - 1; i >= 0; --i) { + while (hull.size() >= 2 && + orientation(hull[hull.size() - 2], + hull[hull.size() - 1], + points[i]) > 0) { + hull.pop_back(); + } + hull.emplace_back(points[i]); + } + + sort(hull.begin(), hull.end(), cmp); + hull.erase(unique(hull.begin(), hull.end(), eq), hull.end()); + return hull; + } +}; From 6ceb6a8b0f8843bd674d5acc5dfdcd887724f515 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Jun 2017 21:09:20 +0800 Subject: [PATCH 3332/4971] Create erect-the-fence.py --- Python/erect-the-fence.py | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/erect-the-fence.py diff --git a/Python/erect-the-fence.py b/Python/erect-the-fence.py new file mode 100644 index 000000000..dc8e84964 --- /dev/null +++ b/Python/erect-the-fence.py @@ -0,0 +1,54 @@ +# Time: O(nlogn) +# Space: O(n) + +# There are some trees, where each tree is represented by +# (x,y) coordinate in a two-dimensional garden. +# Your job is to fence the entire garden using the minimum length of rope +# as it is expensive. The garden is well fenced only if all the trees are enclosed. +# Your task is to help find the coordinates of trees which are exactly located on the fence perimeter. +# +# Example 1: +# Input: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]] +# Output: [[1,1],[2,0],[4,2],[3,3],[2,4]] +# +# Example 2: +# Input: [[1,2],[2,2],[4,2]] +# Output: [[1,2],[2,2],[4,2]] +# +# Even you only have trees in a line, you need to use rope to enclose them. +# Note: +# +# All trees should be enclosed together. +# You cannot cut the rope to enclose trees that will separate them in more than one group. +# All input integers will range from 0 to 100. +# The garden has at least one tree. +# All coordinates are distinct. +#Input points have NO order. No order required for output. + +# Definition for a point. +# class Point(object): +# def __init__(self, a=0, b=0): +# self.x = a +# self.y = b + +class Solution(object): + def outerTrees(self, points): + """ + :type points: List[Point] + :rtype: List[Point] + """ + def orientation(p, q, r): + return (q.y - p.y) * (r.x - q.x) - \ + (q.x - p.x) * (r.y - q.y) + + hull = [] + points.sort(key=lambda p: (p.x, p.y)) + + for i in itertools.chain(xrange(len(points)), \ + reversed(xrange(len(points)))): + while len(hull) >= 2 and \ + orientation(hull[-2], hull[-1], points[i]) > 0: + hull.pop() + hull.append(points[i]) + + return list(set(hull)) From 44a7af3c01de5f18c8697f023048e75c97ce817b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Jun 2017 23:56:41 +0800 Subject: [PATCH 3333/4971] Create merge-two-binary-trees.cpp --- C++/merge-two-binary-trees.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/merge-two-binary-trees.cpp diff --git a/C++/merge-two-binary-trees.cpp b/C++/merge-two-binary-trees.cpp new file mode 100644 index 000000000..dde23b16f --- /dev/null +++ b/C++/merge-two-binary-trees.cpp @@ -0,0 +1,27 @@ +// 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: + TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { + if (!t1) { + return t2; + } + if (!t2) { + return t1; + } + t1->val += t2->val; + t1->left = mergeTrees(t1->left, t2->left); + t1->right = mergeTrees(t1->right, t2->right); + return t1; + } +}; From 5110fabe8887d58e0c74edd457fcae9526aad22b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Jun 2017 00:00:25 +0800 Subject: [PATCH 3334/4971] Create merge-two-binary-trees.py --- Python/merge-two-binary-trees.py | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/merge-two-binary-trees.py diff --git a/Python/merge-two-binary-trees.py b/Python/merge-two-binary-trees.py new file mode 100644 index 000000000..26e56c3a6 --- /dev/null +++ b/Python/merge-two-binary-trees.py @@ -0,0 +1,53 @@ +# Time: O(n) +# Space: O(h) + +# Given two binary trees and imagine that +# when you put one of them to cover the other, +# some nodes of the two trees are overlapped +# while the others are not. +# +# You need to merge them into a new binary tree. +# The merge rule is that if two nodes overlap, +# then sum node values up as the new value of the merged node. +# Otherwise, the NOT null node will be used as the node of new tree. +# +# Example 1: +# Input: +# Tree 1 Tree 2 +# 1 2 +# / \ / \ +# 3 2 1 3 +# / \ \ +# 5 4 7 +# Output: +# Merged tree: +# 3 +# / \ +# 4 5 +# / \ \ +# 5 4 7 + +# Note: The merging process must start from the root nodes of both trees. + +# 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 mergeTrees(self, t1, t2): + """ + :type t1: TreeNode + :type t2: TreeNode + :rtype: TreeNode + """ + if t1 is None: + return t2 + if t2 is None: + return t1 + t1.val += t2.val + t1.left = mergeTrees(t1.left, t2.left) + t1.right = mergeTrees(t1.right, t2.right) + return t1 From 2bf0782a7eb52f8ba19a273676cab025257cd868 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Jun 2017 00:00:50 +0800 Subject: [PATCH 3335/4971] Update merge-two-binary-trees.py --- Python/merge-two-binary-trees.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/merge-two-binary-trees.py b/Python/merge-two-binary-trees.py index 26e56c3a6..02e15e449 100644 --- a/Python/merge-two-binary-trees.py +++ b/Python/merge-two-binary-trees.py @@ -26,7 +26,7 @@ # 4 5 # / \ \ # 5 4 7 - +# # Note: The merging process must start from the root nodes of both trees. # Definition for a binary tree node. From f4af1a3997e0adf42272ddd69bb3c0f63cdd4303 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Jun 2017 00:10:03 +0800 Subject: [PATCH 3336/4971] Create design-in-memory-file-system.cpp --- C++/design-in-memory-file-system.cpp | 91 ++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 C++/design-in-memory-file-system.cpp diff --git a/C++/design-in-memory-file-system.cpp b/C++/design-in-memory-file-system.cpp new file mode 100644 index 000000000..dcf644ba3 --- /dev/null +++ b/C++/design-in-memory-file-system.cpp @@ -0,0 +1,91 @@ +// Time: ls: O(l + klogk), l is the path length, k is the number of entries in the last level directory +// mkdir: O(l) +// addContentToFile: O(l + c), c is the content size +// readContentFromFile: O(l + c) +// Space: O(n + s), n is the number of dir/file nodes, s is the total content size. + +class FileSystem { +public: + FileSystem() : root_(new TrieNode()){ + mkdir("/"); + } + + vector ls(string path) { + auto curr = getNode(path); + + if (curr->isFile) { + return {split(path, '/').back()}; + } + + vector result; + for (const auto& child : curr->children) { + result.emplace_back(child.first); + } + sort(result.begin(), result.end()); + return result; + } + + void mkdir(string path) { + auto curr = putNode(path); + curr->isFile = false; + } + + void addContentToFile(string filePath, string content) { + auto curr = putNode(filePath); + curr->isFile = true; + curr->content += content; + } + + string readContentFromFile(string filePath) { + return getNode(filePath)->content; + } + +private: + struct TrieNode { + bool isFile; + unordered_map children; + string content; + }; + + TrieNode *root_; + + TrieNode *getNode(const string& path) { + vector strs = split(path, '/'); + auto curr = root_; + for (const auto& str : strs) { + curr = curr->children[str]; + } + return curr; + } + + TrieNode *putNode(const string& path) { + vector strs = split(path, '/'); + auto curr = root_; + for (const auto& str : strs) { + if (!curr->children.count(str)) { + curr->children[str] = new TrieNode(); + } + curr = curr->children[str]; + } + return curr; + } + + vector split(const string& s, const char delim) { + vector tokens; + stringstream ss(s); + string token; + while (getline(ss, token, delim)) { + tokens.emplace_back(token); + } + return tokens; + } +}; + +/** + * Your FileSystem object will be instantiated and called as such: + * FileSystem obj = new FileSystem(); + * vector param_1 = obj.ls(path); + * obj.mkdir(path); + * obj.addContentToFile(filePath,content); + * string param_4 = obj.readContentFromFile(filePath); + */ From dd205b8f75360500c87c97c82ad2f939b50a42ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Jun 2017 00:38:51 +0800 Subject: [PATCH 3337/4971] Create design-in-memory-file-system.cpp --- C++/design-in-memory-file-system.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/C++/design-in-memory-file-system.cpp b/C++/design-in-memory-file-system.cpp index dcf644ba3..65423bd9f 100644 --- a/C++/design-in-memory-file-system.cpp +++ b/C++/design-in-memory-file-system.cpp @@ -6,8 +6,8 @@ class FileSystem { public: - FileSystem() : root_(new TrieNode()){ - mkdir("/"); + FileSystem() : root_(new TrieNode()) { + } vector ls(string path) { @@ -75,7 +75,9 @@ class FileSystem { stringstream ss(s); string token; while (getline(ss, token, delim)) { - tokens.emplace_back(token); + if (!token.empty()) { + tokens.emplace_back(token); + } } return tokens; } From cca8d440f1a3c0b0d9c9e0144be47306dc15c445 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Jun 2017 00:45:14 +0800 Subject: [PATCH 3338/4971] Create design-in-memory-file-system.py --- Python/design-in-memory-file-system.py | 122 +++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 Python/design-in-memory-file-system.py diff --git a/Python/design-in-memory-file-system.py b/Python/design-in-memory-file-system.py new file mode 100644 index 000000000..ae5ee030c --- /dev/null +++ b/Python/design-in-memory-file-system.py @@ -0,0 +1,122 @@ +# Time: ls: O(l + klogk), l is the path length, k is the number of entries in the last level directory +# mkdir: O(l) +# addContentToFile: O(l + c), c is the content size +# readContentFromFile: O(l + c) +# Space: O(n + s), n is the number of dir/file nodes, s is the total content size. + +# Design an in-memory file system to simulate the following functions: +# +# ls: Given a path in string format. If it is a file path, +# return a list that only contains this file's name. +# If it is a directory path, return the list of file and directory names in this directory. +# Your output (file and directory names together) should in lexicographic order. +# +# mkdir: Given a directory path that does not exist, +# you should make a new directory according to the path. +# If the middle directories in the path don't exist either, +# you should create them as well. This function has void return type. +# +# addContentToFile: Given a file path and file content in string format. +# If the file doesn't exist, you need to create that file containing given content. +# If the file already exists, you need to append given content to original content. +# This function has void return type. +# +# readContentFromFile: Given a file path, return its content in string format. +# +# Example: +# Input: +# ["FileSystem","ls","mkdir","addContentToFile","ls","readContentFromFile"] +# [[],["/"],["/a/b/c"],["/a/b/c/d","hello"],["/"],["/a/b/c/d"]] +# Output: +# [null,[],null,null,["a"],"hello"] +# +# Note: +# 1. You can assume all file or directory paths are absolute paths +# which begin with / and do not end with / except that the path is just "/". +# 2. You can assume that all operations will be passed valid parameters and +# users will not attempt to retrieve file content or list a directory or file that does not exist. +# 3. You can assume that all directory names and file names only contain lower-case letters, +# and same names won't exist in the same directory. + + +class TrieNode(object): + + def __init__(self): + self.is_file = False + self.children = {} + self.content = "" + +class FileSystem(object): + + def __init__(self): + self.__root = TrieNode() + + + def ls(self, path): + """ + :type path: str + :rtype: List[str] + """ + curr = self.__getNode(path) + + if curr.is_file: + return [self.__split(path, '/')[-1]] + + return sorted(curr.children.keys()) + + + def mkdir(self, path): + """ + :type path: str + :rtype: void + """ + curr = self.__putNode(path) + curr.is_file = False + + + def addContentToFile(self, filePath, content): + """ + :type filePath: str + :type content: str + :rtype: void + """ + curr = self.__putNode(filePath) + curr.is_file = True + curr.content += content + + + def readContentFromFile(self, filePath): + """ + :type filePath: str + :rtype: str + """ + return self.__getNode(filePath).content + + + def __getNode(self, path): + curr = self.__root + for s in self.__split(path, '/'): + curr = curr.children[s] + return curr + + + def __putNode(self, path): + curr = self.__root + for s in self.__split(path, '/'): + if s not in curr.children: + curr.children[s] = TrieNode() + curr = curr.children[s] + return curr + + + def __split(self, path, delim): + if path == '/': + return [] + return path.split('/')[1:] + +# Your FileSystem object will be instantiated and called as such: +# obj = FileSystem() +# param_1 = obj.ls(path) +# obj.mkdir(path) +# obj.addContentToFile(filePath,content) +# param_4 = obj.readContentFromFile(filePath) From 0ff8c88cb049a9c46764c74aabbeaa91bb658219 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 14 Jun 2017 23:50:54 +0800 Subject: [PATCH 3339/4971] Create tag-validator.cpp --- C++/tag-validator.cpp | 75 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 C++/tag-validator.cpp diff --git a/C++/tag-validator.cpp b/C++/tag-validator.cpp new file mode 100644 index 000000000..9e2e66d04 --- /dev/null +++ b/C++/tag-validator.cpp @@ -0,0 +1,75 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + bool isValid(string code) { + auto i = 0; + return validTag(code, &i) && i == code.size(); + } + +private: + bool validTag(const string& s, int *i) { + auto j = *i; + auto tag = parseTagName(s, &j); + if (tag.empty()) { + return false; + } + if (!validContent(s, &j)) { + return false; + } + auto k = j + tag.size() + 2; + if (k >= s.size() || s.substr(j, k + 1 - j) != "") { + return false; + } + *i = k + 1; + return true; + } + + string parseTagName(const string& s, int *i) { + if (s[*i] != '<') { + return ""; + } + auto j = s.find('>', *i); + if (j == string::npos || j - 1 - *i < 1 || 9 < j - 1 - *i) { + return ""; + } + auto tag = s.substr(*i + 1, j - 1 - *i); + for (const auto& c : tag) { + if (c < 'A' || 'Z' < c) { + return ""; + } + } + *i = j + 1; + return tag; + } + + bool validContent(const string& s, int *i) { + auto j = *i; + while (j < s.size()) { + if (!validText(s, &j) && !validCData(s, &j) && !validTag(s, &j)) { + break; + } + } + *i = j; + return true; + } + + bool validText(const string& s, int *i) { + auto j = *i; + *i = s.find("<", *i); + return *i != j; + } + + bool validCData(const string& s, int *i) { + if (s.find("", *i); + if (j == string::npos) { + return false; + } + *i = j + 3; + return true; + } +}; From 8522ad9112aeb3cc3539e2402177d503724b5896 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Jun 2017 00:27:20 +0800 Subject: [PATCH 3340/4971] Create tag-validator.cpp --- C++/tag-validator.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/C++/tag-validator.cpp b/C++/tag-validator.cpp index 9e2e66d04..81fa3da37 100644 --- a/C++/tag-validator.cpp +++ b/C++/tag-validator.cpp @@ -15,9 +15,7 @@ class Solution { if (tag.empty()) { return false; } - if (!validContent(s, &j)) { - return false; - } + parseContent(s, &j); auto k = j + tag.size() + 2; if (k >= s.size() || s.substr(j, k + 1 - j) != "") { return false; @@ -44,7 +42,7 @@ class Solution { return tag; } - bool validContent(const string& s, int *i) { + void parseContent(const string& s, int *i) { auto j = *i; while (j < s.size()) { if (!validText(s, &j) && !validCData(s, &j) && !validTag(s, &j)) { @@ -52,7 +50,6 @@ class Solution { } } *i = j; - return true; } bool validText(const string& s, int *i) { From d1dc47c792d0573aa6234c9221985b6b4cbdbea8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Jun 2017 00:29:03 +0800 Subject: [PATCH 3341/4971] Create tag-validator.cpp --- C++/tag-validator.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/tag-validator.cpp b/C++/tag-validator.cpp index 81fa3da37..c5d39428c 100644 --- a/C++/tag-validator.cpp +++ b/C++/tag-validator.cpp @@ -43,13 +43,11 @@ class Solution { } void parseContent(const string& s, int *i) { - auto j = *i; - while (j < s.size()) { - if (!validText(s, &j) && !validCData(s, &j) && !validTag(s, &j)) { + while (*i < s.size()) { + if (!validText(s, i) && !validCData(s, i) && !validTag(s, i)) { break; } } - *i = j; } bool validText(const string& s, int *i) { From 1c1035eab213cc8fe39596ee6ed32049e08b9a23 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Jun 2017 23:58:55 +0800 Subject: [PATCH 3342/4971] Update tag-validator.cpp --- C++/tag-validator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/tag-validator.cpp b/C++/tag-validator.cpp index c5d39428c..25556dd6e 100644 --- a/C++/tag-validator.cpp +++ b/C++/tag-validator.cpp @@ -5,7 +5,7 @@ class Solution { public: bool isValid(string code) { auto i = 0; - return validTag(code, &i) && i == code.size(); + return validTag(code, &i) && i == code.length(); } private: From 4e9220dac7aaa1ee111ba82417d370d2c45464ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Jun 2017 20:05:24 +0800 Subject: [PATCH 3343/4971] Create tag-validator.py --- Python/tag-validator.py | 133 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 Python/tag-validator.py diff --git a/Python/tag-validator.py b/Python/tag-validator.py new file mode 100644 index 000000000..25946efa0 --- /dev/null +++ b/Python/tag-validator.py @@ -0,0 +1,133 @@ +# Time: O(n) +# Space: O(n) + +# Given a string representing a code snippet, +# you need to implement a tag validator to parse the code and return whether it is valid. +# A code snippet is valid if all the following rules hold: +# +# 1. The code must be wrapped in a valid closed tag. Otherwise, the code is invalid. +# 2. A closed tag (not necessarily valid) has exactly the following format : +# TAG_CONTENT. Among them, is the start tag, +# and is the end tag. The TAG_NAME in start and end tags should be the same. +# A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid. +# 3. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. +# Otherwise, the TAG_NAME is invalid. +# 4. A valid TAG_CONTENT may contain other valid closed tags, +# cdata and any characters (see note1) EXCEPT unmatched <, +# unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. +# Otherwise, the TAG_CONTENT is invalid. +# 5. A start tag is unmatched if no end tag exists with the same TAG_NAME, +# and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. +# 6. A < is unmatched if you cannot find a subsequent >. +# And when you find a < or should be +# parsed as TAG_NAME (not necessarily valid). +# 7. The cdata has the following format : . +# The range of CDATA_CONTENT is defined as the characters between . +# 8. CDATA_CONTENT may contain any characters. +# The function of cdata is to forbid the validator to parse CDATA_CONTENT, +# so even it has some characters that can be parsed as tag (no matter valid or invalid), +# you should treat it as regular characters. +# +# Valid Code Examples: +# Input: "

This is the first line ]]>
" +# Output: True +# Explanation: +# The code is wrapped in a closed tag :
and
. +# The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. +# Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, +# it should be considered as plain text, not parsed as tag. +# So TAG_CONTENT is valid, and then the code is valid. Thus return true. +# +# Input: "
>> ![cdata[]] ]>]]>]]>>]
" +# Output: True +# Explanation: +# We first separate the code into : start_tag|tag_content|end_tag. +# start_tag -> "
" +# end_tag -> "
" +# tag_content could also be separated into : text1|cdata|text2. +# text1 -> ">> ![cdata[]] " +# cdata -> "]>]]>", where the CDATA_CONTENT is "
]>" +# text2 -> "]]>>]" +# +# The reason why start_tag is NOT "
>>" is because of the rule 6. +# The reason why cdata is NOT "]>]]>]]>" is because of the rule 7. +# Invalid Code Examples: +# Input: " " +# Output: False +# Explanation: Unbalanced. If "" is closed, then "" must be unmatched, and vice versa. +# +# Input: "
div tag is not closed
" +# Output: False +# +# Input: "
unmatched <
" +# Output: False +# +# Input: "
closed tags with invalid tag name 123
" +# Output: False +# +# Input: "
unmatched tags with invalid tag name and
" +# Output: False +# +# Input: "
unmatched start tag and unmatched end tag
" +# Output: False +# Note: +# For simplicity, you could assume the input code (including the any characters mentioned above) +# only contain letters, digits, '<','>','/','!','[',']' and ' '. + +class Solution(object): + def isValid(self, code): + """ + :type code: str + :rtype: bool + """ + def validText(s, i): + j = i + i = s.find("<", i) + return i != j, i + + def validCData(s, i): + if s.find("", i) + if j == -1: + return False, i + return True, j+3 + + def parseTagName(s, i): + if s[i] != '<': + return "", i + j = s.find('>', i) + if j == -1 or not (1 <= (j-1-i) <= 9): + return "", i + tag = s[i+1:j] + for c in tag: + if not (ord('A') <= ord(c) <= ord('Z')): + return "", i + return tag, j+1 + + def parseContent(s, i): + while i < len(s): + result, i = validText(s, i) + if result: + continue + result, i = validCData(s, i) + if result: + continue + result, i = validTag(s, i) + if result: + continue + break + return i + + def validTag(s, i): + tag, j = parseTagName(s, i) + if not tag: + return False, i + j = parseContent(s, j) + k = j + len(tag) + 2 + if k >= len(s) or s[j:k+1] != "": + return False, i + return True, k+1 + + result, i = validTag(code, 0) + return result and i == len(code) From 7ca9f6ced81cfb853170f615fb243155502fc492 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Jun 2017 20:16:38 +0800 Subject: [PATCH 3344/4971] Create fraction-addition-and-subtraction.cpp --- C++/fraction-addition-and-subtraction.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/fraction-addition-and-subtraction.cpp diff --git a/C++/fraction-addition-and-subtraction.cpp b/C++/fraction-addition-and-subtraction.cpp new file mode 100644 index 000000000..3c1bb0230 --- /dev/null +++ b/C++/fraction-addition-and-subtraction.cpp @@ -0,0 +1,19 @@ +// Time: O(nlogx), x is the max denominator +// Space: O(n) + +class Solution { +public: + string fractionAddition(string expression) { + istringstream iss(expression); + int A = 0, B = 1, a, b; + char _; + while (iss >> a >> _ >> b) { + A = A * b + a * B; + B *= b; + auto g = abs(__gcd(A, B)); + A /= g; + B /= g; + } + return to_string(A) + '/' + to_string(B); + } +}; From d6e581608507b028b566f5bf830acc9bdc0ec907 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Jun 2017 20:27:40 +0800 Subject: [PATCH 3345/4971] Create fraction-addition-and-subtraction.py --- Python/fraction-addition-and-subtraction.py | 54 +++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/fraction-addition-and-subtraction.py diff --git a/Python/fraction-addition-and-subtraction.py b/Python/fraction-addition-and-subtraction.py new file mode 100644 index 000000000..9e28116a9 --- /dev/null +++ b/Python/fraction-addition-and-subtraction.py @@ -0,0 +1,54 @@ +# Time: O(nlogx), x is the max denominator +# Space: O(n) + +# Given a string representing an expression of fraction addition and subtraction, +# you need to return the calculation result in string format. +# The final result should be irreducible fraction. If your final result is an integer, say 2, +# you need to change it to the format of fraction that has denominator 1. +# So in this case, 2 should be converted to 2/1. +# +# Example 1: +# Input:"-1/2+1/2" +# Output: "0/1" +# Example 2: +# Input:"-1/2+1/2+1/3" +# Output: "1/3" +# Example 3: +# Input:"1/3-1/2" +# Output: "-1/6" +# Example 4: +# Input:"5/3+1/3" +# Output: "2/1" +# Note: +# The input string only contains '0' to '9', '/', '+' and '-'. So does the output. +# Each fraction (input and output) has format ±numerator/denominator. +# If the first input fraction or the output is positive, then '+' will be omitted. +# The input only contains valid irreducible fractions, +# where the numerator and denominator of each fraction will +# always be in the range [1,10]. If the denominator is 1, +# it means this fraction is actually an integer in a fraction format defined above. +# The number of given fractions will be in the range [1,10]. +# The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int. + +class Solution(object): + def fractionAddition(self, expression): + """ + :type expression: str + :rtype: str + """ + def gcd(a, b): + while b: + a, b = b, a%b + return a + + ints = map(int, re.findall('[+-]?\d+', expression)) + print ints + A, B = 0, 1 + for i in xrange(0, len(ints), 2): + a, b = ints[i], ints[i+1] + A = A * b + a * B + B *= b + g = gcd(A, B) + A //= g + B //= g + return '%d/%d' % (A, B) From 76996253b45ff41dbd40783a1c7a2fc9f8e75f30 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Jun 2017 20:28:46 +0800 Subject: [PATCH 3346/4971] Update fraction-addition-and-subtraction.py --- Python/fraction-addition-and-subtraction.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/fraction-addition-and-subtraction.py b/Python/fraction-addition-and-subtraction.py index 9e28116a9..cd51acb8e 100644 --- a/Python/fraction-addition-and-subtraction.py +++ b/Python/fraction-addition-and-subtraction.py @@ -42,7 +42,6 @@ def gcd(a, b): return a ints = map(int, re.findall('[+-]?\d+', expression)) - print ints A, B = 0, 1 for i in xrange(0, len(ints), 2): a, b = ints[i], ints[i+1] From 2f76228dc8e5ea42387fe3c6323e744ffb85004b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Jun 2017 22:53:05 +0800 Subject: [PATCH 3347/4971] Create valid-square.cpp --- C++/valid-square.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/valid-square.cpp diff --git a/C++/valid-square.cpp b/C++/valid-square.cpp new file mode 100644 index 000000000..8d684f9c2 --- /dev/null +++ b/C++/valid-square.cpp @@ -0,0 +1,18 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) { + unordered_set s({ d(p1, p2), d(p1, p3), + d(p1, p4), d(p2, p3), + d(p2, p4), d(p3, p4) }); + return !s.count(0) && s.size() == 2; + } + +private: + int d(vector& p1, vector& p2) { + return (p1[0] - p2[0]) * (p1[0] - p2[0]) + + (p1[1] - p2[1]) * (p1[1] - p2[1]); + } +}; From 4505859c2114517484455225aa44ee48497d0cef Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Jun 2017 23:01:49 +0800 Subject: [PATCH 3348/4971] Update valid-square.cpp --- C++/valid-square.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/valid-square.cpp b/C++/valid-square.cpp index 8d684f9c2..773edf5c7 100644 --- a/C++/valid-square.cpp +++ b/C++/valid-square.cpp @@ -4,14 +4,14 @@ class Solution { public: bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) { - unordered_set s({ d(p1, p2), d(p1, p3), - d(p1, p4), d(p2, p3), - d(p2, p4), d(p3, p4) }); - return !s.count(0) && s.size() == 2; + unordered_set counter({ dist(p1, p2), dist(p1, p3), + dist(p1, p4), dist(p2, p3), + dist(p2, p4), dist(p3, p4) }); + return !counter.count(0) && counter.size() == 2; } private: - int d(vector& p1, vector& p2) { + int dist(vector& p1, vector& p2) { return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]); } From b7f9bbd7afd64c702a2ea296b9e47cb5f563a4a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Jun 2017 23:01:59 +0800 Subject: [PATCH 3349/4971] Create valid-square.py --- Python/valid-square.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/valid-square.py diff --git a/Python/valid-square.py b/Python/valid-square.py new file mode 100644 index 000000000..dfcc55ba3 --- /dev/null +++ b/Python/valid-square.py @@ -0,0 +1,34 @@ +# Time: O(1) +# Space: O(1) + +# Given the coordinates of four points in 2D space, +# return whether the four points could construct a square. +# +# The coordinate (x,y) of a point is represented by an integer array with two integers. +# +# Example: +# Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] +# Output: True +# Note: +# +# All the input integers are in the range [-10000, 10000]. +# A valid square has four equal sides with positive length +# and four equal angles (90-degree angles). +# Input points have no order. + +class Solution(object): + def validSquare(self, p1, p2, p3, p4): + """ + :type p1: List[int] + :type p2: List[int] + :type p3: List[int] + :type p4: List[int] + :rtype: bool + """ + def dist(p1, p2): + return (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 + + counter = collections.Counter([dist(p1, p2), dist(p1, p3),\ + dist(p1, p4), dist(p2, p3),\ + dist(p2, p4), dist(p3, p4)]) + return 0 not in counter and len(counter) == 2 From 48f860d7cc1830c4f0e59ba2b76a940c6e4b72e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Jun 2017 23:03:21 +0800 Subject: [PATCH 3350/4971] Update valid-square.py --- Python/valid-square.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/valid-square.py b/Python/valid-square.py index dfcc55ba3..a70ce921c 100644 --- a/Python/valid-square.py +++ b/Python/valid-square.py @@ -31,4 +31,4 @@ def dist(p1, p2): counter = collections.Counter([dist(p1, p2), dist(p1, p3),\ dist(p1, p4), dist(p2, p3),\ dist(p2, p4), dist(p3, p4)]) - return 0 not in counter and len(counter) == 2 + return counter[0] == 0 and len(counter) == 2 From d5daa234cd4d52abce7d12c5fd1479b2bfd88fde Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Jun 2017 23:04:57 +0800 Subject: [PATCH 3351/4971] Update valid-square.py --- Python/valid-square.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/valid-square.py b/Python/valid-square.py index a70ce921c..a3855abbc 100644 --- a/Python/valid-square.py +++ b/Python/valid-square.py @@ -28,7 +28,7 @@ def validSquare(self, p1, p2, p3, p4): def dist(p1, p2): return (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 - counter = collections.Counter([dist(p1, p2), dist(p1, p3),\ - dist(p1, p4), dist(p2, p3),\ - dist(p2, p4), dist(p3, p4)]) - return counter[0] == 0 and len(counter) == 2 + lookup = set([dist(p1, p2), dist(p1, p3),\ + dist(p1, p4), dist(p2, p3),\ + dist(p2, p4), dist(p3, p4)]) + return 0 not in lookup and len(lookup) == 2 From 8d4d1ce6b9d507892a4ad1ce3fcd34b420216181 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Jun 2017 23:05:37 +0800 Subject: [PATCH 3352/4971] Update valid-square.cpp --- C++/valid-square.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/valid-square.cpp b/C++/valid-square.cpp index 773edf5c7..54d7d3d83 100644 --- a/C++/valid-square.cpp +++ b/C++/valid-square.cpp @@ -4,10 +4,10 @@ class Solution { public: bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) { - unordered_set counter({ dist(p1, p2), dist(p1, p3), - dist(p1, p4), dist(p2, p3), - dist(p2, p4), dist(p3, p4) }); - return !counter.count(0) && counter.size() == 2; + unordered_set lookup({ dist(p1, p2), dist(p1, p3), + dist(p1, p4), dist(p2, p3), + dist(p2, p4), dist(p3, p4) }); + return !lookup.count(0) && lookup.size() == 2; } private: From 025aca09214b0f66c526bd4b6436b713ee0314a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Jun 2017 22:42:40 +0800 Subject: [PATCH 3353/4971] Create longest-harmonious-subsequence.cpp --- C++/longest-harmonious-subsequence.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/longest-harmonious-subsequence.cpp diff --git a/C++/longest-harmonious-subsequence.cpp b/C++/longest-harmonious-subsequence.cpp new file mode 100644 index 000000000..948e5a6ce --- /dev/null +++ b/C++/longest-harmonious-subsequence.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int findLHS(vector& nums) { + unordered_map lookup; + auto result = 0; + for (const auto& num: nums) { + ++lookup[num]; + for (const auto& diff : {-1, 1}) { + if (lookup.count(num + diff)) { + result = max(result, lookup[num] + lookup[num + diff]); + } + } + } + return result; + } +}; From 12f7dddcbe8c7c2160bf8de8f7a9c3082b950003 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Jun 2017 22:45:24 +0800 Subject: [PATCH 3354/4971] Create longest-harmonious-subsequence.py --- Python/longest-harmonious-subsequence.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/longest-harmonious-subsequence.py diff --git a/Python/longest-harmonious-subsequence.py b/Python/longest-harmonious-subsequence.py new file mode 100644 index 000000000..f7511c0de --- /dev/null +++ b/Python/longest-harmonious-subsequence.py @@ -0,0 +1,17 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def findLHS(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + lookup = collections.defaultdict(int) + result = 0 + for num in nums: + lookup[num] += 1 + for diff in [-1, 1]: + if (num + diff) in lookup: + result = max(result, lookup[num] + lookup[num + diff]) + return result From e136a60b6bad14b0cef5fc5cd6f8386154d35c28 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Jun 2017 22:46:07 +0800 Subject: [PATCH 3355/4971] Update longest-harmonious-subsequence.py --- Python/longest-harmonious-subsequence.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Python/longest-harmonious-subsequence.py b/Python/longest-harmonious-subsequence.py index f7511c0de..585179747 100644 --- a/Python/longest-harmonious-subsequence.py +++ b/Python/longest-harmonious-subsequence.py @@ -1,6 +1,18 @@ # Time: O(n) # Space: O(n) +# We define a harmonious array is an array where the difference +# between its maximum value and its minimum value is exactly 1. +# +# Now, given an integer array, you need to find the length of its +# longest harmonious subsequence among all its possible subsequences. +# +# Example 1: +# Input: [1,3,2,2,5,2,3,7] +# Output: 5 +# Explanation: The longest harmonious subsequence is [3,2,2,2,3]. +# Note: The length of the input array will not exceed 20,000. + class Solution(object): def findLHS(self, nums): """ From a1b1a1dd00a96dc41252f0592dae10d14c918185 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Jun 2017 22:46:34 +0800 Subject: [PATCH 3356/4971] Update longest-harmonious-subsequence.cpp --- C++/longest-harmonious-subsequence.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-harmonious-subsequence.cpp b/C++/longest-harmonious-subsequence.cpp index 948e5a6ce..d8a4f9e03 100644 --- a/C++/longest-harmonious-subsequence.cpp +++ b/C++/longest-harmonious-subsequence.cpp @@ -6,7 +6,7 @@ class Solution { int findLHS(vector& nums) { unordered_map lookup; auto result = 0; - for (const auto& num: nums) { + for (const auto& num : nums) { ++lookup[num]; for (const auto& diff : {-1, 1}) { if (lookup.count(num + diff)) { From 0408bb63c55c30ccf7253b385853f33a1f11dc48 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Jun 2017 22:50:50 +0800 Subject: [PATCH 3357/4971] Create range-addition-ii.cpp --- C++/range-addition-ii.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/range-addition-ii.cpp diff --git a/C++/range-addition-ii.cpp b/C++/range-addition-ii.cpp new file mode 100644 index 000000000..e0870df7b --- /dev/null +++ b/C++/range-addition-ii.cpp @@ -0,0 +1,13 @@ +// Time: O(p), p is the number of ops +// Space: O(1) + +class Solution { +public: + int maxCount(int m, int n, vector>& ops) { + for (const auto& op : ops) { + m = min(m, op[0]); + n = min(n, op[1]); + } + return m*n; + } +}; From 4a62def50a5068c7c804a63d6ef45032a251ad54 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Jun 2017 22:53:16 +0800 Subject: [PATCH 3358/4971] Create range-addition-ii.py --- Python/range-addition-ii.py | 51 +++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/range-addition-ii.py diff --git a/Python/range-addition-ii.py b/Python/range-addition-ii.py new file mode 100644 index 000000000..e63e660d6 --- /dev/null +++ b/Python/range-addition-ii.py @@ -0,0 +1,51 @@ +# Time: O(p), p is the number of ops +# Space: O(1) + +# Given an m * n matrix M initialized with all 0's and several update operations. +# +# Operations are represented by a 2D array, +# and each operation is represented by an array with two positive integers a and b, +# which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b. +# +# You need to count and return the number of maximum integers +# in the matrix after performing all the operations. +# +# Example 1: +# Input: +# m = 3, n = 3 +# operations = [[2,2],[3,3]] +# Output: 4 +# Explanation: +# Initially, M = +# [[0, 0, 0], +# [0, 0, 0], +# [0, 0, 0]] +# +# After performing [2,2], M = +# [[1, 1, 0], +# [1, 1, 0], +# [0, 0, 0]] +# +# After performing [3,3], M = +# [[2, 2, 1], +# [2, 2, 1], +# [1, 1, 1]] +# +# So the maximum integer in M is 2, and there are four of it in M. So return 4. +# Note: +# The range of m and n is [1,40000]. +# The range of a is [1,m], and the range of b is [1,n]. +# The range of operations size won't exceed 10,000. + +class Solution(object): + def maxCount(self, m, n, ops): + """ + :type m: int + :type n: int + :type ops: List[List[int]] + :rtype: int + """ + for op in ops: + m = min(m, op[0]) + n = min(n, op[1]) + return m*n From d1556445581983328389f14567a0243f401592f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Jun 2017 22:53:39 +0800 Subject: [PATCH 3359/4971] Update range-addition-ii.cpp --- C++/range-addition-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/range-addition-ii.cpp b/C++/range-addition-ii.cpp index e0870df7b..e9218c9d4 100644 --- a/C++/range-addition-ii.cpp +++ b/C++/range-addition-ii.cpp @@ -8,6 +8,6 @@ class Solution { m = min(m, op[0]); n = min(n, op[1]); } - return m*n; + return m * n; } }; From f9950636c5661d81070159ec5c4b34dc5e7c4012 Mon Sep 17 00:00:00 2001 From: Brijesh Rakholia Date: Tue, 20 Jun 2017 20:29:03 -0400 Subject: [PATCH 3360/4971] Added a check for tabs Whitespace can be of any type - space or tabs. --- C++/string-to-integer-atoi.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/string-to-integer-atoi.cpp b/C++/string-to-integer-atoi.cpp index f82d208a6..c8de958d5 100644 --- a/C++/string-to-integer-atoi.cpp +++ b/C++/string-to-integer-atoi.cpp @@ -12,8 +12,8 @@ class Solution { int sign = 1; int i = 0; - // Skip ' '. - while (str[i] == ' ') { + // Skip whitespace. + while (str[i] == ' ' || str[i] == '\t') { ++i; } From 819a400b0d2b9deaf554bd0f8951eb6ad1d75305 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jun 2017 21:43:03 +0800 Subject: [PATCH 3361/4971] Create minimum-index-sum-of-two-lists.cpp --- C++/minimum-index-sum-of-two-lists.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/minimum-index-sum-of-two-lists.cpp diff --git a/C++/minimum-index-sum-of-two-lists.cpp b/C++/minimum-index-sum-of-two-lists.cpp new file mode 100644 index 000000000..92d67ece1 --- /dev/null +++ b/C++/minimum-index-sum-of-two-lists.cpp @@ -0,0 +1,26 @@ +// Time: O(m * n), m is the size of list1, n is the size of list2 +// Space: O(m * l), l is the average string length + +class Solution { +public: + vector findRestaurant(vector& list1, vector& list2) { + unordered_map lookup; + for (int i = 0; i < list1.size(); ++i) { + lookup[list1[i]] = i; + } + vector result; + int min_sum = numeric_limits::max(); + for (int j = 0; j < list2.size() && j <= min_sum; ++j) { + if (lookup.count(list2[j])) { + auto sum = j + lookup[list2[j]]; + if (sum < min_sum) { + result.clear(); + result.emplace_back(list2[j]); + min_sum = sum; + } else if (sum == min_sum) + result.emplace_back(list2[j]); + } + } + return result; + } +}; From 68ef7ec3e0fd6ad6ab2179a7207f7f0c58f935e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jun 2017 21:49:47 +0800 Subject: [PATCH 3362/4971] Update string-to-integer-atoi.py --- Python/string-to-integer-atoi.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/string-to-integer-atoi.py b/Python/string-to-integer-atoi.py index 970fd09b6..87cb1c4ba 100644 --- a/Python/string-to-integer-atoi.py +++ b/Python/string-to-integer-atoi.py @@ -40,7 +40,7 @@ def myAtoi(self, str): return result i = 0 - while i < len(str) and str[i] == " ": + while i < len(str) and str[i].isspace(): i += 1 sign = 1 From d28596223e8615ab309db784018d85f0f9a65d2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Jun 2017 21:59:10 +0800 Subject: [PATCH 3363/4971] Create minimum-index-sum-of-two-lists.py --- Python/minimum-index-sum-of-two-lists.py | 51 ++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/minimum-index-sum-of-two-lists.py diff --git a/Python/minimum-index-sum-of-two-lists.py b/Python/minimum-index-sum-of-two-lists.py new file mode 100644 index 000000000..5be1ae654 --- /dev/null +++ b/Python/minimum-index-sum-of-two-lists.py @@ -0,0 +1,51 @@ +# Time: O(m * n), m is the size of list1, n is the size of list2 +# Space: O(m * l), l is the max length of string + +# Suppose Andy and Doris want to choose a restaurant for dinner, +# and they both have a list of favorite restaurants represented by strings. +# +# You need to help them find out their common interest with the least list index sum. +# If there is a choice tie between answers, output all of them with no order requirement. +# You could assume there always exists an answer. +# +# Example 1: +# Input: +# ["Shogun", "Tapioca Express", "Burger King", "KFC"] +# ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] +# Output: ["Shogun"] +# Explanation: The only restaurant they both like is "Shogun". +# Example 2: +# Input: +# ["Shogun", "Tapioca Express", "Burger King", "KFC"] +# ["KFC", "Shogun", "Burger King"] +# Output: ["Shogun"] +# Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1). +# Note: +# The length of both lists will be in the range of [1, 1000]. +# The length of strings in both lists will be in the range of [1, 30]. +# The index is starting from 0 to the list length minus 1. +# No duplicates in both lists. + +class Solution(object): + def findRestaurant(self, list1, list2): + """ + :type list1: List[str] + :type list2: List[str] + :rtype: List[str] + """ + lookup = {} + for i, s in enumerate(list1): + lookup[s] = i + + result = [] + min_sum = float("inf") + for j, s in enumerate(list2): + if j > min_sum: + break + if s in lookup: + if j + lookup[s] < min_sum: + result = [s] + min_sum = j + lookup[s] + elif j + lookup[s] == min_sum: + result.append(s) + return result From 02123ba2e4e72c3c366d284595e37bf437eed8ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jun 2017 21:15:23 +0800 Subject: [PATCH 3364/4971] Create non-negative-integers-without-consecutive-ones.cpp --- ...tive-integers-without-consecutive-ones.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C /non-negative-integers-without-consecutive-ones.cpp diff --git a/C /non-negative-integers-without-consecutive-ones.cpp b/C /non-negative-integers-without-consecutive-ones.cpp new file mode 100644 index 000000000..15106151f --- /dev/null +++ b/C /non-negative-integers-without-consecutive-ones.cpp @@ -0,0 +1,28 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int findIntegers(int num) { + vector dp(32); + dp[0] = 1; + dp[1] = 2; + for (int i = 2; i < dp.size(); ++i) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + int i = 30, sum = 0, prev_bit = 0; + for (int i = 30; i >= 0; --i) { + if ((num & (1 << i)) != 0) { + sum += dp[i]; + if (prev_bit == 1) { + --sum; + break; + } + prev_bit = 1; + } else { + prev_bit = 0; + } + } + return sum + 1; + } +}; From afe05c6ba05b3e52aa833f2d0723fbffa0da0b36 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jun 2017 21:17:46 +0800 Subject: [PATCH 3365/4971] Update non-negative-integers-without-consecutive-ones.cpp --- C /non-negative-integers-without-consecutive-ones.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C /non-negative-integers-without-consecutive-ones.cpp b/C /non-negative-integers-without-consecutive-ones.cpp index 15106151f..2d5e08c9c 100644 --- a/C /non-negative-integers-without-consecutive-ones.cpp +++ b/C /non-negative-integers-without-consecutive-ones.cpp @@ -10,12 +10,12 @@ class Solution { for (int i = 2; i < dp.size(); ++i) { dp[i] = dp[i - 1] + dp[i - 2]; } - int i = 30, sum = 0, prev_bit = 0; + int result = 0, prev_bit = 0; for (int i = 30; i >= 0; --i) { if ((num & (1 << i)) != 0) { - sum += dp[i]; + result += dp[i]; if (prev_bit == 1) { - --sum; + --result; break; } prev_bit = 1; @@ -23,6 +23,6 @@ class Solution { prev_bit = 0; } } - return sum + 1; + return result + 1; } }; From 1bad2c344cb29c9d33a1e1c5e0734f1e512b96ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jun 2017 21:18:00 +0800 Subject: [PATCH 3366/4971] Update non-negative-integers-without-consecutive-ones.cpp --- C /non-negative-integers-without-consecutive-ones.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C /non-negative-integers-without-consecutive-ones.cpp b/C /non-negative-integers-without-consecutive-ones.cpp index 2d5e08c9c..02fbe7862 100644 --- a/C /non-negative-integers-without-consecutive-ones.cpp +++ b/C /non-negative-integers-without-consecutive-ones.cpp @@ -1,4 +1,4 @@ -// Time: O(1) +// Time: O(1) // Space: O(1) class Solution { From d63be7c01a1bd6c25f57febe8da8dcb168f7c2cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Jun 2017 21:20:24 +0800 Subject: [PATCH 3367/4971] Create non-negative-integers-without-consecutive-ones.py --- ...ative-integers-without-consecutive-ones.py | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/non-negative-integers-without-consecutive-ones.py diff --git a/Python/non-negative-integers-without-consecutive-ones.py b/Python/non-negative-integers-without-consecutive-ones.py new file mode 100644 index 000000000..37d59f055 --- /dev/null +++ b/Python/non-negative-integers-without-consecutive-ones.py @@ -0,0 +1,41 @@ +# Time: O(1) +# Space: O(1) + +# Given a positive integer n, find the number of non-negative integers less than +# or equal to n, whose binary representations do NOT contain consecutive ones. +# +# Example 1: +# Input: 5 +# Output: 5 +# Explanation: +# Here are the non-negative integers <= 5 with their corresponding binary representations: +# 0 : 0 +# 1 : 1 +# 2 : 10 +# 3 : 11 +# 4 : 100 +# 5 : 101 +# Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. +# Note: 1 <= n <= 10^9 + +class Solution(object): + def findIntegers(self, num): + """ + :type num: int + :rtype: int + """ + dp = [0] * 32 + dp[0], dp[1] = 1, 2 + for i in xrange(2, len(dp)): + dp[i] = dp[i-1] + dp[i-2] + result, prev_bit = 0, 0 + for i in reversed(xrange(31)): + if (num & (1 << i)) != 0: + result += dp[i] + if prev_bit == 1: + result -= 1 + break + prev_bit = 1 + else: + prev_bit = 0 + return result + 1 From 47ab2f990542cef2ba2763ad3bf724d51aad7e44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Jun 2017 23:30:57 +0800 Subject: [PATCH 3368/4971] Create design-compressed-string-iterator.cpp --- C /design-compressed-string-iterator.cpp | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C /design-compressed-string-iterator.cpp diff --git a/C /design-compressed-string-iterator.cpp b/C /design-compressed-string-iterator.cpp new file mode 100644 index 000000000..729715b34 --- /dev/null +++ b/C /design-compressed-string-iterator.cpp @@ -0,0 +1,39 @@ +// Time: O(1) +// Space: O(1) + +class StringIterator { +public: + StringIterator(string compresult_sedString) + : result_(compresult_sedString), + num_(0), + ch_(' ') { + + } + + char next() { + if (!hasNext()) { + return ' '; + } + if (num_ == 0) { + result_ >> ch_ >> num_; + } + --num_; + return ch_; + } + + bool hasNext() { + return !result_.eof() || num_ != 0; + } + +private: + istringstream result_; + int num_; + char ch_; +}; + +/** + * Your StringIterator object will be instantiated and called as such_: + * StringIterator obj = new StringIterator(compresult_sedString); + * ch_ar param_1 = obj.next(); + * bool param_2 = obj.hasNext(); + */ From e3b8663a4a6b119545d70b61508c2f4a730bfcd6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Jun 2017 23:43:45 +0800 Subject: [PATCH 3369/4971] Create design-compressed-string-iterator.py --- Python/design-compressed-string-iterator.py | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/design-compressed-string-iterator.py diff --git a/Python/design-compressed-string-iterator.py b/Python/design-compressed-string-iterator.py new file mode 100644 index 000000000..162840d79 --- /dev/null +++ b/Python/design-compressed-string-iterator.py @@ -0,0 +1,38 @@ +# Time: O(1) +# Space: O(1) + +class StringIterator(object): + + def __init__(self, compressedString): + """ + :type compressedString: str + """ + self.__result = re.findall(r"([a-zA-Z])(\d+)", compressedString) + self.__index, self.__num, self.__ch = 0, 0, ' ' + + def next(self): + """ + :rtype: str + """ + if not self.hasNext(): + return ' ' + if self.__num == 0: + self.__ch = self.__result[self.__index][0] + self.__num = int(self.__result[self.__index][1]) + self.__index += 1 + self.__num -= 1 + return self.__ch + + + def hasNext(self): + """ + :rtype: bool + """ + return self.__index != len(self.__result) or self.__num != 0 + + + +# Your StringIterator object will be instantiated and called as such: +# obj = StringIterator(compressedString) +# param_1 = obj.next() +# param_2 = obj.hasNext() From 25a15eb9e0bd531be8e14636386b02484b875fe1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Jun 2017 23:46:01 +0800 Subject: [PATCH 3370/4971] Delete non-negative-integers-without-consecutive-ones.cpp --- ...tive-integers-without-consecutive-ones.cpp | 28 ------------------- 1 file changed, 28 deletions(-) delete mode 100644 C /non-negative-integers-without-consecutive-ones.cpp diff --git a/C /non-negative-integers-without-consecutive-ones.cpp b/C /non-negative-integers-without-consecutive-ones.cpp deleted file mode 100644 index 02fbe7862..000000000 --- a/C /non-negative-integers-without-consecutive-ones.cpp +++ /dev/null @@ -1,28 +0,0 @@ -// Time: O(1) -// Space: O(1) - -class Solution { -public: - int findIntegers(int num) { - vector dp(32); - dp[0] = 1; - dp[1] = 2; - for (int i = 2; i < dp.size(); ++i) { - dp[i] = dp[i - 1] + dp[i - 2]; - } - int result = 0, prev_bit = 0; - for (int i = 30; i >= 0; --i) { - if ((num & (1 << i)) != 0) { - result += dp[i]; - if (prev_bit == 1) { - --result; - break; - } - prev_bit = 1; - } else { - prev_bit = 0; - } - } - return result + 1; - } -}; From cb6e588534cf3ef9e01bed0a025581ccaa21ffe2 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Fri, 23 Jun 2017 23:46:36 +0800 Subject: [PATCH 3371/4971] update --- C++/design-compressed-string-iterator.cpp | 39 +++++++++++++++++++ ...tive-integers-without-consecutive-ones.cpp | 28 +++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 C++/design-compressed-string-iterator.cpp create mode 100644 C++/non-negative-integers-without-consecutive-ones.cpp diff --git a/C++/design-compressed-string-iterator.cpp b/C++/design-compressed-string-iterator.cpp new file mode 100644 index 000000000..729715b34 --- /dev/null +++ b/C++/design-compressed-string-iterator.cpp @@ -0,0 +1,39 @@ +// Time: O(1) +// Space: O(1) + +class StringIterator { +public: + StringIterator(string compresult_sedString) + : result_(compresult_sedString), + num_(0), + ch_(' ') { + + } + + char next() { + if (!hasNext()) { + return ' '; + } + if (num_ == 0) { + result_ >> ch_ >> num_; + } + --num_; + return ch_; + } + + bool hasNext() { + return !result_.eof() || num_ != 0; + } + +private: + istringstream result_; + int num_; + char ch_; +}; + +/** + * Your StringIterator object will be instantiated and called as such_: + * StringIterator obj = new StringIterator(compresult_sedString); + * ch_ar param_1 = obj.next(); + * bool param_2 = obj.hasNext(); + */ diff --git a/C++/non-negative-integers-without-consecutive-ones.cpp b/C++/non-negative-integers-without-consecutive-ones.cpp new file mode 100644 index 000000000..02fbe7862 --- /dev/null +++ b/C++/non-negative-integers-without-consecutive-ones.cpp @@ -0,0 +1,28 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int findIntegers(int num) { + vector dp(32); + dp[0] = 1; + dp[1] = 2; + for (int i = 2; i < dp.size(); ++i) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + int result = 0, prev_bit = 0; + for (int i = 30; i >= 0; --i) { + if ((num & (1 << i)) != 0) { + result += dp[i]; + if (prev_bit == 1) { + --result; + break; + } + prev_bit = 1; + } else { + prev_bit = 0; + } + } + return result + 1; + } +}; From fbdf5cc2a40b28289a815a3f2504a35c6dd169e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Jun 2017 23:47:05 +0800 Subject: [PATCH 3372/4971] Delete design-compressed-string-iterator.cpp --- C /design-compressed-string-iterator.cpp | 39 ----------------------- 1 file changed, 39 deletions(-) delete mode 100644 C /design-compressed-string-iterator.cpp diff --git a/C /design-compressed-string-iterator.cpp b/C /design-compressed-string-iterator.cpp deleted file mode 100644 index 729715b34..000000000 --- a/C /design-compressed-string-iterator.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// Time: O(1) -// Space: O(1) - -class StringIterator { -public: - StringIterator(string compresult_sedString) - : result_(compresult_sedString), - num_(0), - ch_(' ') { - - } - - char next() { - if (!hasNext()) { - return ' '; - } - if (num_ == 0) { - result_ >> ch_ >> num_; - } - --num_; - return ch_; - } - - bool hasNext() { - return !result_.eof() || num_ != 0; - } - -private: - istringstream result_; - int num_; - char ch_; -}; - -/** - * Your StringIterator object will be instantiated and called as such_: - * StringIterator obj = new StringIterator(compresult_sedString); - * ch_ar param_1 = obj.next(); - * bool param_2 = obj.hasNext(); - */ From c1b2dc745c909c4b211b3734e1c2ddc7bff9fefb Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 24 Jun 2017 20:45:34 +0800 Subject: [PATCH 3373/4971] update --- C++/can-place-flowers.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/can-place-flowers.cpp diff --git a/C++/can-place-flowers.cpp b/C++/can-place-flowers.cpp new file mode 100644 index 000000000..b9b29bab5 --- /dev/null +++ b/C++/can-place-flowers.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool canPlaceFlowers(vector& flowerbed, int n) { + for (int i = 0; i < flowerbed.size(); ++i) { + if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && + (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) { + flowerbed[i] = 1; + --n; + } + if (n <= 0) { + return true; + } + } + return false; + } +}; + From 0776f2a2b60952a5d4a918fd6b802c1a98acf5f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 24 Jun 2017 20:59:36 +0800 Subject: [PATCH 3374/4971] Create can-place-flowers.py --- Python/can-place-flowers.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/can-place-flowers.py diff --git a/Python/can-place-flowers.py b/Python/can-place-flowers.py new file mode 100644 index 000000000..343a031c2 --- /dev/null +++ b/Python/can-place-flowers.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(1) + +# Suppose you have a long flowerbed in which some of the plots are planted and some are not. +# However, flowers cannot be planted in adjacent plots - they would compete for water +# and both would die. +# +# Given a flowerbed (represented as an array containing 0 and 1, +# where 0 means empty and 1 means not empty), and a number n, +# return if n new flowers can be planted in it without violating the no-adjacent-flowers rule. +# +# Example 1: +# Input: flowerbed = [1,0,0,0,1], n = 1 +# Output: True +# Example 2: +# Input: flowerbed = [1,0,0,0,1], n = 2 +# Output: False +# Note: +# The input array won't violate no-adjacent-flowers rule. +# The input array size is in the range of [1, 20000]. +# n is a non-negative integer which won't exceed the input array size. + +class Solution(object): + def canPlaceFlowers(self, flowerbed, n): + """ + :type flowerbed: List[int] + :type n: int + :rtype: bool + """ + for i in xrange(len(flowerbed)): + if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and \ + (i == len(flowerbed)-1 or flowerbed[i+1] == 0): + flowerbed[i] = 1 + n -= 1 + if n <= 0: + return True + return False From f78cafc4a033fff480d7e19182c58494fe921d57 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 25 Jun 2017 23:53:36 +0800 Subject: [PATCH 3375/4971] add --- C++/construct-string-from-binary-tree.cpp | 32 +++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/construct-string-from-binary-tree.cpp diff --git a/C++/construct-string-from-binary-tree.cpp b/C++/construct-string-from-binary-tree.cpp new file mode 100644 index 000000000..36d5fe510 --- /dev/null +++ b/C++/construct-string-from-binary-tree.cpp @@ -0,0 +1,32 @@ +// 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: + string tree2str(TreeNode* t) { + if (!t) { + return ""; + } + + auto s = to_string(t->val); + + if (t->left || t->right) { + s += "(" + tree2str(t->left) + ")"; + } + + if (t->right) { + s += "(" + tree2str(t->right) + ")"; + } + + return s; + } +}; From 6c0959af78d3ce78b5565d1ceca0e2d984c542f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Jun 2017 00:01:21 +0800 Subject: [PATCH 3376/4971] Create construct-string-from-binary-tree.py --- Python/construct-string-from-binary-tree.py | 58 +++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Python/construct-string-from-binary-tree.py diff --git a/Python/construct-string-from-binary-tree.py b/Python/construct-string-from-binary-tree.py new file mode 100644 index 000000000..8bba46ba5 --- /dev/null +++ b/Python/construct-string-from-binary-tree.py @@ -0,0 +1,58 @@ +# Time: O(n) +# Space: O(h) + +# You need to construct a string consists of parenthesis and integers from a binary tree with +# the preorder traversing way. +# +# The null node needs to be represented by empty parenthesis pair "()". +# And you need to omit all the empty parenthesis pairs that don't affect +# the one-to-one mapping relationship between the string and the original binary tree. +# +# Example 1: +# Input: Binary tree: [1,2,3,4] +# 1 +# / \ +# 2 3 +# / +# 4 +# +# Output: "1(2(4))(3)" +# +# Explanation: Originallay it needs to be "1(2(4)())(3()())", +# but you need to omit all the unnecessary empty parenthesis pairs. +# And it will be "1(2(4))(3)". +# Example 2: +# Input: Binary tree: [1,2,3,null,4] +# 1 +# / \ +# 2 3 +# \ +# 4 +# +# Output: "1(2()(4))(3)" +# +# Explanation: Almost the same as the first example, +# except we can't omit the first parenthesis pair to break the one-to-one mapping relationship +# between the input and the output. + + +# 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 tree2str(self, t): + """ + :type t: TreeNode + :rtype: str + """ + if not t: return "" + s = str(t.val) + if t.left or t.right: + s += "(" + self.tree2str(t.left) + ")" + if t.right: + s += "(" + self.tree2str(t.right) + ")" + return s From 69f1ec28ca817d4d9f257743b96b408b8aa2ab12 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 26 Jun 2017 22:10:15 +0800 Subject: [PATCH 3377/4971] add --- C++/find-duplicate-file-in-system.cpp | 28 +++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/find-duplicate-file-in-system.cpp diff --git a/C++/find-duplicate-file-in-system.cpp b/C++/find-duplicate-file-in-system.cpp new file mode 100644 index 000000000..fff191f24 --- /dev/null +++ b/C++/find-duplicate-file-in-system.cpp @@ -0,0 +1,28 @@ +// Time: O(n * l), l is the average length of file content +// Space: O(n * l) + +class Solution { +public: + vector> findDuplicate(vector& paths) { + unordered_map> files; + for (const auto& path : paths) { + stringstream ss(path); + string root; + string s; + getline(ss, root, ' '); + while (getline(ss, s, ' ')) { + auto fileName = root + '/' + s.substr(0, s.find('(')); + auto fileContent = s.substr(s.find('(') + 1, s.find(')') - s.find('(') - 1); + files[fileContent].emplace_back(fileName); + } + } + + vector> result; + for (const auto& file : files) { + if (file.second.size() > 1) { + result.emplace_back(file.second); + } + } + return result; + } +}; From 96d89e4398a68aab8df033847a1cf8fa47cef5dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Jun 2017 22:24:28 +0800 Subject: [PATCH 3378/4971] Create find-duplicate-file-in-system.py --- Python/find-duplicate-file-in-system.py | 66 +++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Python/find-duplicate-file-in-system.py diff --git a/Python/find-duplicate-file-in-system.py b/Python/find-duplicate-file-in-system.py new file mode 100644 index 000000000..34e36011e --- /dev/null +++ b/Python/find-duplicate-file-in-system.py @@ -0,0 +1,66 @@ +# Time: O(n * l), l is the average length of file content +# Space: O(n * l) + +# Given a list of directory info including directory path, +# and all the files with contents in this directory, +# you need to find out all the groups of duplicate files +# in the file system in terms of their paths. +# +# A group of duplicate files consists of at least two files that have exactly the same content. +# +# A single directory info string in the input list has the following format: +# +# "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)" +# +# It means there are n files (f1.txt, f2.txt ... fn.txt +# with content f1_content, f2_content ... fn_content, respectively) in +# directory root/d1/d2/.../dm. Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory. +# +# The output is a list of group of duplicate file paths. For each group, +# it contains all the file paths of the files that have the same content. +# A file path is a string that has the following format: +# +# "directory_path/file_name.txt" +# +# Example 1: +# Input: +# ["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"] +# Output: +# [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] +# Note: +# No order is required for the final output. +# You may assume the directory name, file name and file content only has letters +# and digits, and the length of file content is in the range of [1,50]. +# +# The number of files given is in the range of [1,20000]. +# You may assume no files or directories share the same name in the same directory. +# You may assume each given directory info represents a unique directory. +# Directory path and file info are separated by a single blank space. +# +# Follow-up beyond contest: +# 1. Imagine you are given a real file system, how will you search files? DFS or BFS? +# 2. If the file content is very large (GB level), how will you modify your solution? +# 3. If you can only read the file by 1kb each time, how will you modify your solution? +# 4. What is the time complexity of your modified solution? +# What is the most time-consuming part and memory consuming part of it? How to optimize? +# 5. How to make sure the duplicated files you find are not false positive? + +class Solution(object): + def findDuplicate(self, paths): + """ + :type paths: List[str] + :rtype: List[List[str]] + """ + files = collections.defaultdict(list) + for path in paths: + s = path.split(" ") + for i in xrange(1,len(s)): + file_name = s[0] + "/" + s[i][0:s[i].find("(")] + file_content = s[i][s[i].find("(")+1:s[i].find(")")] + files[file_content].append(file_name) + + result = [] + for file_content, file_names in files.iteritems(): + if len(file_names)>1: + result.append(file_names) + return result From a098baf4197cb129074234bdb9a0e6e432297894 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Jun 2017 22:15:45 +0800 Subject: [PATCH 3379/4971] Create valid-triangle-number.py --- Python/valid-triangle-number.py | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/valid-triangle-number.py diff --git a/Python/valid-triangle-number.py b/Python/valid-triangle-number.py new file mode 100644 index 000000000..6e1dbbe04 --- /dev/null +++ b/Python/valid-triangle-number.py @@ -0,0 +1,37 @@ +# Time: O(n^2) +# Space: O(1) + +# Given an array consists of non-negative integers, +# your task is to count the number of triplets chosen +# from the array that can make triangles +# if we take them as side lengths of a triangle. +# +# Example 1: +# Input: [2,2,3,4] +# Output: 3 +# Explanation: +# Valid combinations are: +# 2,3,4 (using the first 2) +# 2,3,4 (using the second 2) +# 2,2,3 +# Note: +# The length of the given array won't exceed 1000. +# The integers in the given array are in the range of [0, 1000]. + +class Solution(object): + def triangleNumber(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + result = 0 + nums.sort() + for i in xrange(len(nums)-2): + if nums[i] == 0: + continue + k = i+2 + for j in xrange(i+1, len(nums)-1): + while k < len(nums) and nums[i] + nums[j] > nums[k]: + k += 1 + result += k-j-1 + return result From 4433d81d07a0b1b5f6f8ff2315a1515d515886f0 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 27 Jun 2017 22:19:46 +0800 Subject: [PATCH 3380/4971] add --- C++/valid-triangle-number.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/valid-triangle-number.cpp diff --git a/C++/valid-triangle-number.cpp b/C++/valid-triangle-number.cpp new file mode 100644 index 000000000..fd270550f --- /dev/null +++ b/C++/valid-triangle-number.cpp @@ -0,0 +1,24 @@ +// Time: O(n^2) +// Space: O(1) + +class Solution { +public: + int triangleNumber(vector& nums) { + int result = 0; + sort(nums.begin(), nums.end()); + for (int i = 0; i + 2 < nums.size(); ++i) { + if (nums[i] == 0) { + continue; + } + auto k = i + 2; + for (int j = i + 1; j + 1 < nums.size(); ++j) { + while (k < nums.size() && nums[i] + nums[j] > nums[k]) { + ++k; + } + result += k - j - 1; + } + } + return result; + } +}; + From e78b217c96c8d37e608af295b394dbf3a56639fa Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 28 Jun 2017 23:50:27 +0800 Subject: [PATCH 3381/4971] add --- C++/add-bold-tag-in-string.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/add-bold-tag-in-string.cpp diff --git a/C++/add-bold-tag-in-string.cpp b/C++/add-bold-tag-in-string.cpp new file mode 100644 index 000000000..81fc3a957 --- /dev/null +++ b/C++/add-bold-tag-in-string.cpp @@ -0,0 +1,29 @@ +// Time: O(s * d * l), l is the average string length +// Space: O(s) + +class Solution { +public: + string addBoldTag(string s, vector& dict) { + vector bold(s.length()); + for (const auto& d: dict) { + auto pos = -1; + while ((pos = s.find(d, pos + 1)) != string::npos) { + fill(bold.begin() + pos, bold.begin() + pos + d.length(), true); + } + } + string result; + for (int i = 0; i < s.length(); ++i) { + if ((i == 0 || !bold[i - 1]) && bold[i]) { + result += ""; + } else if (i != 0 && bold[i - 1] && !bold[i]) { + result += ""; + } + result.push_back(s[i]); + } + if (bold.back()) { + result += ""; + } + return result; + } +}; + From 28d3bdfbc8784d08cd4a10b7b742c8066cbd470e Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 28 Jun 2017 23:54:43 +0800 Subject: [PATCH 3382/4971] update --- C++/add-bold-tag-in-string.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/C++/add-bold-tag-in-string.cpp b/C++/add-bold-tag-in-string.cpp index 81fc3a957..9e695c2c6 100644 --- a/C++/add-bold-tag-in-string.cpp +++ b/C++/add-bold-tag-in-string.cpp @@ -12,18 +12,17 @@ class Solution { } } string result; + bool prev = false; for (int i = 0; i < s.length(); ++i) { - if ((i == 0 || !bold[i - 1]) && bold[i]) { - result += ""; - } else if (i != 0 && bold[i - 1] && !bold[i]) { - result += ""; + if (prev != bold[i]) { + result += prev ? "
" : ""; + prev = bold[i]; } result.push_back(s[i]); } - if (bold.back()) { + if (prev) { result += ""; } return result; } -}; - +}; \ No newline at end of file From 48e0d7f5c2b0dbf4cc6e45bf91d00f7ec6c0ffc0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 29 Jun 2017 00:06:14 +0800 Subject: [PATCH 3383/4971] Create add-bold-tag-in-string.py --- Python/add-bold-tag-in-string.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/add-bold-tag-in-string.py diff --git a/Python/add-bold-tag-in-string.py b/Python/add-bold-tag-in-string.py new file mode 100644 index 000000000..12b709857 --- /dev/null +++ b/Python/add-bold-tag-in-string.py @@ -0,0 +1,26 @@ +# Time: O(s * d * l), l is the average string length +# Space: O(s) + +class Solution(object): + def addBoldTag(self, s, dict): + """ + :type s: str + :type dict: List[str] + :rtype: str + """ + bold = [0] * len(s) + for d in dict: + pos = s.find(d) + while pos != -1: + bold[pos:pos+len(d)] = [1] * len(d) + pos = s.find(d, pos + 1) + + result, prev = [], 0 + for i in xrange(len(s)): + if prev != bold[i]: + result += "" if prev else "" + prev = bold[i] + result += s[i] + if prev: + result += "" + return "".join(result) From 264b4648dd086c5965baa979b07fd3d8362c291b Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 29 Jun 2017 22:14:27 +0800 Subject: [PATCH 3384/4971] add --- C++/task-scheduler.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/task-scheduler.cpp diff --git a/C++/task-scheduler.cpp b/C++/task-scheduler.cpp new file mode 100644 index 000000000..c37929643 --- /dev/null +++ b/C++/task-scheduler.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(26) = O(1) + +class Solution { +public: + int leastInterval(vector& tasks, int n) { + unordered_map count; + int max_count = 0; + for (const auto& task : tasks) { + ++count[task]; + max_count = max(max_count, count[task]); + } + + auto result = (max_count - 1) * (n + 1); + for (const auto& kvp : count) { + if (kvp.second == max_count) { + ++result; + } + } + return max(result, static_cast(tasks.size())); + } +}; From 704fd0b78a523aced7d4e3de2ccca9087c591d04 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 29 Jun 2017 22:20:30 +0800 Subject: [PATCH 3385/4971] Create task-scheduler.py --- Python/task-scheduler.py | 42 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/task-scheduler.py diff --git a/Python/task-scheduler.py b/Python/task-scheduler.py new file mode 100644 index 000000000..4ee3eacc2 --- /dev/null +++ b/Python/task-scheduler.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(26) = O(1) + +# Given a char array representing tasks CPU need to do. +# It contains capital letters A to Z where different letters represent +# different tasks.Tasks could be done without original order. +# Each task could be done in one interval. +# For each interval, CPU could finish one task or just be idle. +# +# However, there is a non-negative cooling interval n that +# means between two same tasks, there must be at least n intervals that +# CPU are doing different tasks or just be idle. +# +# You need to return the least number of intervals the CPU +# will take to finish all the given tasks. +# +# Example 1: +# Input: tasks = ['A','A','A','B','B','B'], n = 2 +# Output: 8 +# Explanation: A -> B -> idle -> A -> B -> idle -> A -> B. +# Note: +# The number of tasks is in the range [1, 10000]. +# The integer n is in the range [0, 100]. + +class Solution(object): + def leastInterval(self, tasks, n): + """ + :type tasks: List[str] + :type n: int + :rtype: int + """ + count = collections.defaultdict(int) + max_count = 0 + for task in tasks: + count[task] += 1 + max_count = max(max_count, count[task]) + + result = (max_count-1) * (n+1) + for count in count.values(): + if count == max_count: + result += 1 + return max(result, len(tasks)) From 77be9da9eb094f7461007f5d7dfd72b565d39888 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Fri, 30 Jun 2017 23:53:04 +0800 Subject: [PATCH 3386/4971] add --- C++/add-one-row-to-tree.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/add-one-row-to-tree.cpp diff --git a/C++/add-one-row-to-tree.cpp b/C++/add-one-row-to-tree.cpp new file mode 100644 index 000000000..32e307c79 --- /dev/null +++ b/C++/add-one-row-to-tree.cpp @@ -0,0 +1,28 @@ +// 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: + TreeNode* addOneRow(TreeNode* root, int v, int d) { + if (d == 0 || d == 1) { + auto node = new TreeNode(v); + (d == 1 ? node->left : node->right) = root; + return node; + } + if (root && d >= 2) { + root->left = addOneRow(root->left, v, d > 2 ? d - 1 : 1); + root->right = addOneRow(root->right, v, d > 2 ? d - 1 : 0); + } + return root; + } +}; + From 9f276fba97318431d85c08fc0718b30bf39ed1bf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 1 Jul 2017 00:04:33 +0800 Subject: [PATCH 3387/4971] Create add-one-row-to-tree.py --- Python/add-one-row-to-tree.py | 88 +++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Python/add-one-row-to-tree.py diff --git a/Python/add-one-row-to-tree.py b/Python/add-one-row-to-tree.py new file mode 100644 index 000000000..2bda9d172 --- /dev/null +++ b/Python/add-one-row-to-tree.py @@ -0,0 +1,88 @@ +# Time: O(n) +# Space: O(h) + +# Given the root of a binary tree, then value v and depth d, +# you need to add a row of nodes with value v at the given depth d. The root node is at depth 1. +# +# The adding rule is: given a positive integer depth d, +# for each NOT null tree nodes N in depth d-1, create two tree nodes +# with value v as N's left subtree root and right subtree root. +# And N's original left subtree should be the left subtree of the new left subtree root, +# its original right subtree should be the right subtree of the new right subtree root. +# If depth d is 1 that means there is no depth d-1 at all, +# then create a tree node with value v as the new root of the whole original tree, +# and the original tree is the new root's left subtree. +# +# Example 1: +# Input: +# A binary tree as following: +# 4 +# / \ +# 2 6 +# / \ / +# 3 1 5 +# +# v = 1 +# +# d = 2 +# +# Output: +# 4 +# / \ +# 1 1 +# / \ +# 2 6 +# / \ / +# 3 1 5 +# +# Example 2: +# Input: +# A binary tree as following: +# 4 +# / +# 2 +# / \ +# 3 1 +# +# v = 1 +# +# d = 3 +# +# Output: +# 4 +# / +# 2 +# / \ +# 1 1 +# / \ +# 3 1 +# Note: +# 1. The given d is in range [1, maximum depth of the given tree + 1]. +# 2. The given binary tree has at least one tree node. + +# 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 addOneRow(self, root, v, d): + """ + :type root: TreeNode + :type v: int + :type d: int + :rtype: TreeNode + """ + if d in (0, 1): + node = TreeNode(v) + if d == 1: + node.left = root + else: + node.right = root + return node + if root and d >= 2: + root.left = self.addOneRow(root.left, v, d-1 if d > 2 else 1) + root.right = self.addOneRow(root.right, v, d-1 if d > 2 else 0) + return root From 3bad023ea712f3e66234876c3749e7bdbc554eac Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 2 Jul 2017 00:15:37 +0800 Subject: [PATCH 3388/4971] add --- C++/maximum-distance-in-arrays.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/maximum-distance-in-arrays.cpp diff --git a/C++/maximum-distance-in-arrays.cpp b/C++/maximum-distance-in-arrays.cpp new file mode 100644 index 000000000..f5af49463 --- /dev/null +++ b/C++/maximum-distance-in-arrays.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int maxDistance(vector>& arrays) { + int result = 0; + int min_val = arrays[0].front(), max_val = arrays[0].back(); + for (int i = 1; i < arrays.size(); ++i) { + result = max(result, + max(max_val - arrays[i].front(), + arrays[i].back() - min_val)); + min_val = min(min_val, arrays[i].front()); + max_val = max(max_val, arrays[i].back()); + } + return result; + } +}; + From 11ebc05d2a160a56f7dcdc9b7a030b50b034ea15 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 2 Jul 2017 00:20:44 +0800 Subject: [PATCH 3389/4971] add --- Python/maximum-distance-in-arrays.py | 37 ++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/maximum-distance-in-arrays.py diff --git a/Python/maximum-distance-in-arrays.py b/Python/maximum-distance-in-arrays.py new file mode 100644 index 000000000..4a24c82f4 --- /dev/null +++ b/Python/maximum-distance-in-arrays.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(1) + +# Given m arrays, and each array is sorted in ascending order. +# Now you can pick up two integers from two different arrays (each array picks one) +# and calculate the distance. +# We define the distance between two integers a and b to be their absolute difference |a-b|. +# Your task is to find the maximum distance. +# +# Example 1: +# Input: +# [[1,2,3], +# [4,5], +# [1,2,3]] +# Output: 4 +# Explanation: +# One way to reach the maximum distance 4 is to pick 1 in the first or third array +# and pick 5 in the second array. +# Note: +# Each given array will have at least 1 number. There will be at least two non-empty arrays. +# The total number of the integers in all the m arrays will be in the range of [2, 10000]. +# The integers in the m arrays will be in the range of [-10000, 10000]. + +class Solution(object): + def maxDistance(self, arrays): + """ + :type arrays: List[List[int]] + :rtype: int + """ + result, min_val, max_val = 0, arrays[0][0], arrays[0][-1] + for i in xrange(1, len(arrays)): + result = max(result, \ + max(max_val - arrays[i][0], \ + arrays[i][-1] - min_val)) + min_val = min(min_val, arrays[i][0]) + max_val = max(max_val, arrays[i][-1]) + return result \ No newline at end of file From 71978ecacd49d4f05e600658c34f532ec179d426 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 2 Jul 2017 15:17:59 +0800 Subject: [PATCH 3390/4971] add --- C++/minimum-factorization.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/minimum-factorization.cpp diff --git a/C++/minimum-factorization.cpp b/C++/minimum-factorization.cpp new file mode 100644 index 000000000..633c9b048 --- /dev/null +++ b/C++/minimum-factorization.cpp @@ -0,0 +1,21 @@ +// Time: O(loga) +// Space: O(1) + +class Solution { +public: + int smallestFactorization(int a) { + if (a < 2) { + return a; + } + long result = 0, mul = 1; + for (int i = 9; i >= 2; --i) { + while (a % i == 0) { + a /= i; + result = mul * i + result; + mul *= 10; + } + } + return a == 1 && result <= numeric_limits::max() ? static_cast(result) : 0; + } +}; + From 68600dc5243872f51327a569eb7e9e1e948ff315 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 2 Jul 2017 15:24:55 +0800 Subject: [PATCH 3391/4971] Create minimum-factorization.py --- Python/minimum-factorization.py | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/minimum-factorization.py diff --git a/Python/minimum-factorization.py b/Python/minimum-factorization.py new file mode 100644 index 000000000..505ca357f --- /dev/null +++ b/Python/minimum-factorization.py @@ -0,0 +1,37 @@ +# Time: O(loga) +# Space: O(1) + +# Given a positive integer a, +# find the smallest positive integer b whose multiplication of each digit equals to a. +# +# If there is no answer or the answer is not fit in 32-bit signed integer, then return 0. +# +# Example 1 +# Input: +# +# 48 +# Output: +# 68 +# Example 2 +# Input: +# +# 15 +# Output: +# 35 + +class Solution(object): + def smallestFactorization(self, a): + """ + :type a: int + :rtype: int + """ + if a < 2: + return a + result, mul = 0, 1 + for i in reversed(xrange(2, 10)): + while a % i == 0: + a /= i + result = mul*i + result + mul *= 10 + return result if a == 1 and result < 2**31 else 0 + From c51a42221e565a419afde85369ee3a7e182126a2 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 3 Jul 2017 22:47:25 +0800 Subject: [PATCH 3392/4971] add --- C++/maximum-product-of-three-numbers.cpp | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/maximum-product-of-three-numbers.cpp diff --git a/C++/maximum-product-of-three-numbers.cpp b/C++/maximum-product-of-three-numbers.cpp new file mode 100644 index 000000000..57dc25757 --- /dev/null +++ b/C++/maximum-product-of-three-numbers.cpp @@ -0,0 +1,33 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int maximumProduct(vector& nums) { + auto min1 = numeric_limits::max(); + auto min2 = numeric_limits::max(); + auto max1 = numeric_limits::min(); + auto max2 = numeric_limits::min(); + auto max3 = numeric_limits::min(); + for (const auto& n: nums) { + if (n <= min1) { + min2 = min1; + min1 = n; + } else if (n <= min2) { + min2 = n; + } + if (n >= max1) { + max3 = max2; + max2 = max1; + max1 = n; + } else if (n >= max2) { + max3 = max2; + max2 = n; + } else if (n >= max3) { + max3 = n; + } + } + return max(min1 * min2 * max1, max1 * max2 * max3); + } +}; + From 1ad51488c5ae3da00aab263301b777be3065e264 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 3 Jul 2017 22:51:48 +0800 Subject: [PATCH 3393/4971] Create maximum-product-of-three-numbers.py --- Python/maximum-product-of-three-numbers.py | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/maximum-product-of-three-numbers.py diff --git a/Python/maximum-product-of-three-numbers.py b/Python/maximum-product-of-three-numbers.py new file mode 100644 index 000000000..73a618c2d --- /dev/null +++ b/Python/maximum-product-of-three-numbers.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(1) + +# Given an integer array, find three numbers whose product is maximum and output the maximum product. +# +# Example 1: +# Input: [1,2,3] +# Output: 6 +# Example 2: +# Input: [1,2,3,4] +# Output: 24 +# Note: +# The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. +# Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. + +class Solution(object): + def maximumProduct(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + min1, min2 = float("inf"), float("inf") + max1, max2, max3 = float("-inf"), float("-inf"), float("-inf") + + for n in nums: + if n <= min1: + min2 = min1 + min1 = n + elif n <= min2: + min2 = n + + if n >= max1: + max3 = max2 + max2 = max1 + max1 = n + elif n >= max2: + max3 = max2 + max2 = n + elif n >= max3: + max3 = n + + return max(min1 * min2 * max1, max1 * max2 * max3) From 32114b486467c5d10b64d34019485d7822594ef8 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 4 Jul 2017 23:05:17 +0800 Subject: [PATCH 3394/4971] add --- C++/k-inverse-pairs-array.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/k-inverse-pairs-array.cpp diff --git a/C++/k-inverse-pairs-array.cpp b/C++/k-inverse-pairs-array.cpp new file mode 100644 index 000000000..76037da9f --- /dev/null +++ b/C++/k-inverse-pairs-array.cpp @@ -0,0 +1,23 @@ +// Time: O(n * k) +// Space: O(k) + +class Solution { +public: + int kInversePairs(int n, int k) { + static const int M = 1000000007; + vector> dp(2, vector(k + 1)); + dp[0][0] = 1; + for(int i = 1; i <= n; ++i){ + dp[i % 2] = vector(k + 1); + dp[i % 2][0] = 1; + for (int j = 1; j <= k; ++j) { + dp[i % 2][j] = (dp[i % 2][j - 1] + dp[(i - 1) % 2][j]) % M; + if (j - i >= 0) { + dp[i % 2][j] = (dp[i % 2][j] - dp[(i - 1) % 2][j - i] + M) % M; + } + } + } + return dp[n % 2][k]; + } +}; + From 7b5d63689e06657a5e2edc7de014bb82f1b066f2 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 4 Jul 2017 23:08:48 +0800 Subject: [PATCH 3395/4971] add --- C++/k-inverse-pairs-array.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/k-inverse-pairs-array.cpp b/C++/k-inverse-pairs-array.cpp index 76037da9f..bc3647ed8 100644 --- a/C++/k-inverse-pairs-array.cpp +++ b/C++/k-inverse-pairs-array.cpp @@ -7,7 +7,7 @@ class Solution { static const int M = 1000000007; vector> dp(2, vector(k + 1)); dp[0][0] = 1; - for(int i = 1; i <= n; ++i){ + for (int i = 1; i <= n; ++i) { dp[i % 2] = vector(k + 1); dp[i % 2][0] = 1; for (int j = 1; j <= k; ++j) { From 1c61b5744fe285bea1e007cf6ec9cd5501dc803b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 4 Jul 2017 23:12:49 +0800 Subject: [PATCH 3396/4971] Create k-inverse-pairs-array.py --- Python/k-inverse-pairs-array.py | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/k-inverse-pairs-array.py diff --git a/Python/k-inverse-pairs-array.py b/Python/k-inverse-pairs-array.py new file mode 100644 index 000000000..7c7bb2848 --- /dev/null +++ b/Python/k-inverse-pairs-array.py @@ -0,0 +1,42 @@ +# Time: O(n * k) +# Space: O(k) + +# Given two integers n and k, find how many different arrays consist of numbers +# from 1 to n such that there are exactly k inverse pairs. +# +# We define an inverse pair as following: For ith and jth element in the array, +# if i < j and a[i] > a[j] then it's an inverse pair; Otherwise, it's not. +# +# Since the answer may very large, the answer should be modulo 109 + 7. +# +# Example 1: +# Input: n = 3, k = 0 +# Output: 1 +# Explanation: +# Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pair. +# Example 2: +# Input: n = 3, k = 1 +# Output: 2 +# Explanation: +# The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. +# Note: +# The integer n is in the range [1, 1000] and k is in the range [0, 1000]. + +class Solution(object): + def kInversePairs(self, n, k): + """ + :type n: int + :type k: int + :rtype: int + """ + M = 1000000007 + dp = [[0] * (k+1) for _ in xrange(2)] + dp[0][0] = 1 + for i in xrange(1, n+1): + dp[i%2] = [0] * (k+1) + dp[i%2][0] = 1 + for j in xrange(1, k+1): + dp[i%2][j] = (dp[i%2][j-1] + dp[(i-1)%2][j]) % M + if j - i >= 0: + dp[i%2][j] = (dp[i%2][j] - dp[(i-1)%2][j-i]) % M + return dp[n % 2][k] From c9e9a5b75c200ee80c633ef22bec179e738db2f8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 4 Jul 2017 23:13:28 +0800 Subject: [PATCH 3397/4971] Update k-inverse-pairs-array.py --- Python/k-inverse-pairs-array.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/k-inverse-pairs-array.py b/Python/k-inverse-pairs-array.py index 7c7bb2848..e6cf34588 100644 --- a/Python/k-inverse-pairs-array.py +++ b/Python/k-inverse-pairs-array.py @@ -37,6 +37,6 @@ def kInversePairs(self, n, k): dp[i%2][0] = 1 for j in xrange(1, k+1): dp[i%2][j] = (dp[i%2][j-1] + dp[(i-1)%2][j]) % M - if j - i >= 0: + if j-i >= 0: dp[i%2][j] = (dp[i%2][j] - dp[(i-1)%2][j-i]) % M return dp[n % 2][k] From b09803468c0dbe80b590a4ffff157315b48a1f2b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 4 Jul 2017 23:13:56 +0800 Subject: [PATCH 3398/4971] Update k-inverse-pairs-array.py --- Python/k-inverse-pairs-array.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/k-inverse-pairs-array.py b/Python/k-inverse-pairs-array.py index e6cf34588..da1e592dd 100644 --- a/Python/k-inverse-pairs-array.py +++ b/Python/k-inverse-pairs-array.py @@ -30,13 +30,13 @@ def kInversePairs(self, n, k): :rtype: int """ M = 1000000007 - dp = [[0] * (k+1) for _ in xrange(2)] + dp = [[0]*(k+1) for _ in xrange(2)] dp[0][0] = 1 for i in xrange(1, n+1): - dp[i%2] = [0] * (k+1) + dp[i%2] = [0]*(k+1) dp[i%2][0] = 1 for j in xrange(1, k+1): dp[i%2][j] = (dp[i%2][j-1] + dp[(i-1)%2][j]) % M if j-i >= 0: dp[i%2][j] = (dp[i%2][j] - dp[(i-1)%2][j-i]) % M - return dp[n % 2][k] + return dp[n%2][k] From 51ada8c27c64725c1d767690d9fda661be6dc49d Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 5 Jul 2017 22:59:42 +0800 Subject: [PATCH 3399/4971] add --- C++/course-schedule-iii.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/course-schedule-iii.cpp diff --git a/C++/course-schedule-iii.cpp b/C++/course-schedule-iii.cpp new file mode 100644 index 000000000..9a996fa62 --- /dev/null +++ b/C++/course-schedule-iii.cpp @@ -0,0 +1,23 @@ +// Time: O(nlogn) +// Space: O(k), k is the number of courses you can take + +class Solution { +public: + int scheduleCourse(vector>& courses) { + sort(courses.begin(), courses.end(), + [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + priority_queue max_heap; + int now = 0; + for (const auto& course : courses) { + max_heap.emplace(course[0]); + now += course[0]; + if (now > course[1]) { + now -= max_heap.top(), max_heap.pop(); + } + } + return heap.size(); + } +}; + From e0643525277187f68726b3aaf5c12507a1fe4f24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 5 Jul 2017 23:03:13 +0800 Subject: [PATCH 3400/4971] Create course-schedule-iii.py --- Python/course-schedule-iii.py | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/course-schedule-iii.py diff --git a/Python/course-schedule-iii.py b/Python/course-schedule-iii.py new file mode 100644 index 000000000..af874fc69 --- /dev/null +++ b/Python/course-schedule-iii.py @@ -0,0 +1,42 @@ +# Time: O(nlogn) +# Space: O(k), k is the number of courses you can take + +# There are n different online courses numbered from 1 to n. +# Each course has some duration(course length) t and closed on dth day. +# A course should be taken continuously for t days and must be finished before or on the dth day. +# You will start at the 1st day. +# +# Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken. +# +# Example: +# Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]] +# Output: 3 +# Explanation: +# There're totally 4 courses, but you can take 3 courses at most: +# First, take the 1st course, it costs 100 days so you will finish it on the 100th day, +# and ready to take the next course on the 101st day. +# Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, +# and ready to take the next course on the 1101st day. +# Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. +# The 4th course cannot be taken now, since you will finish it on the 3300th day, +# which exceeds the closed date. +# +# Note: +# The integer 1 <= d, t, n <= 10,000. +# You can't take two courses simultaneously. + +class Solution(object): + def scheduleCourse(self, courses): + """ + :type courses: List[List[int]] + :rtype: int + """ + courses.sort(key=lambda(t, end): end) + max_heap = [] + now = 0 + for t, end in courses: + now += t + heapq.heappush(max_heap, -t) + if now > end: + now += heapq.heappop(max_heap) + return len(max_heap) From 905c1c63046e5de00e6a84299246c4cef7867604 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 6 Jul 2017 23:09:01 +0800 Subject: [PATCH 3401/4971] add --- C++/design-excel-sum-formula.cpp | 96 ++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 C++/design-excel-sum-formula.cpp diff --git a/C++/design-excel-sum-formula.cpp b/C++/design-excel-sum-formula.cpp new file mode 100644 index 000000000..19eec9faa --- /dev/null +++ b/C++/design-excel-sum-formula.cpp @@ -0,0 +1,96 @@ +// Time: set: O((r * c)^2) +// get: O(1) +// sum: O((r * c)^2) +// Space: O(r * c) + +class Excel { +public: + Excel(int H, char W) : Exl_(H + 1, vector(W - 'A' + 1)) { + } + + // Time: O((r * c)^2) + void set(int r, char c, int v) { + auto col = c - 'A'; + reset_dependency(r, col); + update_others(r, col, v); + } + + // Time: O(1) + int get(int r, char c) { + return Exl_[r][c - 'A']; + } + + // Time: O((r * c)^2) + int sum(int r, char c, vector strs) { + auto col = c - 'A'; + reset_dependency(r, col); + auto result = update_dependency(r, col, strs); + update_others(r, col, result); + return result; + } + +private: + // Time: O(r * c) + void reset_dependency(int r, int col) { + auto key = r * 26 + col; + if (bward_.count(key)) { + for (const auto& k : bward_[key]) { + fward_[k].erase(key); + } + bward_[key].clear(); + } + } + + // Time: O(r * c * l), l is the length of strs + int update_dependency(int r, int col, const vector& strs) { + auto result = 0; + for (const auto& s : strs) { + int p = s.find(':'), left, right, top, bottom; + left = s[0] - 'A'; + right = s[p + 1] - 'A'; + top = (p == string::npos) ? stoi(s.substr(1)) : stoi(s.substr(1, p - 1)); + bottom = stoi(s.substr(p + 2)); + for (int i = top; i <= bottom; ++i) { + for (int j = left; j <= right; ++j) { + result += Exl_[i][j]; + ++fward_[i * 26 + j][r * 26 + col]; + bward_[r * 26 + col].emplace(i * 26 + j); + } + } + } + return result; + } + + // Time: O((r * c)^2) + void update_others(int r, int col, int v) { + auto prev = Exl_[r][col]; + Exl_[r][col] = v; + queue> q, update; + q.emplace(make_pair(r * 26 + col, v - prev)); + while (!q.empty()) { + int key, diff; + tie(key, diff) = q.front(), q.pop(); + if (fward_.count(key)) { + for (auto it = fward_[key].begin(); it != fward_[key].end(); ++it) { + int k, count; + tie(k, count) = *it; + q.emplace(make_pair(k, diff * count)); + Exl_[k / 26][k % 26] += diff * count; + } + } + } + } + + unordered_map> fward_; + unordered_map> bward_; + vector> Exl_; +}; + +/** + * Your Excel object will be instantiated and called as such: + * Excel obj = new Excel(H, W); + * obj.set(r,c,v); + * int param_2 = obj.get(r,c); + * int param_3 = obj.sum(r,c,strs); + */ + From a6c5e847790f4e3f21c6176b231146291af48ceb Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 6 Jul 2017 23:12:33 +0800 Subject: [PATCH 3402/4971] update --- C++/design-excel-sum-formula.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/design-excel-sum-formula.cpp b/C++/design-excel-sum-formula.cpp index 19eec9faa..99ac63f9a 100644 --- a/C++/design-excel-sum-formula.cpp +++ b/C++/design-excel-sum-formula.cpp @@ -24,7 +24,7 @@ class Excel { int sum(int r, char c, vector strs) { auto col = c - 'A'; reset_dependency(r, col); - auto result = update_dependency(r, col, strs); + auto result = calc_and_update_dependency(r, col, strs); update_others(r, col, result); return result; } @@ -42,7 +42,7 @@ class Excel { } // Time: O(r * c * l), l is the length of strs - int update_dependency(int r, int col, const vector& strs) { + int calc_and_update_dependency(int r, int col, const vector& strs) { auto result = 0; for (const auto& s : strs) { int p = s.find(':'), left, right, top, bottom; @@ -93,4 +93,4 @@ class Excel { * int param_2 = obj.get(r,c); * int param_3 = obj.sum(r,c,strs); */ - + \ No newline at end of file From 1d39d58056405eed45d0c54705ea3ba30661e74f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Fri, 7 Jul 2017 23:32:21 +0800 Subject: [PATCH 3403/4971] update --- C++/design-excel-sum-formula.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/design-excel-sum-formula.cpp b/C++/design-excel-sum-formula.cpp index 99ac63f9a..e629ead2e 100644 --- a/C++/design-excel-sum-formula.cpp +++ b/C++/design-excel-sum-formula.cpp @@ -37,7 +37,7 @@ class Excel { for (const auto& k : bward_[key]) { fward_[k].erase(key); } - bward_[key].clear(); + bward_.erase(key); } } @@ -93,4 +93,3 @@ class Excel { * int param_2 = obj.get(r,c); * int param_3 = obj.sum(r,c,strs); */ - \ No newline at end of file From 8121f36d024a120d36890fc5a32900a58c9bfdb4 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Fri, 7 Jul 2017 23:48:11 +0800 Subject: [PATCH 3404/4971] update --- C++/design-excel-sum-formula.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/design-excel-sum-formula.cpp b/C++/design-excel-sum-formula.cpp index e629ead2e..2a627293e 100644 --- a/C++/design-excel-sum-formula.cpp +++ b/C++/design-excel-sum-formula.cpp @@ -65,7 +65,7 @@ class Excel { void update_others(int r, int col, int v) { auto prev = Exl_[r][col]; Exl_[r][col] = v; - queue> q, update; + queue> q; q.emplace(make_pair(r * 26 + col, v - prev)); while (!q.empty()) { int key, diff; From be64c2f27375fd64ba776a5f4f8f4d784f916452 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 8 Jul 2017 00:08:59 +0800 Subject: [PATCH 3405/4971] Create design-excel-sum-formula.py --- Python/design-excel-sum-formula.py | 90 ++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Python/design-excel-sum-formula.py diff --git a/Python/design-excel-sum-formula.py b/Python/design-excel-sum-formula.py new file mode 100644 index 000000000..24a1b47ca --- /dev/null +++ b/Python/design-excel-sum-formula.py @@ -0,0 +1,90 @@ +# Time: set: O((r * c)^2) +# get: O(1) +# sum: O((r * c)^2) +# Space: O(r * c) + +class Excel(object): + + def __init__(self, H, W): + """ + :type H: int + :type W: str + """ + self.__exl = [[0 for _ in xrange(ord(W)-ord('A')+1)] \ + for _ in xrange(H+1)] + self.__fward = collections.defaultdict(lambda : collections.defaultdict(int)) + self.__bward = collections.defaultdict(set) + + + def set(self, r, c, v): + """ + :type r: int + :type c: str + :type v: int + :rtype: void + """ + self.__reset_dependency(r, c); + self.__update_others(r, c, v); + + + def get(self, r, c): + """ + :type r: int + :type c: str + :rtype: int + """ + return self.__exl[r][ord(c) - ord('A')] + + + def sum(self, r, c, strs): + """ + :type r: int + :type c: str + :type strs: List[str] + :rtype: int + """ + self.__reset_dependency(r, c) + result = self.__calc_and_update_dependency(r, c, strs) + self.__update_others(r, c, result) + return result + + + def __reset_dependency(self, r, c): + key = (r, c) + if key in self.__bward.keys(): + for k in self.__bward[key]: + self.__fward[k].pop(key, None) + self.__bward[key] = set() + + + def __calc_and_update_dependency(self, r, c, strs): + result = 0 + for s in strs: + s, e = s.split(':')[0], s.split(':')[1] if ':' in s else s + left, right, top, bottom = ord(s[0])-ord('A'), ord(e[0])-ord('A'), int(s[1:]), int(e[1:]) + for i in xrange(top, bottom+1): + for j in xrange(left, right+1): + result += self.__exl[i][j] + self.__fward[(i, chr(ord('A')+j))][(r, c)] += 1 + self.__bward[(r, c)].add((i, chr(ord('A')+j))) + return result + + + def __update_others(self, r, c, v): + prev = self.__exl[r][ord(c)-ord('A')] + self.__exl[r][ord(c)-ord('A')] = v + q = collections.deque() + q.append(((r, c), v-prev)) + while q: + key, diff = q.popleft() + if key in self.__fward: + for k, count in self.__fward[key].iteritems(): + q.append((k, diff*count)) + self.__exl[k[0]][ord(k[1])-ord('A')] += diff*count + + +# Your Excel object will be instantiated and called as such: +# obj = Excel(H, W) +# obj.set(r,c,v) +# param_2 = obj.get(r,c) +# param_3 = obj.sum(r,c,strs) From 28948f0136303f9d572ef3d846f1ca60a94b4fb6 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 9 Jul 2017 12:36:44 +0800 Subject: [PATCH 3406/4971] add --- C++/largest-palindrome-product.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/largest-palindrome-product.cpp diff --git a/C++/largest-palindrome-product.cpp b/C++/largest-palindrome-product.cpp new file mode 100644 index 000000000..f6513ef75 --- /dev/null +++ b/C++/largest-palindrome-product.cpp @@ -0,0 +1,29 @@ +// Time: O(10^(2n)) +// Space: O(n) + +class Solution { +public: + int largestPalindrome(int n) { + if (n == 1) { + return 9; + } + int upper = pow(10, n) - 1; + int lower = pow(10, n - 1); + for (int i = upper; i >= lower; --i) { + auto candidate = buildPalindrome(i); + for (long long j = upper; j * j >= candidate; --j) { + if (candidate % j == 0) { + return candidate % 1337; + } + } + } + return -1; + } + +private: + long long buildPalindrome(int n) { + string s = to_string(n); + reverse(s.begin(), s.end()); + return stoll(to_string(n) + s); + } +}; From 288c9b5bd62304c2de03027f16737a81d9a6cc1f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Jul 2017 12:57:00 +0800 Subject: [PATCH 3407/4971] Create largest-palindrome-product.py --- Python/largest-palindrome-product.py | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/largest-palindrome-product.py diff --git a/Python/largest-palindrome-product.py b/Python/largest-palindrome-product.py new file mode 100644 index 000000000..c189a0011 --- /dev/null +++ b/Python/largest-palindrome-product.py @@ -0,0 +1,32 @@ +# Time: O(10^(2n)) +# Space: O(n) + +# Find the largest palindrome made from the product of two n-digit numbers. +# Since the result could be very large, you should return the largest palindrome mod 1337. +# +# Example: +# Input: 2 +# Output: 987 +# Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 +# +# Note: +# The range of n is [1,8]. + +class Solution_TLE(object): + def largestPalindrome(self, n): + """ + :type n: int + :rtype: int + """ + if n == 1: + return 9 + + upper, lower = 10**n-1, 10**(n-1) + for i in reversed(xrange(lower, upper+1)): + candidate = int(str(i) + str(i)[::-1]) + j = upper + while j * j >= candidate: + if candidate % j == 0: + return candidate % 1337 + j -= 1 + return -1 From e301d2991fa6123b6746f5b689f9a3f3ff08e38b Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 9 Jul 2017 14:47:34 +0800 Subject: [PATCH 3408/4971] add --- C++/single-element-in-a-sorted-array.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/single-element-in-a-sorted-array.cpp diff --git a/C++/single-element-in-a-sorted-array.cpp b/C++/single-element-in-a-sorted-array.cpp new file mode 100644 index 000000000..3f800b08e --- /dev/null +++ b/C++/single-element-in-a-sorted-array.cpp @@ -0,0 +1,21 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int singleNonDuplicate(vector& nums) { + int left = 0, right = nums.size() - 1; + while (left <= right) { + auto mid = left + (right - left) / 2; + if (!(mid % 2 == 0 && mid + 1 < nums.size() && + nums[mid] == nums[mid + 1]) && + !(mid % 2 == 1 && nums[mid] == nums[mid - 1])) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return nums[left]; + } +}; + From b1a6662173317370571cc7fa55abbc8ff46da338 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 9 Jul 2017 14:51:33 +0800 Subject: [PATCH 3409/4971] Create single-element-in-a-sorted-array.py --- Python/single-element-in-a-sorted-array.py | 31 ++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/single-element-in-a-sorted-array.py diff --git a/Python/single-element-in-a-sorted-array.py b/Python/single-element-in-a-sorted-array.py new file mode 100644 index 000000000..4a7dcb18b --- /dev/null +++ b/Python/single-element-in-a-sorted-array.py @@ -0,0 +1,31 @@ +# Time: O(logn) +# Space: O(1) + +# Given a sorted array consisting of only integers +# where every element appears twice except for one element +# which appears once. Find this single element that appears only once. +# +# Example 1: +# Input: [1,1,2,3,3,4,4,8,8] +# Output: 2 +# Example 2: +# Input: [3,3,7,7,10,11,11] +# Output: 10 +# Note: Your solution should run in O(log n) time and O(1) space. + +class Solution(object): + def singleNonDuplicate(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + left, right = 0, len(nums)-1 + while left <= right: + mid = left + (right - left) / 2 + if not (mid%2 == 0 and mid+1 < len(nums) and \ + nums[mid] == nums[mid+1]) and \ + not (mid%2 == 1 and nums[mid] == nums[mid-1]): + right = mid-1 + else: + left = mid+1 + return nums[left] From 5448f6680272712e3849443608f4f309053fe11a Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 10 Jul 2017 23:58:27 +0800 Subject: [PATCH 3410/4971] add --- C++/smallest-range.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/smallest-range.cpp diff --git a/C++/smallest-range.cpp b/C++/smallest-range.cpp new file mode 100644 index 000000000..e510647bf --- /dev/null +++ b/C++/smallest-range.cpp @@ -0,0 +1,40 @@ +// Time: O(nlogk) +// Space: O(k) + +class Solution { +public: + vector smallestRange(vector>& nums) { + using VIT = vector::iterator; + + const auto comp = [](const pair& p1, const pair& p2) { + return *p1.first > *p2.first; + }; + + int left = numeric_limits::max(), right = numeric_limits::min(); + priority_queue, vector>, decltype(comp)> min_heap(comp); + for (auto &row : nums) { + left = min(left, row[0]); + right = max(right, row[0]); + min_heap.emplace(row.begin(), row.end()); + } + + vector result = {left, right}; + while (!min_heap.empty()) { + auto p = min_heap.top(); + min_heap.pop(); + ++p.first; + if (p.first == p.second) { + break; + } + min_heap.emplace(p); + + left = *min_heap.top().first; + right = max(right, *p.first); + if (right - left < result[1] - result[0]) { + result = {left, right}; + } + } + return result; + } +}; + From 4aaf1c7a6882aa5feafebecaf08e59e6278f178a Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 11 Jul 2017 00:17:03 +0800 Subject: [PATCH 3411/4971] add --- C++/smallest-range.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/smallest-range.cpp b/C++/smallest-range.cpp index e510647bf..f0a3bfdb2 100644 --- a/C++/smallest-range.cpp +++ b/C++/smallest-range.cpp @@ -8,7 +8,7 @@ class Solution { const auto comp = [](const pair& p1, const pair& p2) { return *p1.first > *p2.first; - }; + }; int left = numeric_limits::max(), right = numeric_limits::min(); priority_queue, vector>, decltype(comp)> min_heap(comp); From 26a4b82fe665f8d2289a73ac23407ccdf77c3ce3 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 11 Jul 2017 00:32:34 +0800 Subject: [PATCH 3412/4971] update --- C++/smallest-range.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/smallest-range.cpp b/C++/smallest-range.cpp index f0a3bfdb2..7dc577ba4 100644 --- a/C++/smallest-range.cpp +++ b/C++/smallest-range.cpp @@ -12,7 +12,7 @@ class Solution { int left = numeric_limits::max(), right = numeric_limits::min(); priority_queue, vector>, decltype(comp)> min_heap(comp); - for (auto &row : nums) { + for (const auto &row : nums) { left = min(left, row[0]); right = max(right, row[0]); min_heap.emplace(row.begin(), row.end()); From ec17a8e23bf10d848a027729dab0fbbd91455ad3 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 11 Jul 2017 00:33:25 +0800 Subject: [PATCH 3413/4971] Revert "update" This reverts commit 26a4b82fe665f8d2289a73ac23407ccdf77c3ce3. --- C++/smallest-range.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/smallest-range.cpp b/C++/smallest-range.cpp index 7dc577ba4..f0a3bfdb2 100644 --- a/C++/smallest-range.cpp +++ b/C++/smallest-range.cpp @@ -12,7 +12,7 @@ class Solution { int left = numeric_limits::max(), right = numeric_limits::min(); priority_queue, vector>, decltype(comp)> min_heap(comp); - for (const auto &row : nums) { + for (auto &row : nums) { left = min(left, row[0]); right = max(right, row[0]); min_heap.emplace(row.begin(), row.end()); From 0cde2319ded92be83d8b40d5463430d454a780bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 11 Jul 2017 01:07:58 +0800 Subject: [PATCH 3414/4971] Create smallest-range.py --- Python/smallest-range.py | 47 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/smallest-range.py diff --git a/Python/smallest-range.py b/Python/smallest-range.py new file mode 100644 index 000000000..c49850f6b --- /dev/null +++ b/Python/smallest-range.py @@ -0,0 +1,47 @@ +# Time: O(nlogk) +# Space: O(k) + +# You have k lists of sorted integers in ascending order. +# Find the smallest range that includes at least one number from each of the k lists. +# +# We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c. +# +# Example 1: +# Input:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] +# Output: [20,24] +# Explanation: +# List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. +# List 2: [0, 9, 12, 20], 20 is in range [20,24]. +# List 3: [5, 18, 22, 30], 22 is in range [20,24]. +# Note: +# The given list may contain duplicates, so ascending order means >= here. +# 1 <= k <= 3500 +# -105 <= value of elements <= 10^5. +# For Java users, please note that the input type has been changed to List>. +# And after you reset the code template, you'll see this point. + +class Solution(object): + def smallestRange(self, nums): + """ + :type nums: List[List[int]] + :rtype: List[int] + """ + left, right = float("inf"), float("-inf") + min_heap = [] + for row in nums: + left = min(left, row[0]) + right = max(right, row[0]) + it = iter(row) + heapq.heappush(min_heap, (next(it, None), it)) + + result = (left, right) + while min_heap: + (val, it) = heapq.heappop(min_heap) + val = next(it, None) + if val is None: + break + heapq.heappush(min_heap, (val, it)) + left, right = min_heap[0][0], max(right, val); + if right - left < result[1] - result[0]: + result = (left, right) + return result From 3bb08bbaccee83ba698f8fd3e81e4fd153698cf5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 11 Jul 2017 01:08:36 +0800 Subject: [PATCH 3415/4971] Update smallest-range.py --- Python/smallest-range.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/smallest-range.py b/Python/smallest-range.py index c49850f6b..280dd05cf 100644 --- a/Python/smallest-range.py +++ b/Python/smallest-range.py @@ -16,7 +16,7 @@ # Note: # The given list may contain duplicates, so ascending order means >= here. # 1 <= k <= 3500 -# -105 <= value of elements <= 10^5. +# -10^5 <= value of elements <= 10^5. # For Java users, please note that the input type has been changed to List>. # And after you reset the code template, you'll see this point. From a04de78220e740660ef469aac25aec725f33f87c Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 12 Jul 2017 22:58:15 +0800 Subject: [PATCH 3416/4971] add --- C++/sum-of-square-numbers.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 C++/sum-of-square-numbers.cpp diff --git a/C++/sum-of-square-numbers.cpp b/C++/sum-of-square-numbers.cpp new file mode 100644 index 000000000..1d8272234 --- /dev/null +++ b/C++/sum-of-square-numbers.cpp @@ -0,0 +1,16 @@ +// Time: O(sqrt(c) * logc) +// Space: O(1) + +class Solution { +public: + bool judgeSquareSum(int c) { + for (long long a = 0; a * a <= c; ++a) { + auto b = static_cast(sqrt(c - a * a)); + if (c - a * a == b * b) { + return true; + } + } + return false; + } +}; + From bc45ffea97472b666dd3366655ed0c1a035f7956 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 12 Jul 2017 23:00:58 +0800 Subject: [PATCH 3417/4971] update --- C++/sum-of-square-numbers.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/sum-of-square-numbers.cpp b/C++/sum-of-square-numbers.cpp index 1d8272234..bf24612ce 100644 --- a/C++/sum-of-square-numbers.cpp +++ b/C++/sum-of-square-numbers.cpp @@ -6,7 +6,7 @@ class Solution { bool judgeSquareSum(int c) { for (long long a = 0; a * a <= c; ++a) { auto b = static_cast(sqrt(c - a * a)); - if (c - a * a == b * b) { + if (a * a + b * b == c) { return true; } } From b0b1df65fcd9286e9e45edd8e5aaeaaca84c15c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 12 Jul 2017 23:10:07 +0800 Subject: [PATCH 3418/4971] Create sum-of-square-numbers.py --- Python/sum-of-square-numbers.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Python/sum-of-square-numbers.py diff --git a/Python/sum-of-square-numbers.py b/Python/sum-of-square-numbers.py new file mode 100644 index 000000000..bf1a22f24 --- /dev/null +++ b/Python/sum-of-square-numbers.py @@ -0,0 +1,25 @@ +# Time: O(sqrt(c) * logc) +# Space: O(1) + +# Given a non-negative integer c, your task is to decide +# whether there're two integers a and b such that a2 + b2 = c. +# +# Example 1: +# Input: 5 +# Output: True +# Explanation: 1 * 1 + 2 * 2 = 5 +# Example 2: +# Input: 3 +# Output: False + +class Solution(object): + def judgeSquareSum(self, c): + """ + :type c: int + :rtype: bool + """ + for a in xrange(int(math.sqrt(c))+1): + b = int(math.sqrt(c-a**2)) + if a**2 + b**2 == c: + return True + return False From bcefbd8afdf414eb1740d9b98d3fbbec8739d6d8 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 13 Jul 2017 23:48:42 +0800 Subject: [PATCH 3419/4971] add --- C++/find-the-derangement-of-an-array.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 C++/find-the-derangement-of-an-array.cpp diff --git a/C++/find-the-derangement-of-an-array.cpp b/C++/find-the-derangement-of-an-array.cpp new file mode 100644 index 000000000..2293e7719 --- /dev/null +++ b/C++/find-the-derangement-of-an-array.cpp @@ -0,0 +1,16 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findDerangement(int n) { + static const int M = 1000000007; + long long mul = 1, sum = 0; + for (int i = n; i >= 0; --i) { + sum = (sum + M + (i % 2 == 0 ? 1 : -1) * mul) % M; + mul = (mul * i) % M; + } + return static_cast(sum); + } +}; + From cb05f4ad2bdf136e262f5341089714370c995f5c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 13 Jul 2017 23:50:18 +0800 Subject: [PATCH 3420/4971] Create find-the-derangement-of-an-array.py --- Python/find-the-derangement-of-an-array.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Python/find-the-derangement-of-an-array.py diff --git a/Python/find-the-derangement-of-an-array.py b/Python/find-the-derangement-of-an-array.py new file mode 100644 index 000000000..67ac500b2 --- /dev/null +++ b/Python/find-the-derangement-of-an-array.py @@ -0,0 +1,15 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def findDerangement(self, n): + """ + :type n: int + :rtype: int + """ + M = 1000000007 + mul, total = 1, 0 + for i in reversed(xrange(n+1)): + total = (total + M + (1 if i % 2 == 0 else -1) * mul) % M + mul = (mul * i) % M + return total From e6174d2e2d94c8057a898aa765eb3a8eaee8b3fe Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Fri, 14 Jul 2017 23:54:48 +0800 Subject: [PATCH 3421/4971] add --- C++/average-of-levels-in-binary-tree.cpp | 40 ++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/average-of-levels-in-binary-tree.cpp diff --git a/C++/average-of-levels-in-binary-tree.cpp b/C++/average-of-levels-in-binary-tree.cpp new file mode 100644 index 000000000..721878b5e --- /dev/null +++ b/C++/average-of-levels-in-binary-tree.cpp @@ -0,0 +1,40 @@ +// 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: + vector averageOfLevels(TreeNode* root) { + vector result; + queue q; + q.emplace(root); + while (!q.empty()) { + int64_t sum = 0, count = 0; + queue next; + while (!q.empty()) { + auto n = q.front(); + q.pop(); + sum += n->val; + ++count; + if (n->left) { + next.emplace(n->left); + } + if (n->right) { + next.emplace(n->right); + } + } + swap(q, next); + result.emplace_back(sum * 1.0 / count); + } + return result; + } +}; + From a46f960e811123a137e4e5fe4350f6a850e9b33e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 15 Jul 2017 00:03:51 +0800 Subject: [PATCH 3422/4971] Create average-of-levels-in-binary-tree.py --- Python/average-of-levels-in-binary-tree.py | 50 ++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/average-of-levels-in-binary-tree.py diff --git a/Python/average-of-levels-in-binary-tree.py b/Python/average-of-levels-in-binary-tree.py new file mode 100644 index 000000000..572699d3c --- /dev/null +++ b/Python/average-of-levels-in-binary-tree.py @@ -0,0 +1,50 @@ +# Time: O(n) +# Space: O(h) + +# Given a non-empty binary tree, +# return the average value of the nodes on each level in the form of an array. +# +# Example 1: +# Input: +# 3 +# / \ +# 9 20 +# / \ +# 15 7 +# Output: [3, 14.5, 11] +# Explanation: +# The average value of nodes on level 0 is 3, +# on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. +# +# Note: +# The range of node's value is in the range of 32-bit signed integer. + +# 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 averageOfLevels(self, root): + """ + :type root: TreeNode + :rtype: List[float] + """ + result = [] + q = collections.deque([root]) + while q: + total, count = 0, 0 + next_q = collections.deque([]) + while q: + n = q.popleft() + total += n.val; + count += 1 + if n.left: + next_q.append(n.left) + if n.right: + next_q.append(n.right) + q, next_q = next_q, q + result.append(float(total) / count) + return result From 47277e2428b7c980d842c74318e9ffe2f860a611 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 16 Jul 2017 23:51:02 +0800 Subject: [PATCH 3423/4971] update --- C++/average-of-levels-in-binary-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/average-of-levels-in-binary-tree.cpp b/C++/average-of-levels-in-binary-tree.cpp index 721878b5e..731edd9ee 100644 --- a/C++/average-of-levels-in-binary-tree.cpp +++ b/C++/average-of-levels-in-binary-tree.cpp @@ -17,7 +17,7 @@ class Solution { queue q; q.emplace(root); while (!q.empty()) { - int64_t sum = 0, count = 0; + long long sum = 0, count = 0; queue next; while (!q.empty()) { auto n = q.front(); From a68b16c154267682c8e158c5bad03f055db54f65 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 17 Jul 2017 00:19:33 +0800 Subject: [PATCH 3424/4971] add --- C++/exclusive-time-of-functions.cpp | 38 +++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 C++/exclusive-time-of-functions.cpp diff --git a/C++/exclusive-time-of-functions.cpp b/C++/exclusive-time-of-functions.cpp new file mode 100644 index 000000000..84329b6c4 --- /dev/null +++ b/C++/exclusive-time-of-functions.cpp @@ -0,0 +1,38 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector exclusiveTime(int n, vector& logs) { + vector result(n); + stack stk; + int prev = 0; + for (const auto& log : logs) { + vector tokens = split(log, ':'); + if (tokens[1] == "start") { + if (!stk.empty()) { + result[stk.top()] += stoi(tokens[2]) - prev; + } + stk.emplace(stoi(tokens[0])); + prev = stoi(tokens[2]); + } else { + result[stk.top()] += stoi(tokens[2]) - prev + 1; + stk.pop(); + prev = stoi(tokens[2]) + 1; + } + } + return result; + } + +private: + vector split(const string& s, const char delim) { + vector tokens; + stringstream ss(s); + string token; + while (getline(ss, token, delim)) { + tokens.emplace_back(token); + } + return tokens; + } +}; + From e9b81166a732ddfbd472678f15fe3a17d8ed76b0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 17 Jul 2017 00:25:33 +0800 Subject: [PATCH 3425/4971] Create exclusive-time-of-functions.py --- Python/exclusive-time-of-functions.py | 62 +++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Python/exclusive-time-of-functions.py diff --git a/Python/exclusive-time-of-functions.py b/Python/exclusive-time-of-functions.py new file mode 100644 index 000000000..02127e25c --- /dev/null +++ b/Python/exclusive-time-of-functions.py @@ -0,0 +1,62 @@ +# Time: O(n) +# Space: O(n) + +# Given the running logs of n functions that are executed +# in a nonpreemptive single threaded CPU, find the exclusive time of these functions. +# +# Each function has a unique id, start from 0 to n-1. +# A function may be called recursively or by another function. +# +# A log is a string has this format : function_id:start_or_end:timestamp. +# For example, "0:start:0" means function 0 starts from the very beginning of time 0. +# "0:end:0" means function 0 ends to the very end of time 0. +# +# Exclusive time of a function is defined as the time spent within this function, +# the time spent by calling other functions should not be considered as +# this function's exclusive time. +# You should return the exclusive time of each function sorted by their function id. +# +# Example 1: +# Input: +# n = 2 +# logs = +# ["0:start:0", +# "1:start:2", +# "1:end:5", +# "0:end:6"] +# Output:[3, 4] +# +# Explanation: +# Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. +# Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. +# Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. +# So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time. +# +# Note: +# Input logs will be sorted by timestamp, NOT log id. +# Your output should be sorted by function id, +# which means the 0th element of your output corresponds to the exclusive time of function 0. +# Two functions won't start or end at the same time. +# Functions could be called recursively, and will always end. +# 1 <= n <= 100 + +class Solution(object): + def exclusiveTime(self, n, logs): + """ + :type n: int + :type logs: List[str] + :rtype: List[int] + """ + result = [0] * n + stk, prev = [], 0 + for log in logs: + tokens = log.split(":") + if tokens[1] == "start": + if stk: + result[stk[-1]] += int(tokens[2]) - prev + stk.append(int(tokens[0])) + prev = int(tokens[2]) + else: + result[stk.pop()] += int(tokens[2]) - prev + 1 + prev = int(tokens[2]) + 1 + return result From 80bc37e6e9bce5511c3294b12a4a43ec2e9fec7e Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 18 Jul 2017 00:11:25 +0800 Subject: [PATCH 3426/4971] add --- C++/shopping-offers.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/shopping-offers.cpp diff --git a/C++/shopping-offers.cpp b/C++/shopping-offers.cpp new file mode 100644 index 000000000..e92b4696e --- /dev/null +++ b/C++/shopping-offers.cpp @@ -0,0 +1,31 @@ +// Time: O(n * 2^n) +// Space: O(n) + +class Solution { +public: + int shoppingOffers(vector& price, vector>& special, vector& needs) { + return shoppingOffersHelper(price, special, needs, 0); + } + +private: + int shoppingOffersHelper(const vector& price, const vector>& special, vector& needs, int i) { + if (i == special.size()) { + return inner_product(price.begin(), price.end(), needs.begin(), 0); + } + + int result = shoppingOffersHelper(price, special, needs, i + 1); + + for (int j = 0; j < special[i].size() - 1; ++j) { + needs[j] -= special[i][j]; + } + if (all_of(needs.begin(), needs.end(), [](int i) { return i >= 0; })) { + result = min(result, special[i].back() + shoppingOffersHelper(price, special, needs, i)); + } + for (int j = 0; j < special[i].size() - 1; ++j) { + needs[j] += special[i][j]; + } + + return result; + } +}; + From 9c690556f801960e1eb0096188228638946c9de8 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 18 Jul 2017 00:36:46 +0800 Subject: [PATCH 3427/4971] update --- C++/shopping-offers.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/shopping-offers.cpp b/C++/shopping-offers.cpp index e92b4696e..09b8ec402 100644 --- a/C++/shopping-offers.cpp +++ b/C++/shopping-offers.cpp @@ -15,13 +15,13 @@ class Solution { int result = shoppingOffersHelper(price, special, needs, i + 1); - for (int j = 0; j < special[i].size() - 1; ++j) { + for (int j = 0; j < needs.size(); ++j) { needs[j] -= special[i][j]; } if (all_of(needs.begin(), needs.end(), [](int i) { return i >= 0; })) { result = min(result, special[i].back() + shoppingOffersHelper(price, special, needs, i)); } - for (int j = 0; j < special[i].size() - 1; ++j) { + for (int j = 0; j < needs.size(); ++j) { needs[j] += special[i][j]; } From e78eac59849fc80311bc760697f52922de074d50 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 18 Jul 2017 00:39:10 +0800 Subject: [PATCH 3428/4971] Create shopping-offers.py --- Python/shopping-offers.py | 60 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/shopping-offers.py diff --git a/Python/shopping-offers.py b/Python/shopping-offers.py new file mode 100644 index 000000000..63fe142b0 --- /dev/null +++ b/Python/shopping-offers.py @@ -0,0 +1,60 @@ +# Time: O(n * 2^n) +# Space: O(n) + +# In LeetCode Store, there are some kinds of items to sell. Each item has a price. +# +# However, there are some special offers, and a special offer consists of one or +# more different kinds of items with a sale price. +# +# You are given the each item's price, a set of special offers, +# and the number we need to buy for each item. The job is to output the lowest price you have to pay +# for exactly certain items as given, where you could make optimal use of the special offers. +# +# Each special offer is represented in the form of an array, +# the last number represents the price you need to pay for this special offer, +# other numbers represents how many specific items you could get if you buy this offer. +# +# You could use any of special offers as many times as you want. +# +# Example 1: +# Input: [2,5], [[3,0,5],[1,2,10]], [3,2] +# Output: 14 +# Explanation: +# There are two kinds of items, A and B. Their prices are $2 and $5 respectively. +# In special offer 1, you can pay $5 for 3A and 0B +# In special offer 2, you can pay $10 for 1A and 2B. +# You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. +# Example 2: +# Input: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1] +# Output: 11 +# Explanation: +# The price of A is $2, and $3 for B, $4 for C. +# You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. +# You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. +# You cannot add more items, though only $9 for 2A ,2B and 1C. +# Note: +# There are at most 6 kinds of items, 100 special offers. +# For each item, you need to buy at most 6 of them. +# You are not allowed to buy more items than you want, even if that would lower the overall price. + +class Solution(object): + def shoppingOffers(self, price, special, needs): + """ + :type price: List[int] + :type special: List[List[int]] + :type needs: List[int] + :rtype: int + """ + def shoppingOffersHelper(price, special, needs, i): + if i == len(special): + return sum(map(lambda x, y: x*y, price, needs)) + result = shoppingOffersHelper(price, special, needs, i+1) + for j in xrange(len(needs)): + needs[j] -= special[i][j] + if all(need >= 0 for need in needs): + result = min(result, special[i][-1] + shoppingOffersHelper(price, special, needs, i)) + for j in xrange(len(needs)): + needs[j] += special[i][j] + return result + + return shoppingOffersHelper(price, special, needs, 0) From ab28c6b087a6f194e25a78398db5a7a6fdcf99d2 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 19 Jul 2017 00:00:42 +0800 Subject: [PATCH 3429/4971] add --- C++/decode-ways-ii.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/decode-ways-ii.cpp diff --git a/C++/decode-ways-ii.cpp b/C++/decode-ways-ii.cpp new file mode 100644 index 000000000..25429a0be --- /dev/null +++ b/C++/decode-ways-ii.cpp @@ -0,0 +1,35 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int numDecodings(string s) { + static const int M = 1000000007; + static const int W = 3; + vector dp(W); + dp[0] = 1; + dp[1] = s[0] == '*' ? 9 : (s[0] == '0' ? 0 : 1); + for (int i = 1; i < s.length(); ++i) { + if (s[i] == '*') { + dp[(i + 1) % W] = 9 * dp[i % W]; + if (s[i - 1] == '1') { + dp[(i + 1) % W] = (dp[(i + 1) % W] + 9 * dp[(i - 1) % W]) % M; + } else if (s[i - 1] == '2') { + dp[(i + 1) % W] = (dp[(i + 1) % W] + 6 * dp[(i - 1) % W]) % M; + } else if (s[i - 1] == '*') { + dp[(i + 1) % W] = (dp[(i + 1) % W] + 15 * dp[(i - 1) % W]) % M; + } + } else { + dp[(i + 1) % W] = s[i] != '0' ? dp[i % W] : 0; + if (s[i - 1] == '1') { + dp[(i + 1) % W] = (dp[(i + 1) % W] + dp[(i - 1) % W]) % M; + } else if (s[i - 1] == '2' && s[i] <= '6') { + dp[(i + 1) % W] = (dp[(i + 1) % W] + dp[(i - 1) % W]) % M; + } else if (s[i - 1] == '*') { + dp[(i + 1) % W] = (dp[(i + 1) % W] + (s[i] <= '6' ? 2 : 1) * dp[(i - 1) % W]) % M; + } + } + } + return static_cast(dp[s.length() % W]); + } +}; From 71ba9f9625535908c9739565429736876b347ad7 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 19 Jul 2017 00:02:53 +0800 Subject: [PATCH 3430/4971] update --- C++/decode-ways-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/decode-ways-ii.cpp b/C++/decode-ways-ii.cpp index 25429a0be..752e69bcb 100644 --- a/C++/decode-ways-ii.cpp +++ b/C++/decode-ways-ii.cpp @@ -8,7 +8,7 @@ class Solution { static const int W = 3; vector dp(W); dp[0] = 1; - dp[1] = s[0] == '*' ? 9 : (s[0] == '0' ? 0 : 1); + dp[1] = s[0] == '*' ? 9 : (s[0] != '0' ? 1 : 0); for (int i = 1; i < s.length(); ++i) { if (s[i] == '*') { dp[(i + 1) % W] = 9 * dp[i % W]; From 86be544db0a920fd942f9479769c8fca5da3e2b1 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 19 Jul 2017 00:07:34 +0800 Subject: [PATCH 3431/4971] update --- C++/decode-ways-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/decode-ways-ii.cpp b/C++/decode-ways-ii.cpp index 752e69bcb..40e586fb5 100644 --- a/C++/decode-ways-ii.cpp +++ b/C++/decode-ways-ii.cpp @@ -8,7 +8,7 @@ class Solution { static const int W = 3; vector dp(W); dp[0] = 1; - dp[1] = s[0] == '*' ? 9 : (s[0] != '0' ? 1 : 0); + dp[1] = s[0] == '*' ? 9 : (s[0] != '0' ? dp[0] : 0); for (int i = 1; i < s.length(); ++i) { if (s[i] == '*') { dp[(i + 1) % W] = 9 * dp[i % W]; From 6616b9db668a5b65bd7553a5c2a8808728e33364 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Jul 2017 00:09:34 +0800 Subject: [PATCH 3432/4971] Create decode-ways-ii.py --- Python/decode-ways-ii.py | 55 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/decode-ways-ii.py diff --git a/Python/decode-ways-ii.py b/Python/decode-ways-ii.py new file mode 100644 index 000000000..f628b3f00 --- /dev/null +++ b/Python/decode-ways-ii.py @@ -0,0 +1,55 @@ +# Time: O(n) +# Space: O(1) + +# A message containing letters from A-Z is being encoded to numbers using the following mapping way: +# +# 'A' -> 1 +# 'B' -> 2 +# ... +# 'Z' -> 26 +# Beyond that, now the encoded string can also contain the character '*', +# which can be treated as one of the numbers from 1 to 9. +# +# Given the encoded message containing digits and the character '*', return the total number of ways to decode it. +# +# Also, since the answer may be very large, you should return the output mod 109 + 7. +# +# Example 1: +# Input: "*" +# Output: 9 +# Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I". +# Example 2: +# Input: "1*" +# Output: 9 + 9 = 18 +# Note: +# The length of the input string will fit in range [1, 105]. +# The input string will only contain the character '*' and digits '0' - '9'. + +class Solution(object): + def numDecodings(self, s): + """ + :type s: str + :rtype: int + """ + M, W = 1000000007, 3 + dp = [0] * W + dp[0] = 1 + dp[1] = 9 if s[0] == '*' else dp[0] if s[0] != '0' else 0 + for i in xrange(1, len(s)): + if s[i] == '*': + dp[(i + 1) % W] = 9 * dp[i % W] + if s[i - 1] == '1': + dp[(i + 1) % W] = (dp[(i + 1) % W] + 9 * dp[(i - 1) % W]) % M + elif s[i - 1] == '2': + dp[(i + 1) % W] = (dp[(i + 1) % W] + 6 * dp[(i - 1) % W]) % M + elif s[i - 1] == '*': + dp[(i + 1) % W] = (dp[(i + 1) % W] + 15 * dp[(i - 1) % W]) % M + else: + dp[(i + 1) % W] = dp[i % W] if s[i] != '0' else 0 + if s[i - 1] == '1': + dp[(i + 1) % W] = (dp[(i + 1) % W] + dp[(i - 1) % W]) % M + elif s[i - 1] == '2' and s[i] <= '6': + dp[(i + 1) % W] = (dp[(i + 1) % W] + dp[(i - 1) % W]) % M + elif s[i - 1] == '*': + dp[(i + 1) % W] = (dp[(i + 1) % W] + (2 if s[i] <= '6' else 1) * dp[(i - 1) % W]) % M + return dp[len(s) % W] From c5e598a3bdc28ccded76d247e40c0585be487cab Mon Sep 17 00:00:00 2001 From: Swaroop Gadiyaram Date: Tue, 18 Jul 2017 17:57:25 -0700 Subject: [PATCH 3433/4971] Update merge-two-binary-trees.py Added self for recursive calls --- Python/merge-two-binary-trees.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/merge-two-binary-trees.py b/Python/merge-two-binary-trees.py index 02e15e449..3fc1c04ef 100644 --- a/Python/merge-two-binary-trees.py +++ b/Python/merge-two-binary-trees.py @@ -48,6 +48,6 @@ def mergeTrees(self, t1, t2): if t2 is None: return t1 t1.val += t2.val - t1.left = mergeTrees(t1.left, t2.left) - t1.right = mergeTrees(t1.right, t2.right) + t1.left = self.mergeTrees(t1.left, t2.left) + t1.right = self.mergeTrees(t1.right, t2.right) return t1 From 692851a78fb0b196536bf62badd2435dc67bf347 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 19 Jul 2017 10:37:54 +0800 Subject: [PATCH 3434/4971] Update first-unique-character-in-a-string.py --- Python/first-unique-character-in-a-string.py | 33 ++++---------------- 1 file changed, 6 insertions(+), 27 deletions(-) diff --git a/Python/first-unique-character-in-a-string.py b/Python/first-unique-character-in-a-string.py index 3994a8649..9dbbff04e 100644 --- a/Python/first-unique-character-in-a-string.py +++ b/Python/first-unique-character-in-a-string.py @@ -12,44 +12,23 @@ # s = "loveleetcode", # return 2. # Note: You may assume the string contain only lowercase letters. -import collections -import string +from collections import defaultdict + class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ - lookup = collections.defaultdict(int) + lookup = defaultdict(int) candidtates = set() for i, c in enumerate(s): if lookup[c]: candidtates.discard(lookup[c]) else: - lookup[c] = i + 1 - candidtates.add(i + 1) - - return min(candidtates) - 1 if candidtates else -1 + lookup[c] = i+1 + candidtates.add(i+1) - def firstUniqChar2(self, s): - """ - :type s: str - :rtype: int - """ - return min([s.find(c) for c in string.ascii_lowercase if s.count(c) == 1] or [-1]) - - def firstUniqChar3(self, s): - """ - :type s: str - :rtype: int - """ - cnt = collections.Counter(s) - if cnt: - for i in cnt.keys(): - if cnt[i] == 1: - return s.index(i) - return -1 - else: - return -1 + return min(candidtates)-1 if candidtates else -1 From 3ed65938e6b801cb656f017c9dbdf726b349356b Mon Sep 17 00:00:00 2001 From: Swaroop Gadiyaram Date: Tue, 18 Jul 2017 22:01:36 -0700 Subject: [PATCH 3435/4971] Update valid-anagram.py Added two more methods --- Python/valid-anagram.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Python/valid-anagram.py b/Python/valid-anagram.py index 5fe61e61e..0477caec1 100644 --- a/Python/valid-anagram.py +++ b/Python/valid-anagram.py @@ -37,6 +37,21 @@ def isAnagram(self, s, t): return False return True + + def isAnagram2(self, s, t): + return all([s.count(c)==t.count(c) for c in string.ascii_lowercase]) + + def isAnagram3(self, s, t): + if len(s) != len(t): + return False + count = collections.defaultdict(int) + for c in s: + count[c] += 1 + for c in t: + count[c] -= 1 + if count[c] < 0: + return False + return True # Time: O(nlogn) # Space: O(n) From e519727b28ced51001c1f580b6dbffe116c161fd Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 20 Jul 2017 23:08:36 +0800 Subject: [PATCH 3436/4971] add --- C++/solve-the-equation.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/solve-the-equation.cpp diff --git a/C++/solve-the-equation.cpp b/C++/solve-the-equation.cpp new file mode 100644 index 000000000..dcdd4206a --- /dev/null +++ b/C++/solve-the-equation.cpp @@ -0,0 +1,29 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + string solveEquation(string equation) { + equation = regex_replace(equation, regex("(^|[+=-])x"), "$011x"); + + auto pos = equation.find('='); + auto l = coef(equation.substr(0, pos)); + auto r = coef(equation.substr(pos + 1)); + + auto a = l.first - r.first; + auto b = r.second - l.second; + + return a != 0 ? "x=" + to_string(b / a) : b != 0 ? "No solution" : "Infinite solutions"; + } + +private: + pair coef(string s) { + auto a = 0, b = 0; + auto e = regex("(^|[+-])\\d+x?"); + for (regex_token_iterator it(s.begin(), s.end(), e), end; + it != end; ++it) { + (it->str().back() == 'x' ? a : b) += stoi(*it); + } + return {a, b}; + } +}; From a7cbffc4ad33f100299000a459041626963d19f5 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 20 Jul 2017 23:53:01 +0800 Subject: [PATCH 3437/4971] update --- C++/solve-the-equation.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/C++/solve-the-equation.cpp b/C++/solve-the-equation.cpp index dcdd4206a..cacf34c27 100644 --- a/C++/solve-the-equation.cpp +++ b/C++/solve-the-equation.cpp @@ -2,6 +2,33 @@ // Space: O(n) class Solution { +public: + string solveEquation(string equation) { + auto a = 0, b = 0; + auto side = 1; + int submatches[] = { 1, 2, 3, 4 }; + auto e = regex("(=)|([-+]?)(\\d*)(x?)"); + for (regex_token_iterator it(equation.begin(), equation.end(), e, submatches), end; + it != end;) { + auto eq = (it++)->str(); + auto sign = (it++)->str(); + auto num = (it++)->str(); + auto isx = (it++)->str(); + if (!eq.empty()) { + side = -1; + } else if (!isx.empty()) { + a += side * stoi(sign + "1") * stoi(num.empty() ? "1" : num); + } else if (!num.empty()) { + b -= side * stoi(sign + num); + } + } + return a != 0 ? "x=" + to_string(b / a) : b != 0 ? "No solution" : "Infinite solutions"; + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { public: string solveEquation(string equation) { equation = regex_replace(equation, regex("(^|[+=-])x"), "$011x"); From 71c8e8e3d6395b51a453e591bee882cd3e024d26 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 20 Jul 2017 23:56:39 +0800 Subject: [PATCH 3438/4971] Create solve-the-equation.py --- Python/solve-the-equation.py | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/solve-the-equation.py diff --git a/Python/solve-the-equation.py b/Python/solve-the-equation.py new file mode 100644 index 000000000..9e6ee9a68 --- /dev/null +++ b/Python/solve-the-equation.py @@ -0,0 +1,44 @@ +# Time: O(n) +# Space: O(n) + +# Solve a given equation and return the value of x in the form of string "x=#value". +# The equation contains only '+', '-' operation, the variable x and its coefficient. +# +# If there is no solution for the equation, return "No solution". +# +# If there are infinite solutions for the equation, return "Infinite solutions". +# +# If there is exactly one solution for the equation, we ensure that the value of x is an integer. +# +# Example 1: +# Input: "x+5-3+x=6+x-2" +# Output: "x=2" +# Example 2: +# Input: "x=x" +# Output: "Infinite solutions" +# Example 3: +# Input: "2x=x" +# Output: "x=0" +# Example 4: +# Input: "2x+3x-6x=x+2" +# Output: "x=-1" +# Example 5: +# Input: "x=x+2" +# Output: "No solution" + +class Solution(object): + def solveEquation(self, equation): + """ + :type equation: str + :rtype: str + """ + a, b = 0, 0 + side = 1 + for eq, sign, num, isx in re.findall('(=)|([-+]?)(\d*)(x?)', equation): + if eq: + side = -1 + elif isx: + a += side * int(sign + '1') * int(num or 1) + elif num: + b -= side * int(sign + num) + return 'x=%d' % (b / a) if a else 'No solution' if b else 'Infinite solutions' From fac68c9f3e8a24bc2d74b810b8118188db7ef616 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 21 Jul 2017 00:04:09 +0800 Subject: [PATCH 3439/4971] Update solve-the-equation.py --- Python/solve-the-equation.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/solve-the-equation.py b/Python/solve-the-equation.py index 9e6ee9a68..a5ccdb1bb 100644 --- a/Python/solve-the-equation.py +++ b/Python/solve-the-equation.py @@ -32,8 +32,7 @@ def solveEquation(self, equation): :type equation: str :rtype: str """ - a, b = 0, 0 - side = 1 + a, b, side = 0, 0, 1 for eq, sign, num, isx in re.findall('(=)|([-+]?)(\d*)(x?)', equation): if eq: side = -1 From c55a1ed0400a9f1ac5fcfc334f85483e6baf85c3 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 22 Jul 2017 22:52:37 +0800 Subject: [PATCH 3440/4971] add --- C++/design-search-autocomplete-system.cpp | 107 ++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 C++/design-search-autocomplete-system.cpp diff --git a/C++/design-search-autocomplete-system.cpp b/C++/design-search-autocomplete-system.cpp new file mode 100644 index 000000000..545388d73 --- /dev/null +++ b/C++/design-search-autocomplete-system.cpp @@ -0,0 +1,107 @@ +class AutocompleteSystem { +public: + AutocompleteSystem(vector sentences, vector times) { + for (int i = 0; i < sentences.size(); ++i) { + trie_.insert(sentences[i], times[i]); + } + } + + vector input(char c) { + if (c == '#') { + trie_.insert(cur_sent_, 1); + cur_sent_.clear(); + return {}; + } else { + cur_sent_.push_back(c); + } + return trie_.lookup(cur_sent_); + } + +private: + class TrieNode { + public: + using P = pair; + class Compare { + public: + bool operator()(const P& p1, const P& p2) { + return p1.first != p2.first ? p1.first > p2.first : p1.second < p2.second; + } + }; + + void insert(const string& s, int times) { + auto* p = this; + for (const auto& c : s) { + if (!p->leaves_.count(c)) { + p->leaves_[c] = new TrieNode; + } + p = p->leaves_[c]; + } + p->times_ += times; + } + + vector lookup(string& s) { + auto* p = this; + for (const auto& c : s) { + if (!p->leaves_.count(c)) { + return {}; + } + p = p->leaves_[c]; + } + priority_queue, Compare> min_heap; + traverseHelper(s, p, &min_heap); + vector result; + while (!min_heap.empty()) { + cout << min_heap.top().second << endl; + result.emplace_back(min_heap.top().second); + min_heap.pop(); + } + reverse(result.begin(), result.end()); + return result; + } + + void traverseHelper(string& s, TrieNode *t, priority_queue, Compare> *min_heap) { + if (t->times_ > 0) { + min_heap->emplace(t->times_, s); + if (min_heap->size() == 4) { + min_heap->pop(); + } + } + + for (auto i = 'a'; i <= 'z'; ++i) { + if (t->leaves_.count(i)) { + s.push_back(i); + traverseHelper(s, t->leaves_[i], min_heap); + s.pop_back(); + } + } + if (t->leaves_.count(' ')) { + s.push_back(' '); + traverseHelper(s, t->leaves_[' '], min_heap); + s.pop_back(); + } + } + + TrieNode() : times_(0) { + } + + ~TrieNode() { + for (auto& kv : leaves_) { + if (kv.second) { + delete kv.second; + } + } + } + private: + unordered_map leaves_; + int times_; + }; + + TrieNode trie_; + string cur_sent_; +}; + +/** + * Your AutocompleteSystem object will be instantiated and called as such: + * AutocompleteSystem obj = new AutocompleteSystem(sentences, times); + * vector param_1 = obj.input(c); + */ From ca250b7c7c87f2313a122d909a9b4c5cad46db6e Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 22 Jul 2017 23:02:22 +0800 Subject: [PATCH 3441/4971] add --- C++/design-search-autocomplete-system.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/C++/design-search-autocomplete-system.cpp b/C++/design-search-autocomplete-system.cpp index 545388d73..a6e938bcd 100644 --- a/C++/design-search-autocomplete-system.cpp +++ b/C++/design-search-autocomplete-system.cpp @@ -1,3 +1,7 @@ +// Time: O(s + n), s is the length of the prefix, +// n is the number of the subtree nodes of trie given with the prefix +// Space: O(t), t is the size of trie + class AutocompleteSystem { public: AutocompleteSystem(vector sentences, vector times) { @@ -7,14 +11,15 @@ class AutocompleteSystem { } vector input(char c) { + vector result; if (c == '#') { trie_.insert(cur_sent_, 1); cur_sent_.clear(); - return {}; } else { cur_sent_.push_back(c); + result = trie_.lookup(cur_sent_); } - return trie_.lookup(cur_sent_); + return result; } private: @@ -28,6 +33,7 @@ class AutocompleteSystem { } }; + // Time: O(s) void insert(const string& s, int times) { auto* p = this; for (const auto& c : s) { @@ -39,6 +45,7 @@ class AutocompleteSystem { p->times_ += times; } + // Time: O(s + n) vector lookup(string& s) { auto* p = this; for (const auto& c : s) { @@ -51,7 +58,6 @@ class AutocompleteSystem { traverseHelper(s, p, &min_heap); vector result; while (!min_heap.empty()) { - cout << min_heap.top().second << endl; result.emplace_back(min_heap.top().second); min_heap.pop(); } @@ -59,6 +65,7 @@ class AutocompleteSystem { return result; } + // Time: O(n) void traverseHelper(string& s, TrieNode *t, priority_queue, Compare> *min_heap) { if (t->times_ > 0) { min_heap->emplace(t->times_, s); @@ -104,4 +111,4 @@ class AutocompleteSystem { * Your AutocompleteSystem object will be instantiated and called as such: * AutocompleteSystem obj = new AutocompleteSystem(sentences, times); * vector param_1 = obj.input(c); - */ + */ \ No newline at end of file From 948b10db478553d2b10575aae510657edae53cc6 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 22 Jul 2017 23:14:48 +0800 Subject: [PATCH 3442/4971] update --- C++/design-search-autocomplete-system.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/C++/design-search-autocomplete-system.cpp b/C++/design-search-autocomplete-system.cpp index a6e938bcd..917e76af7 100644 --- a/C++/design-search-autocomplete-system.cpp +++ b/C++/design-search-autocomplete-system.cpp @@ -25,7 +25,8 @@ class AutocompleteSystem { private: class TrieNode { public: - using P = pair; + using P = pair; + static const int TOP_COUNT = 3; class Compare { public: bool operator()(const P& p1, const P& p2) { @@ -69,7 +70,7 @@ class AutocompleteSystem { void traverseHelper(string& s, TrieNode *t, priority_queue, Compare> *min_heap) { if (t->times_ > 0) { min_heap->emplace(t->times_, s); - if (min_heap->size() == 4) { + if (min_heap->size() == TOP_COUNT + 1) { min_heap->pop(); } } From f33e031386ca5738167084445140d418bd5cb7df Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 22 Jul 2017 23:16:47 +0800 Subject: [PATCH 3443/4971] update --- C++/design-search-autocomplete-system.cpp | 25 ++++++++++++----------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/C++/design-search-autocomplete-system.cpp b/C++/design-search-autocomplete-system.cpp index 917e76af7..b37d16a38 100644 --- a/C++/design-search-autocomplete-system.cpp +++ b/C++/design-search-autocomplete-system.cpp @@ -34,6 +34,17 @@ class AutocompleteSystem { } }; + TrieNode() : times_(0) { + } + + ~TrieNode() { + for (auto& kv : leaves_) { + if (kv.second) { + delete kv.second; + } + } + } + // Time: O(s) void insert(const string& s, int times) { auto* p = this; @@ -65,7 +76,8 @@ class AutocompleteSystem { reverse(result.begin(), result.end()); return result; } - + + private: // Time: O(n) void traverseHelper(string& s, TrieNode *t, priority_queue, Compare> *min_heap) { if (t->times_ > 0) { @@ -89,17 +101,6 @@ class AutocompleteSystem { } } - TrieNode() : times_(0) { - } - - ~TrieNode() { - for (auto& kv : leaves_) { - if (kv.second) { - delete kv.second; - } - } - } - private: unordered_map leaves_; int times_; }; From 884bd83248e17a0abf8e95dd3d3b80402cfab1ea Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 22 Jul 2017 23:18:16 +0800 Subject: [PATCH 3444/4971] update --- C++/design-search-autocomplete-system.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/design-search-autocomplete-system.cpp b/C++/design-search-autocomplete-system.cpp index b37d16a38..d34625943 100644 --- a/C++/design-search-autocomplete-system.cpp +++ b/C++/design-search-autocomplete-system.cpp @@ -27,6 +27,7 @@ class AutocompleteSystem { public: using P = pair; static const int TOP_COUNT = 3; + class Compare { public: bool operator()(const P& p1, const P& p2) { @@ -77,7 +78,7 @@ class AutocompleteSystem { return result; } - private: + private: // Time: O(n) void traverseHelper(string& s, TrieNode *t, priority_queue, Compare> *min_heap) { if (t->times_ > 0) { From d26a71dfa75ae56af6b386a41ab745296fcdbe7d Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 23 Jul 2017 02:09:26 +0800 Subject: [PATCH 3445/4971] update --- C++/design-search-autocomplete-system.cpp | 106 ++++++++-------------- 1 file changed, 40 insertions(+), 66 deletions(-) diff --git a/C++/design-search-autocomplete-system.cpp b/C++/design-search-autocomplete-system.cpp index d34625943..b64dbf642 100644 --- a/C++/design-search-autocomplete-system.cpp +++ b/C++/design-search-autocomplete-system.cpp @@ -1,23 +1,34 @@ -// Time: O(s + n), s is the length of the prefix, -// n is the number of the subtree nodes of trie given with the prefix +// Time: O(s), s is the length of the prefix // Space: O(t), t is the size of trie class AutocompleteSystem { public: - AutocompleteSystem(vector sentences, vector times) { + AutocompleteSystem(vector sentences, vector times) : cur_node_(&trie_) { for (int i = 0; i < sentences.size(); ++i) { - trie_.insert(sentences[i], times[i]); + sentence_to_count_[sentences[i]] = times[i]; + trie_.insert(sentences[i], sentence_to_count_[sentences[i]]); } } vector input(char c) { vector result; if (c == '#') { - trie_.insert(cur_sent_, 1); - cur_sent_.clear(); + ++sentence_to_count_[search_]; + trie_.insert(search_, sentence_to_count_[search_]); + cur_node_ = &trie_; + search_.clear(); } else { - cur_sent_.push_back(c); - result = trie_.lookup(cur_sent_); + search_.push_back(c); + if (cur_node_) { + if (!cur_node_->leaves_.count(c)) { + cur_node_ = nullptr; + return {}; + } + cur_node_ = cur_node_->leaves_[c]; + for (const auto& p : cur_node_->infos_) { + result.emplace_back(p.second); + } + } } return result; } @@ -25,19 +36,8 @@ class AutocompleteSystem { private: class TrieNode { public: - using P = pair; static const int TOP_COUNT = 3; - class Compare { - public: - bool operator()(const P& p1, const P& p2) { - return p1.first != p2.first ? p1.first > p2.first : p1.second < p2.second; - } - }; - - TrieNode() : times_(0) { - } - ~TrieNode() { for (auto& kv : leaves_) { if (kv.second) { @@ -48,66 +48,40 @@ class AutocompleteSystem { // Time: O(s) void insert(const string& s, int times) { - auto* p = this; + auto* cur = this; + cur->add_info(s, times); for (const auto& c : s) { - if (!p->leaves_.count(c)) { - p->leaves_[c] = new TrieNode; + if (!cur->leaves_.count(c)) { + cur->leaves_[c] = new TrieNode; } - p = p->leaves_[c]; + cur = cur->leaves_[c]; + cur->add_info(s, times); } - p->times_ += times; } - // Time: O(s + n) - vector lookup(string& s) { - auto* p = this; - for (const auto& c : s) { - if (!p->leaves_.count(c)) { - return {}; - } - p = p->leaves_[c]; - } - priority_queue, Compare> min_heap; - traverseHelper(s, p, &min_heap); - vector result; - while (!min_heap.empty()) { - result.emplace_back(min_heap.top().second); - min_heap.pop(); - } - reverse(result.begin(), result.end()); - return result; - } - - private: - // Time: O(n) - void traverseHelper(string& s, TrieNode *t, priority_queue, Compare> *min_heap) { - if (t->times_ > 0) { - min_heap->emplace(t->times_, s); - if (min_heap->size() == TOP_COUNT + 1) { - min_heap->pop(); - } - } - - for (auto i = 'a'; i <= 'z'; ++i) { - if (t->leaves_.count(i)) { - s.push_back(i); - traverseHelper(s, t->leaves_[i], min_heap); - s.pop_back(); - } + // Time: O(1) + void add_info(const string& s, int times) { + auto it = find_if(infos_.begin(), infos_.end(), + [&s, ×](const pair& p){ return p.second == s;} ); + if (it != infos_.end()) { + it->first = -times; + } else { + infos_.emplace_back(-times, s); } - if (t->leaves_.count(' ')) { - s.push_back(' '); - traverseHelper(s, t->leaves_[' '], min_heap); - s.pop_back(); + sort(infos_.begin(), infos_.end()); + if (infos_.size() > TOP_COUNT) { + infos_.pop_back(); } } + vector> infos_; unordered_map leaves_; - int times_; }; TrieNode trie_; - string cur_sent_; + TrieNode *cur_node_; + string search_; + unordered_map sentence_to_count_; }; /** From 9c733e126117e79f590049ef010c6e3e56208b0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Jul 2017 02:31:18 +0800 Subject: [PATCH 3446/4971] Create design-search-autocomplete-system.py --- Python/design-search-autocomplete-system.py | 74 +++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Python/design-search-autocomplete-system.py diff --git a/Python/design-search-autocomplete-system.py b/Python/design-search-autocomplete-system.py new file mode 100644 index 000000000..a643d7f42 --- /dev/null +++ b/Python/design-search-autocomplete-system.py @@ -0,0 +1,74 @@ +# Time: O(p^2), p is the length of the prefix +# Space: O(p * t), t is the number of nodes of trie + +class TrieNode(object): + + def __init__(self): + self.__TOP_COUNT = 3 + self.infos = [] + self.leaves = {} + + + def insert(self, s, times): + cur = self + cur.add_info(s, times) + for c in s: + if c not in cur.leaves: + cur.leaves[c] = TrieNode() + cur = cur.leaves[c] + cur.add_info(s, times) + + + def add_info(self, s, times): + for p in self.infos: + if p[1] == s: + p[0] = -times + break + else: + self.infos.append([-times, s]) + self.infos.sort() + if len(self.infos) > self.__TOP_COUNT: + self.infos.pop() + + +class AutocompleteSystem(object): + def __init__(self, sentences, times): + """ + :type sentences: List[str] + :type times: List[int] + """ + self.__trie = TrieNode() + self.__cur_node = self.__trie + self.__search = [] + self.__sentence_to_count = collections.defaultdict(int) + for sentence, count in zip(sentences, times): + self.__sentence_to_count[sentence] = count + self.__trie.insert(sentence, count) + + + def input(self, c): + """ + :type c: str + :rtype: List[str] + """ + result = [] + if c == '#': + self.__sentence_to_count["".join(self.__search)] += 1 + self.__trie.insert("".join(self.__search), self.__sentence_to_count["".join(self.__search)]) + self.__cur_node = self.__trie + self.__search = [] + else: + self.__search.append(c) + if self.__cur_node: + if c not in self.__cur_node.leaves: + self.__cur_node = None + return [] + self.__cur_node = self.__cur_node.leaves[c] + result = [p[1] for p in self.__cur_node.infos] + return result + + + +# Your AutocompleteSystem object will be instantiated and called as such: +# obj = AutocompleteSystem(sentences, times) +# param_1 = obj.input(c) From 6624d09979c2ad5d1f1a465949e0c06e27ce09c1 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 23 Jul 2017 02:31:54 +0800 Subject: [PATCH 3447/4971] update --- C++/design-search-autocomplete-system.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/design-search-autocomplete-system.cpp b/C++/design-search-autocomplete-system.cpp index b64dbf642..a943b0bb5 100644 --- a/C++/design-search-autocomplete-system.cpp +++ b/C++/design-search-autocomplete-system.cpp @@ -1,5 +1,5 @@ -// Time: O(s), s is the length of the prefix -// Space: O(t), t is the size of trie +// Time: O(p^2), p is the length of the prefix +// Space: O(p * t), t is the number of nodes of trie class AutocompleteSystem { public: From ee3f9f544c58709cf7df409e67629042e9a7786f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Jul 2017 02:35:10 +0800 Subject: [PATCH 3448/4971] Update design-search-autocomplete-system.py --- Python/design-search-autocomplete-system.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/design-search-autocomplete-system.py b/Python/design-search-autocomplete-system.py index a643d7f42..757a73da0 100644 --- a/Python/design-search-autocomplete-system.py +++ b/Python/design-search-autocomplete-system.py @@ -1,5 +1,6 @@ # Time: O(p^2), p is the length of the prefix -# Space: O(p * t), t is the number of nodes of trie +# Space: O(p * t + s), t is the number of nodes of trie +# , s is the size of the sentences class TrieNode(object): From e717d068486959a6983dc92c4529b5b95c112ce1 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 23 Jul 2017 02:35:48 +0800 Subject: [PATCH 3449/4971] update --- C++/design-search-autocomplete-system.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/design-search-autocomplete-system.cpp b/C++/design-search-autocomplete-system.cpp index a943b0bb5..a93f873d9 100644 --- a/C++/design-search-autocomplete-system.cpp +++ b/C++/design-search-autocomplete-system.cpp @@ -1,5 +1,6 @@ // Time: O(p^2), p is the length of the prefix -// Space: O(p * t), t is the number of nodes of trie +// Space: O(p * t + s), t is the number of nodes of trie +// , s is the size of the sentences class AutocompleteSystem { public: From c5ae855af4c999ab2cbf6d4b5c77a0f04a84c13a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Jul 2017 02:36:46 +0800 Subject: [PATCH 3450/4971] Update design-search-autocomplete-system.py --- Python/design-search-autocomplete-system.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/design-search-autocomplete-system.py b/Python/design-search-autocomplete-system.py index 757a73da0..f7a4d04b7 100644 --- a/Python/design-search-autocomplete-system.py +++ b/Python/design-search-autocomplete-system.py @@ -33,6 +33,7 @@ def add_info(self, s, times): class AutocompleteSystem(object): + def __init__(self, sentences, times): """ :type sentences: List[str] @@ -69,7 +70,6 @@ def input(self, c): return result - # Your AutocompleteSystem object will be instantiated and called as such: # obj = AutocompleteSystem(sentences, times) # param_1 = obj.input(c) From 130df560bf3cf75cf6933f67b83891211c38142e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 23 Jul 2017 02:45:52 +0800 Subject: [PATCH 3451/4971] Delete .gitignore --- .gitignore | 91 ------------------------------------------------------ 1 file changed, 91 deletions(-) delete mode 100644 .gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 4042179a6..000000000 --- a/.gitignore +++ /dev/null @@ -1,91 +0,0 @@ -.idea/ - -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -env/ -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.egg-info/ -.installed.cfg -*.egg - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# IPython Notebook -.ipynb_checkpoints - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule - -# dotenv -.env - -# virtualenv -venv/ -ENV/ - -# Spyder project settings -.spyderproject - -# Rope project settings -.ropeproject From 7b7547b9f8f861094fe7dd50215910b7fbc7970c Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 24 Jul 2017 23:41:33 +0800 Subject: [PATCH 3452/4971] add --- C++/maximum-average-subarray-i.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/maximum-average-subarray-i.cpp diff --git a/C++/maximum-average-subarray-i.cpp b/C++/maximum-average-subarray-i.cpp new file mode 100644 index 000000000..4407e3d1f --- /dev/null +++ b/C++/maximum-average-subarray-i.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + double findMaxAverage(vector& nums, int k) { + double sum = 0; + for (int i = 0; i < k; ++i) { + sum += nums[i]; + } + double result = sum; + for (int i = k; i < nums.size(); ++i) { + sum += nums[i] - nums[i-k]; + result = max(result, sum); + } + return result / k; + } +}; + From f8d8580dfffee35236478ec75116b291499c085c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 24 Jul 2017 23:45:03 +0800 Subject: [PATCH 3453/4971] Create maximum-average-subarray-i.py --- Python/maximum-average-subarray-i.py | 30 ++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/maximum-average-subarray-i.py diff --git a/Python/maximum-average-subarray-i.py b/Python/maximum-average-subarray-i.py new file mode 100644 index 000000000..7f39cf7a6 --- /dev/null +++ b/Python/maximum-average-subarray-i.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(1) + +# Given an array consisting of n integers, +# find the contiguous subarray of given length k that has the maximum average value. +# And you need to output the maximum average value. +# +# Example 1: +# Input: [1,12,-5,-6,50,3], k = 4 +# Output: 12.75 +# Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 +# Note: +# 1 <= k <= n <= 30,000. +# Elements of the given array will be in the range [-10,000, 10,000]. + +class Solution(object): + def findMaxAverage(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: float + """ + total = 0 + for i in xrange(k): + total += nums[i] + result = total + for i in xrange(k, len(nums)): + total += nums[i] - nums[i-k] + result = max(result, total) + return float(result) / k From 3e0a3d3070b5e3b93e8bba2ebeff3aa576606e59 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 25 Jul 2017 23:58:18 +0800 Subject: [PATCH 3454/4971] add --- C++/maximum-average-subarray-ii.cpp | 40 +++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/maximum-average-subarray-ii.cpp diff --git a/C++/maximum-average-subarray-ii.cpp b/C++/maximum-average-subarray-ii.cpp new file mode 100644 index 000000000..9a098cce1 --- /dev/null +++ b/C++/maximum-average-subarray-ii.cpp @@ -0,0 +1,40 @@ +// Time: O(nlog(max_val - min_val)) +// Space: O(1) + +class Solution { +public: + double findMaxAverage(vector& nums, int k) { + double left = *min_element(nums.begin(), nums.end()); + double right = *max_element(nums.begin(), nums.end()); + while (abs(left - right) > 0.00001) { + double mid = left + (right - left) / 2; + if (!check(nums, mid, k)) { + right = mid; + } else { + left = mid; + } + } + return left; + } + +private: + bool check(const vector& nums, double mid, int k) { + double sum = 0, prev = 0, min_sum = 0; + for (int i = 0; i < k; ++i) { + sum += nums[i] - mid; + } + if (sum >= 0) { + return true; + } + for (int i = k; i < nums.size(); ++i) { + sum += nums[i] - mid; + prev += nums[i - k] - mid; + min_sum = min(prev, min_sum); + if (sum >= min_sum) { + return true; + } + } + return true; + } +}; + From 9f780b85a41bca304b875bfa4ec3288ee38778e7 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 26 Jul 2017 00:37:05 +0800 Subject: [PATCH 3455/4971] update --- C++/maximum-average-subarray-ii.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/C++/maximum-average-subarray-ii.cpp b/C++/maximum-average-subarray-ii.cpp index 9a098cce1..4b9e4c2b0 100644 --- a/C++/maximum-average-subarray-ii.cpp +++ b/C++/maximum-average-subarray-ii.cpp @@ -6,9 +6,9 @@ class Solution { double findMaxAverage(vector& nums, int k) { double left = *min_element(nums.begin(), nums.end()); double right = *max_element(nums.begin(), nums.end()); - while (abs(left - right) > 0.00001) { + while (right - left > 0.00001) { double mid = left + (right - left) / 2; - if (!check(nums, mid, k)) { + if (isMidLargerOrEqualToTarget(mid, nums, k)) { right = mid; } else { left = mid; @@ -18,23 +18,22 @@ class Solution { } private: - bool check(const vector& nums, double mid, int k) { + bool isMidLargerOrEqualToTarget(double mid, const vector& nums, int k) { double sum = 0, prev = 0, min_sum = 0; for (int i = 0; i < k; ++i) { sum += nums[i] - mid; } - if (sum >= 0) { - return true; + if (sum > 0) { + return false; } for (int i = k; i < nums.size(); ++i) { sum += nums[i] - mid; prev += nums[i - k] - mid; min_sum = min(prev, min_sum); - if (sum >= min_sum) { - return true; + if (sum > min_sum) { + return false; } } - return true; + return true; } -}; - +}; \ No newline at end of file From 4d3054c61ab6ce757bc29fc3d963935b1160e4bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Jul 2017 01:29:23 +0800 Subject: [PATCH 3456/4971] Create maximum-average-subarray-ii.py --- Python/maximum-average-subarray-ii.py | 44 +++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/maximum-average-subarray-ii.py diff --git a/Python/maximum-average-subarray-ii.py b/Python/maximum-average-subarray-ii.py new file mode 100644 index 000000000..02773cfe5 --- /dev/null +++ b/Python/maximum-average-subarray-ii.py @@ -0,0 +1,44 @@ +# Time: O(n) +# Space: O(n) + + +# Given an array consisting of n integers, find the contiguous subarray whose length is greater than or equal to k that has the maximum average value. And you need to output the maximum average value. +# +# Example 1: +# Input: [1,12,-5,-6,50,3], k = 4 +# Output: 12.75 +# Explanation: +# when length is 5, maximum average value is 10.8, +# when length is 6, maximum average value is 9.16667. +# Thus return 12.75. +# Note: +# 1 <= k <= n <= 10,000. +# Elements of the given array will be in range [-10,000, 10,000]. +# The answer with the calculation error less than 10-5 will be accepted. + +class Solution(object): + def findMaxAverage(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: float + """ + def getDelta(avg, accu): + minval, minval_pos = 2**32, -1 + delta = 0 + for i in xrange(len(nums)): + accu[i+1] = nums[i] + accu[i] - avg + if i >= (k-1): + if accu[i-k+1] < minval: + minval = accu[i-k+1] + minval_pos = i-k+1 + if accu[i+1] - minval >= 0: + delta = max(delta, 1.0 * (accu[i+1] - minval) / (i+1 - minval_pos)) + return delta + + accu = [0.0] * (len(nums) + 1) + left, delta = min(nums), float("inf") + while delta > 1e-5: + delta = getDelta(left, accu) + left += delta + return left From 6a0ba50675bd8e91c878d10e9c6550593b26d90e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Jul 2017 01:30:21 +0800 Subject: [PATCH 3457/4971] Update maximum-average-subarray-ii.py --- Python/maximum-average-subarray-ii.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/maximum-average-subarray-ii.py b/Python/maximum-average-subarray-ii.py index 02773cfe5..23fbe089f 100644 --- a/Python/maximum-average-subarray-ii.py +++ b/Python/maximum-average-subarray-ii.py @@ -1,8 +1,9 @@ # Time: O(n) # Space: O(n) - -# Given an array consisting of n integers, find the contiguous subarray whose length is greater than or equal to k that has the maximum average value. And you need to output the maximum average value. +# Given an array consisting of n integers, find the contiguous subarray +# whose length is greater than or equal to k that has the maximum average value. +# And you need to output the maximum average value. # # Example 1: # Input: [1,12,-5,-6,50,3], k = 4 From 6e484e83f5658c028059820e66c3ffe723124524 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Jul 2017 01:30:56 +0800 Subject: [PATCH 3458/4971] Update maximum-average-subarray-ii.py --- Python/maximum-average-subarray-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximum-average-subarray-ii.py b/Python/maximum-average-subarray-ii.py index 23fbe089f..0612dd46d 100644 --- a/Python/maximum-average-subarray-ii.py +++ b/Python/maximum-average-subarray-ii.py @@ -15,7 +15,7 @@ # Note: # 1 <= k <= n <= 10,000. # Elements of the given array will be in range [-10,000, 10,000]. -# The answer with the calculation error less than 10-5 will be accepted. +# The answer with the calculation error less than 1e-5 will be accepted. class Solution(object): def findMaxAverage(self, nums, k): From 02f3d5851f4cb61e350391e74dd5a4e06ce82e12 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Jul 2017 01:42:25 +0800 Subject: [PATCH 3459/4971] Update maximum-average-subarray-ii.py --- Python/maximum-average-subarray-ii.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Python/maximum-average-subarray-ii.py b/Python/maximum-average-subarray-ii.py index 0612dd46d..eb651ef4a 100644 --- a/Python/maximum-average-subarray-ii.py +++ b/Python/maximum-average-subarray-ii.py @@ -16,7 +16,6 @@ # 1 <= k <= n <= 10,000. # Elements of the given array will be in range [-10,000, 10,000]. # The answer with the calculation error less than 1e-5 will be accepted. - class Solution(object): def findMaxAverage(self, nums, k): """ @@ -24,7 +23,7 @@ def findMaxAverage(self, nums, k): :type k: int :rtype: float """ - def getDelta(avg, accu): + def getDelta(nums, k, avg, accu): minval, minval_pos = 2**32, -1 delta = 0 for i in xrange(len(nums)): @@ -40,6 +39,6 @@ def getDelta(avg, accu): accu = [0.0] * (len(nums) + 1) left, delta = min(nums), float("inf") while delta > 1e-5: - delta = getDelta(left, accu) + delta = getDelta(nums, k, left, accu) left += delta return left From 02a331da70d20b2063f8a5b1ccb341442fcb3b44 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 26 Jul 2017 02:01:52 +0800 Subject: [PATCH 3460/4971] update --- C++/maximum-average-subarray-ii.cpp | 39 +++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/C++/maximum-average-subarray-ii.cpp b/C++/maximum-average-subarray-ii.cpp index 4b9e4c2b0..1e5d9b1b8 100644 --- a/C++/maximum-average-subarray-ii.cpp +++ b/C++/maximum-average-subarray-ii.cpp @@ -1,7 +1,42 @@ -// Time: O(nlog(max_val - min_val)) -// Space: O(1) +// Time: O(n) +// Space: O(n) class Solution { +public: + double findMaxAverage(vector& nums, int k) { + double left = *min_element(nums.begin(), nums.end()); + double delta = numeric_limits::max(); + while (delta > 1e-5) { + delta = getDelta(nums, k, left); + left += delta; + } + return left; + } + +private: + double getDelta(const vector& nums, int k, double avg) { + vector accu(nums.size() + 1); + int minval_pos = -1; + double delta = 0.0; + for (int i = 0; i < nums.size(); ++i) { + accu[i + 1] = nums[i] + accu[i] - avg; + if (i >= k - 1) { + if (minval_pos == -1 || accu[i - k + 1] < accu[minval_pos]) { + minval_pos = i - k + 1; + } + if (accu[i+1] - accu[minval_pos] >= 0) { + delta = max(delta, (accu[i + 1] - accu[minval_pos]) / (i + 1 - minval_pos)); + } + } + } + return delta; + } +}; + + +// Time: O(nlogm), m is (max_val - min_val) +// Space: O(1) +class Solution2 { public: double findMaxAverage(vector& nums, int k) { double left = *min_element(nums.begin(), nums.end()); From 96af70b2fd1e7a39cc02ab24f45f5f85f1299313 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 26 Jul 2017 02:03:09 +0800 Subject: [PATCH 3461/4971] update --- C++/maximum-average-subarray-ii.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/maximum-average-subarray-ii.cpp b/C++/maximum-average-subarray-ii.cpp index 1e5d9b1b8..3d8d658e8 100644 --- a/C++/maximum-average-subarray-ii.cpp +++ b/C++/maximum-average-subarray-ii.cpp @@ -7,14 +7,14 @@ class Solution { double left = *min_element(nums.begin(), nums.end()); double delta = numeric_limits::max(); while (delta > 1e-5) { - delta = getDelta(nums, k, left); + delta = getDelta(left, nums, k); left += delta; } return left; } private: - double getDelta(const vector& nums, int k, double avg) { + double getDelta(double avg, const vector& nums, int k) { vector accu(nums.size() + 1); int minval_pos = -1; double delta = 0.0; @@ -41,7 +41,7 @@ class Solution2 { double findMaxAverage(vector& nums, int k) { double left = *min_element(nums.begin(), nums.end()); double right = *max_element(nums.begin(), nums.end()); - while (right - left > 0.00001) { + while (right - left > 1e-5) { double mid = left + (right - left) / 2; if (isMidLargerOrEqualToTarget(mid, nums, k)) { right = mid; From 469b8c353f898a4b402717cbcca4a5a28ae8db6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Jul 2017 02:05:34 +0800 Subject: [PATCH 3462/4971] Update maximum-average-subarray-ii.py --- Python/maximum-average-subarray-ii.py | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/Python/maximum-average-subarray-ii.py b/Python/maximum-average-subarray-ii.py index eb651ef4a..7bd337bbf 100644 --- a/Python/maximum-average-subarray-ii.py +++ b/Python/maximum-average-subarray-ii.py @@ -1,9 +1,8 @@ # Time: O(n) # Space: O(n) -# Given an array consisting of n integers, find the contiguous subarray -# whose length is greater than or equal to k that has the maximum average value. -# And you need to output the maximum average value. + +# Given an array consisting of n integers, find the contiguous subarray whose length is greater than or equal to k that has the maximum average value. And you need to output the maximum average value. # # Example 1: # Input: [1,12,-5,-6,50,3], k = 4 @@ -15,7 +14,8 @@ # Note: # 1 <= k <= n <= 10,000. # Elements of the given array will be in range [-10,000, 10,000]. -# The answer with the calculation error less than 1e-5 will be accepted. +# The answer with the calculation error less than 10-5 will be accepted. + class Solution(object): def findMaxAverage(self, nums, k): """ @@ -23,22 +23,21 @@ def findMaxAverage(self, nums, k): :type k: int :rtype: float """ - def getDelta(nums, k, avg, accu): - minval, minval_pos = 2**32, -1 - delta = 0 + def getDelta(avg, nums, k): + accu = [0.0] * (len(nums) + 1) + minval_pos = None + delta = 0.0 for i in xrange(len(nums)): accu[i+1] = nums[i] + accu[i] - avg if i >= (k-1): - if accu[i-k+1] < minval: - minval = accu[i-k+1] + if minval_pos == None or accu[i-k+1] < accu[minval_pos]: minval_pos = i-k+1 - if accu[i+1] - minval >= 0: - delta = max(delta, 1.0 * (accu[i+1] - minval) / (i+1 - minval_pos)) + if accu[i+1] - accu[minval_pos] >= 0: + delta = max(delta, 1.0 * (accu[i+1] - accu[minval_pos]) / (i+1 - minval_pos)) return delta - accu = [0.0] * (len(nums) + 1) left, delta = min(nums), float("inf") while delta > 1e-5: - delta = getDelta(nums, k, left, accu) + delta = getDelta(left, nums, k) left += delta return left From 50b8fe9dc3160195d6010ab63193bf3032fa633e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Jul 2017 02:06:14 +0800 Subject: [PATCH 3463/4971] Update maximum-average-subarray-ii.py --- Python/maximum-average-subarray-ii.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/maximum-average-subarray-ii.py b/Python/maximum-average-subarray-ii.py index 7bd337bbf..abf16159a 100644 --- a/Python/maximum-average-subarray-ii.py +++ b/Python/maximum-average-subarray-ii.py @@ -1,8 +1,9 @@ # Time: O(n) # Space: O(n) - -# Given an array consisting of n integers, find the contiguous subarray whose length is greater than or equal to k that has the maximum average value. And you need to output the maximum average value. +# Given an array consisting of n integers, find the contiguous subarray +# whose length is greater than or equal to k that has the maximum average value. +# And you need to output the maximum average value. # # Example 1: # Input: [1,12,-5,-6,50,3], k = 4 From 39d8cf3fe9a522954a0e64c049cc51159883b388 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Jul 2017 02:06:27 +0800 Subject: [PATCH 3464/4971] Update maximum-average-subarray-ii.py --- Python/maximum-average-subarray-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximum-average-subarray-ii.py b/Python/maximum-average-subarray-ii.py index abf16159a..e4a0bf860 100644 --- a/Python/maximum-average-subarray-ii.py +++ b/Python/maximum-average-subarray-ii.py @@ -15,7 +15,7 @@ # Note: # 1 <= k <= n <= 10,000. # Elements of the given array will be in range [-10,000, 10,000]. -# The answer with the calculation error less than 10-5 will be accepted. +# The answer with the calculation error less than 1e-5 will be accepted. class Solution(object): def findMaxAverage(self, nums, k): From b033d54569194a069e284567e9ba0600181f99db Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 26 Jul 2017 02:18:23 +0800 Subject: [PATCH 3465/4971] Update maximum-average-subarray-ii.py --- Python/maximum-average-subarray-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximum-average-subarray-ii.py b/Python/maximum-average-subarray-ii.py index e4a0bf860..e068afebb 100644 --- a/Python/maximum-average-subarray-ii.py +++ b/Python/maximum-average-subarray-ii.py @@ -34,7 +34,7 @@ def getDelta(avg, nums, k): if minval_pos == None or accu[i-k+1] < accu[minval_pos]: minval_pos = i-k+1 if accu[i+1] - accu[minval_pos] >= 0: - delta = max(delta, 1.0 * (accu[i+1] - accu[minval_pos]) / (i+1 - minval_pos)) + delta = max(delta, (accu[i+1] - accu[minval_pos]) / (i+1 - minval_pos)) return delta left, delta = min(nums), float("inf") From 88dcceaba5bef7f799f936ab50de7db6d096ee03 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 27 Jul 2017 23:33:55 +0800 Subject: [PATCH 3466/4971] add --- C++/design-log-storage-system.cpp | 45 +++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 C++/design-log-storage-system.cpp diff --git a/C++/design-log-storage-system.cpp b/C++/design-log-storage-system.cpp new file mode 100644 index 000000000..893b057ba --- /dev/null +++ b/C++/design-log-storage-system.cpp @@ -0,0 +1,45 @@ +// Time: O(logn) +// Space: O(n) + +class LogSystem { +public: + LogSystem() { + granularity_["Year"] = 4; + granularity_["Month"] = 7; + granularity_["Day"] = 10; + granularity_["Hour"] = 13; + granularity_["Minute"] = 16; + granularity_["Second"] = 19; + } + + // Time: O(logn), n is the size of the total logs + void put(int id, string timestamp) { + lookup_.emplace(timestamp, id); + } + + // Time: O(logn + d), d is the size of the found logs + vector retrieve(string s, string e, string gra) { + s = s.substr(0, granularity_[gra]) + s_filter_.substr(granularity_[gra]); + e = e.substr(0, granularity_[gra]) + e_filter_.substr(granularity_[gra]); + + vector result; + auto end = lookup_.upper_bound(e); + for (auto it = lookup_.lower_bound(s); it != end; ++it) { + result.emplace_back(it->second); + } + return result; + } + +private: + string s_filter_ = "0001:01:01:00:00:00"; + string e_filter_ = "9999:12:31:23:59:59"; + unordered_map granularity_; + multimap lookup_; +}; + +/** + * Your LogSystem object will be instantiated and called as such: + * LogSystem obj = new LogSystem(); + * obj.put(id,timestamp); + * vector param_2 = obj.retrieve(s,e,gra); + */ From dbd2f53bc61395e328d898e8185a60d51a253bfa Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 27 Jul 2017 23:38:25 +0800 Subject: [PATCH 3467/4971] update --- C++/design-log-storage-system.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/design-log-storage-system.cpp b/C++/design-log-storage-system.cpp index 893b057ba..cba11e80c 100644 --- a/C++/design-log-storage-system.cpp +++ b/C++/design-log-storage-system.cpp @@ -1,4 +1,5 @@ -// Time: O(logn) +// Time: put: O(logn), n is the size of the total logs +// retrieve: O(logn + d), d is the size of the found logs // Space: O(n) class LogSystem { @@ -12,12 +13,10 @@ class LogSystem { granularity_["Second"] = 19; } - // Time: O(logn), n is the size of the total logs void put(int id, string timestamp) { lookup_.emplace(timestamp, id); } - // Time: O(logn + d), d is the size of the found logs vector retrieve(string s, string e, string gra) { s = s.substr(0, granularity_[gra]) + s_filter_.substr(granularity_[gra]); e = e.substr(0, granularity_[gra]) + e_filter_.substr(granularity_[gra]); From 728d92892ed04788dfbbd50acf0f24d1de2d866e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 28 Jul 2017 23:35:03 +0800 Subject: [PATCH 3468/4971] Create design-log-storage-system.py --- Python/design-log-storage-system.py | 40 +++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/design-log-storage-system.py diff --git a/Python/design-log-storage-system.py b/Python/design-log-storage-system.py new file mode 100644 index 000000000..52d63883a --- /dev/null +++ b/Python/design-log-storage-system.py @@ -0,0 +1,40 @@ +# Time: put: O(1) +# retrieve: O(n + dlogd), n is the size of the total logs +# , d is the size of the found logs +# Space: O(n) + +class LogSystem(object): + + def __init__(self): + self.__logs = [] + self.__granularity = {'Year': 5, 'Month': 8, 'Day': 11, \ + 'Hour': 14, 'Minute': 17, 'Second': 20} + + + def put(self, id, timestamp): + """ + :type id: int + :type timestamp: str + :rtype: void + """ + self.__logs.append((id, timestamp)) + + + def retrieve(self, s, e, gra): + """ + :type s: str + :type e: str + :type gra: str + :rtype: List[int] + """ + i = self.__granularity[gra] + begin = s[:i] + end = e[:i] + return sorted(id for id, timestamp in self.__logs \ + if begin <= timestamp[:i] <= end) + + +# Your LogSystem object will be instantiated and called as such: +# obj = LogSystem() +# obj.put(id,timestamp) +# param_2 = obj.retrieve(s,e,gra) From 75725a06e96bd1f70a7ad7f049ef88a7c728d9c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 29 Jul 2017 10:59:27 -0500 Subject: [PATCH 3469/4971] Update design-log-storage-system.py --- Python/design-log-storage-system.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/design-log-storage-system.py b/Python/design-log-storage-system.py index 52d63883a..976a44f50 100644 --- a/Python/design-log-storage-system.py +++ b/Python/design-log-storage-system.py @@ -7,8 +7,8 @@ class LogSystem(object): def __init__(self): self.__logs = [] - self.__granularity = {'Year': 5, 'Month': 8, 'Day': 11, \ - 'Hour': 14, 'Minute': 17, 'Second': 20} + self.__granularity = {'Year': 4, 'Month': 7, 'Day': 10, \ + 'Hour': 13, 'Minute': 16, 'Second': 19} def put(self, id, timestamp): From 60939e5d25610fdfbcf1cc301d59e49e66717e5b Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 30 Jul 2017 21:36:13 +0800 Subject: [PATCH 3470/4971] add --- C++/set-mismatch.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/set-mismatch.cpp diff --git a/C++/set-mismatch.cpp b/C++/set-mismatch.cpp new file mode 100644 index 000000000..000dfb599 --- /dev/null +++ b/C++/set-mismatch.cpp @@ -0,0 +1,24 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector findErrorNums(vector& nums) { + vector result(2); + for (const auto& i : nums) { + if (nums[abs(i) - 1] < 0) { // twice + result[0] = abs(i); + } else { + nums[abs(i) - 1] *= -1; + } + } + for (int i = 0; i < nums.size(); ++i) { + if (nums[i] > 0) { // missing + result[1] = i + 1; + } else { + nums[i] *= -1; + } + } + return result; + } +}; From 624c3097ba97b6c1d6f6c5fec9b677b31fd59d23 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Jul 2017 21:42:27 +0800 Subject: [PATCH 3471/4971] Create set-mismatch.py --- Python/set-mismatch.py | 50 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/set-mismatch.py diff --git a/Python/set-mismatch.py b/Python/set-mismatch.py new file mode 100644 index 000000000..44dff2864 --- /dev/null +++ b/Python/set-mismatch.py @@ -0,0 +1,50 @@ +# Time: O(n) +# Space: O(1) + +# The set S originally contains numbers from 1 to n. +# But unfortunately, due to the data error, one of the numbers +# in the set got duplicated to another number in the set, which results +# in repetition of one number and loss of another number. +# +# Given an array nums representing the data status of this set after the error. +# Your task is to firstly find the number occurs twice and then find the number +# that is missing. Return them in the form of an array. +# +# Example 1: +# Input: nums = [1,2,2,4] +# Output: [2,3] +# Note: +# The given array size will in the range [2, 10000]. +# The given array's numbers won't have any order. + +class Solution(object): + def findErrorNums(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + result = [0] * 2 + for i in nums: + if nums[abs(i)-1] < 0: + result[0] = abs(i) + else: + nums[abs(i)-1] *= -1 + for i in xrange(len(nums)): + if nums[i] > 0: + result[1] = i+1 + else: + nums[i] *= -1 + return result + +# Time: O(n) +# Space: O(1) +class Solution2(object): + def findErrorNums(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + N = len(nums) + x_minus_y = sum(nums) - N*(N+1)//2 + x_plus_y = (sum(x*x for x in nums) - N*(N+1)*(2*N+1)/6) // x_minus_y + return (x_plus_y+x_minus_y) // 2, (x_plus_y-x_minus_y) // 2 From 040b630daedede93fbdb5d78970dddd55aced1bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Jul 2017 22:17:25 +0800 Subject: [PATCH 3472/4971] Update set-mismatch.py --- Python/set-mismatch.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Python/set-mismatch.py b/Python/set-mismatch.py index 44dff2864..beb6e00b0 100644 --- a/Python/set-mismatch.py +++ b/Python/set-mismatch.py @@ -18,6 +18,24 @@ # The given array's numbers won't have any order. class Solution(object): + def findErrorNums(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + x_xor_y = reduce(operator.xor, nums) ^ reduce(operator.xor, xrange(1, len(nums)+1)) + bit = x_xor_y & ~(x_xor_y - 1) + result = [0, 0] + for i, num in enumerate(nums): + result[bool(num & bit)] ^= num + result[bool((i+1) & bit)] ^= i+1 + if result[1] in nums: result[0], result[1] = result[1], result[0] + return result + + +# Time: O(n) +# Space: O(1) +class Solution2(object): def findErrorNums(self, nums): """ :type nums: List[int] @@ -36,9 +54,10 @@ def findErrorNums(self, nums): nums[i] *= -1 return result + # Time: O(n) # Space: O(1) -class Solution2(object): +class Solution3(object): def findErrorNums(self, nums): """ :type nums: List[int] From 5a45e85fd78c3852fd04536be9153cbdd26e4a3f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 30 Jul 2017 22:28:37 +0800 Subject: [PATCH 3473/4971] add --- C++/set-mismatch.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/C++/set-mismatch.cpp b/C++/set-mismatch.cpp index 000dfb599..f5a28b1e6 100644 --- a/C++/set-mismatch.cpp +++ b/C++/set-mismatch.cpp @@ -2,6 +2,29 @@ // Space: O(1) class Solution { +public: + vector findErrorNums(vector& nums) { + int x_xor_y = 0; + for (int i = 0; i < nums.size(); ++i) { + x_xor_y ^= nums[i] ^ (i + 1); + } + int bit = x_xor_y & ~(x_xor_y - 1); + vector result(2); + for (int i = 0; i < nums.size(); ++i) { + result[static_cast(nums[i] & bit)] ^= nums[i]; + result[static_cast((i + 1) & bit)] ^= i + 1; + } + if (find(nums.begin(), nums.end(), result[0]) == nums.end()) { + swap(result[0], result[1]); + } + return result; + } +}; + + +// Time: O(n) +// Space: O(1) +class Solution2 { public: vector findErrorNums(vector& nums) { vector result(2); From 347e00b7ef878928a29c22e4fcbb1771518f0691 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Jul 2017 22:31:16 +0800 Subject: [PATCH 3474/4971] Update set-mismatch.py --- Python/set-mismatch.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Python/set-mismatch.py b/Python/set-mismatch.py index beb6e00b0..74690103c 100644 --- a/Python/set-mismatch.py +++ b/Python/set-mismatch.py @@ -23,13 +23,16 @@ def findErrorNums(self, nums): :type nums: List[int] :rtype: List[int] """ - x_xor_y = reduce(operator.xor, nums) ^ reduce(operator.xor, xrange(1, len(nums)+1)) + x_xor_y = 0 + for i in xrange(len(nums)): + x_xor_y ^= nums[i] ^ (i+1) bit = x_xor_y & ~(x_xor_y - 1) result = [0, 0] for i, num in enumerate(nums): result[bool(num & bit)] ^= num result[bool((i+1) & bit)] ^= i+1 - if result[1] in nums: result[0], result[1] = result[1], result[0] + if result[0] not in nums: + result[0], result[1] = result[1], result[0] return result From 762b8de8c42d0f907613267038782db7cb12336f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Jul 2017 22:33:33 +0800 Subject: [PATCH 3475/4971] Update set-mismatch.py --- Python/set-mismatch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/set-mismatch.py b/Python/set-mismatch.py index 74690103c..c9ab2185d 100644 --- a/Python/set-mismatch.py +++ b/Python/set-mismatch.py @@ -27,7 +27,7 @@ def findErrorNums(self, nums): for i in xrange(len(nums)): x_xor_y ^= nums[i] ^ (i+1) bit = x_xor_y & ~(x_xor_y - 1) - result = [0, 0] + result = [0] * 2 for i, num in enumerate(nums): result[bool(num & bit)] ^= num result[bool((i+1) & bit)] ^= i+1 From db0236e89346c47f9fa3de839ef489713c195f4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 30 Jul 2017 22:34:29 +0800 Subject: [PATCH 3476/4971] Update set-mismatch.py --- Python/set-mismatch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/set-mismatch.py b/Python/set-mismatch.py index c9ab2185d..662ae25d4 100644 --- a/Python/set-mismatch.py +++ b/Python/set-mismatch.py @@ -26,7 +26,7 @@ def findErrorNums(self, nums): x_xor_y = 0 for i in xrange(len(nums)): x_xor_y ^= nums[i] ^ (i+1) - bit = x_xor_y & ~(x_xor_y - 1) + bit = x_xor_y & ~(x_xor_y-1) result = [0] * 2 for i, num in enumerate(nums): result[bool(num & bit)] ^= num From 3a25ef58439f55c5f09af6212113083d2245362a Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 31 Jul 2017 21:49:44 +0800 Subject: [PATCH 3477/4971] add --- C++/maximum-length-of-pair-chain.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/maximum-length-of-pair-chain.cpp diff --git a/C++/maximum-length-of-pair-chain.cpp b/C++/maximum-length-of-pair-chain.cpp new file mode 100644 index 000000000..e834b846e --- /dev/null +++ b/C++/maximum-length-of-pair-chain.cpp @@ -0,0 +1,21 @@ +// Time: O(nlogn) +// Space: O(1) + +class Solution { +public: + int findLongestChain(vector>& pairs) { + sort(pairs.begin(), pairs.end(), + [](const vector& a, const vector& b) { + return a[1] < b[1]; + }); + int cnt = 0; + for (int i = 0, j = 0; j < pairs.size(); ++j) { + if (j == 0 || pairs[i][1] < pairs[j][0]) { + ++cnt; + i = j; + } + } + return cnt; + } +}; + From 0fe4a3c3a1d31230c9b5c931ff1e33584f1ccd4e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 31 Jul 2017 21:56:23 +0800 Subject: [PATCH 3478/4971] Create maximum-length-of-pair-chain.py --- Python/maximum-length-of-pair-chain.py | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/maximum-length-of-pair-chain.py diff --git a/Python/maximum-length-of-pair-chain.py b/Python/maximum-length-of-pair-chain.py new file mode 100644 index 000000000..c6586aa3c --- /dev/null +++ b/Python/maximum-length-of-pair-chain.py @@ -0,0 +1,32 @@ +# Time: O(nlogn) +# Space: O(1) + +# You are given n pairs of numbers. +# In every pair, the first number is always smaller than the second number. +# +# Now, we define a pair (c, d) can follow another pair (a, b) +# if and only if b < c. Chain of pairs can be formed in this fashion. +# +# Given a set of pairs, find the length longest chain which can be formed. +# You needn't use up all the given pairs. You can select pairs in any order. +# +# Example 1: +# Input: [[1,2], [2,3], [3,4]] +# Output: 2 +# Explanation: The longest chain is [1,2] -> [3,4] +# Note: +# The number of given pairs will be in the range [1, 1000]. + +class Solution(object): + def findLongestChain(self, pairs): + """ + :type pairs: List[List[int]] + :rtype: int + """ + pairs.sort(key=lambda x: x[1]) + cnt, i = 0, 0 + for j in xrange(len(pairs)): + if j == 0 or pairs[i][1] < pairs[j][0]: + cnt += 1 + i = j + return cnt From 41f761acc38540cb45fba0303dd3f3f7cdad3e57 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 1 Aug 2017 21:58:25 +0800 Subject: [PATCH 3479/4971] add --- C++/palindromic-substrings.cpp | 46 ++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/palindromic-substrings.cpp diff --git a/C++/palindromic-substrings.cpp b/C++/palindromic-substrings.cpp new file mode 100644 index 000000000..f3012a70f --- /dev/null +++ b/C++/palindromic-substrings.cpp @@ -0,0 +1,46 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int countSubstrings(string s) { + auto result = 0; + for (const auto& max_len : manacher(s)) { + result += (max_len + 1) / 2; + } + return result; + } + +private: + vector manacher(const string& s) { + string T = preProcess(s); + const 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; + 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]; + } + } + return P; + } + + 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 2034ea7dc27ab93212f992263444f42b8bb64f61 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Aug 2017 22:42:29 +0800 Subject: [PATCH 3480/4971] Update path-sum-iii.py --- Python/path-sum-iii.py | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/Python/path-sum-iii.py b/Python/path-sum-iii.py index a02b434f0..67af4636d 100644 --- a/Python/path-sum-iii.py +++ b/Python/path-sum-iii.py @@ -1,5 +1,5 @@ -# Time: O(n^2) -# Space: O(h) +# Time: O(n) +# Space: O(n) # You are given a binary tree in which each node contains an integer value. # @@ -35,7 +35,42 @@ # self.left = None # self.right = None +# 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 + class Solution(object): + def pathSum(self, root, sum): + """ + :type root: TreeNode + :type sum: int + :rtype: int + """ + def helper(root, cur, sum, lookup): + if root is None: + return 0 + cur += root.val + result = lookup[cur - sum] + lookup[cur] += 1 + result += helper(root.left, cur, sum, lookup) + \ + helper(root.right, cur, sum, lookup) + lookup[cur] -= 1 + return result + + lookup = collections.defaultdict(int) + lookup[0] = 1 + return helper(root, 0, sum, lookup) + + +# Time: O(n^2) +# Space: O(h) +class Solution2(object): def pathSum(self, root, sum): """ :type root: TreeNode From 7a89d0da47053791a12d0622f8355beb4fda06e4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Aug 2017 22:55:17 +0800 Subject: [PATCH 3481/4971] Update path-sum-iii.cpp --- C++/path-sum-iii.cpp | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/C++/path-sum-iii.cpp b/C++/path-sum-iii.cpp index 5d20da082..7723668dc 100644 --- a/C++/path-sum-iii.cpp +++ b/C++/path-sum-iii.cpp @@ -1,4 +1,4 @@ -// Time: O(n^2) +// Time: O(n) // Space: O(h) /** @@ -11,6 +11,34 @@ * }; */ class Solution { +public: + int pathSum(TreeNode* root, int sum) { + unordered_map lookup; + lookup[0] = 1; + return pathSumHelper(root, 0, sum, &lookup); + } + +private: + int pathSumHelper(TreeNode* root, int curr, int sum, unordered_map *lookup) { + if (!root) { + return 0; + } + curr += root->val; + int result = lookup->count(curr - sum) ? (*lookup)[curr - sum] : 0; + ++(*lookup)[curr]; + result += pathSumHelper(root->left, curr, sum, lookup) + pathSumHelper(root->right, curr, sum, lookup); + --(*lookup)[curr]; + if ((*lookup)[curr] == 0) { + lookup->erase(curr); + } + return result; + } +}; + + +// Time: O(n^2) +// Space: O(h) +class Solution2 { public: int pathSum(TreeNode* root, int sum) { if (!root) { From 2dab897dd6e8f6937790be5f239222be7c7c96a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Aug 2017 22:55:51 +0800 Subject: [PATCH 3482/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c56c382b1..f2e6c6028 100644 --- a/README.md +++ b/README.md @@ -385,7 +385,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 || 395| [Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./C++/longest-substring-with-at-least-k-repeating-characters.cpp) [Python](./Python/longest-substring-with-at-least-k-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 404| [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./C++/sum-of-left-leaves.cpp) [Python](./Python/sum-of-left-leaves.py) | _O(n)_ | _O(h)_ | Easy || -437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n^2)_ | _O(h)_ | Easy || +437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n)_ | _O(h)_ | Easy || 549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| ## Binary Search From 63554af613a44fde176ee3f9d655b35d663d89d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Aug 2017 22:59:08 +0800 Subject: [PATCH 3483/4971] Update path-sum-iii.py --- Python/path-sum-iii.py | 30 +++++++++++------------------- 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/Python/path-sum-iii.py b/Python/path-sum-iii.py index 67af4636d..5458537cf 100644 --- a/Python/path-sum-iii.py +++ b/Python/path-sum-iii.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(n) +# Space: O(h) # You are given a binary tree in which each node contains an integer value. # @@ -35,16 +35,6 @@ # self.left = None # self.right = None -# 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 - class Solution(object): def pathSum(self, root, sum): """ @@ -52,20 +42,22 @@ def pathSum(self, root, sum): :type sum: int :rtype: int """ - def helper(root, cur, sum, lookup): + def pathSumHelper(root, curr, sum, lookup): if root is None: return 0 - cur += root.val - result = lookup[cur - sum] - lookup[cur] += 1 - result += helper(root.left, cur, sum, lookup) + \ - helper(root.right, cur, sum, lookup) - lookup[cur] -= 1 + curr += root.val + result = lookup[curr-sum] if curr-sum in lookup else 0 + lookup[curr] += 1 + result += pathSumHelper(root.left, curr, sum, lookup) + \ + pathSumHelper(root.right, curr, sum, lookup) + lookup[curr] -= 1 + if lookup[curr] == 0: + del lookup[curr] return result lookup = collections.defaultdict(int) lookup[0] = 1 - return helper(root, 0, sum, lookup) + return pathSumHelper(root, 0, sum, lookup) # Time: O(n^2) From e6b17a3510e9f6a6954926205ff19e0069d6f56f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 1 Aug 2017 23:14:48 +0800 Subject: [PATCH 3484/4971] Create palindromic-substrings.py --- Python/palindromic-substrings.py | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/palindromic-substrings.py diff --git a/Python/palindromic-substrings.py b/Python/palindromic-substrings.py new file mode 100644 index 000000000..7cc38189e --- /dev/null +++ b/Python/palindromic-substrings.py @@ -0,0 +1,39 @@ +# Time: O(n) +# Space: O(n) + +# Given a string, your task is to count how many palindromic substrings in this string. +# +# The substrings with different start indexes or end indexes are counted as +# different substrings even they consist of same characters. +# +# Example 1: +# Input: "abc" +# Output: 3 +# Explanation: Three palindromic strings: "a", "b", "c". +# Example 2: +# Input: "aaa" +# Output: 6 +# Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". +# Note: +# The input string length won't exceed 1000. + +class Solution(object): + def countSubstrings(self, s): + """ + :type s: str + :rtype: int + """ + def manacher(s): + s = '^#' + '#'.join(s) + '#$' + P = [0] * len(s) + C, R = 0, 0 + for i in xrange(1, len(s) - 1): + i_mirror = 2*C-i + if R > i: + P[i] = min(R-i, P[i_mirror]) + while s[i+1+P[i]] == s[i-1-P[i]]: + P[i] += 1 + if i+P[i] > R: + C, R = i, i+P[i] + return P + return sum((max_len+1)/2 for max_len in manacher(s)) From 2100f71067dc8fb4f3c92728547f51c83f05b5ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 2 Aug 2017 23:58:48 +0800 Subject: [PATCH 3485/4971] Update path-sum-iii.py --- Python/path-sum-iii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/path-sum-iii.py b/Python/path-sum-iii.py index 5458537cf..ed24dde54 100644 --- a/Python/path-sum-iii.py +++ b/Python/path-sum-iii.py @@ -70,7 +70,7 @@ def pathSum(self, root, sum): :rtype: int """ def pathSumHelper(root, prev, sum): - if not root: + if root is None: return 0 curr = prev + root.val; @@ -78,7 +78,7 @@ def pathSumHelper(root, prev, sum): pathSumHelper(root.left, curr, sum) + \ pathSumHelper(root.right, curr, sum) - if not root: + if root is None: return 0 return pathSumHelper(root, 0, sum) + \ From 3a0effad53b38cb4baf3ca75ca703e162c150491 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Aug 2017 00:50:42 +0800 Subject: [PATCH 3486/4971] Create replace-words.cpp --- C++/replace-words.cpp | 50 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 C++/replace-words.cpp diff --git a/C++/replace-words.cpp b/C++/replace-words.cpp new file mode 100644 index 000000000..86e892b76 --- /dev/null +++ b/C++/replace-words.cpp @@ -0,0 +1,50 @@ +// Time: O(n) +// Space: O(t), t is the number of nodes in trie + +class Solution { +public: + string replaceWords(vector& dict, string sentence) { + TrieNode trie; + string result; + for (const auto& s : dict) { + trie.Insert(s); + } + auto curr = ≜ + for (int i = 0; i < sentence.length(); ++i) { + if (sentence[i] == ' ' || !curr || !curr->isString) { + result += sentence[i]; + } + if (sentence[i] == ' ') { + curr = ≜ + } else if (curr && !curr->isString) { + curr = curr->leaves[sentence[i]]; + } + } + return result; + } + +private: + struct TrieNode { + bool isString = false; + unordered_map leaves; + + void 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]; + } + p->isString = true; + } + + ~TrieNode() { + for (auto& kv : leaves) { + if (kv.second) { + delete kv.second; + } + } + } + }; +}; From fc40df4ff44bdb6ac980945cd4a66edda5ad4722 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Aug 2017 00:54:02 +0800 Subject: [PATCH 3487/4971] Update replace-words.cpp --- C++/replace-words.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/replace-words.cpp b/C++/replace-words.cpp index 86e892b76..33633eae6 100644 --- a/C++/replace-words.cpp +++ b/C++/replace-words.cpp @@ -10,14 +10,14 @@ class Solution { trie.Insert(s); } auto curr = ≜ - for (int i = 0; i < sentence.length(); ++i) { - if (sentence[i] == ' ' || !curr || !curr->isString) { - result += sentence[i]; + for (const auto& c : sentence) { + if (c == ' ' || !curr || !curr->isString) { + result += c; } - if (sentence[i] == ' ') { + if (c == ' ') { curr = ≜ } else if (curr && !curr->isString) { - curr = curr->leaves[sentence[i]]; + curr = curr->leaves[c]; } } return result; From d6569d74e0707bdb690e9631d9e517b8a22b1b14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Aug 2017 01:16:37 +0800 Subject: [PATCH 3488/4971] Create replace-words.py --- Python/replace-words.py | 58 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Python/replace-words.py diff --git a/Python/replace-words.py b/Python/replace-words.py new file mode 100644 index 000000000..2500fd796 --- /dev/null +++ b/Python/replace-words.py @@ -0,0 +1,58 @@ +# Time: O(n) +# Space: O(t), t is the number of nodes in trie + +# In English, we have a concept called root, which can be followed by +# some other words to form another longer word - let's call this word successor. +# For example, the root an, followed by other, which can form another word another. +# +# Now, given a dictionary consisting of many roots and a sentence. +# You need to replace all the successor in the sentence with the root forming it. +# If a successor has many roots can form it, replace it with the root with the shortest length. +# +# You need to output the sentence after the replacement. +# +# Example 1: +# Input: dict = ["cat", "bat", "rat"] +# sentence = "the cattle was rattled by the battery" +# Output: "the cat was rat by the bat" +# Note: +# The input will only have lower-case letters. +# 1 <= dict words number <= 1000 +# 1 <= sentence words number <= 1000 +# 1 <= root length <= 100 +# 1 <= sentence words length <= 1000 + +class TrieNode(object): + def __init__(self): + self.is_string = False + self.leaves = collections.defaultdict(TrieNode) + + def insert(self, word): + cur = self + for c in word: + cur = cur.leaves[c] + cur.is_string = True + + +class Solution(object): + def replaceWords(self, dict, sentence): + """ + :type dict: List[str] + :type sentence: str + :rtype: str + """ + trie = TrieNode() + for s in dict: + trie.insert(s) + + def replace(word): + cur = trie + for i, c in enumerate(word): + if c not in cur.leaves: + break + cur = cur.leaves[c] + if cur.is_string: + return word[:i+1] + return word + + return " ".join(map(replace, sentence.split())) From 312035af189be807c58820ae66910fae7595c48f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Aug 2017 01:35:52 +0800 Subject: [PATCH 3489/4971] Update replace-words.py --- Python/replace-words.py | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/Python/replace-words.py b/Python/replace-words.py index 2500fd796..42d57bce4 100644 --- a/Python/replace-words.py +++ b/Python/replace-words.py @@ -22,36 +22,24 @@ # 1 <= root length <= 100 # 1 <= sentence words length <= 1000 -class TrieNode(object): - def __init__(self): - self.is_string = False - self.leaves = collections.defaultdict(TrieNode) - - def insert(self, word): - cur = self - for c in word: - cur = cur.leaves[c] - cur.is_string = True - class Solution(object): def replaceWords(self, dict, sentence): - """ - :type dict: List[str] - :type sentence: str - :rtype: str - """ - trie = TrieNode() + _trie = lambda: collections.defaultdict(_trie) + trie = _trie() for s in dict: - trie.insert(s) + cur = trie + for c in s: + cur = cur[c] + cur.setdefault("_end") def replace(word): cur = trie for i, c in enumerate(word): - if c not in cur.leaves: + if c not in cur: break - cur = cur.leaves[c] - if cur.is_string: + cur = cur[c] + if "_end" in cur: return word[:i+1] return word From 5844dc79e419932a090c14c43bc8ed24e03fb285 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 3 Aug 2017 01:36:48 +0800 Subject: [PATCH 3490/4971] Update replace-words.py --- Python/replace-words.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Python/replace-words.py b/Python/replace-words.py index 42d57bce4..de82dc0f9 100644 --- a/Python/replace-words.py +++ b/Python/replace-words.py @@ -22,9 +22,13 @@ # 1 <= root length <= 100 # 1 <= sentence words length <= 1000 - class Solution(object): def replaceWords(self, dict, sentence): + """ + :type dict: List[str] + :type sentence: str + :rtype: str + """ _trie = lambda: collections.defaultdict(_trie) trie = _trie() for s in dict: From 019d56345f3c9b0b36b1c2b456e955f97e17efb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 4 Aug 2017 23:23:50 +0800 Subject: [PATCH 3491/4971] Update replace-words.py --- Python/replace-words.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Python/replace-words.py b/Python/replace-words.py index de82dc0f9..f63beadda 100644 --- a/Python/replace-words.py +++ b/Python/replace-words.py @@ -32,18 +32,18 @@ def replaceWords(self, dict, sentence): _trie = lambda: collections.defaultdict(_trie) trie = _trie() for s in dict: - cur = trie + curr = trie for c in s: - cur = cur[c] - cur.setdefault("_end") + curr = curr[c] + curr.setdefault("_end") def replace(word): - cur = trie + curr = trie for i, c in enumerate(word): - if c not in cur: + if c not in curr: break - cur = cur[c] - if "_end" in cur: + curr = curr[c] + if "_end" in curr: return word[:i+1] return word From 39518ed7002fb57760a0cf072bffcc992ba5433d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Aug 2017 23:12:45 +0800 Subject: [PATCH 3492/4971] Create dota2-senate.cpp --- C++/dota2-senate.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/dota2-senate.cpp diff --git a/C++/dota2-senate.cpp b/C++/dota2-senate.cpp new file mode 100644 index 000000000..e81597cce --- /dev/null +++ b/C++/dota2-senate.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + string predictPartyVictory(string senate) { + queue radiant, dire; + const auto& n = senate.length(); + for (int i = 0; i < n; ++i) { + (senate[i] == 'R') ? radiant.emplace(i) : dire.emplace(i); + } + while (!radiant.empty() && !dire.empty()) { + int r_idx = radiant.front(), d_idx = dire.front(); + radiant.pop(), dire.pop(); + (r_idx < d_idx) ? radiant.emplace(r_idx + n) : dire.emplace(d_idx + n); + } + return (radiant.size() > dire.size()) ? "Radiant" : "Dire"; + } +}; From beee62b30efe510c07b0ac1a9688dd61bfa650ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 5 Aug 2017 23:20:05 +0800 Subject: [PATCH 3493/4971] Create dota2-senate.py --- Python/dota2-senate.py | 65 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Python/dota2-senate.py diff --git a/Python/dota2-senate.py b/Python/dota2-senate.py new file mode 100644 index 000000000..bbed007e5 --- /dev/null +++ b/Python/dota2-senate.py @@ -0,0 +1,65 @@ +# Time: O(n) +# Space: O(n) + +# In the world of Dota2, there are two parties: the Radiant and the Dire. +# +# The Dota2 senate consists of senators coming from two parties. +# Now the senate wants to make a decision about a change in the Dota2 game. +# The voting for this change is a round-based procedure. +# In each round, each senator can exercise one of the two rights: +# +# Ban one senator's right: +# A senator can make another senator lose all his rights in this and all the following rounds. +# Announce the victory: +# If this senator found the senators who still have rights to vote are all from the same party, +# he can announce the victory and make the decision about the change in the game. +# +# Given a string representing each senator's party belonging. +# The character 'R' and 'D' represent the Radiant party and the Dire party respectively. +# Then if there are n senators, the size of the given string will be n. +# +# The round-based procedure starts from the first senator to the last senator in the given order. +# This procedure will last until the end of voting. All the senators +# who have lost their rights will be skipped during the procedure. +# +# Suppose every senator is smart enough and will play the best strategy for his own party, +# you need to predict which party will finally announce the victory and make the change in the Dota2 game. +# The output should be Radiant or Dire. +# +# Example 1: +# Input: "RD" +# Output: "Radiant" +# Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. +# And the second senator can't exercise any rights any more since his right has been banned. +# And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. +# Example 2: +# Input: "RDD" +# Output: "Dire" +# Explanation: +# The first senator comes from Radiant and he can just ban the next senator's right in the round 1. +# And the second senator can't exercise any rights anymore since his right has been banned. +# And the third senator comes from Dire and he can ban the first senator's right in the round 1. +# And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. +# Note: +# The length of the given string will in the range [1, 10,000]. + +class Solution(object): + def predictPartyVictory(self, senate): + """ + :type senate: str + :rtype: str + """ + n = len(senate) + radiant, dire = collections.deque(), collections.deque() + for i, c in enumerate(senate): + if c == 'R': + radiant.append(i) + else: + dire.append(i) + while radiant and dire: + r_idx, d_idx = radiant.popleft(), dire.popleft() + if r_idx < d_idx: + radiant.append(r_idx+n) + else: + dire.append(d_idx+n) + return "Radiant" if len(radiant) > len(dire) else "Dire" From 38205cd7f9351254d2f2d2292c7422db7e3bc522 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 19:53:33 +0800 Subject: [PATCH 3494/4971] Create 2-keys-keyboard.cpp --- C++/2-keys-keyboard.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/2-keys-keyboard.cpp diff --git a/C++/2-keys-keyboard.cpp b/C++/2-keys-keyboard.cpp new file mode 100644 index 000000000..01343232d --- /dev/null +++ b/C++/2-keys-keyboard.cpp @@ -0,0 +1,18 @@ +// Time: O(sqrt(n)) +// Space: O(1) + +class Solution { +public: + int minSteps(int n) { + auto result = 0; + // the answer is the sum of prime factors + for (auto p = 2 ; p * p <= n; ++p) { + while (n % p == 0) { + result += p; + n /= p; + } + } + result += (n > 1) ? n : 0; + return result; + } +}; From 891737a86e8f7007ac6d040f3f01afc420cd8c99 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 20:01:55 +0800 Subject: [PATCH 3495/4971] Create 2-keys-keyboard.py --- Python/2-keys-keyboard.py | 40 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/2-keys-keyboard.py diff --git a/Python/2-keys-keyboard.py b/Python/2-keys-keyboard.py new file mode 100644 index 000000000..24282da4d --- /dev/null +++ b/Python/2-keys-keyboard.py @@ -0,0 +1,40 @@ +# Time: O(sqrt(n)) +# Space: O(1) + +# Initially on a notepad only one character 'A' is present. +# You can perform two operations on this notepad for each step: +# +# Copy All: You can copy all the characters present on the notepad (partial copy is not allowed). +# Paste: You can paste the characters which are copied last time. +# Given a number n. +# You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. +# Output the minimum number of steps to get n 'A'. +# +# Example 1: +# Input: 3 +# Output: 3 +# Explanation: +# Intitally, we have one character 'A'. +# In step 1, we use Copy All operation. +# In step 2, we use Paste operation to get 'AA'. +# In step 3, we use Paste operation to get 'AAA'. +# Note: +# The n will be in the range [1, 1000]. + +class Solution(object): + def minSteps(self, n): + """ + :type n: int + :rtype: int + """ + result = 0 + p = 2 + # the answer is the sum of prime factors + while p**2 <= n: + while n % p == 0: + result += p + n //= p + p += 1 + if n > 1: + result += n + return result From 7dbab1a6615a49513fe16c74550ddf2f52b0f698 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 22:18:55 +0800 Subject: [PATCH 3496/4971] Create 4-keys-keyboard.py --- Python/4-keys-keyboard.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Python/4-keys-keyboard.py diff --git a/Python/4-keys-keyboard.py b/Python/4-keys-keyboard.py new file mode 100644 index 000000000..1dab08996 --- /dev/null +++ b/Python/4-keys-keyboard.py @@ -0,0 +1,16 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def maxA(self, N): + """ + :type N: int + :rtype: int + """ + if N <= 6: + return N + dp = [i for i in range(N+1)] + for i in xrange(7, N+1): + dp[i % 6] = max(dp[(i-4) % 6]*3,dp[(i-5) % 6]*4) + return dp[N % 6] + From e5011127353458956dbeace8695bf285f151a2ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 22:26:37 +0800 Subject: [PATCH 3497/4971] Update 4-keys-keyboard.py --- Python/4-keys-keyboard.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/4-keys-keyboard.py b/Python/4-keys-keyboard.py index 1dab08996..89b3a90c1 100644 --- a/Python/4-keys-keyboard.py +++ b/Python/4-keys-keyboard.py @@ -7,9 +7,9 @@ def maxA(self, N): :type N: int :rtype: int """ - if N <= 6: + if N < 7: return N - dp = [i for i in range(N+1)] + dp = [i for i in xrange(N+1)] for i in xrange(7, N+1): dp[i % 6] = max(dp[(i-4) % 6]*3,dp[(i-5) % 6]*4) return dp[N % 6] From b269ed70223591c81d13f97e48c74ced12cec661 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 22:26:45 +0800 Subject: [PATCH 3498/4971] Update 4-keys-keyboard.py --- Python/4-keys-keyboard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/4-keys-keyboard.py b/Python/4-keys-keyboard.py index 89b3a90c1..5ffbcae00 100644 --- a/Python/4-keys-keyboard.py +++ b/Python/4-keys-keyboard.py @@ -11,6 +11,6 @@ def maxA(self, N): return N dp = [i for i in xrange(N+1)] for i in xrange(7, N+1): - dp[i % 6] = max(dp[(i-4) % 6]*3,dp[(i-5) % 6]*4) + dp[i % 6] = max(dp[(i-4) % 6]*3, dp[(i-5) % 6]*4) return dp[N % 6] From c2fcc7df98285219430514c746f92cc9ddf200db Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 22:38:08 +0800 Subject: [PATCH 3499/4971] Create 4-keys-keyboard.cpp --- C++/4-keys-keyboard.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/4-keys-keyboard.cpp diff --git a/C++/4-keys-keyboard.cpp b/C++/4-keys-keyboard.cpp new file mode 100644 index 000000000..754021f6b --- /dev/null +++ b/C++/4-keys-keyboard.cpp @@ -0,0 +1,17 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int maxA(int N) { + if (N < 7) { + return N; + } + vector dp(6); + iota(dp.begin(), dp.end(), 0); + for (int i = 7; i <= N; ++i) { + dp[i % 6] = max(dp[(i - 4) % 6] * 3, dp[(i - 5) % 6] * 4); + } + return dp[N % 6]; + } +}; From c634bd0096f858add85f72cd24b5e10ec8bb190e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 23:53:43 +0800 Subject: [PATCH 3500/4971] Update 4-keys-keyboard.py --- Python/4-keys-keyboard.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/Python/4-keys-keyboard.py b/Python/4-keys-keyboard.py index 5ffbcae00..28e4b5564 100644 --- a/Python/4-keys-keyboard.py +++ b/Python/4-keys-keyboard.py @@ -1,7 +1,27 @@ -# Time: O(n) +# Time: O(1) # Space: O(1) class Solution(object): + def maxA(self, N): + """ + :type N: int + :rtype: int + """ + if N <= 6: return N + if N == 10: return 20 + + n = N // 5 + 1 # n3 + n4 increases one every 5 keys + # (1) n = n3 + n4 + # (2) N + 1 = 4 * n3 + 5 * n4 + # 5 x (1) - (2) => 5*n - N - 1 = n3 + n3 = 5*n - N - 1 + n4 = n - n3 + return 3**n3 * 4**n4 + + +# Time: O(n) +# Space: O(1) +class Solution2(object): def maxA(self, N): """ :type N: int From 92506d7b3e6c2a6a3eab63b78e4dbc8e4e6810a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 23:54:28 +0800 Subject: [PATCH 3501/4971] Update 4-keys-keyboard.py --- Python/4-keys-keyboard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/4-keys-keyboard.py b/Python/4-keys-keyboard.py index 28e4b5564..a8e95dcdf 100644 --- a/Python/4-keys-keyboard.py +++ b/Python/4-keys-keyboard.py @@ -7,7 +7,7 @@ def maxA(self, N): :type N: int :rtype: int """ - if N <= 6: return N + if N < 7: return N if N == 10: return 20 n = N // 5 + 1 # n3 + n4 increases one every 5 keys From 7f5494bd9d488055b14a2881a95180fc6b3da51b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 23:57:38 +0800 Subject: [PATCH 3502/4971] Update 4-keys-keyboard.cpp --- C++/4-keys-keyboard.cpp | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/C++/4-keys-keyboard.cpp b/C++/4-keys-keyboard.cpp index 754021f6b..014854c6a 100644 --- a/C++/4-keys-keyboard.cpp +++ b/C++/4-keys-keyboard.cpp @@ -1,7 +1,29 @@ -// Time: O(n) +// Time: O(1) // Space: O(1) class Solution { +public: + int maxA(int N) { + if (N < 7) { + return N; + } + if (N == 10) { + return 20; + } + auto n = N / 5 + 1; // n3 + n4 increases one every 5 keys + // (1) n = n3 + n4 + // (2) N + 1 = 4 * n3 + 5 * n4 + // 5 x (1) - (2) => 5*n - N - 1 = n3 + auto n3 = 5 * n - N - 1; + auto n4 = n - n3; + return pow(3, n3) * pow(4, n4); + } +}; + + +// Time: O(n) +// Space: O(1) +class Solution2 { public: int maxA(int N) { if (N < 7) { From faf7ccff50d315b899fa977d7e8091b1efd9641d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 23:59:29 +0800 Subject: [PATCH 3503/4971] Update 4-keys-keyboard.cpp --- C++/4-keys-keyboard.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/4-keys-keyboard.cpp b/C++/4-keys-keyboard.cpp index 014854c6a..46fb5bb39 100644 --- a/C++/4-keys-keyboard.cpp +++ b/C++/4-keys-keyboard.cpp @@ -7,7 +7,7 @@ class Solution { if (N < 7) { return N; } - if (N == 10) { + if (N == 10) { // the following rule doesn't hold in N = 10 return 20; } auto n = N / 5 + 1; // n3 + n4 increases one every 5 keys From a043230a226ed1c516ef368137c6c6a0262212a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 Aug 2017 23:59:46 +0800 Subject: [PATCH 3504/4971] Update 4-keys-keyboard.cpp --- C++/4-keys-keyboard.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/4-keys-keyboard.cpp b/C++/4-keys-keyboard.cpp index 46fb5bb39..6ddccef1d 100644 --- a/C++/4-keys-keyboard.cpp +++ b/C++/4-keys-keyboard.cpp @@ -7,7 +7,7 @@ class Solution { if (N < 7) { return N; } - if (N == 10) { // the following rule doesn't hold in N = 10 + if (N == 10) { // the following rule doesn't hold when N = 10 return 20; } auto n = N / 5 + 1; // n3 + n4 increases one every 5 keys From d3be97e1d100510e27e3b032871cd8a29ff93927 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Aug 2017 00:00:17 +0800 Subject: [PATCH 3505/4971] Update 4-keys-keyboard.py --- Python/4-keys-keyboard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/4-keys-keyboard.py b/Python/4-keys-keyboard.py index a8e95dcdf..7af359b3d 100644 --- a/Python/4-keys-keyboard.py +++ b/Python/4-keys-keyboard.py @@ -8,7 +8,7 @@ def maxA(self, N): :rtype: int """ if N < 7: return N - if N == 10: return 20 + if N == 10: return 20 # the following rule doesn't hold when N = 10 n = N // 5 + 1 # n3 + n4 increases one every 5 keys # (1) n = n3 + n4 From 2f09a0c59746794a3b497583a2bf79d006c017c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Aug 2017 00:03:02 +0800 Subject: [PATCH 3506/4971] Update 4-keys-keyboard.py --- Python/4-keys-keyboard.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/4-keys-keyboard.py b/Python/4-keys-keyboard.py index 7af359b3d..c8c4e976e 100644 --- a/Python/4-keys-keyboard.py +++ b/Python/4-keys-keyboard.py @@ -27,8 +27,7 @@ def maxA(self, N): :type N: int :rtype: int """ - if N < 7: - return N + if N < 7: return N dp = [i for i in xrange(N+1)] for i in xrange(7, N+1): dp[i % 6] = max(dp[(i-4) % 6]*3, dp[(i-5) % 6]*4) From 40caa400342a170f6f51361977f6d087a7b8d249 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 Aug 2017 00:03:52 +0800 Subject: [PATCH 3507/4971] Update 4-keys-keyboard.py --- Python/4-keys-keyboard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/4-keys-keyboard.py b/Python/4-keys-keyboard.py index c8c4e976e..38d212b56 100644 --- a/Python/4-keys-keyboard.py +++ b/Python/4-keys-keyboard.py @@ -28,7 +28,7 @@ def maxA(self, N): :rtype: int """ if N < 7: return N - dp = [i for i in xrange(N+1)] + dp = range(N+1) for i in xrange(7, N+1): dp[i % 6] = max(dp[(i-4) % 6]*3, dp[(i-5) % 6]*4) return dp[N % 6] From 13a12d80cfad6704a76bab364b9125cc94d905d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Aug 2017 23:32:13 +0800 Subject: [PATCH 3508/4971] Create find-duplicate-subtrees.cpp --- C++/find-duplicate-subtrees.cpp | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/find-duplicate-subtrees.cpp diff --git a/C++/find-duplicate-subtrees.cpp b/C++/find-duplicate-subtrees.cpp new file mode 100644 index 000000000..a145dc4f9 --- /dev/null +++ b/C++/find-duplicate-subtrees.cpp @@ -0,0 +1,40 @@ +// Time: O(n) +// Space: O(n * 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 findDuplicateSubtrees(TreeNode* root) { + unordered_map> lookup; + vector result; + serialize(root, &lookup); + for (auto it = lookup.begin(); it != lookup.end(); ++it) { + if (it->second.size() > 1) { + result.emplace_back(it->second[0]); + } + } + return result; + } + +private: + string serializeHelper(TreeNode* node, unordered_map>* lookup) { + if (!node) { + return ""; + } + string s = "("; + s += serializeHelper(node->left, lookup); + s += to_string(node->val); + s += serializeHelper(node->right, lookup); + s += ")"; + (*lookup)[s].emplace_back(node); + return s; + } +}; From 474f50174030fc8fd4ca5f838984e92b1218600f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Aug 2017 23:33:19 +0800 Subject: [PATCH 3509/4971] Update find-duplicate-subtrees.cpp --- C++/find-duplicate-subtrees.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/find-duplicate-subtrees.cpp b/C++/find-duplicate-subtrees.cpp index a145dc4f9..d6506a806 100644 --- a/C++/find-duplicate-subtrees.cpp +++ b/C++/find-duplicate-subtrees.cpp @@ -15,7 +15,7 @@ class Solution { vector findDuplicateSubtrees(TreeNode* root) { unordered_map> lookup; vector result; - serialize(root, &lookup); + serializeHelper(root, &lookup); for (auto it = lookup.begin(); it != lookup.end(); ++it) { if (it->second.size() > 1) { result.emplace_back(it->second[0]); From c999a1cb302b3130ad63658a29159c417befbcd6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Aug 2017 23:38:35 +0800 Subject: [PATCH 3510/4971] Update find-duplicate-subtrees.cpp --- C++/find-duplicate-subtrees.cpp | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/C++/find-duplicate-subtrees.cpp b/C++/find-duplicate-subtrees.cpp index d6506a806..ed12ff7ee 100644 --- a/C++/find-duplicate-subtrees.cpp +++ b/C++/find-duplicate-subtrees.cpp @@ -13,28 +13,26 @@ class Solution { public: vector findDuplicateSubtrees(TreeNode* root) { - unordered_map> lookup; + unordered_map lookup; vector result; - serializeHelper(root, &lookup); - for (auto it = lookup.begin(); it != lookup.end(); ++it) { - if (it->second.size() > 1) { - result.emplace_back(it->second[0]); - } - } + postOrderTraversal(root, &lookup, &result); return result; } private: - string serializeHelper(TreeNode* node, unordered_map>* lookup) { + string postOrderTraversal(TreeNode* node, unordered_map* lookup, vector *result) { if (!node) { return ""; } string s = "("; - s += serializeHelper(node->left, lookup); + s += postOrderTraversal(node->left, lookup, result); s += to_string(node->val); - s += serializeHelper(node->right, lookup); + s += postOrderTraversal(node->right, lookup, result); s += ")"; - (*lookup)[s].emplace_back(node); + if ((*lookup)[s] == 1) { + result->emplace_back(node); + } + ++(*lookup)[s]; return s; } }; From 3783a941872e217f54bc51c927acd3a6984525cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Aug 2017 23:45:44 +0800 Subject: [PATCH 3511/4971] Update find-duplicate-subtrees.cpp --- C++/find-duplicate-subtrees.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/find-duplicate-subtrees.cpp b/C++/find-duplicate-subtrees.cpp index ed12ff7ee..a91d2dbec 100644 --- a/C++/find-duplicate-subtrees.cpp +++ b/C++/find-duplicate-subtrees.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(n * h) // Space: O(n * h) /** From bb7522655f23b531a81f043f033f7cbc432f591d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 8 Aug 2017 23:48:04 +0800 Subject: [PATCH 3512/4971] Create find-duplicate-subtrees.py --- Python/find-duplicate-subtrees.py | 53 +++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/find-duplicate-subtrees.py diff --git a/Python/find-duplicate-subtrees.py b/Python/find-duplicate-subtrees.py new file mode 100644 index 000000000..ae7e84a8f --- /dev/null +++ b/Python/find-duplicate-subtrees.py @@ -0,0 +1,53 @@ +# Time: O(n * h) +# Space: O(n * h) + +# Given a binary tree, return all duplicate subtrees. +# For each kind of duplicate subtrees, you only need to return the root node of any one of them. +# +# Two trees are duplicate if they have the same structure with same node values. +# +# Example 1: +# 1 +# / \ +# 2 3 +# / / \ +# 4 2 4 +# / +# 4 +# The following are two duplicate subtrees: +# 2 +# / +# 4 +# and +# 4 +# Therefore, you need to return above trees' root in the form of a list. + +# 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 findDuplicateSubtrees(self, root): + """ + :type root: TreeNode + :rtype: List[TreeNode] + """ + def postOrderTraversal(node, lookup, result): + if not node: + return "" + s = "(" + postOrderTraversal(node.left, lookup, result) + \ + str(node.val) + \ + postOrderTraversal(node.right, lookup, result) + \ + ")" + if lookup[s] == 1: + result.append(node) + lookup[s] += 1 + return s + + lookup = collections.defaultdict(int) + result = [] + postOrderTraversal(root, lookup, result) + return result From 174459588c0ea3522388db6106f2b862df464b28 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 9 Aug 2017 22:09:42 +0800 Subject: [PATCH 3513/4971] Create two-sum-iv-input-is-a-bst.cpp --- C++/two-sum-iv-input-is-a-bst.cpp | 67 +++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 C++/two-sum-iv-input-is-a-bst.cpp diff --git a/C++/two-sum-iv-input-is-a-bst.cpp b/C++/two-sum-iv-input-is-a-bst.cpp new file mode 100644 index 000000000..3cbeeb4f4 --- /dev/null +++ b/C++/two-sum-iv-input-is-a-bst.cpp @@ -0,0 +1,67 @@ +// 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: + bool findTarget(TreeNode* root, int k) { + if (!root) { + return false; + } + BSTIterator left(root, true), right(root, false); + while (*left < *right) { + if (*left + *right == k) { + return true; + } else if (*left + *right < k) { + ++left; + } else { + ++right; + } + } + return false; + } + +private: + class BSTIterator { + public: + BSTIterator(TreeNode *root, bool forward) : + node_(root), + forward_(forward) { + ++(*this); + }; + + int operator*() { + return cur_; + } + + void operator++() { + while (node_ || !s_.empty()) { + if (node_) { + s_.emplace(node_); + node_ = forward_ ? node_->left : node_->right; + } else { + node_ = s_.top(); + s_.pop(); + cur_ = node_->val; + node_ = forward_ ? node_->right : node_->left; + break; + } + } + } + + private: + TreeNode* node_; + bool forward_; + stack s_; + int cur_; + }; +}; From eae7c9734ab0490774d16ff0b6475aaaf2b14f7e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Aug 2017 00:06:59 +0800 Subject: [PATCH 3514/4971] Create two-sum-iv-input-is-a-bst.py --- Python/two-sum-iv-input-is-a-bst.py | 77 +++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Python/two-sum-iv-input-is-a-bst.py diff --git a/Python/two-sum-iv-input-is-a-bst.py b/Python/two-sum-iv-input-is-a-bst.py new file mode 100644 index 000000000..e55b985bc --- /dev/null +++ b/Python/two-sum-iv-input-is-a-bst.py @@ -0,0 +1,77 @@ +# Time: O(n) +# Space: O(h) + +# Given a Binary Search Tree and a target number, +# return true if there exist two elements in the BST such that their sum is equal to the given target. +# +# Example 1: +# Input: +# 5 +# / \ +# 3 6 +# / \ \ +# 2 4 7 +# +# Target = 9 +# +# Output: True +# Example 2: +# Input: +# 5 +# / \ +# 3 6 +# / \ \ +# 2 4 7 +# +# Target = 28 +# +# Output: False + +# 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 findTarget(self, root, k): + """ + :type root: TreeNode + :type k: int + :rtype: bool + """ + class BSTIterator(object): + def __init__(self, root, forward): + self.__node = root + self.__forward = forward + self.__s = [] + self.__cur = None + self.next() + + def val(self): + return self.__cur + + def next(self): + while self.__node or self.__s: + if self.__node: + self.__s.append(self.__node) + self.__node = self.__node.left if self.__forward else self.__node.right + else: + self.__node = self.__s.pop() + self.__cur = self.__node.val + self.__node = self.__node.right if self.__forward else self.__node.left + break + + + if not root: + return False + left, right = BSTIterator(root, True), BSTIterator(root, False) + while left.val() < right.val(): + if left.val() + right.val() == k: + return True + elif left.val() + right.val() < k: + left.next() + else: + right.next() + return False From 697ce268e803d77093eb384ab9a6b64aec7b1e5b Mon Sep 17 00:00:00 2001 From: Swaroop Gadiyaram Date: Wed, 9 Aug 2017 19:16:38 -0700 Subject: [PATCH 3515/4971] Update unique-paths-ii.py Modified the solution to a much simpler code --- Python/unique-paths-ii.py | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/Python/unique-paths-ii.py b/Python/unique-paths-ii.py index 8848514ca..013ae1930 100644 --- a/Python/unique-paths-ii.py +++ b/Python/unique-paths-ii.py @@ -24,29 +24,23 @@ class Solution: # @param obstacleGrid, a list of lists of integers # @return an integer def uniquePathsWithObstacles(self, obstacleGrid): + """ + :type obstacleGrid: List[List[int]] + :rtype: int + """ m, n = len(obstacleGrid), len(obstacleGrid[0]) - ways = [0] * n - if obstacleGrid[0][0] == 0: - ways[0] = 1 - - for j in xrange(1, n): - if obstacleGrid[0][j] == 1: - ways[j] = 0 - else: - ways[j] = ways[j - 1] - - for i in xrange(1, m): + ways = [0]*n + ways[0] = 1 + for i in range(m): if obstacleGrid[i][0] == 1: ways[0] = 0 - - for j in xrange(1, n): + for j in range(n): if obstacleGrid[i][j] == 1: ways[j] = 0 - else: - ways[j] += ways[j - 1] - - return ways[n - 1] + elif j>0: + ways[j] += ways[j-1] + return ways[-1] if __name__ == "__main__": obstacleGrid = [ @@ -54,4 +48,4 @@ def uniquePathsWithObstacles(self, obstacleGrid): [0,1,0], [0,0,0] ] - print Solution().uniquePathsWithObstacles(obstacleGrid) \ No newline at end of file + print Solution().uniquePathsWithObstacles(obstacleGrid) From 7edf31efc7b6ddc3a578080a696fa441d9c93f2d Mon Sep 17 00:00:00 2001 From: Swaroop Gadiyaram Date: Wed, 9 Aug 2017 19:19:10 -0700 Subject: [PATCH 3516/4971] Update unique-paths-ii.py --- Python/unique-paths-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/unique-paths-ii.py b/Python/unique-paths-ii.py index 013ae1930..ee53e127e 100644 --- a/Python/unique-paths-ii.py +++ b/Python/unique-paths-ii.py @@ -32,10 +32,10 @@ def uniquePathsWithObstacles(self, obstacleGrid): ways = [0]*n ways[0] = 1 - for i in range(m): + for i in xrange(m): if obstacleGrid[i][0] == 1: ways[0] = 0 - for j in range(n): + for j in xrange(n): if obstacleGrid[i][j] == 1: ways[j] = 0 elif j>0: From ba55ca50940a37d6d88b3638088402c86cca49b0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Aug 2017 23:35:41 +0800 Subject: [PATCH 3517/4971] Create maximum-binary-tree.cpp --- C++/maximum-binary-tree.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/maximum-binary-tree.cpp diff --git a/C++/maximum-binary-tree.cpp b/C++/maximum-binary-tree.cpp new file mode 100644 index 000000000..2b275d427 --- /dev/null +++ b/C++/maximum-binary-tree.cpp @@ -0,0 +1,31 @@ +// 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: + TreeNode* constructMaximumBinaryTree(vector& nums) { + // https://github.com/kamyu104/LintCode/blob/master/C++/max-tree.cpp + vector nodeStack; + for (int i = 0; i < nums.size(); ++i) { + auto node = new TreeNode(nums[i]); + while (!nodeStack.empty() && nums[i] > nodeStack.back()->val) { + node->left = nodeStack.back(); + nodeStack.pop_back(); + } + if (!nodeStack.empty()) { + nodeStack.back()->right = node; + } + nodeStack.emplace_back(node); + } + return nodeStack.front(); + } +}; From 94dd508d8161eb9554de7e54cfe66e7dbc6598f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 10 Aug 2017 23:39:44 +0800 Subject: [PATCH 3518/4971] Create maximum-binary-tree.py --- Python/maximum-binary-tree.py | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/maximum-binary-tree.py diff --git a/Python/maximum-binary-tree.py b/Python/maximum-binary-tree.py new file mode 100644 index 000000000..c100fd3d0 --- /dev/null +++ b/Python/maximum-binary-tree.py @@ -0,0 +1,50 @@ +# Time: O(n) +# Space: O(n) + +# Given an integer array with no duplicates. +# A maximum tree building on this array is defined as follow: +# +# The root is the maximum number in the array. +# The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. +# The right subtree is the maximum tree constructed from right part subarray divided by the maximum number. +# Construct the maximum tree by the given array and output the root node of this tree. +# +# Example 1: +# Input: [3,2,1,6,0,5] +# Output: return the tree root node representing the following tree: +# +# 6 +# / \ +# 3 5 +# \ / +# 2 0 +# \ +# 1 +# Note: +# The size of the given array will be in the range [1,1000]. + + +# 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 constructMaximumBinaryTree(self, nums): + """ + :type nums: List[int] + :rtype: TreeNode + """ + # https://github.com/kamyu104/LintCode/blob/master/C++/max-tree.cpp + nodeStack = [] + for num in nums: + node = TreeNode(num); + while nodeStack and num > nodeStack[-1].val: + node.left = nodeStack[-1] + nodeStack.pop() + if nodeStack: + nodeStack[-1].right = node + nodeStack.append(node) + return nodeStack[0] From f8d1df02b4a4054910f286b163e1f253c6280856 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Aug 2017 23:42:07 +0800 Subject: [PATCH 3519/4971] Create print-binary-tree.cpp --- C++/print-binary-tree.cpp | 46 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/print-binary-tree.cpp diff --git a/C++/print-binary-tree.cpp b/C++/print-binary-tree.cpp new file mode 100644 index 000000000..a92984cd8 --- /dev/null +++ b/C++/print-binary-tree.cpp @@ -0,0 +1,46 @@ +// 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: + vector> printTree(TreeNode* root) { + auto h = getHeight(root), w = getWidth(root); + vector> result(h, vector(w, "")); + preorderTraversal(root, 0, 0, w - 1, &result); + return result; + } + +private: + int getHeight(TreeNode* root) { + if (!root) { + return 0; + } + return max(getHeight(root->left), getHeight(root->right)) + 1; + } + + int getWidth(TreeNode* root) { + if (!root) { + return 0; + } + return 2 * max(getWidth(root->left), getWidth(root->right)) + 1; + } + + void preorderTraversal(TreeNode *root, int level, int left, int right, vector> *result) { + if (!root) { + return; + } + auto mid = left + (right - left) / 2; + (*result)[level][mid] = to_string(root->val); + preorderTraversal(root->left, level + 1, left, mid - 1, result); + preorderTraversal(root->right, level + 1, mid + 1, right, result); + } +}; From 6b26f53163e656f2c81c7940aacfc2278c7208cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Aug 2017 23:53:49 +0800 Subject: [PATCH 3520/4971] Create print-binary-tree.py --- Python/print-binary-tree.py | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/print-binary-tree.py diff --git a/Python/print-binary-tree.py b/Python/print-binary-tree.py new file mode 100644 index 000000000..aa637aaf8 --- /dev/null +++ b/Python/print-binary-tree.py @@ -0,0 +1,38 @@ +# 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 printTree(self, root): + """ + :type root: TreeNode + :rtype: List[List[str]] + """ + def getWidth(root): + if not root: + return 0 + return 2 * max(getWidth(root.left), getWidth(root.right)) + 1 + + def getHeight(root): + if not root: + return 0 + return max(getHeight(root.left), getHeight(root.right)) + 1 + + def preorderTraversal(root, level, left, right, result): + if not root: + return + mid = left + (right - left) / 2 + result[level][mid] = str(root.val) + preorderTraversal(root.left, level+1, left, mid-1, result) + preorderTraversal(root.right, level+1, mid+1, right, result) + + h, w = getHeight(root), getWidth(root) + result = [[""] * w for _ in xrange(h)] + preorderTraversal(root, 0, 0, w-1, result) + return result From 8ba5325b95c0ef19b3c994a5c64c5ad89235c387 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 11 Aug 2017 23:55:35 +0800 Subject: [PATCH 3521/4971] Update print-binary-tree.py --- Python/print-binary-tree.py | 51 ++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/Python/print-binary-tree.py b/Python/print-binary-tree.py index aa637aaf8..d6f09fb32 100644 --- a/Python/print-binary-tree.py +++ b/Python/print-binary-tree.py @@ -1,6 +1,55 @@ # Time: O(n) # Space: O(h) +# Print a binary tree in an m*n 2D string array following these rules: +# +# The row number m should be equal to the height of the given binary tree. +# The column number n should always be an odd number. +# The root node's value (in string format) should be put in the exactly middle of the first row it can be put. +# The column and the row where the root node belongs will separate the rest space into two parts +# (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and +# print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. +# Even if one subtree is none while the other is not, you don't need to print anything for the none subtree +# but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, +# then you don't need to leave space for both of them. +# Each unused space should contain an empty string "". +# Print the subtrees following the same rules. +# Example 1: +# Input: +# 1 +# / +# 2 +# Output: +# [["", "1", ""], +# ["2", "", ""]] +# Example 2: +# Input: +# 1 +# / \ +# 2 3 +# \ +# 4 +# Output: +# [["", "", "", "1", "", "", ""], +# ["", "2", "", "", "", "3", ""], +# ["", "", "4", "", "", "", ""]] +# Example 3: +# Input: +# 1 +# / \ +# 2 5 +# / +# 3 +# / +# 4 +# Output: +# +# [["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""] +# ["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""] +# ["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""] +# ["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]] +# Note: The height of binary tree is in the range of [1, 10]. +# # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): @@ -27,7 +76,7 @@ def getHeight(root): def preorderTraversal(root, level, left, right, result): if not root: return - mid = left + (right - left) / 2 + mid = left + (right-left)/2 result[level][mid] = str(root.val) preorderTraversal(root.left, level+1, left, mid-1, result) preorderTraversal(root.right, level+1, mid+1, right, result) From 21deb9b9ade3324a326b21555f0e35cf26064a5a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 12 Aug 2017 00:03:08 +0800 Subject: [PATCH 3522/4971] Update print-binary-tree.cpp --- C++/print-binary-tree.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/print-binary-tree.cpp b/C++/print-binary-tree.cpp index a92984cd8..12f1ac47d 100644 --- a/C++/print-binary-tree.cpp +++ b/C++/print-binary-tree.cpp @@ -1,5 +1,5 @@ -// Time: O(n) -// Space: O(h) +// Time: O(h * 2^h) +// Space: O(h * 2^h) /** * Definition for a binary tree node. From 719d5da5bfeede5a0f81bea8263c1d57e8bbedf3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 12 Aug 2017 00:03:45 +0800 Subject: [PATCH 3523/4971] Update print-binary-tree.py --- Python/print-binary-tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/print-binary-tree.py b/Python/print-binary-tree.py index d6f09fb32..33b00ff1d 100644 --- a/Python/print-binary-tree.py +++ b/Python/print-binary-tree.py @@ -1,5 +1,5 @@ -# Time: O(n) -# Space: O(h) +# Time: O(h * 2^h) +# Space: O(h * 2^h) # Print a binary tree in an m*n 2D string array following these rules: # From ffb6a7c599dd186473b0b2ce3cf22ba078033bb2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 Aug 2017 11:14:13 +0800 Subject: [PATCH 3524/4971] Create coin-path.cpp --- C++/coin-path.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 C++/coin-path.cpp diff --git a/C++/coin-path.cpp b/C++/coin-path.cpp new file mode 100644 index 000000000..e0536c3e1 --- /dev/null +++ b/C++/coin-path.cpp @@ -0,0 +1,38 @@ +// Time: O(n * B) +// Space: O(n) + +class Solution { +public: + vector cheapestJump(vector& A, int B) { + vector result; + if (A.empty() || A.back() == -1) { + return result; + } + const int n = A.size(); + vector dp(n, numeric_limits::max()), next(n, -1); + dp[n - 1] = A[n - 1]; + for (int i = n - 2; i >= 0; --i) { + if (A[i] == -1) { + continue; + } + for (int j = i + 1; j <= min(i + B, n - 1); ++j) { + if (dp[j] == numeric_limits::max()) { + continue; + } + if (A[i] + dp[j] < dp[i]) { + dp[i] = A[i] + dp[j]; + next[i] = j; + } + } + } + if (dp[0] == numeric_limits::max()) { + return result; + } + int k = 0; + while (k != -1) { + result.emplace_back(k + 1); + k = next[k]; + } + return result; + } +}; From 0b2fb8b75c5ec466b1df82abfd22ea0317ec7c4f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 Aug 2017 11:19:21 +0800 Subject: [PATCH 3525/4971] Create coin-path.py --- Python/coin-path.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/coin-path.py diff --git a/Python/coin-path.py b/Python/coin-path.py new file mode 100644 index 000000000..6d43de5c4 --- /dev/null +++ b/Python/coin-path.py @@ -0,0 +1,30 @@ +# Time: O(n * B) +# Space: O(n) + +class Solution(object): + def cheapestJump(self, A, B): + """ + :type A: List[int] + :type B: int + :rtype: List[int] + """ + result = [] + if not A or A[-1] == -1: + return result + n = len(A) + dp, next_pos = [float("inf")] * n, [-1] * n + dp[n-1] = A[n-1] + for i in reversed(xrange(n-1)): + if A[i] == -1: + continue + for j in xrange(i+1, min(i+B+1,n)): + if A[i] + dp[j] < dp[i]: + dp[i] = A[i] + dp[j] + next_pos[i] = j + if dp[0] == float("inf"): + return result + k = 0 + while k != -1: + result.append(k+1) + k = next_pos[k] + return result From e4f3f01753f822eefe5870a9ee15de0534d046a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Aug 2017 23:00:56 +0800 Subject: [PATCH 3526/4971] Create judge-route-circle.cpp --- C++/judge-route-circle.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/judge-route-circle.cpp diff --git a/C++/judge-route-circle.cpp b/C++/judge-route-circle.cpp new file mode 100644 index 000000000..26c9262c7 --- /dev/null +++ b/C++/judge-route-circle.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool judgeCircle(string moves) { + auto v = 0, h = 0; + for (const auto& move : moves) { + switch (move) { + case 'U': ++v; break; + case 'D': --v; break; + case 'R': ++h; break; + case 'L': --h; break; + } + } + return v == 0 && h == 0; + } +}; From 96f8f4f466e9d5e086cdec41a79444db4963190d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 Aug 2017 23:04:44 +0800 Subject: [PATCH 3527/4971] Create judge-route-circle.py --- Python/judge-route-circle.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/judge-route-circle.py diff --git a/Python/judge-route-circle.py b/Python/judge-route-circle.py new file mode 100644 index 000000000..79cfe6d5d --- /dev/null +++ b/Python/judge-route-circle.py @@ -0,0 +1,34 @@ +# Time: O(n) +# Space: O(1) + +# Initially, there is a Robot at position (0, 0). Given a sequence of its moves, +# judge if this robot makes a circle, which means it moves back to the original place. +# +# The move sequence is represented by a string. And each move is represent by a character. +# The valid robot moves are R (Right), L (Left), U (Up) and D (down). +# The output should be true or false representing whether the robot makes a circle. +# +# Example 1: +# Input: "UD" +# Output: true +# Example 2: +# Input: "LL" +# Output: false + +class Solution(object): + def judgeCircle(self, moves): + """ + :type moves: str + :rtype: bool + """ + v, h = 0, 0 + for move in moves: + if move == 'U': + v += 1 + elif move == 'D': + v -= 1 + elif move == 'R': + h += 1 + elif move == 'L': + h -= 1 + return v == 0 and h == 0 From 4cdd9848e399301b9ce8a789358ecba783564dfc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 15 Aug 2017 21:40:17 +0800 Subject: [PATCH 3528/4971] Create find-k-closest-elements.cpp --- C++/find-k-closest-elements.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/find-k-closest-elements.cpp diff --git a/C++/find-k-closest-elements.cpp b/C++/find-k-closest-elements.cpp new file mode 100644 index 000000000..1b674d85a --- /dev/null +++ b/C++/find-k-closest-elements.cpp @@ -0,0 +1,14 @@ +// Time: O(logn + k) +// Space: O(1) + +class Solution { +public: + vector findClosestElements(vector& arr, int k, int x) { + auto i = distance(arr.begin(), lower_bound(arr.begin(), arr.end(), x)); + int left = i - 1, right = i; + while (k--) { + (right >= arr.size() || (left >= 0 && abs(arr[left] - x) <= abs(arr[right] - x) )) ? --left : ++right; + } + return vector(arr.begin() + left + 1, arr.begin() + right); + } +}; From 1a85234d4e9be24be45ae71fb91646aab25a1730 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 15 Aug 2017 21:44:28 +0800 Subject: [PATCH 3529/4971] Create find-k-closest-elements.py --- Python/find-k-closest-elements.py | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/find-k-closest-elements.py diff --git a/Python/find-k-closest-elements.py b/Python/find-k-closest-elements.py new file mode 100644 index 000000000..d983de952 --- /dev/null +++ b/Python/find-k-closest-elements.py @@ -0,0 +1,36 @@ +# Time: O(logn + k) +# Space: O(1) + +# Given a sorted array, two integers k and x, find the k closest elements to x in the array. +# The result should also be sorted in ascending order. +# If there is a tie, the smaller elements are always preferred. +# +# Example 1: +# Input: [1,2,3,4,5], k=4, x=3 +# Output: [1,2,3,4] +# Example 2: +# Input: [1,2,3,4,5], k=4, x=-1 +# Output: [1,2,3,4] +# Note: +# The value k is positive and will always be smaller than the length of the sorted array. +# Length of the given array is positive and will not exceed 10^4 +# Absolute value of elements in the array and x will not exceed 10^4 + +class Solution(object): + def findClosestElements(self, arr, k, x): + """ + :type arr: List[int] + :type k: int + :type x: int + :rtype: List[int] + """ + i = bisect.bisect_left(arr, x) + left, right = i-1, i + while k: + if right >= len(arr) or \ + (left >= 0 and abs(arr[left]-x) <= abs(arr[right]-x)): + left -= 1 + else: + right += 1 + k -= 1 + return arr[left+1:right] From f96d2b4baf7d275f3be03be185bef5b7a713ea91 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Aug 2017 23:04:13 +0800 Subject: [PATCH 3530/4971] Create split-array-into-consecutive-subsequences.cpp --- ...it-array-into-consecutive-subsequences.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/split-array-into-consecutive-subsequences.cpp diff --git a/C++/split-array-into-consecutive-subsequences.cpp b/C++/split-array-into-consecutive-subsequences.cpp new file mode 100644 index 000000000..67bfe6c79 --- /dev/null +++ b/C++/split-array-into-consecutive-subsequences.cpp @@ -0,0 +1,29 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool isPossible(vector& nums) { + auto pre = numeric_limits::min(), cur = 0; + auto cnt1 = 0, cnt2 = 0, cnt3 = 0; // count of each length ending at cur + for (int i = 0; i < nums.size(); pre = cur) { + auto cnt = 0; + for (cur = nums[i]; i < nums.size() && cur == nums[i]; ++cnt, ++i); + + if (cur != pre + 1) { + if (cnt1 != 0 || cnt2 != 0) { + return false; + } + tie(cnt1, cnt2, cnt3) = make_tuple(cnt, 0, 0); + } else { + if (cnt < cnt1 + cnt2) { + return false; + } + tie(cnt1, cnt2, cnt3) = make_tuple(max(0, cnt - (cnt1 + cnt2 + cnt3)), + cnt1, + cnt2 + min(cnt3, cnt - (cnt1 + cnt2))); + } + } + return cnt1 == 0 && cnt2 == 0; + } +}; From 20d7c5dd5b40a17d917bfd62054cc1ee08ef5b9d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Aug 2017 23:11:44 +0800 Subject: [PATCH 3531/4971] Create split-array-into-consecutive-subsequences.py --- ...lit-array-into-consecutive-subsequences.py | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/split-array-into-consecutive-subsequences.py diff --git a/Python/split-array-into-consecutive-subsequences.py b/Python/split-array-into-consecutive-subsequences.py new file mode 100644 index 000000000..9502bfef0 --- /dev/null +++ b/Python/split-array-into-consecutive-subsequences.py @@ -0,0 +1,55 @@ +# Time: O(n) +# Space: O(1) + +# You are given an integer array sorted in ascending order (may contain duplicates), +# you need to split them into several subsequences, +# where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split. +# +# Example 1: +# Input: [1,2,3,3,4,5] +# Output: True +# Explanation: +# You can split them into two consecutive subsequences : +# 1, 2, 3 +# 3, 4, 5 +# Example 2: +# Input: [1,2,3,3,4,4,5,5] +# Output: True +# Explanation: +# You can split them into two consecutive subsequences : +# 1, 2, 3, 4, 5 +# 3, 4, 5 +# Example 3: +# Input: [1,2,3,4,4,5] +# Output: False +# Note: +# The length of the input is in range of [1, 10000] + +class Solution(object): + def isPossible(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + pre, cur = float("-inf"), 0 + cnt1, cnt2, cnt3 = 0, 0, 0 + i = 0 + while i < len(nums): + cnt = 0 + cur = nums[i] + while i < len(nums) and cur == nums[i]: + cnt += 1 + i += 1 + + if cur != pre + 1: + if cnt1 != 0 or cnt2 != 0: + return False + cnt1, cnt2, cnt3 = cnt, 0, 0 + else: + if cnt < cnt1 + cnt2: + return False + cnt1, cnt2, cnt3 = max(0, cnt - (cnt1 + cnt2 + cnt3)), \ + cnt1, \ + cnt2 + min(cnt3, cnt - (cnt1 + cnt2)) + pre = cur + return cnt1 == 0 and cnt2 == 0 From 74d094e1071f4fadffbb5f2351c4e171e528b68e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 16 Aug 2017 23:12:13 +0800 Subject: [PATCH 3532/4971] Update split-array-into-consecutive-subsequences.py --- Python/split-array-into-consecutive-subsequences.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/split-array-into-consecutive-subsequences.py b/Python/split-array-into-consecutive-subsequences.py index 9502bfef0..c5c0008ca 100644 --- a/Python/split-array-into-consecutive-subsequences.py +++ b/Python/split-array-into-consecutive-subsequences.py @@ -44,7 +44,7 @@ def isPossible(self, nums): if cur != pre + 1: if cnt1 != 0 or cnt2 != 0: return False - cnt1, cnt2, cnt3 = cnt, 0, 0 + cnt1, cnt2, cnt3 = cnt, 0, 0 else: if cnt < cnt1 + cnt2: return False From 481254fc19809d37e0c4ea2833f7ce475ab2543c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 17 Aug 2017 00:43:51 +0800 Subject: [PATCH 3533/4971] Create remove-9.cpp --- C++/remove-9.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/remove-9.cpp diff --git a/C++/remove-9.cpp b/C++/remove-9.cpp new file mode 100644 index 000000000..48b926441 --- /dev/null +++ b/C++/remove-9.cpp @@ -0,0 +1,15 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int newInteger(int n) { + int result = 0, base = 1; + while (n > 0) { + result += (n % 9) * base; + n /= 9; + base *= 10; + } + return result; + } +}; From e67e517eca7971f1397a8daec3fa64d0e8678e18 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 17 Aug 2017 00:47:05 +0800 Subject: [PATCH 3534/4971] Create remove-9.py --- Python/remove-9.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/remove-9.py diff --git a/Python/remove-9.py b/Python/remove-9.py new file mode 100644 index 000000000..c1ae25330 --- /dev/null +++ b/Python/remove-9.py @@ -0,0 +1,27 @@ +# Time: O(logn) +# Space: O(1) + +# Start from integer 1, remove any integer that contains 9 such as 9, 19, 29... +# +# So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ... +# +# Given a positive integer n, you need to return the n-th integer after removing. +# Note that 1 will be the first integer. +# +# Example 1: +# Input: 9 +# Output: 10 +# Hint: n will not exceed 9 x 10^8. + +class Solution(object): + def newInteger(self, n): + """ + :type n: int + :rtype: int + """ + result, base = 0, 1 + while n > 0: + result += (n%9) * base + n /= 9 + base *= 10 + return result From 03df38ac81ae936ae57ad621748b96e556741fd9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 18 Aug 2017 20:57:00 +0800 Subject: [PATCH 3535/4971] Update README.md --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f2e6c6028..6c3653e8e 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ -# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) ![Progress](https://img.shields.io/badge/progress-468%20%2F%20468-ff69b4.svg) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) -Up to date (2016-12-18), there are `447` Algorithms / `13` Database / `4` Shell / `4` Draft questions on [LeetCode Online Judge](https://leetcode.com/). -The number of questions is increasing recently. -Here is the classification of all `468` questions. +The number of LeetCode questions is increasing every week. 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 f81cb0cd96b373ebffb03ba4c46d31e149b71f03 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 20 Aug 2017 13:41:51 +0800 Subject: [PATCH 3536/4971] Update intersection-of-two-linked-lists.py --- Python/intersection-of-two-linked-lists.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Python/intersection-of-two-linked-lists.py b/Python/intersection-of-two-linked-lists.py index 4642fdcc5..328df54fb 100644 --- a/Python/intersection-of-two-linked-lists.py +++ b/Python/intersection-of-two-linked-lists.py @@ -35,6 +35,8 @@ def getIntersectionNode(self, headA, headB): curA, curB = headA, headB begin, tailA, tailB = None, None, None + # a->c->b->c + # b->c->a->c while curA and curB: if curA == curB: begin = curA From 6fa4579c8a215954bf3bd46c1687218bb4e951ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Aug 2017 21:52:46 +0800 Subject: [PATCH 3537/4971] Create image-smoother.cpp --- C++/image-smoother.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/image-smoother.cpp diff --git a/C++/image-smoother.cpp b/C++/image-smoother.cpp new file mode 100644 index 000000000..75e5fc7e9 --- /dev/null +++ b/C++/image-smoother.cpp @@ -0,0 +1,34 @@ +// Time: O(m * n) +// Space: O(1) + +class Solution { +public: + vector> imageSmoother(vector>& M) { + const auto m = M.size(), n = M[0].size(); + vector> result(M); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + result[i][j] = getGray(M, i, j); + } + } + return result; + } +private: + int getGray(const vector>& M, int i, int j) { + const auto& m = M.size(), n = M[0].size(); + static const vector> directions = { {-1, -1}, {0, -1}, {1, -1}, + {-1, 0}, {1, 0}, + {-1, 1} ,{0, 1}, {1, 1} }; + double total = M[i][j]; + int count = 1; + for (const auto& direction : directions) { + const auto& ii = i + direction.first; + const auto& jj = j + direction.second; + if (0 <= ii && ii < m && 0 <= jj & jj < n) { + total += M[ii][jj]; + ++count; + } + } + return static_cast(total / count); + } +}; From 93478630a4e269eaaf3d11121048256ab99d6f17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Aug 2017 21:54:55 +0800 Subject: [PATCH 3538/4971] Update image-smoother.cpp --- C++/image-smoother.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/image-smoother.cpp b/C++/image-smoother.cpp index 75e5fc7e9..5de2cc17e 100644 --- a/C++/image-smoother.cpp +++ b/C++/image-smoother.cpp @@ -18,7 +18,7 @@ class Solution { const auto& m = M.size(), n = M[0].size(); static const vector> directions = { {-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, - {-1, 1} ,{0, 1}, {1, 1} }; + {-1, 1}, {0, 1}, {1, 1} }; double total = M[i][j]; int count = 1; for (const auto& direction : directions) { From b9ed8c72ba427448e9de6b1d05d0bf6e6dd8a3d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Aug 2017 21:56:21 +0800 Subject: [PATCH 3539/4971] Update image-smoother.cpp --- C++/image-smoother.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/image-smoother.cpp b/C++/image-smoother.cpp index 5de2cc17e..52cbd89b8 100644 --- a/C++/image-smoother.cpp +++ b/C++/image-smoother.cpp @@ -24,7 +24,7 @@ class Solution { for (const auto& direction : directions) { const auto& ii = i + direction.first; const auto& jj = j + direction.second; - if (0 <= ii && ii < m && 0 <= jj & jj < n) { + if (0 <= ii && ii < m && 0 <= jj && jj < n) { total += M[ii][jj]; ++count; } From 54a36a1a57b501e2da1fb77ccb6fb67d787895fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Aug 2017 22:05:58 +0800 Subject: [PATCH 3540/4971] Update image-smoother.cpp --- C++/image-smoother.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/C++/image-smoother.cpp b/C++/image-smoother.cpp index 52cbd89b8..446acd925 100644 --- a/C++/image-smoother.cpp +++ b/C++/image-smoother.cpp @@ -13,18 +13,19 @@ class Solution { } return result; } + private: int getGray(const vector>& M, int i, int j) { const auto& m = M.size(), n = M[0].size(); static const vector> directions = { {-1, -1}, {0, -1}, {1, -1}, - {-1, 0}, {1, 0}, + {-1, 0}, {0, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1} }; - double total = M[i][j]; - int count = 1; + double total = 0.0; + int count = 0; for (const auto& direction : directions) { const auto& ii = i + direction.first; const auto& jj = j + direction.second; - if (0 <= ii && ii < m && 0 <= jj && jj < n) { + if (0 <= ii && ii < m && 0 <= jj & jj < n) { total += M[ii][jj]; ++count; } From 4fcd7d2f344fc577fe5d73d55ba630a9b2d5aa83 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Aug 2017 22:08:21 +0800 Subject: [PATCH 3541/4971] Create image-smoother.py --- Python/image-smoother.py | 49 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/image-smoother.py diff --git a/Python/image-smoother.py b/Python/image-smoother.py new file mode 100644 index 000000000..44e03c24e --- /dev/null +++ b/Python/image-smoother.py @@ -0,0 +1,49 @@ +# Time: O(m * n) +# Space: O(1) + +# Given a 2D integer matrix M representing the gray scale of an image, +# you need to design a smoother to make the gray scale of each cell becomes +# the average gray scale (rounding down) of all the 8 surrounding cells and itself. +# If a cell has less than 8 surrounding cells, then use as many as you can. +# +# Example 1: +# Input: +# [[1,1,1], +# [1,0,1], +# [1,1,1]] +# Output: +# [[0, 0, 0], +# [0, 0, 0], +# [0, 0, 0]] +# Explanation: +# For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 +# For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 +# For the point (1,1): floor(8/9) = floor(0.88888889) = 0 +# Note: +# The value in the given matrix is in the range of [0, 255]. +# The length and width of the given matrix are in the range of [1, 150]. + +class Solution(object): + def imageSmoother(self, M): + """ + :type M: List[List[int]] + :rtype: List[List[int]] + """ + def getGray(M, i, j): + directions = [[-1, -1], [0, -1], [1, -1], \ + [-1, 0], [0, 0], [1, 0], \ + [-1, 1], [0, 1], [1, 1]] + + total, count = 0, 0.0 + for direction in directions: + ii, jj = i + direction[0], j + direction[1] + if 0 <= ii < len(M) and 0 <= jj < len(M[0]): + total += M[ii][jj] + count += 1.0 + return int(total / count) + + result = [[0 for _ in xrange(len(M[0]))] for _ in xrange(len(M))] + for i in xrange(len(M)): + for j in xrange(len(M[0])): + result[i][j] = getGray(M, i, j); + return result From bd74689e83fadf6dd91122b71dcdd8533c9c820b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 Aug 2017 22:08:55 +0800 Subject: [PATCH 3542/4971] Update image-smoother.cpp --- C++/image-smoother.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/image-smoother.cpp b/C++/image-smoother.cpp index 446acd925..57feb4300 100644 --- a/C++/image-smoother.cpp +++ b/C++/image-smoother.cpp @@ -25,7 +25,7 @@ class Solution { for (const auto& direction : directions) { const auto& ii = i + direction.first; const auto& jj = j + direction.second; - if (0 <= ii && ii < m && 0 <= jj & jj < n) { + if (0 <= ii && ii < m && 0 <= jj && jj < n) { total += M[ii][jj]; ++count; } From 2af8c8e3c6c22643256a7c0d8b6b67dd1082188e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Aug 2017 22:53:00 +0800 Subject: [PATCH 3543/4971] Create maximum-width-of-binary-tree.cpp --- C++/maximum-width-of-binary-tree.cpp | 34 ++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/maximum-width-of-binary-tree.cpp diff --git a/C++/maximum-width-of-binary-tree.cpp b/C++/maximum-width-of-binary-tree.cpp new file mode 100644 index 000000000..7985e5979 --- /dev/null +++ b/C++/maximum-width-of-binary-tree.cpp @@ -0,0 +1,34 @@ +// 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 widthOfBinaryTree(TreeNode* root) { + vector leftmosts; + int result = 0; + dfs(root, 1, 0, &leftmosts, &result); + return result; + } + +private: + void dfs(TreeNode* node, int id, int depth, vector *leftmosts, int *result) { + if (!node) { + return; + } + if (depth >= leftmosts->size()) { + leftmosts->emplace_back(id); + } + *result = max(*result, id - (*leftmosts)[depth] + 1); + dfs(node->left, id * 2, depth + 1, leftmosts, result); + dfs(node->right, id * 2 + 1, depth + 1, leftmosts, result); + } +}; From 78d948c3813f04fca1898220eca0c2bfd2fcd5e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Aug 2017 23:03:34 +0800 Subject: [PATCH 3544/4971] Update maximum-width-of-binary-tree.cpp --- C++/maximum-width-of-binary-tree.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/C++/maximum-width-of-binary-tree.cpp b/C++/maximum-width-of-binary-tree.cpp index 7985e5979..711af584a 100644 --- a/C++/maximum-width-of-binary-tree.cpp +++ b/C++/maximum-width-of-binary-tree.cpp @@ -14,21 +14,20 @@ class Solution { public: int widthOfBinaryTree(TreeNode* root) { vector leftmosts; - int result = 0; - dfs(root, 1, 0, &leftmosts, &result); - return result; + return dfs(root, 1, 0, &leftmosts); } private: - void dfs(TreeNode* node, int id, int depth, vector *leftmosts, int *result) { + int dfs(TreeNode* node, int id, int depth, vector *leftmosts) { if (!node) { - return; + return 0; } if (depth >= leftmosts->size()) { leftmosts->emplace_back(id); } - *result = max(*result, id - (*leftmosts)[depth] + 1); - dfs(node->left, id * 2, depth + 1, leftmosts, result); - dfs(node->right, id * 2 + 1, depth + 1, leftmosts, result); + int result = id - (*leftmosts)[depth] + 1; + result = max(result, dfs(node->left, id * 2, depth + 1, leftmosts)); + result = max(result, dfs(node->right, id * 2 + 1, depth + 1, leftmosts)); + return result; } }; From 373629ffba6b86bcc44e808b0a7743ddc705fec7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Aug 2017 23:06:29 +0800 Subject: [PATCH 3545/4971] Create maximum-width-of-binary-tree.py --- Python/maximum-width-of-binary-tree.py | 83 ++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Python/maximum-width-of-binary-tree.py diff --git a/Python/maximum-width-of-binary-tree.py b/Python/maximum-width-of-binary-tree.py new file mode 100644 index 000000000..18c22347e --- /dev/null +++ b/Python/maximum-width-of-binary-tree.py @@ -0,0 +1,83 @@ +# Time: O(n) +# Space: O(h) + +# Given a binary tree, write a function to get the maximum width of the given tree. +# The width of a tree is the maximum width among all levels. The binary tree has the same structure +# as a full binary tree, but some nodes are null. +# +# The width of one level is defined as the length between the end-nodes +# (the leftmost and right most non-null nodes in the level, +# where the null nodes between the end-nodes are also counted into the length calculation. +# +# Example 1: +# Input: +# +# 1 +# / \ +# 3 2 +# / \ \ +# 5 3 9 +# +# Output: 4 +# Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9). +# Example 2: +# Input: +# +# 1 +# / +# 3 +# / \ +# 5 3 +# +# Output: 2 +# Explanation: The maximum width existing in the third level with the length 2 (5,3). +# Example 3: +# Input: +# +# 1 +# / \ +# 3 2 +# / +# 5 +# +# Output: 2 +# Explanation: The maximum width existing in the second level with the length 2 (3,2). +# Example 4: +# Input: +# +# 1 +# / \ +# 3 2 +# / \ +# 5 9 +# / \ +# 6 7 +# Output: 8 +# Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7). +# +# Note: Answer will in the range of 32-bit signed integer. + # +# 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 widthOfBinaryTree(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def dfs(node, i, depth, leftmosts): + if not node: + return 0 + if depth >= len(leftmosts): + leftmosts.append(i) + return max(i-leftmosts[depth]+1, \ + dfs(node.left, i*2, depth+1, leftmosts), \ + dfs(node.right, i*2+1, depth+1, leftmosts)) + + leftmosts = [] + return dfs(root, 1, 0, leftmosts) From 99fe3efcf781e5de2f14c2a6273d54ad99569408 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 Aug 2017 23:07:26 +0800 Subject: [PATCH 3546/4971] Update maximum-width-of-binary-tree.py --- Python/maximum-width-of-binary-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximum-width-of-binary-tree.py b/Python/maximum-width-of-binary-tree.py index 18c22347e..4bb5125c0 100644 --- a/Python/maximum-width-of-binary-tree.py +++ b/Python/maximum-width-of-binary-tree.py @@ -56,7 +56,7 @@ # Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7). # # Note: Answer will in the range of 32-bit signed integer. - # +# # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): From 439f1463718d8133c7db0eb2406aac28941fc2d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Aug 2017 22:14:50 +0800 Subject: [PATCH 3547/4971] Create equal-tree-partition.cpp --- C++/equal-tree-partition.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/equal-tree-partition.cpp diff --git a/C++/equal-tree-partition.cpp b/C++/equal-tree-partition.cpp new file mode 100644 index 000000000..a86602cdd --- /dev/null +++ b/C++/equal-tree-partition.cpp @@ -0,0 +1,35 @@ +// 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: + bool checkEqualTree(TreeNode* root) { + unordered_map lookup; + auto total = getSumHelper(root, &lookup); + if (total == 0) { + return lookup[total] > 1; + } + return total % 2 == 0 && lookup.count(total / 2); + } + +private: + int getSumHelper(TreeNode* root, unordered_map *lookup) { + if (!root) { + return 0; + } + int total = root->val + + getSumHelper(root->left, lookup) + + getSumHelper(root->right, lookup); + ++(*lookup)[total]; + return total; + } +}; From 988b4462ad6a603976a6effcb86c23e8c36a246a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Aug 2017 22:21:20 +0800 Subject: [PATCH 3548/4971] Update equal-tree-partition.cpp --- C++/equal-tree-partition.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/equal-tree-partition.cpp b/C++/equal-tree-partition.cpp index a86602cdd..2555131fd 100644 --- a/C++/equal-tree-partition.cpp +++ b/C++/equal-tree-partition.cpp @@ -22,13 +22,13 @@ class Solution { } private: - int getSumHelper(TreeNode* root, unordered_map *lookup) { - if (!root) { + int getSumHelper(TreeNode* node, unordered_map *lookup) { + if (!node) { return 0; } - int total = root->val + - getSumHelper(root->left, lookup) + - getSumHelper(root->right, lookup); + int total = node->val + + getSumHelper(node->left, lookup) + + getSumHelper(node->right, lookup); ++(*lookup)[total]; return total; } From 669e3cfc7f9c58f67665b304034e89d3b47d8e5e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 23 Aug 2017 22:23:14 +0800 Subject: [PATCH 3549/4971] Create equal-tree-partition.py --- Python/equal-tree-partition.py | 69 ++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Python/equal-tree-partition.py diff --git a/Python/equal-tree-partition.py b/Python/equal-tree-partition.py new file mode 100644 index 000000000..d01e4d2b6 --- /dev/null +++ b/Python/equal-tree-partition.py @@ -0,0 +1,69 @@ +# Time: O(n) +# Space: O(n) + +# Given a binary tree with n nodes, your task is to check +# if it's possible to partition the tree to two trees which have the equal sum +# of values after removing exactly one edge on the original tree. +# +# Example 1: +# Input: +# 5 +# / \ +# 10 10 +# / \ +# 2 3 +# +# Output: True +# Explanation: +# 5 +# / +# 10 +# +# Sum: 15 +# +# 10 +# / \ +# 2 3 +# +# Sum: 15 +# Example 2: +# Input: +# 1 +# / \ +# 2 10 +# / \ +# 2 20 +# +# Output: False +# Explanation: You can't split the tree into two trees with equal sum after removing exactly one edge on the tree. +# Note: +# The range of tree node value is in the range of [-100000, 100000]. +# 1 <= n <= 10000 + +# 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 checkEqualTree(self, root): + """ + :type root: TreeNode + :rtype: bool + """ + def getSumHelper(node, lookup): + if not node: + return 0 + total = node.val + \ + getSumHelper(node.left, lookup) + \ + getSumHelper(node.right, lookup) + lookup[total] += 1 + return total + + lookup = collections.defaultdict(int) + total = getSumHelper(root, lookup) + if total == 0: + return lookup[total] > 1 + return total%2 == 0 and (total/2) in lookup From b01b1e038826d972ca7cb679b49ad308a1751bbb Mon Sep 17 00:00:00 2001 From: Swaroop Gadiyaram Date: Wed, 23 Aug 2017 11:31:37 -0700 Subject: [PATCH 3550/4971] Update find-peak-element.py Adding another solution with same complexity but less case checks --- Python/find-peak-element.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Python/find-peak-element.py b/Python/find-peak-element.py index 03b265932..4ce67cba4 100644 --- a/Python/find-peak-element.py +++ b/Python/find-peak-element.py @@ -37,7 +37,22 @@ def findPeakElement(self, nums): left = mid + 1 return left - + + def findPeakElement2(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + left, right = 0, len(nums) - 1 + + while left < right: + mid = left + (right - left) / 2 + if nums[mid] > nums[mid + 1]: + right = mid + else: + left = mid + 1 + + return left if __name__ == "__main__": # print Solution().findPeakElement([1,2,1]) From e0a9dcdca5124b0a92fc4eb0cd4fd1d0d070bed5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 24 Aug 2017 23:52:55 +0800 Subject: [PATCH 3551/4971] Create strange-printer.py --- Python/strange-printer.py | 43 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/strange-printer.py diff --git a/Python/strange-printer.py b/Python/strange-printer.py new file mode 100644 index 000000000..534463942 --- /dev/null +++ b/Python/strange-printer.py @@ -0,0 +1,43 @@ +# Time: O(n^3) +# Space: O(n^2) + +# There is a strange printer with the following two special requirements: +# +# The printer can only print a sequence of the same character each time. +# At each turn, the printer can print new characters starting from +# and ending at any places, and will cover the original existing characters. +# +# Given a string consists of lower English letters only, +# your job is to count the minimum number of turns the printer needed in order to print it. +# +# Example 1: +# Input: "aaabbb" +# Output: 2 +# Explanation: Print "aaa" first and then print "bbb". +# Example 2: +# Input: "aba" +# Output: 2 +# Explanation: Print "aaa" first and then print "b" from +# the second place of the string, which will cover the existing character 'a'. +# +# Hint: Length of the given string will not exceed 100. + +class Solution(object): + def strangePrinter(self, s): + """ + :type s: str + :rtype: int + """ + def dp(s, i, j, lookup): + if i > j: + return 0 + if (i, j) not in lookup: + lookup[(i, j)] = dp(s, i, j-1, lookup) + 1 + for k in xrange(i, j): + if s[k] == s[j]: + lookup[(i, j)] = min(lookup[(i, j)], \ + dp(s, i, k, lookup) + dp(s, k+1, j-1, lookup)) + return lookup[(i, j)] + + lookup = {} + return dp(s, 0, len(s)-1, lookup) From 5ac26d042ee1481474612f27cc102812b36b7d90 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Aug 2017 00:06:13 +0800 Subject: [PATCH 3552/4971] Update find-peak-element.cpp --- C++/find-peak-element.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/C++/find-peak-element.cpp b/C++/find-peak-element.cpp index 8e9dc8bf2..466c5240d 100644 --- a/C++/find-peak-element.cpp +++ b/C++/find-peak-element.cpp @@ -8,10 +8,7 @@ class Solution { while (left < right) { const auto mid = left + (right - left) / 2; - if ((mid == 0 || nums[mid - 1] < nums[mid]) && - (mid + 1 == nums.size() || nums[mid] > nums[mid + 1])) { - return mid; - } else if (!(mid == 0 || nums[mid - 1] < nums[mid])) { + if (nums[mid] > nums[mid + 1]) { right = mid; } else { left = mid + 1; From 36d8470be71b0e7dbea1fe7aa53a818e11e61f5c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Aug 2017 00:06:50 +0800 Subject: [PATCH 3553/4971] Update find-peak-element.py --- Python/find-peak-element.py | 22 ++-------------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/Python/find-peak-element.py b/Python/find-peak-element.py index 4ce67cba4..dfa85fd2d 100644 --- a/Python/find-peak-element.py +++ b/Python/find-peak-element.py @@ -18,7 +18,7 @@ # Your solution should be in logarithmic complexity. -class Solution(object): +class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] @@ -26,25 +26,6 @@ def findPeakElement(self, nums): """ left, right = 0, len(nums) - 1 - while left < right: - mid = left + (right - left) / 2 - if (mid == 0 or nums[mid - 1] < nums[mid]) and \ - (mid + 1 == len(nums) or nums[mid] > nums[mid + 1]): - return mid - elif not (mid == 0 or nums[mid - 1] < nums[mid]): - right = mid - else: - left = mid + 1 - - return left - - def findPeakElement2(self, nums): - """ - :type nums: List[int] - :rtype: int - """ - left, right = 0, len(nums) - 1 - while left < right: mid = left + (right - left) / 2 if nums[mid] > nums[mid + 1]: @@ -54,6 +35,7 @@ def findPeakElement2(self, nums): return left + if __name__ == "__main__": # print Solution().findPeakElement([1,2,1]) print Solution().findPeakElement([1,2,3,1]) From abaa799e53513858651abade09077e05e2e2eeb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 Aug 2017 00:18:29 +0800 Subject: [PATCH 3554/4971] Create strange-printer.cpp --- C++/strange-printer.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/strange-printer.cpp diff --git a/C++/strange-printer.cpp b/C++/strange-printer.cpp new file mode 100644 index 000000000..89997ba20 --- /dev/null +++ b/C++/strange-printer.cpp @@ -0,0 +1,27 @@ +// Time: O(n^3) +// Space: O(n^2) + +class Solution { +public: + int strangePrinter(string s) { + vector> lookup(s.length(), vector(s.length())); + return dp(s, 0, s.length() - 1, &lookup); + } + +private: + int dp(const string& s, int i, int j, vector> *lookup) { + if (i > j) { + return 0; + } + if (!(*lookup)[i][j]) { + (*lookup)[i][j] = dp(s, i, j - 1, lookup) + 1; + for (int k = i; k < j; ++k) { + if (s[k] == s[j]) { + (*lookup)[i][j] = min((*lookup)[i][j], + dp(s, i, k, lookup) + dp(s, k + 1, j - 1, lookup)); + } + } + } + return (*lookup)[i][j]; + } +}; From cc05c0bb6ebbd99d58bbd7868e1b4a3540e959b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 26 Aug 2017 23:31:34 +0800 Subject: [PATCH 3555/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index c37a7626f..b6687d576 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -20,7 +20,7 @@ class LFUCache{ } } - void set(int key, int value) + void put(int key, int value) { if (!capa_) { return; } @@ -66,5 +66,5 @@ class LFUCache{ * Your LFUCache object will be instantiated and called as such: * LFUCache obj = new LFUCache(capacity); * int param_1 = obj.get(key); - * obj.set(key,value); + * obj.put(key,value); */ From e0eaff0210d6e305b3bfedeea3d29c7c38a2a20d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Aug 2017 00:51:35 +0800 Subject: [PATCH 3556/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 87 +++++++++++++++++++++++------------------------ 1 file changed, 42 insertions(+), 45 deletions(-) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index b6687d576..f9bd6a4d1 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -1,65 +1,62 @@ // Time: O(1), per operation. // Space: O(k), k is the capacity of cache. -#include - -class LFUCache{ +class LFUCache { public: - // @param capacity, an integer - LFUCache(int capacity) : capa_(capacity) { + LFUCache(int capacity) : capa_(capacity), size_(0) { } - + int get(int key) { - if (map_.find(key) != map_.end() && capa_) { - // It key exists, update it. - const auto value = map_[key]->value; - update(key, value); - return value; - } else { + if (!key_to_val_freq_.count(key)) { return -1; } + + freq_to_keys_[key_to_val_freq_[key].second].erase(key_to_it_[key]); + if (freq_to_keys_[key_to_val_freq_[key].second].empty()) { + freq_to_keys_.erase(key_to_val_freq_[key].second); + if (min_freq_ == key_to_val_freq_[key].second) { + ++min_freq_; + } + } + + ++key_to_val_freq_[key].second; + freq_to_keys_[key_to_val_freq_[key].second].emplace_back(key); + key_to_it_[key] = prev(freq_to_keys_[key_to_val_freq_[key].second].end()); + + return key_to_val_freq_[key].first; } + + void put(int key, int value) { + if (capa_ <= 0) { + return; + } - void put(int key, int value) { - if (!capa_) { + if (get(key) != -1) { + key_to_val_freq_[key].first = value; return; } - // If cache is full while inserting, remove the last one. - if (map_.find(key) == map_.end() && list_.size() == capa_) { - auto del = list_.front(); list_.pop_front(); - map_.erase(del.key); + + if (size_ == capa_) { + key_to_val_freq_.erase(freq_to_keys_[min_freq_].front()); + key_to_it_.erase(freq_to_keys_[min_freq_].front()); + freq_to_keys_[min_freq_].pop_front(); + --size_; } - update(key, value); + + min_freq_ = 1; + key_to_val_freq_[key] = {value, min_freq_}; + freq_to_keys_[min_freq_].emplace_back(key); + key_to_it_[key] = prev(freq_to_keys_[min_freq_].end()); + ++size_; } private: - struct node { - node(int k, int v, int f) : key(k), value(v), freq(f) {} - int key; - int value; - int freq; - }; - using List = list; - List list_; // key, value - unordered_map map_; // key, list iterator int capa_; - - // Update (key, iterator of (key, value)) pair - void update(int key, int value) { - int freq = 0; - auto l_it = list_.begin(); - auto it = map_.find(key); - if (it != map_.end()) { - freq = it->second->freq; - l_it = next(it->second); - list_.erase(it->second); - } - ++freq; - while (l_it != list_.end() && freq >= l_it->freq) { - ++l_it; - } - map_[key] = list_.emplace(l_it, node(key, value, freq)); - } + int size_; + int min_freq_; + unordered_map> freq_to_keys_; // freq to key list; + unordered_map::iterator> key_to_it_; // key to list iterator; + unordered_map> key_to_val_freq_; // key to {value,freq}; }; /** From 61948373847f8d0ff27e5022107a1301e7062b85 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Aug 2017 00:58:55 +0800 Subject: [PATCH 3557/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index f9bd6a4d1..6cb8f2f54 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -54,9 +54,9 @@ class LFUCache { int capa_; int size_; int min_freq_; - unordered_map> freq_to_keys_; // freq to key list; - unordered_map::iterator> key_to_it_; // key to list iterator; - unordered_map> key_to_val_freq_; // key to {value,freq}; + unordered_map> freq_to_keys_; // freq to list of keys + unordered_map::iterator> key_to_it_; // key to list iterator + unordered_map> key_to_val_freq_; // key to {value, freq} }; /** From 00da5fb0340765554f1b919857ef557e4c335deb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Aug 2017 01:40:15 +0800 Subject: [PATCH 3558/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index 6cb8f2f54..34d7f8b48 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -40,6 +40,9 @@ class LFUCache { key_to_val_freq_.erase(freq_to_keys_[min_freq_].front()); key_to_it_.erase(freq_to_keys_[min_freq_].front()); freq_to_keys_[min_freq_].pop_front(); + if (freq_to_keys_[min_freq_].empty()) { + freq_to_keys_.erase(min_freq_); + } --size_; } From 93df464ec396774cb161b51d4988773e4ce95e44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Aug 2017 13:57:51 +0800 Subject: [PATCH 3559/4971] Create lfu-cache.py --- Python/lfu-cache.py | 131 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 Python/lfu-cache.py diff --git a/Python/lfu-cache.py b/Python/lfu-cache.py new file mode 100644 index 000000000..fc19999d3 --- /dev/null +++ b/Python/lfu-cache.py @@ -0,0 +1,131 @@ +# Time: O(1), per operation +# Space: O(k), k is the capacity of cache + +# Design and implement a data structure for Least Frequently Used (LFU) cache. +# It should support the following operations: get and put. +# +# get(key) - Get the value (will always be positive) of the key +# if the key exists in the cache, otherwise return -1. +# put(key, value) - Set or insert the value if the key is not already present. +# When the cache reaches its capacity, +# it should invalidate the least frequently used item before inserting a new item. +# For the purpose of this problem, when there is a tie +# (i.e., two or more keys that have the same frequency), +# the least recently used key would be evicted. +# +# Follow up: +# Could you do both operations in O(1) time complexity? +# +# Example: +# +# LFUCache cache = new LFUCache( 2 /* capacity */ ); +# +# cache.put(1, 1); +# cache.put(2, 2); +# cache.get(1); // returns 1 +# cache.put(3, 3); // evicts key 2 +# cache.get(2); // returns -1 (not found) +# cache.get(3); // returns 3. +# cache.put(4, 4); // evicts key 1. +# cache.get(1); // returns -1 (not found) +# cache.get(3); // returns 3 +# cache.get(4); // returns 4 + +class ListNode(object): + def __init__(self, key): + self.key = key + self.next = None + self.prev = None + + +class LinkedList(object): + def __init__(self): + self.head = None + self.tail = None + + def append(self, node): + if self.head is None: + self.head = node + else: + self.tail.next = node + node.prev = self.tail + self.tail = node + + def delete(self, node): + if node.prev: + node.prev.next = node.next + else: + self.head = node.next + if node.next: + node.next.prev = node.prev + else: + self.tail = node.prev + del node + + +class LFUCache(object): + + def __init__(self, capacity): + """ + :type capacity: int + """ + self.__capa = capacity + self.__size = 0 + self.__min_freq = 0 + self.__freq_to_nodes = collections.defaultdict(LinkedList) + self.__key_to_node = {} + self.__key_to_val_freq = {} + + + def get(self, key): + """ + :type key: int + :rtype: int + """ + if key not in self.__key_to_val_freq: + return -1 + + self.__freq_to_nodes[self.__key_to_val_freq[key][1]].delete(self.__key_to_node[key]) + if not self.__freq_to_nodes[self.__key_to_val_freq[key][1]].head: + del self.__freq_to_nodes[self.__key_to_val_freq[key][1]] + if self.__min_freq == self.__key_to_val_freq[key][1]: + self.__min_freq += 1 + + self.__key_to_val_freq[key][1] += 1 + self.__freq_to_nodes[self.__key_to_val_freq[key][1]].append(ListNode(key)) + self.__key_to_node[key] = self.__freq_to_nodes[self.__key_to_val_freq[key][1]].tail + + return self.__key_to_val_freq[key][0] + + + def put(self, key, value): + """ + :type key: int + :type value: int + :rtype: void + """ + if self.__capa <= 0: + return + + if self.get(key) != -1: + self.__key_to_val_freq[key][0] = value + return + + if self.__size == self.__capa: + del self.__key_to_val_freq[self.__freq_to_nodes[self.__min_freq].head.key] + del self.__key_to_node[self.__freq_to_nodes[self.__min_freq].head.key] + self.__freq_to_nodes[self.__min_freq].delete(self.__freq_to_nodes[self.__min_freq].head) + if not self.__freq_to_nodes[self.__min_freq].head: + del self.__freq_to_nodes[self.__min_freq] + self.__size -= 1 + + self.__min_freq = 1 + self.__key_to_val_freq[key] = [value, self.__min_freq] + self.__freq_to_nodes[self.__min_freq].append(ListNode(key)) + self.__key_to_node[key] = self.__freq_to_nodes[self.__min_freq].tail + self.__size += 1 + +# Your LFUCache object will be instantiated and called as such: +# obj = LFUCache(capacity) +# param_1 = obj.get(key) +# obj.put(key,value) From fa47c0f474b835f311126fd1709b428e3c1e4c34 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Aug 2017 14:58:12 +0800 Subject: [PATCH 3560/4971] Update lfu-cache.py --- Python/lfu-cache.py | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/Python/lfu-cache.py b/Python/lfu-cache.py index fc19999d3..087f61380 100644 --- a/Python/lfu-cache.py +++ b/Python/lfu-cache.py @@ -32,8 +32,10 @@ # cache.get(4); // returns 4 class ListNode(object): - def __init__(self, key): + def __init__(self, key, value, freq): self.key = key + self.val = value + self.freq = freq self.next = None self.prev = None @@ -74,7 +76,6 @@ def __init__(self, capacity): self.__min_freq = 0 self.__freq_to_nodes = collections.defaultdict(LinkedList) self.__key_to_node = {} - self.__key_to_val_freq = {} def get(self, key): @@ -82,20 +83,21 @@ def get(self, key): :type key: int :rtype: int """ - if key not in self.__key_to_val_freq: + if key not in self.__key_to_node: return -1 - self.__freq_to_nodes[self.__key_to_val_freq[key][1]].delete(self.__key_to_node[key]) - if not self.__freq_to_nodes[self.__key_to_val_freq[key][1]].head: - del self.__freq_to_nodes[self.__key_to_val_freq[key][1]] - if self.__min_freq == self.__key_to_val_freq[key][1]: + old_node = self.__key_to_node[key] + self.__key_to_node[key] = ListNode(key, old_node.val, old_node.freq) + self.__freq_to_nodes[old_node.freq].delete(old_node) + if not self.__freq_to_nodes[self.__key_to_node[key].freq].head: + del self.__freq_to_nodes[self.__key_to_node[key].freq] + if self.__min_freq == self.__key_to_node[key].freq: self.__min_freq += 1 - - self.__key_to_val_freq[key][1] += 1 - self.__freq_to_nodes[self.__key_to_val_freq[key][1]].append(ListNode(key)) - self.__key_to_node[key] = self.__freq_to_nodes[self.__key_to_val_freq[key][1]].tail - return self.__key_to_val_freq[key][0] + self.__key_to_node[key].freq += 1 + self.__freq_to_nodes[self.__key_to_node[key].freq].append(self.__key_to_node[key]) + + return self.__key_to_node[key].val def put(self, key, value): @@ -108,11 +110,10 @@ def put(self, key, value): return if self.get(key) != -1: - self.__key_to_val_freq[key][0] = value + self.__key_to_node[key].val = value return if self.__size == self.__capa: - del self.__key_to_val_freq[self.__freq_to_nodes[self.__min_freq].head.key] del self.__key_to_node[self.__freq_to_nodes[self.__min_freq].head.key] self.__freq_to_nodes[self.__min_freq].delete(self.__freq_to_nodes[self.__min_freq].head) if not self.__freq_to_nodes[self.__min_freq].head: @@ -120,9 +121,8 @@ def put(self, key, value): self.__size -= 1 self.__min_freq = 1 - self.__key_to_val_freq[key] = [value, self.__min_freq] - self.__freq_to_nodes[self.__min_freq].append(ListNode(key)) - self.__key_to_node[key] = self.__freq_to_nodes[self.__min_freq].tail + self.__key_to_node[key] = ListNode(key, value, self.__min_freq) + self.__freq_to_nodes[self.__key_to_node[key].freq].append(self.__key_to_node[key]) self.__size += 1 # Your LFUCache object will be instantiated and called as such: From 067ae3a42bbb39407f9cd8d0a913cd4c8b20d5a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Aug 2017 15:25:26 +0800 Subject: [PATCH 3561/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 42 ++++++++++++++++++++---------------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index 34d7f8b48..7a773c01c 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -7,23 +7,24 @@ class LFUCache { } int get(int key) { - if (!key_to_val_freq_.count(key)) { + if (!key_to_nodeit_.count(key)) { return -1; } - freq_to_keys_[key_to_val_freq_[key].second].erase(key_to_it_[key]); - if (freq_to_keys_[key_to_val_freq_[key].second].empty()) { - freq_to_keys_.erase(key_to_val_freq_[key].second); - if (min_freq_ == key_to_val_freq_[key].second) { + auto new_node = *key_to_nodeit_[key]; + auto& freq = std::get<2>(new_node); + freq_to_nodes_[freq].erase(key_to_nodeit_[key]); + if (freq_to_nodes_[freq].empty()) { + freq_to_nodes_.erase(freq); + if (min_freq_ == freq) { ++min_freq_; } } - - ++key_to_val_freq_[key].second; - freq_to_keys_[key_to_val_freq_[key].second].emplace_back(key); - key_to_it_[key] = prev(freq_to_keys_[key_to_val_freq_[key].second].end()); + ++freq; + freq_to_nodes_[freq].emplace_back(new_node); + key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end()); - return key_to_val_freq_[key].first; + return std::get<1>(*key_to_nodeit_[key]); } void put(int key, int value) { @@ -32,24 +33,22 @@ class LFUCache { } if (get(key) != -1) { - key_to_val_freq_[key].first = value; + std::get<1>(*key_to_nodeit_[key]) = value; return; } if (size_ == capa_) { - key_to_val_freq_.erase(freq_to_keys_[min_freq_].front()); - key_to_it_.erase(freq_to_keys_[min_freq_].front()); - freq_to_keys_[min_freq_].pop_front(); - if (freq_to_keys_[min_freq_].empty()) { - freq_to_keys_.erase(min_freq_); + key_to_nodeit_.erase(std::get<0>(freq_to_nodes_[min_freq_].front())); + freq_to_nodes_[min_freq_].pop_front(); + if (freq_to_nodes_[min_freq_].empty()) { + freq_to_nodes_.erase(min_freq_); } --size_; } min_freq_ = 1; - key_to_val_freq_[key] = {value, min_freq_}; - freq_to_keys_[min_freq_].emplace_back(key); - key_to_it_[key] = prev(freq_to_keys_[min_freq_].end()); + freq_to_nodes_[min_freq_].emplace_back(make_tuple(key, value, min_freq_)); + key_to_nodeit_[key] = prev(freq_to_nodes_[min_freq_].end()); ++size_; } @@ -57,9 +56,8 @@ class LFUCache { int capa_; int size_; int min_freq_; - unordered_map> freq_to_keys_; // freq to list of keys - unordered_map::iterator> key_to_it_; // key to list iterator - unordered_map> key_to_val_freq_; // key to {value, freq} + unordered_map>> freq_to_nodes_; // freq to list of {key, val, freq} + unordered_map>::iterator> key_to_nodeit_; // key to list iterator }; /** From a9e8b646bc18632a6fcb15d335c7b6a505422eec Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Aug 2017 15:30:42 +0800 Subject: [PATCH 3562/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index 7a773c01c..4d503a9e8 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -12,7 +12,7 @@ class LFUCache { } auto new_node = *key_to_nodeit_[key]; - auto& freq = std::get<2>(new_node); + auto& freq = std::get(new_node); freq_to_nodes_[freq].erase(key_to_nodeit_[key]); if (freq_to_nodes_[freq].empty()) { freq_to_nodes_.erase(freq); @@ -24,7 +24,7 @@ class LFUCache { freq_to_nodes_[freq].emplace_back(new_node); key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end()); - return std::get<1>(*key_to_nodeit_[key]); + return std::get(*key_to_nodeit_[key]); } void put(int key, int value) { @@ -38,7 +38,7 @@ class LFUCache { } if (size_ == capa_) { - key_to_nodeit_.erase(std::get<0>(freq_to_nodes_[min_freq_].front())); + key_to_nodeit_.erase(std::get(freq_to_nodes_[min_freq_].front())); freq_to_nodes_[min_freq_].pop_front(); if (freq_to_nodes_[min_freq_].empty()) { freq_to_nodes_.erase(min_freq_); @@ -53,6 +53,7 @@ class LFUCache { } private: + enum Data {KEY, VAL, FREQ}; int capa_; int size_; int min_freq_; From 55ce2cd7746fdbcfda715c13984298ae23140f54 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Aug 2017 15:32:45 +0800 Subject: [PATCH 3563/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index 4d503a9e8..3ed03bec4 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -33,7 +33,7 @@ class LFUCache { } if (get(key) != -1) { - std::get<1>(*key_to_nodeit_[key]) = value; + std::get(*key_to_nodeit_[key]) = value; return; } From 53337bab08715f64a2ae793473661cd30161cb2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Aug 2017 15:42:08 +0800 Subject: [PATCH 3564/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index 3ed03bec4..7fcb75dca 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -1,5 +1,5 @@ -// Time: O(1), per operation. -// Space: O(k), k is the capacity of cache. +// Time: O(1), per operation +// Space: O(k), k is the capacity of cache class LFUCache { public: @@ -21,7 +21,7 @@ class LFUCache { } } ++freq; - freq_to_nodes_[freq].emplace_back(new_node); + freq_to_nodes_[freq].emplace_back(move(new_node)); key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end()); return std::get(*key_to_nodeit_[key]); @@ -47,7 +47,7 @@ class LFUCache { } min_freq_ = 1; - freq_to_nodes_[min_freq_].emplace_back(make_tuple(key, value, min_freq_)); + freq_to_nodes_[min_freq_].emplace_back(key, value, min_freq_); key_to_nodeit_[key] = prev(freq_to_nodes_[min_freq_].end()); ++size_; } From 58c57fc8a5b6c58c2d933900a8b78cc7bf1dfd59 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 27 Aug 2017 15:44:02 +0800 Subject: [PATCH 3565/4971] Update lfu-cache.cpp --- C++/lfu-cache.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/lfu-cache.cpp b/C++/lfu-cache.cpp index 7fcb75dca..6f454c313 100644 --- a/C++/lfu-cache.cpp +++ b/C++/lfu-cache.cpp @@ -3,7 +3,7 @@ class LFUCache { public: - LFUCache(int capacity) : capa_(capacity), size_(0) { + LFUCache(int capacity) : capa_(capacity), size_(0), min_freq_(0) { } int get(int key) { From f76eab044196aa05b391687d4d333fe6da4b693c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Aug 2017 22:32:29 +0800 Subject: [PATCH 3566/4971] Create non-decreasing-array.cpp --- C++/non-decreasing-array.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/non-decreasing-array.cpp diff --git a/C++/non-decreasing-array.cpp b/C++/non-decreasing-array.cpp new file mode 100644 index 000000000..41cfacdf0 --- /dev/null +++ b/C++/non-decreasing-array.cpp @@ -0,0 +1,24 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool checkPossibility(vector& nums) { + int cnt = 0; + for (int i = 1, prev = nums[0]; i < nums.size(); ++i) { + if (prev > nums[i]) { + if (cnt++) { + return false; + } + if (i - 2 < 0 || nums[i - 2] <= nums[i]) { + prev = nums[i]; // nums[i - 1] = nums[i], prev = nums[i] + } else { + prev = nums[i - 1]; // nums[i] = nums[i - 1], prev = nums[i] + } + } else { + prev = nums[i]; + } + } + return true; + } +}; From cabfa87a91710f4eef0502af852ca1d883fd3420 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Aug 2017 22:37:22 +0800 Subject: [PATCH 3567/4971] Create non-decreasing-array.py --- Python/non-decreasing-array.py | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/non-decreasing-array.py diff --git a/Python/non-decreasing-array.py b/Python/non-decreasing-array.py new file mode 100644 index 000000000..0697275ef --- /dev/null +++ b/Python/non-decreasing-array.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(1) + +# Given an array with n integers, your task is to check if +# it could become non-decreasing by modifying at most 1 element. +# +# We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). +# +# Example 1: +# Input: [4,2,3] +# Output: True +# Explanation: You could modify the first +# 4 +# to +# 1 +# to get a non-decreasing array. +# Example 2: +# Input: [4,2,1] +# Output: False +# Explanation: You can't get a non-decreasing array by modify at most one element. +# Note: The n belongs to [1, 10,000]. + +class Solution(object): + def checkPossibility(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + modified, prev = False, nums[0] + for i in xrange(1, len(nums)): + if prev > nums[i]: + if modified: + return False + if i-2 < 0 or nums[i-2] <= nums[i]: + prev = nums[i] # nums[i-1] = nums[i], prev = nums[i] + else: + prev = nums[i-1] # nums[i] = nums[i-1], prev = nums[i] + modified = True + else: + prev = nums[i] + return True + From 8fd45bd474e6d59d73f56929305caf682c8a4248 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Aug 2017 22:47:51 +0800 Subject: [PATCH 3568/4971] Update non-decreasing-array.py --- Python/non-decreasing-array.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/non-decreasing-array.py b/Python/non-decreasing-array.py index 0697275ef..e5e51c42f 100644 --- a/Python/non-decreasing-array.py +++ b/Python/non-decreasing-array.py @@ -33,8 +33,8 @@ def checkPossibility(self, nums): return False if i-2 < 0 or nums[i-2] <= nums[i]: prev = nums[i] # nums[i-1] = nums[i], prev = nums[i] - else: - prev = nums[i-1] # nums[i] = nums[i-1], prev = nums[i] +# else: +# prev = nums[i-1] # nums[i] = nums[i-1], prev = nums[i] modified = True else: prev = nums[i] From 256b2f1d9bc4808c65a26252fa2337ada5accf4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 Aug 2017 22:48:40 +0800 Subject: [PATCH 3569/4971] Update non-decreasing-array.cpp --- C++/non-decreasing-array.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/non-decreasing-array.cpp b/C++/non-decreasing-array.cpp index 41cfacdf0..87e288d8e 100644 --- a/C++/non-decreasing-array.cpp +++ b/C++/non-decreasing-array.cpp @@ -12,8 +12,8 @@ class Solution { } if (i - 2 < 0 || nums[i - 2] <= nums[i]) { prev = nums[i]; // nums[i - 1] = nums[i], prev = nums[i] - } else { - prev = nums[i - 1]; // nums[i] = nums[i - 1], prev = nums[i] +// } else { +// prev = nums[i - 1]; // nums[i] = nums[i - 1], prev = nums[i] } } else { prev = nums[i]; From 4175966f0fb667a8134d32b369704469a6284554 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Aug 2017 22:22:32 +0800 Subject: [PATCH 3570/4971] Create path-sum-iv.cpp --- C++/path-sum-iv.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 C++/path-sum-iv.cpp diff --git a/C++/path-sum-iv.cpp b/C++/path-sum-iv.cpp new file mode 100644 index 000000000..a6bdcb687 --- /dev/null +++ b/C++/path-sum-iv.cpp @@ -0,0 +1,41 @@ +// Time: O(n) +// Space: O(w), w is the max node count of the level in the tree + +class Solution { +public: + int pathSum(vector& nums) { + if (nums.empty()) { + return 0; + } + int result = 0; + queue q; + node dummy(10); + node* parent_ptr = &dummy; + for (const auto& num : nums) { + node child(num); + while (!parent_ptr->isParent(child)) { + result += parent_ptr->leaf ? parent_ptr->val : 0; + parent_ptr = &q.front(); + q.pop(); + } + parent_ptr->leaf = false; + child.val += parent_ptr->val; + q.emplace(move(child)); + } + while (!q.empty()) { + result += q.front().val; + q.pop(); + } + return result; + } + +private: + struct node { + int level, i, val; + bool leaf; + node(int n) : level(n / 100 - 1), i((n % 100) / 10 - 1), val(n % 10), leaf(true) {}; + inline bool isParent(const node& other) { + return level == other.level - 1 && i == other.i / 2; + }; + }; +}; From 63952681d89ff5be71529953bd272e959a451766 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Aug 2017 22:23:32 +0800 Subject: [PATCH 3571/4971] Update path-sum-iv.cpp --- C++/path-sum-iv.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/path-sum-iv.cpp b/C++/path-sum-iv.cpp index a6bdcb687..fe92a4861 100644 --- a/C++/path-sum-iv.cpp +++ b/C++/path-sum-iv.cpp @@ -10,7 +10,7 @@ class Solution { int result = 0; queue q; node dummy(10); - node* parent_ptr = &dummy; + auto parent_ptr = &dummy; for (const auto& num : nums) { node child(num); while (!parent_ptr->isParent(child)) { From ee54048a1d9900d9269506f7423dbad259bbd47a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Aug 2017 22:41:30 +0800 Subject: [PATCH 3572/4971] Create path-sum-iv.py --- Python/path-sum-iv.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/path-sum-iv.py diff --git a/Python/path-sum-iv.py b/Python/path-sum-iv.py new file mode 100644 index 000000000..cdea8cdc4 --- /dev/null +++ b/Python/path-sum-iv.py @@ -0,0 +1,38 @@ +# Time: O(n) +# Space: O(w), w is the max node count of the level in the tree + +class Solution(object): + def pathSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + class Node(object): + def __init__(self, num): + self.level = num/100 - 1 + self.i = (num%100)/10 - 1 + self.val = num%10 + self.leaf = True + + def isParent(self, other): + return self.level == other.level-1 and \ + self.i == other.i/2 + + if not nums: + return 0 + result = 0 + q = collections.deque() + dummy = Node(10) + parent = dummy + for num in nums: + child = Node(num) + while not parent.isParent(child): + result += parent.val if parent.leaf else 0 + parent = q[0] + q.popleft() + parent.leaf = False + child.val += parent.val + q.append(child) + while q: + result += q.pop().val + return result From 252acb3c257a59025d7efc9ef65071fc66287c0f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 29 Aug 2017 22:42:21 +0800 Subject: [PATCH 3573/4971] Update path-sum-iv.py --- Python/path-sum-iv.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/path-sum-iv.py b/Python/path-sum-iv.py index cdea8cdc4..e9ac5bc01 100644 --- a/Python/path-sum-iv.py +++ b/Python/path-sum-iv.py @@ -28,8 +28,7 @@ def isParent(self, other): child = Node(num) while not parent.isParent(child): result += parent.val if parent.leaf else 0 - parent = q[0] - q.popleft() + parent = q.popleft() parent.leaf = False child.val += parent.val q.append(child) From 4eec850e4583044a76d9f858546a5a259c0cefda Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Aug 2017 09:41:44 +0800 Subject: [PATCH 3574/4971] Update path-sum-iv.cpp --- C++/path-sum-iv.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/path-sum-iv.cpp b/C++/path-sum-iv.cpp index fe92a4861..6d6bbec0f 100644 --- a/C++/path-sum-iv.cpp +++ b/C++/path-sum-iv.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(w), w is the max node count of the level in the tree +// Space: O(p), p is the number of paths class Solution { public: From ee62967db1bd499befd5f93e223a235a1154aa6c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 Aug 2017 09:42:15 +0800 Subject: [PATCH 3575/4971] Update path-sum-iv.py --- Python/path-sum-iv.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/path-sum-iv.py b/Python/path-sum-iv.py index e9ac5bc01..ead4b0735 100644 --- a/Python/path-sum-iv.py +++ b/Python/path-sum-iv.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(w), w is the max node count of the level in the tree +# Space: O(p), p is the number of paths class Solution(object): def pathSum(self, nums): From ae26bcc6cdb5c95a0e2fef2deb3495d5b8fe807c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 31 Aug 2017 23:06:06 +0800 Subject: [PATCH 3576/4971] Create beautiful-arrangement-ii.cpp --- C++/beautiful-arrangement-ii.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/beautiful-arrangement-ii.cpp diff --git a/C++/beautiful-arrangement-ii.cpp b/C++/beautiful-arrangement-ii.cpp new file mode 100644 index 000000000..7ac4f78fe --- /dev/null +++ b/C++/beautiful-arrangement-ii.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector constructArray(int n, int k) { + vector result; + int left = 1, right = n; + while (left <= right) { + if (k > 1) { + result.emplace_back(k-- % 2 ? left++ : right--); + } + else { + result.emplace_back(k % 2 ? left++ : right--); + } + } + return result; + } +}; From 581f5cb6414d339b1195b7de7ddfcdf613b9bf14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 31 Aug 2017 23:09:43 +0800 Subject: [PATCH 3577/4971] Update beautiful-arrangement-ii.cpp --- C++/beautiful-arrangement-ii.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/beautiful-arrangement-ii.cpp b/C++/beautiful-arrangement-ii.cpp index 7ac4f78fe..26afe6cca 100644 --- a/C++/beautiful-arrangement-ii.cpp +++ b/C++/beautiful-arrangement-ii.cpp @@ -7,11 +7,9 @@ class Solution { vector result; int left = 1, right = n; while (left <= right) { + result.emplace_back(k % 2 ? left++ : right--); if (k > 1) { - result.emplace_back(k-- % 2 ? left++ : right--); - } - else { - result.emplace_back(k % 2 ? left++ : right--); + --k; } } return result; From ca7655b1898a20f938826edc969f7471e3113aed Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 31 Aug 2017 23:13:05 +0800 Subject: [PATCH 3578/4971] Create beautiful-arrangement-ii.py --- Python/beautiful-arrangement-ii.py | 45 ++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/beautiful-arrangement-ii.py diff --git a/Python/beautiful-arrangement-ii.py b/Python/beautiful-arrangement-ii.py new file mode 100644 index 000000000..007a28eb6 --- /dev/null +++ b/Python/beautiful-arrangement-ii.py @@ -0,0 +1,45 @@ +# Time: O(n) +# Space: O(1) + +# Given two integers n and k, +# you need to construct a list which contains n different positive integers ranging +# from 1 to n and obeys the following requirement: +# Suppose this list is [a1, a2, a3, ... , an], +# then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers. +# +# If there are multiple answers, print any of them. +# +# Example 1: +# Input: n = 3, k = 1 +# Output: [1, 2, 3] +# Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, +# and the [1, 1] has exactly 1 distinct integer: 1. +# +# Example 2: +# Input: n = 3, k = 2 +# Output: [1, 3, 2] +# Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, +# and the [2, 1] has exactly 2 distinct integers: 1 and 2. +# +# Note: +# The n and k are in the range 1 <= k < n <= 10^4. + +class Solution(object): + def constructArray(self, n, k): + """ + :type n: int + :type k: int + :rtype: List[int] + """ + result = [] + left, right = 1, n + while left <= right: + if k % 2: + result.append(left) + left += 1 + else: + result.append(right) + right -= 1 + if k > 1: + k -= 1 + return result From 48300c0263b44558b68f75608fdc30013001d831 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Sep 2017 13:23:37 +0800 Subject: [PATCH 3579/4971] Create kth-smallest-number-in-multiplication-table.cpp --- ...mallest-number-in-multiplication-table.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/kth-smallest-number-in-multiplication-table.cpp diff --git a/C++/kth-smallest-number-in-multiplication-table.cpp b/C++/kth-smallest-number-in-multiplication-table.cpp new file mode 100644 index 000000000..8b4e55762 --- /dev/null +++ b/C++/kth-smallest-number-in-multiplication-table.cpp @@ -0,0 +1,26 @@ +// Time: O(m * log(m * n)) + +class Solution { +public: + int findKthNumber(int m, int n, int k) { + int left = 1, right = m * n; + while (left <= right) { + const auto mid = left + (right - left) / 2; + if (count(mid, m, n) >= k) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } + +private: + int count(int target, int m, int n) { + auto count = 0; + for (int i = 1; i <= m; ++i) { + count += min(target / i , n); + } + return count; + } +}; From bb158da53241394df3a8ef15a53f93cd9eac7aee Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Sep 2017 13:26:19 +0800 Subject: [PATCH 3580/4971] Update kth-smallest-number-in-multiplication-table.cpp --- C++/kth-smallest-number-in-multiplication-table.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/kth-smallest-number-in-multiplication-table.cpp b/C++/kth-smallest-number-in-multiplication-table.cpp index 8b4e55762..bc3e788a4 100644 --- a/C++/kth-smallest-number-in-multiplication-table.cpp +++ b/C++/kth-smallest-number-in-multiplication-table.cpp @@ -1,4 +1,5 @@ // Time: O(m * log(m * n)) +// Space: O(1) class Solution { public: From 09e58e92aeafbd2e9ddd45b0e94efe4412f7c55a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Sep 2017 13:27:34 +0800 Subject: [PATCH 3581/4971] Create kth-smallest-number-in-multiplication-table.py --- ...smallest-number-in-multiplication-table.py | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/kth-smallest-number-in-multiplication-table.py diff --git a/Python/kth-smallest-number-in-multiplication-table.py b/Python/kth-smallest-number-in-multiplication-table.py new file mode 100644 index 000000000..eb8f10ba5 --- /dev/null +++ b/Python/kth-smallest-number-in-multiplication-table.py @@ -0,0 +1,54 @@ +# Time: O(m * log(m * n)) +# Space: O(1) + +# Nearly every one have used the Multiplication Table. +# But could you find out the k-th smallest number quickly from the multiplication table? +# +# Given the height m and the length n of a m * n Multiplication Table, and a positive integer k, +# you need to return the k-th smallest number in this table. +# +# Example 1: +# Input: m = 3, n = 3, k = 5 +# Output: +# Explanation: +# The Multiplication Table: +# 1 2 3 +# 2 4 6 +# 3 6 9 +# +# The 5-th smallest number is 3 (1, 2, 2, 3, 3). +# Example 2: +# Input: m = 2, n = 3, k = 6 +# Output: +# Explanation: +# The Multiplication Table: +# 1 2 3 +# 2 4 6 +# +# The 6-th smallest number is 6 (1, 2, 2, 3, 4, 6). +# Note: +# The m and n will be in the range [1, 30000]. +# The k will be in the range [1, m * n] + +class Solution(object): + def findKthNumber(self, m, n, k): + """ + :type m: int + :type n: int + :type k: int + :rtype: int + """ + def count(target, m, n): + count = 0 + for i in xrange(1, m+1): + count += min(target//i , n) + return count + + left, right = 1, m*n; + while left <= right: + mid = left + (right - left) / 2 + if count(mid, m, n) >= k: + right = mid-1 + else: + left = mid+1 + return left From b41d0893bc9975eb8071852ec16337bad9d3aa93 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Sep 2017 13:32:31 +0800 Subject: [PATCH 3582/4971] Update kth-smallest-number-in-multiplication-table.py --- Python/kth-smallest-number-in-multiplication-table.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Python/kth-smallest-number-in-multiplication-table.py b/Python/kth-smallest-number-in-multiplication-table.py index eb8f10ba5..fa6a80578 100644 --- a/Python/kth-smallest-number-in-multiplication-table.py +++ b/Python/kth-smallest-number-in-multiplication-table.py @@ -39,10 +39,7 @@ def findKthNumber(self, m, n, k): :rtype: int """ def count(target, m, n): - count = 0 - for i in xrange(1, m+1): - count += min(target//i , n) - return count + return sum(min(target // i, n) for i in xrange(1, m+1)) left, right = 1, m*n; while left <= right: From b279f5cc24487ec838bc8543e033592f60c87163 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Sep 2017 13:33:15 +0800 Subject: [PATCH 3583/4971] Update kth-smallest-number-in-multiplication-table.py --- Python/kth-smallest-number-in-multiplication-table.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/kth-smallest-number-in-multiplication-table.py b/Python/kth-smallest-number-in-multiplication-table.py index fa6a80578..dc5ee176e 100644 --- a/Python/kth-smallest-number-in-multiplication-table.py +++ b/Python/kth-smallest-number-in-multiplication-table.py @@ -39,11 +39,11 @@ def findKthNumber(self, m, n, k): :rtype: int """ def count(target, m, n): - return sum(min(target // i, n) for i in xrange(1, m+1)) + return sum(min(target//i, n) for i in xrange(1, m+1)) left, right = 1, m*n; while left <= right: - mid = left + (right - left) / 2 + mid = left + (right-left)/2 if count(mid, m, n) >= k: right = mid-1 else: From 653221002d97f4ab646b11c01016763550912036 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Sep 2017 23:37:59 +0800 Subject: [PATCH 3584/4971] Update word-ladder.py --- Python/word-ladder.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/Python/word-ladder.py b/Python/word-ladder.py index 61e80abdf..21d11d670 100644 --- a/Python/word-ladder.py +++ b/Python/word-ladder.py @@ -21,24 +21,26 @@ # # BFS -class Solution: - # @param start, a string - # @param end, a string - # @param dict, a set of string - # @return an integer - def ladderLength(self, start, end, word_list): - distance, cur, visited = 0, [start], set([start]) +class Solution(object): + def ladderLength(self, beginWord, endWord, wordList): + """ + :type beginWord: str + :type endWord: str + :type wordList: List[str] + :rtype: int + """ + distance, cur, visited, lookup = 0, [beginWord], set([beginWord]), set(wordList) while cur: _next = [] for word in cur: - if word == end: + if word == endWord: return distance + 1 for i in xrange(len(word)): for j in 'abcdefghijklmnopqrstuvwxyz': candidate = word[:i] + j + word[i + 1:] - if candidate not in visited and candidate in word_list: + if candidate not in visited and candidate in lookup: _next.append(candidate) visited.add(candidate) distance += 1 @@ -46,6 +48,7 @@ def ladderLength(self, start, end, word_list): return 0 + if __name__ == "__main__": print Solution().ladderLength("hit", "cog", set(["hot", "dot", "dog", "lot", "log"])) print Solution().ladderLength("hit", "cog", set(["hot", "dot", "dog", "lot", "log", "cog"])) From 71e0ba555ee49befa01fcd9fc78c3528e2ab63a9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Sep 2017 23:51:32 +0800 Subject: [PATCH 3585/4971] Update word-ladder.py --- Python/word-ladder.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/word-ladder.py b/Python/word-ladder.py index 21d11d670..3a97d25a8 100644 --- a/Python/word-ladder.py +++ b/Python/word-ladder.py @@ -32,7 +32,7 @@ def ladderLength(self, beginWord, endWord, wordList): distance, cur, visited, lookup = 0, [beginWord], set([beginWord]), set(wordList) while cur: - _next = [] + next_queue = [] for word in cur: if word == endWord: @@ -41,10 +41,10 @@ def ladderLength(self, beginWord, endWord, wordList): for j in 'abcdefghijklmnopqrstuvwxyz': candidate = word[:i] + j + word[i + 1:] if candidate not in visited and candidate in lookup: - _next.append(candidate) + next_queue.append(candidate) visited.add(candidate) distance += 1 - cur = _next + cur = next_queue return 0 From 5e7513928a742f46ff905f2b665522dcdf773087 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 Sep 2017 15:17:51 +0800 Subject: [PATCH 3586/4971] Update integer-to-roman.py --- Python/integer-to-roman.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Python/integer-to-roman.py b/Python/integer-to-roman.py index 3aa53f397..f2447305b 100644 --- a/Python/integer-to-roman.py +++ b/Python/integer-to-roman.py @@ -6,11 +6,16 @@ # Input is guaranteed to be within the range from 1 to 3999. # - -class Solution: - # @return a string +class Solution(object): def intToRoman(self, num): - numeral_map = {1: "I", 4: "IV", 5: "V", 9: "IX", 10: "X", 40: "XL", 50: "L", 90: "XC", 100: "C", 400: "CD", 500: "D", 900: "CM", 1000: "M"} + """ + :type num: int + :rtype: str + """ + numeral_map = {1: "I", 4: "IV", 5: "V", 9: "IX", \ + 10: "X", 40: "XL", 50: "L", 90: "XC", \ + 100: "C", 400: "CD", 500: "D", 900: "CM", \ + 1000: "M"} keyset, result = sorted(numeral_map.keys()), "" while num > 0: @@ -21,6 +26,7 @@ def intToRoman(self, num): return result + if __name__ == "__main__": print Solution().intToRoman(999) - print Solution().intToRoman(3999) \ No newline at end of file + print Solution().intToRoman(3999) From 6ab507805d6a724b11a1cfc349e2ec801e8d1f16 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 Sep 2017 17:57:58 +0800 Subject: [PATCH 3587/4971] Update integer-to-roman.py --- Python/integer-to-roman.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/integer-to-roman.py b/Python/integer-to-roman.py index f2447305b..eed075b1b 100644 --- a/Python/integer-to-roman.py +++ b/Python/integer-to-roman.py @@ -16,7 +16,7 @@ def intToRoman(self, num): 10: "X", 40: "XL", 50: "L", 90: "XC", \ 100: "C", 400: "CD", 500: "D", 900: "CM", \ 1000: "M"} - keyset, result = sorted(numeral_map.keys()), "" + keyset, result = sorted(numeral_map.keys()), [] while num > 0: for key in reversed(keyset): @@ -24,7 +24,7 @@ def intToRoman(self, num): num -= key result += numeral_map[key] - return result + return "".join(result) if __name__ == "__main__": From f22e0eea75c78d77afce1aad4e35c64b8367236c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Sep 2017 13:00:01 +0800 Subject: [PATCH 3588/4971] Create second-minimum-node-in-a-binary-tree.cpp --- C++/second-minimum-node-in-a-binary-tree.cpp | 36 ++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C++/second-minimum-node-in-a-binary-tree.cpp diff --git a/C++/second-minimum-node-in-a-binary-tree.cpp b/C++/second-minimum-node-in-a-binary-tree.cpp new file mode 100644 index 000000000..c543784f7 --- /dev/null +++ b/C++/second-minimum-node-in-a-binary-tree.cpp @@ -0,0 +1,36 @@ +// 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 findSecondMinimumValue(TreeNode* root) { + set bst; + findSecondMinimumValueHelper(root, &bst); + if (bst.size() < 2) { + return -1; + } + return *bst.rbegin(); + } + +private: + void findSecondMinimumValueHelper(TreeNode* root, set *bst) { + if (!root) { + return; + } + bst->emplace(root->val); + if (bst->size() > 2) { + bst->erase(prev(bst->end())); + } + findSecondMinimumValueHelper(root->left, bst); + findSecondMinimumValueHelper(root->right, bst); + } +}; From 4937cd5138bf36e744a9f5e69bc0ae66fcc2f727 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Sep 2017 13:00:26 +0800 Subject: [PATCH 3589/4971] Update second-minimum-node-in-a-binary-tree.cpp --- C++/second-minimum-node-in-a-binary-tree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/second-minimum-node-in-a-binary-tree.cpp b/C++/second-minimum-node-in-a-binary-tree.cpp index c543784f7..19134d7dd 100644 --- a/C++/second-minimum-node-in-a-binary-tree.cpp +++ b/C++/second-minimum-node-in-a-binary-tree.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(1) +// Space: O(h) /** * Definition for a binary tree node. From 0277a1f1fc5ff63100b10d4e427c267e19330cbc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Sep 2017 13:17:12 +0800 Subject: [PATCH 3590/4971] Create second-minimum-node-in-a-binary-tree.py --- .../second-minimum-node-in-a-binary-tree.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/second-minimum-node-in-a-binary-tree.py diff --git a/Python/second-minimum-node-in-a-binary-tree.py b/Python/second-minimum-node-in-a-binary-tree.py new file mode 100644 index 000000000..86230d47f --- /dev/null +++ b/Python/second-minimum-node-in-a-binary-tree.py @@ -0,0 +1,32 @@ +# 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 findSecondMinimumValue(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def findSecondMinimumValueHelper(root, max_heap, lookup): + if not root: + return + if root.val not in lookup: + heapq.heappush(max_heap, -root.val) + lookup.add(root.val) + if len(max_heap) > 2: + lookup.remove(-heapq.heappop(max_heap)) + findSecondMinimumValueHelper(root.left, max_heap, lookup) + findSecondMinimumValueHelper(root.right, max_heap, lookup) + + max_heap, lookup = [], set() + findSecondMinimumValueHelper(root, max_heap, lookup) + if len(max_heap) < 2: + return -1 + return -max_heap[0] From 4e8861a99b577aa92ee10cd2856ab72ac41f7fc3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Sep 2017 13:36:58 +0800 Subject: [PATCH 3591/4971] Create trim-a-binary-search-tree.cpp --- C++/trim-a-binary-search-tree.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/trim-a-binary-search-tree.cpp diff --git a/C++/trim-a-binary-search-tree.cpp b/C++/trim-a-binary-search-tree.cpp new file mode 100644 index 000000000..d7ebff2bc --- /dev/null +++ b/C++/trim-a-binary-search-tree.cpp @@ -0,0 +1,29 @@ +// 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: + TreeNode* trimBST(TreeNode* root, int L, int R) { + if (!root) { + return nullptr; + } + if (root->val < L) { + return trimBST(root->right, L, R); + } + if (root->val > R) { + return trimBST(root->left, L, R); + } + root->left = trimBST(root->left, L, R); + root->right = trimBST(root->right, L, R); + return root; + } +}; From c452b97e690e3fd28e957f129147e2b53c70802f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Sep 2017 13:37:39 +0800 Subject: [PATCH 3592/4971] Create trim-a-binary-search-tree.py --- Python/trim-a-binary-search-tree.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python/trim-a-binary-search-tree.py diff --git a/Python/trim-a-binary-search-tree.py b/Python/trim-a-binary-search-tree.py new file mode 100644 index 000000000..d7ebff2bc --- /dev/null +++ b/Python/trim-a-binary-search-tree.py @@ -0,0 +1,29 @@ +// 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: + TreeNode* trimBST(TreeNode* root, int L, int R) { + if (!root) { + return nullptr; + } + if (root->val < L) { + return trimBST(root->right, L, R); + } + if (root->val > R) { + return trimBST(root->left, L, R); + } + root->left = trimBST(root->left, L, R); + root->right = trimBST(root->right, L, R); + return root; + } +}; From e92c7eeca377c63b5618247d8b27d59545213d82 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Sep 2017 13:53:47 +0800 Subject: [PATCH 3593/4971] Create maximum-swap.cpp --- C++/maximum-swap.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/maximum-swap.cpp diff --git a/C++/maximum-swap.cpp b/C++/maximum-swap.cpp new file mode 100644 index 000000000..97626c791 --- /dev/null +++ b/C++/maximum-swap.cpp @@ -0,0 +1,21 @@ +// Time: O(l), l is the length of the number string +// Space: O(l) + +class Solution { +public: + int maximumSwap(int num) { + string digits = to_string(num); + int left = 0, right = 0; + int max_idx = digits.length() - 1; + for (int i = digits.length() - 1; i >= 0; --i) { + if (digits[i] > digits[max_idx]) { + max_idx = i; + } else if (digits[max_idx] > digits[i]) { + left = i; + right = max_idx; + } + } + swap(digits[left], digits[right]); + return stoi(digits); + } +}; From 5eb4047a7d1766a1c6441ee0d71bc61de9ee16d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Sep 2017 13:58:36 +0800 Subject: [PATCH 3594/4971] Create maximum-swap.py --- Python/maximum-swap.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Python/maximum-swap.py diff --git a/Python/maximum-swap.py b/Python/maximum-swap.py new file mode 100644 index 000000000..0e47dacc1 --- /dev/null +++ b/Python/maximum-swap.py @@ -0,0 +1,19 @@ +# Time: O(l), l is the length of the number string +# Space: O(l) + +class Solution(object): + def maximumSwap(self, num): + """ + :type num: int + :rtype: int + """ + digits = list(str(num)) + left, right = 0, 0 + max_idx = len(digits)-1 + for i in reversed(xrange(len(digits))): + if digits[i] > digits[max_idx]: + max_idx = i + elif digits[max_idx] > digits[i]: + left, right = i, max_idx + digits[left], digits[right] = digits[right], digits[left] + return int("".join(digits)) From fea5787c24e80be88b6744afa7ea9d0473ac405e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Sep 2017 14:05:45 +0800 Subject: [PATCH 3595/4971] Create bulb-switcher-ii.cpp --- C++/bulb-switcher-ii.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/bulb-switcher-ii.cpp diff --git a/C++/bulb-switcher-ii.cpp b/C++/bulb-switcher-ii.cpp new file mode 100644 index 000000000..fca08182a --- /dev/null +++ b/C++/bulb-switcher-ii.cpp @@ -0,0 +1,14 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int flipLights(int n, int m) { + if (m == 0) return 1; + if (n == 1) return 2; + if (m == 1 && n == 2) return 3; + if (m == 1 || n == 2) return 4; + if (m == 2) return 7; + return 8; + } +}; From 4b696c2a54f7afd95013763c098aec30b08409d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Sep 2017 14:06:49 +0800 Subject: [PATCH 3596/4971] Create bulb-switcher-ii.py --- Python/bulb-switcher-ii.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Python/bulb-switcher-ii.py diff --git a/Python/bulb-switcher-ii.py b/Python/bulb-switcher-ii.py new file mode 100644 index 000000000..6652e9ef9 --- /dev/null +++ b/Python/bulb-switcher-ii.py @@ -0,0 +1,16 @@ +# Time: O(1) +# Space: O(1) + +class Solution(object): + def flipLights(self, n, m): + """ + :type n: int + :type m: int + :rtype: int + """ + if m == 0: return 1 + if n == 1: return 2 + if m == 1 and n == 2: return 3 + if m == 1 or n == 2 return 4 + if m == 2: return 7 + return 8 From 6e710561943298c737539ed84408f1e46658b72a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Sep 2017 16:35:12 +0800 Subject: [PATCH 3597/4971] Update bulb-switcher-ii.py --- Python/bulb-switcher-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/bulb-switcher-ii.py b/Python/bulb-switcher-ii.py index 6652e9ef9..cd721443b 100644 --- a/Python/bulb-switcher-ii.py +++ b/Python/bulb-switcher-ii.py @@ -11,6 +11,6 @@ def flipLights(self, n, m): if m == 0: return 1 if n == 1: return 2 if m == 1 and n == 2: return 3 - if m == 1 or n == 2 return 4 + if m == 1 or n == 2: return 4 if m == 2: return 7 return 8 From 221c94db63b6ffee6aa76d95082ef9ac05bfbb53 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 12:57:09 +0800 Subject: [PATCH 3598/4971] Update trim-a-binary-search-tree.py --- Python/trim-a-binary-search-tree.py | 92 ++++++++++++++++++++--------- 1 file changed, 64 insertions(+), 28 deletions(-) diff --git a/Python/trim-a-binary-search-tree.py b/Python/trim-a-binary-search-tree.py index d7ebff2bc..992b05378 100644 --- a/Python/trim-a-binary-search-tree.py +++ b/Python/trim-a-binary-search-tree.py @@ -1,29 +1,65 @@ -// Time: O(n) -// Space: O(h) +# 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: - TreeNode* trimBST(TreeNode* root, int L, int R) { - if (!root) { - return nullptr; - } - if (root->val < L) { - return trimBST(root->right, L, R); - } - if (root->val > R) { - return trimBST(root->left, L, R); - } - root->left = trimBST(root->left, L, R); - root->right = trimBST(root->right, L, R); - return root; - } -}; +# Given a binary search tree and the lowest and highest boundaries as L and R, +# trim the tree so that all its elements lies in [L, R] (R >= L). +# You might need to change the root of the tree, so the result should +# return the new root of the trimmed binary search tree. +# +# Example 1: +# Input: +# 1 +# / \ +# 0 2 +# +# L = 1 +# R = 2 +# +# Output: +# 1 +# \ +# 2 +# Example 2: +# Input: +# 3 +# / \ +# 0 4 +# \ +# 2 +# / +# 1 +# +# L = 1 +# R = 3 +# +# Output: +# 3 +# / +# 2 +# / +# 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 trimBST(self, root, L, R): + """ + :type root: TreeNode + :type L: int + :type R: int + :rtype: TreeNode + """ + if not root: + return None + if root.val < L: + return self.trimBST(root.right, L, R) + if root.val > R: + return self.trimBST(root.left, L, R) + root.left, root.right = self.trimBST(root.left, L, R), self.trimBST(root.right, L, R) + return root + From 18b935db446f19f6a1a2bb18b033ec1670b5b0c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 12:59:02 +0800 Subject: [PATCH 3599/4971] Update maximum-swap.py --- Python/maximum-swap.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Python/maximum-swap.py b/Python/maximum-swap.py index 0e47dacc1..e9d049a2d 100644 --- a/Python/maximum-swap.py +++ b/Python/maximum-swap.py @@ -1,6 +1,20 @@ # Time: O(l), l is the length of the number string # Space: O(l) +# Given a non-negative integer, you could swap two digits at most once +# to get the maximum valued number. Return the maximum valued number you could get. +# +# Example 1: +# Input: 2736 +# Output: 7236 +# Explanation: Swap the number 2 and the number 7. +# Example 2: +# Input: 9973 +# Output: 9973 +# Explanation: No swap. +# Note: +# The given number is in the range [0, 10^8] + class Solution(object): def maximumSwap(self, num): """ From 5005fffef7388b7a0f345fdc7aec11370fa8cfb8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 13:00:17 +0800 Subject: [PATCH 3600/4971] Update second-minimum-node-in-a-binary-tree.py --- .../second-minimum-node-in-a-binary-tree.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Python/second-minimum-node-in-a-binary-tree.py b/Python/second-minimum-node-in-a-binary-tree.py index 86230d47f..ac2b21761 100644 --- a/Python/second-minimum-node-in-a-binary-tree.py +++ b/Python/second-minimum-node-in-a-binary-tree.py @@ -1,6 +1,34 @@ # Time: O(n) # Space: O(h) +# Given a non-empty special binary tree consisting of nodes with the non-negative value, +# where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, +# then this node's value is the smaller value among its two sub-nodes. +# +# Given such a binary tree, you need to output the second minimum value in the set made of +# all the nodes' value in the whole tree. +# +# If no such second minimum value exists, output -1 instead. +# +# Example 1: +# Input: +# 2 +# / \ +# 2 5 +# / \ +# 5 7 +# +# Output: 5 +# Explanation: The smallest value is 2, the second smallest value is 5. +# Example 2: +# Input: +# 2 +# / \ +# 2 2 +# +# Output: -1 +# Explanation: The smallest value is 2, but there isn't any second smallest value. + # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): From ec08f4d1d15e1a718c32e70a071365246b6d84aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 13:01:59 +0800 Subject: [PATCH 3601/4971] Update bulb-switcher-ii.py --- Python/bulb-switcher-ii.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Python/bulb-switcher-ii.py b/Python/bulb-switcher-ii.py index cd721443b..3ce93572a 100644 --- a/Python/bulb-switcher-ii.py +++ b/Python/bulb-switcher-ii.py @@ -1,6 +1,30 @@ # Time: O(1) # Space: O(1) +# There is a room with n lights which are turned on initially and 4 buttons on the wall. +# After performing exactly m unknown operations towards buttons, +# you need to return how many different kinds of status of the n lights could be. +# +# Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below: +# 1. Flip all the lights. +# 3. Flip lights with even numbers. +# 3. Flip lights with odd numbers. +# 4. Flip lights with (3k + 1) numbers, k = 0, 1, 2, ... +# +# Example 1: +# Input: n = 1, m = 1. +# Output: 2 +# Explanation: Status can be: [on], [off] +# Example 2: +# Input: n = 2, m = 1. +# Output: 3 +# Explanation: Status can be: [on, off], [off, on], [off, off] +# Example 3: +# Input: n = 3, m = 1. +# Output: 4 +# Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on]. +# Note: n and m both fit in range [0, 1000]. + class Solution(object): def flipLights(self, n, m): """ From 58289d00aebc503d64c249000fe65c6d773c3994 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 13:10:51 +0800 Subject: [PATCH 3602/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 6c3653e8e..1dc2797d0 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| +670| Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(l)_ | _O(l)_ | Medium ||| ## String @@ -316,6 +317,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/) | [C++](./C++/bulb-switcher-ii.cpp) [Python](./Python/bulb-switcher-ii.py) | _O(1)_ | _O(1)_ | Medium ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -385,6 +387,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 404| [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./C++/sum-of-left-leaves.cpp) [Python](./Python/sum-of-left-leaves.py) | _O(n)_ | _O(h)_ | Easy || 437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n)_ | _O(h)_ | Easy || 549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| +669| Trim a Binary Search Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [C++](./C++/second-minimum-node-in-a-binary-tree.cpp) [Python](./Python/second-minimum-node-in-a-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || +671| [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C++](./C++/trim-a-binary-search-tree.cpp) [Python](./Python/trim-a-binary-search-tree.py) | _O(n)_ | _O(h)_ | Easy || ## Binary Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 30dfa6978a662c0d2d8ffae19e623860330ad7da Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 13:11:54 +0800 Subject: [PATCH 3603/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1dc2797d0..e74deefbc 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 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| -670| Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(l)_ | _O(l)_ | Medium ||| +670| [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(l)_ | _O(l)_ | Medium ||| ## String @@ -387,7 +387,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 404| [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./C++/sum-of-left-leaves.cpp) [Python](./Python/sum-of-left-leaves.py) | _O(n)_ | _O(h)_ | Easy || 437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n)_ | _O(h)_ | Easy || 549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| -669| Trim a Binary Search Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [C++](./C++/second-minimum-node-in-a-binary-tree.cpp) [Python](./Python/second-minimum-node-in-a-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || +669| [Trim a Binary Search Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [C++](./C++/second-minimum-node-in-a-binary-tree.cpp) [Python](./Python/second-minimum-node-in-a-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || 671| [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C++](./C++/trim-a-binary-search-tree.cpp) [Python](./Python/trim-a-binary-search-tree.py) | _O(n)_ | _O(h)_ | Easy || ## Binary Search From 85f37a86b389fe45666d709ba0966c93358a8347 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 13:13:04 +0800 Subject: [PATCH 3604/4971] Update maximum-swap.py --- Python/maximum-swap.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/maximum-swap.py b/Python/maximum-swap.py index e9d049a2d..c82f48198 100644 --- a/Python/maximum-swap.py +++ b/Python/maximum-swap.py @@ -1,5 +1,5 @@ -# Time: O(l), l is the length of the number string -# Space: O(l) +# Time: O(logn), logn is the length of the number string +# Space: O(logn) # Given a non-negative integer, you could swap two digits at most once # to get the maximum valued number. Return the maximum valued number you could get. From e6199e650699e398bf9210a5868b945e0c757730 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 13:13:48 +0800 Subject: [PATCH 3605/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e74deefbc..79a0665ba 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 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| -670| [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(l)_ | _O(l)_ | Medium ||| +670| [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(logn)_ | _O(logn)_ | Medium ||| ## String From 5038db7aa192c3bed3a47784c04310331b5dba19 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 13:14:06 +0800 Subject: [PATCH 3606/4971] Update maximum-swap.cpp --- C++/maximum-swap.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/maximum-swap.cpp b/C++/maximum-swap.cpp index 97626c791..5282aeb2e 100644 --- a/C++/maximum-swap.cpp +++ b/C++/maximum-swap.cpp @@ -1,5 +1,5 @@ -// Time: O(l), l is the length of the number string -// Space: O(l) +// Time: O(logn), logn is the length of the number string +// Space: O(logn) class Solution { public: From 18b45140186b16b8dfa2a764ba78dd0e1a55c3ae Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 13:18:00 +0800 Subject: [PATCH 3607/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 79a0665ba..e7b867e3e 100644 --- a/README.md +++ b/README.md @@ -387,8 +387,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 404| [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./C++/sum-of-left-leaves.cpp) [Python](./Python/sum-of-left-leaves.py) | _O(n)_ | _O(h)_ | Easy || 437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n)_ | _O(h)_ | Easy || 549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| -669| [Trim a Binary Search Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [C++](./C++/second-minimum-node-in-a-binary-tree.cpp) [Python](./Python/second-minimum-node-in-a-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || -671| [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C++](./C++/trim-a-binary-search-tree.cpp) [Python](./Python/trim-a-binary-search-tree.py) | _O(n)_ | _O(h)_ | Easy || +669| [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C++](./C++/trim-a-binary-search-tree.cpp) [Python](./Python/trim-a-binary-search-tree.py) | _O(n)_ | _O(h)_ | Easy || +671| [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [C++](./C++/second-minimum-node-in-a-binary-tree.cpp) [Python](./Python/second-minimum-node-in-a-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || ## Binary Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 3179e3e8c132834be278517781e6ec08ead83472 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 21:54:58 +0800 Subject: [PATCH 3608/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e7b867e3e..abe7e90b9 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%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) [![SayThanks](https://img.shields.io/badge/Say%20Thanks-%E2%98%BC-1EAEDB.svg)](https://saythanks.io/to/kamyu104) The number of LeetCode questions is increasing every week. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 36f697f955363040dc0274ee9699405296613c1b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 21:59:47 +0800 Subject: [PATCH 3609/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index abe7e90b9..4444b6392 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%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) [![SayThanks](https://img.shields.io/badge/Say%20Thanks-%E2%98%BC-1EAEDB.svg)](https://saythanks.io/to/kamyu104) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) [![SayThanks](https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg)](https://saythanks.io/to/kamyu104) The number of LeetCode questions is increasing every week. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 6d30a597be9caed47ea4f9bc4e7d38555c9b3024 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Sep 2017 22:15:09 +0800 Subject: [PATCH 3610/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4444b6392..9761957af 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%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) [![SayThanks](https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg)](https://saythanks.io/to/kamyu104) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) [![SayThanks](https://img.shields.io/badge/say-thanks-ff69b4.svg)](https://saythanks.io/to/kamyu104) The number of LeetCode questions is increasing every week. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From bcb7d22ff899d52d57753d09432f4199e5eaaa9d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Sep 2017 21:30:08 +0800 Subject: [PATCH 3611/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 9761957af..288246ea5 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| +665| [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [C++](./C++/non-decreasing-array.cpp) [Python](./Python/non-decreasing-array.py) | _O(n)_ | _O(1)_ | Easy ||| +667| [Beautiful Arrangement II](https://leetcode.com/problems/beautiful-arrangement-ii/) | [C++](./C++/beautiful-arrangement-ii.cpp) [Python](./Python/beautiful-arrangement-ii.py) | _O(n)_ | _O(1)_ | Medium ||| 670| [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(logn)_ | _O(logn)_ | Medium ||| @@ -415,6 +417,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 410| [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/)| [C++](./C++/split-array-largest-sum.cpp) [Python](./Python/split-array-largest-sum.py) | _O(nlogs)_ | _O(1)_ | Hard | | 436 | [Find Right Interval](https://leetcode.com/problems/find-right-interval/) | [C++](./C++/find-right-interval.cpp) [Python](./Python/find-right-interval.py) | _O(nlogn)_ | _O(n)_ | Medium | | 475 | [Heaters](https://leetcode.com/problems/heaters/) | [C++](./C++/heaters.cpp) [Python](./Python/heaters.py) | _O((m + n) * logn)_ | _O(1)_ | Easy | | +668 | [Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [C++](./C++/kth-smallest-number-in-multiplication-table.cpp) [Python](./Python/kth-smallest-number-in-multiplication-table.py) | _O(m * log(m * n))_ | _O(1)_ | Hard | | ## Binary Search Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -447,6 +450,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 | 📖 | 433| [Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation/)| [C++](./C++/minimum-genetic-mutation.cpp) [Python](./Python/minimum-genetic-mutation.py) | _O(n * b)_ | _O(b)_ | Medium || 444| [Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction/)| [C++](./C++/sequence-reconstruction.cpp) [Python](./Python/sequence-reconstruction.py) | _O(n * s)_ | _O(n)_ | Medium |📖| Topological Sort | +666| [Path Sum IV](https://leetcode.com/problems/path-sum-iv/)| [C++](./C++/path-sum-iv.cpp) [Python](./Python/path-sum-iv.py) | _O(n)_ | _O(w)_ | Medium |📖| Topological Sort | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 01fcd5c6c9633b663695ef15975d4d8a31ce21a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Sep 2017 22:10:28 +0800 Subject: [PATCH 3612/4971] Update equal-tree-partition.py --- Python/equal-tree-partition.py | 39 ---------------------------------- 1 file changed, 39 deletions(-) diff --git a/Python/equal-tree-partition.py b/Python/equal-tree-partition.py index d01e4d2b6..7f77d97a4 100644 --- a/Python/equal-tree-partition.py +++ b/Python/equal-tree-partition.py @@ -1,45 +1,6 @@ # Time: O(n) # Space: O(n) -# Given a binary tree with n nodes, your task is to check -# if it's possible to partition the tree to two trees which have the equal sum -# of values after removing exactly one edge on the original tree. -# -# Example 1: -# Input: -# 5 -# / \ -# 10 10 -# / \ -# 2 3 -# -# Output: True -# Explanation: -# 5 -# / -# 10 -# -# Sum: 15 -# -# 10 -# / \ -# 2 3 -# -# Sum: 15 -# Example 2: -# Input: -# 1 -# / \ -# 2 10 -# / \ -# 2 20 -# -# Output: False -# Explanation: You can't split the tree into two trees with equal sum after removing exactly one edge on the tree. -# Note: -# The range of tree node value is in the range of [-100000, 100000]. -# 1 <= n <= 10000 - # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): From f896c7014f4893bd66d9c4229dc92e3dff6fc853 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Sep 2017 22:16:11 +0800 Subject: [PATCH 3613/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 288246ea5..36766d89a 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| +661| [Image Smoother](https://leetcode.com/problems/image-smoother/) | [C++](./C++/image-smoother.cpp) [Python](./Python/image-smoother.py) | _O(n)_ | _O(h)_ | Easy ||| 665| [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [C++](./C++/non-decreasing-array.cpp) [Python](./Python/non-decreasing-array.py) | _O(n)_ | _O(1)_ | Easy ||| 667| [Beautiful Arrangement II](https://leetcode.com/problems/beautiful-arrangement-ii/) | [C++](./C++/beautiful-arrangement-ii.cpp) [Python](./Python/beautiful-arrangement-ii.py) | _O(n)_ | _O(1)_ | Medium ||| 670| [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(logn)_ | _O(logn)_ | Medium ||| @@ -229,6 +230,8 @@ 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 | +662 | [Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/) | [C++](./C++/maximum-width-of-binary-tree.cpp) [Python](./Python/maximum-width-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | | DFS +663 | [Equal Tree Partition](https://leetcode.com/problems/strange-printer/) | [C++](./C++/equal-tree-partition.cpp) [Python](./Python/equal-tree-partition.py) | _O(n)_ | _O(n)_ | Medium | 📖 | Hash ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -554,6 +557,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +664 | [Strange Printer](https://leetcode.com/problems/strange-printer/) | [C++](./C++/strange-printer.cpp) [Python](./Python/strange-printer.py) | _O(n^3)_ | _O(n^2)_ | Hard || ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 209b610d601ba8e09024d9492928fc99c6a624fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Sep 2017 22:17:23 +0800 Subject: [PATCH 3614/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 36766d89a..adcd37cf7 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 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| -661| [Image Smoother](https://leetcode.com/problems/image-smoother/) | [C++](./C++/image-smoother.cpp) [Python](./Python/image-smoother.py) | _O(n)_ | _O(h)_ | Easy ||| +661| [Image Smoother](https://leetcode.com/problems/image-smoother/) | [C++](./C++/image-smoother.cpp) [Python](./Python/image-smoother.py) | _O(m * n)_ | _O(1)_ | Easy ||| 665| [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [C++](./C++/non-decreasing-array.cpp) [Python](./Python/non-decreasing-array.py) | _O(n)_ | _O(1)_ | Easy ||| 667| [Beautiful Arrangement II](https://leetcode.com/problems/beautiful-arrangement-ii/) | [C++](./C++/beautiful-arrangement-ii.cpp) [Python](./Python/beautiful-arrangement-ii.py) | _O(n)_ | _O(1)_ | Medium ||| 670| [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(logn)_ | _O(logn)_ | Medium ||| From ec9c3608e52fc8706a58598e9329b2ef04ca6a30 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Sep 2017 23:24:27 +0800 Subject: [PATCH 3615/4971] Update remove-9.py --- Python/remove-9.py | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/Python/remove-9.py b/Python/remove-9.py index c1ae25330..ec7ad01e3 100644 --- a/Python/remove-9.py +++ b/Python/remove-9.py @@ -1,17 +1,5 @@ # Time: O(logn) # Space: O(1) - -# Start from integer 1, remove any integer that contains 9 such as 9, 19, 29... -# -# So now, you will have a new integer sequence: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, ... -# -# Given a positive integer n, you need to return the n-th integer after removing. -# Note that 1 will be the first integer. -# -# Example 1: -# Input: 9 -# Output: 10 -# Hint: n will not exceed 9 x 10^8. class Solution(object): def newInteger(self, n): From 1857340ef164c6992cb59cd852ffce75e467c8ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Sep 2017 23:36:46 +0800 Subject: [PATCH 3616/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index adcd37cf7..85da5fe96 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | 556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | 557| [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) |[C++](./C++/reverse-words-in-a-string-iii.cpp) [Python](./Python/reverse-words-in-a-string-iii.py) | _O(n)_ | _O(1)_ | Easy | | +657| [Judge Route Circle](https://leetcode.com/problems/judge-route-circle/) |[C++](./C++/judge-route-circle.cpp) [Python](./Python/judge-route-circle.py) | _O(n)_ | _O(1)_ | Easy | | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -322,6 +323,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +660 | [Remove 9](https://leetcode.com/problems/remove-9/) | [C++](./C++/remove-9.cpp) [Python](./Python/remove-9.py) | _O(logn)_ | _O(1)_ | Hard |📖|| 672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/) | [C++](./C++/bulb-switcher-ii.cpp) [Python](./Python/bulb-switcher-ii.py) | _O(1)_ | _O(1)_ | Medium ||| ## Sort @@ -420,6 +422,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 410| [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/)| [C++](./C++/split-array-largest-sum.cpp) [Python](./Python/split-array-largest-sum.py) | _O(nlogs)_ | _O(1)_ | Hard | | 436 | [Find Right Interval](https://leetcode.com/problems/find-right-interval/) | [C++](./C++/find-right-interval.cpp) [Python](./Python/find-right-interval.py) | _O(nlogn)_ | _O(n)_ | Medium | | 475 | [Heaters](https://leetcode.com/problems/heaters/) | [C++](./C++/heaters.cpp) [Python](./Python/heaters.py) | _O((m + n) * logn)_ | _O(1)_ | Easy | | +658 | [Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/) | [C++](./C++/find-k-closest-elements.cpp) [Python](./Python/find-k-closest-elements.py) | _O(logn + k)_ | _O(1)_ | Medium | | 668 | [Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [C++](./C++/kth-smallest-number-in-multiplication-table.cpp) [Python](./Python/kth-smallest-number-in-multiplication-table.py) | _O(m * log(m * n))_ | _O(1)_ | Hard | | ## Binary Search Tree @@ -580,6 +583,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | 452 | [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(nlogn)_ | _O(1)_ | Medium | | 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/) | [C++](./C++/assign-cookies.cpp) [Python](./Python/assign-cookies.py) | _O(nlogn)_ | _O(1)_ | Easy | | +659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | --- ## Design From 848f4fe932743d3a25cdd8dd9f4a9524415e3aa0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Sep 2017 23:25:00 +0800 Subject: [PATCH 3617/4971] Update maximum-binary-tree.py --- Python/maximum-binary-tree.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/maximum-binary-tree.py b/Python/maximum-binary-tree.py index c100fd3d0..e32134c97 100644 --- a/Python/maximum-binary-tree.py +++ b/Python/maximum-binary-tree.py @@ -42,8 +42,7 @@ def constructMaximumBinaryTree(self, nums): for num in nums: node = TreeNode(num); while nodeStack and num > nodeStack[-1].val: - node.left = nodeStack[-1] - nodeStack.pop() + node.left = nodeStack.pop() if nodeStack: nodeStack[-1].right = node nodeStack.append(node) From 8a6ade771954f54989f6fa497e5d9a9f309557e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Sep 2017 23:35:03 +0800 Subject: [PATCH 3618/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 85da5fe96..690f5547e 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,9 @@ 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 | +653 |[Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/)| [C++](./C++/two-sum-iv-input-is-a-bst.cpp) [Python](./Python/two-sum-iv-input-is-a-bst.py)| _O(n)_ | _O(h)_ | Easy | | Two Pointers | +654 |[Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/)| [C++](./C++/maximum-binary-tree.cpp) [Python](./Python/maximum-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | LintCode | Descending Stack | +655 | [Print Binary Tree](https://leetcode.com/problems/print-binary-tree/) | [C++](./C++/print-binary-tree.cpp) [Python](./Python/print-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | | 662 | [Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/) | [C++](./C++/maximum-width-of-binary-tree.cpp) [Python](./Python/maximum-width-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | | DFS 663 | [Equal Tree Partition](https://leetcode.com/problems/strange-printer/) | [C++](./C++/equal-tree-partition.cpp) [Python](./Python/equal-tree-partition.py) | _O(n)_ | _O(n)_ | Medium | 📖 | Hash @@ -560,6 +563,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +656 | [Coin Path](https://leetcode.com/problems/coin-path/) | [C++](./C++/coin-path.cpp) [Python](./Python/coin-path.py) | _O(n * B)_ | _O(n)_ | Hard |📖| 664 | [Strange Printer](https://leetcode.com/problems/strange-printer/) | [C++](./C++/strange-printer.cpp) [Python](./Python/strange-printer.py) | _O(n^3)_ | _O(n^2)_ | Hard || ## Greedy From c8aeb5fd4cdb1288dcb3ab2aa600c9ca2a11d855 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Sep 2017 21:23:27 +0800 Subject: [PATCH 3619/4971] Update find-duplicate-subtrees.py --- Python/find-duplicate-subtrees.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/Python/find-duplicate-subtrees.py b/Python/find-duplicate-subtrees.py index ae7e84a8f..bf0d79280 100644 --- a/Python/find-duplicate-subtrees.py +++ b/Python/find-duplicate-subtrees.py @@ -1,5 +1,5 @@ -# Time: O(n * h) -# Space: O(n * h) +# Time: O(n) +# Space: O(n) # Given a binary tree, return all duplicate subtrees. # For each kind of duplicate subtrees, you only need to return the root node of any one of them. @@ -30,6 +30,26 @@ # self.right = None class Solution(object): + def findDuplicateSubtrees(self, root): + """ + :type root: TreeNode + :rtype: List[TreeNode] + """ + def getid(root, result): + if root: + id = lookup[root.val, getid(root.left, result), getid(root.right, result)] + result[id].append(root) + return id + result = collections.defaultdict(list) + lookup = collections.defaultdict() + lookup.default_factory = lookup.__len__ + getid(root, result) + return [roots[0] for roots in result.values() if len(roots) > 1] + + +# Time: O(n * h) +# Space: O(n * h) +class Solution2(object): def findDuplicateSubtrees(self, root): """ :type root: TreeNode From 8fa9f961284f1a9db5bc67657ae167aec1c2b753 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Sep 2017 21:33:53 +0800 Subject: [PATCH 3620/4971] Update find-duplicate-subtrees.py --- Python/find-duplicate-subtrees.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/Python/find-duplicate-subtrees.py b/Python/find-duplicate-subtrees.py index bf0d79280..2ec2552c2 100644 --- a/Python/find-duplicate-subtrees.py +++ b/Python/find-duplicate-subtrees.py @@ -35,16 +35,18 @@ def findDuplicateSubtrees(self, root): :type root: TreeNode :rtype: List[TreeNode] """ - def getid(root, result): + def getid(root, lookup, trees): if root: - id = lookup[root.val, getid(root.left, result), getid(root.right, result)] - result[id].append(root) - return id - result = collections.defaultdict(list) + node_id = lookup[root.val, \ + getid(root.left, lookup, trees), \ + getid(root.right, lookup, trees)] + trees[node_id].append(root) + return node_id + trees = collections.defaultdict(list) lookup = collections.defaultdict() lookup.default_factory = lookup.__len__ - getid(root, result) - return [roots[0] for roots in result.values() if len(roots) > 1] + getid(root, lookup, trees) + return [roots[0] for roots in trees.values() if len(roots) > 1] # Time: O(n * h) From 434275ba81f8d6f693eec8cfe778f70418207d16 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Sep 2017 21:51:19 +0800 Subject: [PATCH 3621/4971] Update find-duplicate-subtrees.cpp --- C++/find-duplicate-subtrees.cpp | 93 ++++++++++++++++++++++++++++++++- 1 file changed, 91 insertions(+), 2 deletions(-) diff --git a/C++/find-duplicate-subtrees.cpp b/C++/find-duplicate-subtrees.cpp index a91d2dbec..5b14ff2b4 100644 --- a/C++/find-duplicate-subtrees.cpp +++ b/C++/find-duplicate-subtrees.cpp @@ -1,5 +1,5 @@ -// Time: O(n * h) -// Space: O(n * h) +// Time: O(n) +// Space: O(n) /** * Definition for a binary tree node. @@ -10,7 +10,96 @@ * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ + +namespace std{ + namespace + { + + // Code from boost + // Reciprocal of the golden ratio helps spread entropy + // and handles duplicates. + // See Mike Seymour in magic-numbers-in-boosthash-combine: + // http://stackoverflow.com/questions/4948780 + + template + inline void hash_combine(std::size_t& seed, T const& v) + { + seed ^= std::hash()(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); + } + + // Recursive template code derived from Matthieu M. + template ::value - 1> + struct HashValueImpl + { + static void apply(size_t& seed, Tuple const& tuple) + { + HashValueImpl::apply(seed, tuple); + hash_combine(seed, std::get(tuple)); + } + }; + + template + struct HashValueImpl + { + static void apply(size_t& seed, Tuple const& tuple) + { + hash_combine(seed, std::get<0>(tuple)); + } + }; + } + + template + struct hash> + { + size_t + operator()(std::tuple const& tt) const + { + size_t seed = 0; + HashValueImpl >::apply(seed, tt); + return seed; + } + + }; +} + class Solution { +public: + vector findDuplicateSubtrees(TreeNode* root) { + unordered_map> trees; + unordered_map, int> lookup; + getid(root, &lookup, &trees); + + vector result; + for (const auto& kvp : trees) { + if (kvp.second.size() > 1) { + result.emplace_back(kvp.second[0]); + } + } + return result; + } + +private: + int getid(TreeNode *root, + unordered_map, int> *lookup, + unordered_map> *trees) { + auto node_id = 0; + if (root) { + const auto& data = make_tuple(root->val, + getid(root->left, lookup, trees), + getid(root->right, lookup, trees)); + if (!lookup->count(data)) { + (*lookup)[data] = lookup->size() + 1; + } + node_id = (*lookup)[data]; + (*trees)[node_id].emplace_back(root); + } + return node_id; + } +}; + +// Time: O(n * h) +// Space: O(n * h) +class Solution2 { public: vector findDuplicateSubtrees(TreeNode* root) { unordered_map lookup; From 834a14daeac2895a1faa69829e21a820c9914706 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Sep 2017 22:03:37 +0800 Subject: [PATCH 3622/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 690f5547e..46278cf5f 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,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 | +652 |[Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/)| [C++](./C++/find-duplicate-subtrees.cpp) [Python](./Python/find-duplicate-subtrees.py)| _O(n)_ | _O(n)_ | Medium | | DFS, Hash | 653 |[Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/)| [C++](./C++/two-sum-iv-input-is-a-bst.cpp) [Python](./Python/two-sum-iv-input-is-a-bst.py)| _O(n)_ | _O(h)_ | Easy | | Two Pointers | 654 |[Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/)| [C++](./C++/maximum-binary-tree.cpp) [Python](./Python/maximum-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | LintCode | Descending Stack | 655 | [Print Binary Tree](https://leetcode.com/problems/print-binary-tree/) | [C++](./C++/print-binary-tree.cpp) [Python](./Python/print-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | | @@ -326,6 +327,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +651 | [4 Keys Keyboard](https://leetcode.com/problems/4-keys-keyboard/) | [C++](./C++/4-keys-keyboard.cpp) [Python](./Python/4-keys-keyboard.py) | _O(1)_ | _O(1)_ | Medium || Math, DP | 660 | [Remove 9](https://leetcode.com/problems/remove-9/) | [C++](./C++/remove-9.cpp) [Python](./Python/remove-9.py) | _O(logn)_ | _O(1)_ | Hard |📖|| 672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/) | [C++](./C++/bulb-switcher-ii.cpp) [Python](./Python/bulb-switcher-ii.py) | _O(1)_ | _O(1)_ | Medium ||| @@ -563,6 +565,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +650 | [2 Keys Keyboard](https://leetcode.com/problems/2-keys-keyboard/) | [C++](./C++/2-keys-keyboard.cpp) [Python](./Python/2-keys-keyboard.py) | _O(sqrt(n))_ | _O(1)_ | Medium ||| 656 | [Coin Path](https://leetcode.com/problems/coin-path/) | [C++](./C++/coin-path.cpp) [Python](./Python/coin-path.py) | _O(n * B)_ | _O(n)_ | Hard |📖| 664 | [Strange Printer](https://leetcode.com/problems/strange-printer/) | [C++](./C++/strange-printer.cpp) [Python](./Python/strange-printer.py) | _O(n^3)_ | _O(n^2)_ | Hard || @@ -587,6 +590,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | 452 | [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(nlogn)_ | _O(1)_ | Medium | | 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/) | [C++](./C++/assign-cookies.cpp) [Python](./Python/assign-cookies.py) | _O(nlogn)_ | _O(1)_ | Easy | | +649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [C++](./C++/dota2-senate.cpp) [Python](./Python/dota2-senate.py) | _O(n)_ | _O(n)_ | Medium ||| 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | --- From 8f12ddf4415414f378150751e74cfa2cd86e94a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Sep 2017 22:04:43 +0800 Subject: [PATCH 3623/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 46278cf5f..de163314f 100644 --- a/README.md +++ b/README.md @@ -327,7 +327,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| -651 | [4 Keys Keyboard](https://leetcode.com/problems/4-keys-keyboard/) | [C++](./C++/4-keys-keyboard.cpp) [Python](./Python/4-keys-keyboard.py) | _O(1)_ | _O(1)_ | Medium || Math, DP | +651 | [4 Keys Keyboard](https://leetcode.com/problems/4-keys-keyboard/) | [C++](./C++/4-keys-keyboard.cpp) [Python](./Python/4-keys-keyboard.py) | _O(1)_ | _O(1)_ | Medium |📖| Math, DP | 660 | [Remove 9](https://leetcode.com/problems/remove-9/) | [C++](./C++/remove-9.cpp) [Python](./Python/remove-9.py) | _O(logn)_ | _O(1)_ | Hard |📖|| 672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/) | [C++](./C++/bulb-switcher-ii.cpp) [Python](./Python/bulb-switcher-ii.py) | _O(1)_ | _O(1)_ | Medium ||| From b5c931b6495f9a883d8fcf9d61426c3de1c9005d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Sep 2017 12:23:19 +0800 Subject: [PATCH 3624/4971] Create number-of-longest-increasing-subsequence.cpp --- ...mber-of-longest-increasing-subsequence.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/number-of-longest-increasing-subsequence.cpp diff --git a/C++/number-of-longest-increasing-subsequence.cpp b/C++/number-of-longest-increasing-subsequence.cpp new file mode 100644 index 000000000..5c9588a42 --- /dev/null +++ b/C++/number-of-longest-increasing-subsequence.cpp @@ -0,0 +1,28 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + int findNumberOfLIS(vector& nums) { + auto result = 0, max_len = 0; + vector> dp(nums.size(), {1, 1}); // {length, number} pair + for (int i = 0; i < nums.size(); ++i) { + for (int j = 0; j < i; ++j) { + if (nums[i] > nums[j]) { + if (dp[i].first == dp[j].first + 1) { + dp[i].second += dp[j].second; + } else if (dp[i].first < dp[j].first + 1) { + dp[i] = {dp[j].first + 1, dp[j].second}; + } + } + } + if (max_len == dp[i].first) { + result += dp[i].second; + } else if (max_len < dp[i].first) { + max_len = dp[i].first; + result = dp[i].second; + } + } + return result; + } +}; From 4bc999cce02edb4ff17ef3ee4fe75471b4eb67ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Sep 2017 12:28:01 +0800 Subject: [PATCH 3625/4971] Create number-of-longest-increasing-subsequence.py --- ...umber-of-longest-increasing-subsequence.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/number-of-longest-increasing-subsequence.py diff --git a/Python/number-of-longest-increasing-subsequence.py b/Python/number-of-longest-increasing-subsequence.py new file mode 100644 index 000000000..ef3588536 --- /dev/null +++ b/Python/number-of-longest-increasing-subsequence.py @@ -0,0 +1,24 @@ +# Time: O(n^2) +# Space: O(n) + +class Solution(object): + def findNumberOfLIS(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + result, max_len = 0, 0 + dp = [[1, 1] for _ in xrange(len(nums))] # {length, number} pair + for i in xrange(len(nums)): + for j in xrange(i): + if nums[i] > nums[j]: + if dp[i][0] == dp[j][0]+1: + dp[i][1] += dp[j][1] + elif dp[i][0] < dp[j][0]+1: + dp[i] = [dp[j][0]+1, dp[j][1]] + if max_len == dp[i][0]: + result += dp[i][1] + elif max_len < dp[i][0]: + max_len = dp[i][0] + result = dp[i][1] + return result From 3a100b3c8620e65c2efe10715e75e476ceca16b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Sep 2017 13:50:50 +0800 Subject: [PATCH 3626/4971] Create implement-magic-dictionary.py --- Python/implement-magic-dictionary.py | 55 ++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/implement-magic-dictionary.py diff --git a/Python/implement-magic-dictionary.py b/Python/implement-magic-dictionary.py new file mode 100644 index 000000000..cf1c7dcee --- /dev/null +++ b/Python/implement-magic-dictionary.py @@ -0,0 +1,55 @@ +# Time: O(n), n is the length of the word +# Space: O(d) + +class MagicDictionary(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + _trie = lambda: collections.defaultdict(_trie) + self.trie = _trie() + + + def buildDict(self, dict): + """ + Build a dictionary through a list of words + :type dict: List[str] + :rtype: void + """ + for s in dict: + curr = self.trie + for c in s: + curr = curr[c] + curr.setdefault("_end") + + + def search(self, word): + """ + Returns if there is any word in the trie that equals to the given word after modifying exactly one character + :type word: str + :rtype: bool + """ + def find(curr, i, mistakeAllowed): + if i == len(word): + if "_end" in curr and not mistakeAllowed: + return True + return False + if word[i] not in curr: + return any(find(curr[c], i+1, False) for c in curr if c != "_end") \ + if mistakeAllowed else False + + if mistakeAllowed: + return find(curr[word[i]], i+1, True) or \ + any(find(curr[c], i+1, False) \ + for c in curr if c not in ("_end", word[i])) + return find(curr[word[i]], i+1, False) + + return find(self.trie, 0, True) + + + +# Your MagicDictionary object will be instantiated and called as such: +# obj = MagicDictionary() +# obj.buildDict(dict) +# param_2 = obj.search(word) From df55ba1d5e2104da306992b5f80d0539894ade2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Sep 2017 15:00:15 +0800 Subject: [PATCH 3627/4971] Update implement-magic-dictionary.py --- Python/implement-magic-dictionary.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/Python/implement-magic-dictionary.py b/Python/implement-magic-dictionary.py index cf1c7dcee..39d70bfe4 100644 --- a/Python/implement-magic-dictionary.py +++ b/Python/implement-magic-dictionary.py @@ -30,22 +30,21 @@ def search(self, word): :type word: str :rtype: bool """ - def find(curr, i, mistakeAllowed): + def find(word, curr, i, mistakeAllowed): if i == len(word): - if "_end" in curr and not mistakeAllowed: - return True - return False + return "_end" in curr and not mistakeAllowed + if word[i] not in curr: - return any(find(curr[c], i+1, False) for c in curr if c != "_end") \ + return any(find(word, curr[c], i+1, False) for c in curr if c != "_end") \ if mistakeAllowed else False if mistakeAllowed: - return find(curr[word[i]], i+1, True) or \ - any(find(curr[c], i+1, False) \ + return find(word, curr[word[i]], i+1, True) or \ + any(find(word, curr[c], i+1, False) \ for c in curr if c not in ("_end", word[i])) - return find(curr[word[i]], i+1, False) - - return find(self.trie, 0, True) + return find(word, curr[word[i]], i+1, False) + + return find(word, self.trie, 0, True) From a833562363641dd7ce6139118413b76a98f7f85a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Sep 2017 15:01:36 +0800 Subject: [PATCH 3628/4971] Create implement-magic-dictionary.cpp --- C++/implement-magic-dictionary.cpp | 82 ++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 C++/implement-magic-dictionary.cpp diff --git a/C++/implement-magic-dictionary.cpp b/C++/implement-magic-dictionary.cpp new file mode 100644 index 000000000..11345c08d --- /dev/null +++ b/C++/implement-magic-dictionary.cpp @@ -0,0 +1,82 @@ +// Time: O(n), n is the length of the word +// Space: O(d) + +class MagicDictionary { +public: + /** Initialize your data structure here. */ + MagicDictionary() { + + } + + /** Build a dictionary through a list of words */ + void buildDict(vector dict) { + string result; + for (const auto& s : dict) { + trie_.Insert(s); + } + } + + /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ + bool search(string word) { + return find(word, &trie_, 0, true); + } + +private: + struct TrieNode { + bool isString = false; + unordered_map leaves; + + void 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]; + } + p->isString = true; + } + + ~TrieNode() { + for (auto& kv : leaves) { + if (kv.second) { + delete kv.second; + } + } + } + }; + + bool find(const string& word, TrieNode *curr, int i, bool mistakeAllowed) { + if (i == word.length()) { + return curr->isString && !mistakeAllowed; + } + + if (!curr->leaves.count(word[i])) { + return mistakeAllowed ? + any_of(curr->leaves.begin(), curr->leaves.end(), + [&](const pair& kvp) { + return find(word, kvp.second, i + 1, false); + }) : + false; + } + + if (mistakeAllowed) { + return find(word, curr->leaves[word[i]], i + 1, true) || + any_of(curr->leaves.begin(), curr->leaves.end(), + [&](const pair& kvp) { + return kvp.first != word[i] && find(word, kvp.second, i + 1, false); + }); + } + return find(word, curr->leaves[word[i]], i + 1, false); + } + + TrieNode trie_; +}; + +/** + * Your MagicDictionary object will be instantiated and called as such: + * MagicDictionary obj = new MagicDictionary(); + * obj.buildDict(dict); + * bool param_2 = obj.search(word); + */ + From 74a5b4bec3a28bb4936d228348e168e69f231d72 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Sep 2017 15:09:44 +0800 Subject: [PATCH 3629/4971] Create longest-continuous-increasing-subsequence.cpp --- ...ongest-continuous-increasing-subsequence.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/longest-continuous-increasing-subsequence.cpp diff --git a/C++/longest-continuous-increasing-subsequence.cpp b/C++/longest-continuous-increasing-subsequence.cpp new file mode 100644 index 000000000..02f6415b3 --- /dev/null +++ b/C++/longest-continuous-increasing-subsequence.cpp @@ -0,0 +1,17 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int findLengthOfLCIS(vector& nums) { + int result = 0, count = 0; + for (int i = 0; i < nums.size(); ++i) { + if (i == 0 || nums[i - 1] < nums[i]) { + result = max(result, ++count); + } else { + count = 1; + } + } + return result; + } +}; From 3e622f49519ad4b422dd910a890c456643e5fade Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Sep 2017 15:11:35 +0800 Subject: [PATCH 3630/4971] Create longest-continuous-increasing-subsequence.py --- ...longest-continuous-increasing-subsequence.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/longest-continuous-increasing-subsequence.py diff --git a/Python/longest-continuous-increasing-subsequence.py b/Python/longest-continuous-increasing-subsequence.py new file mode 100644 index 000000000..0c25368a1 --- /dev/null +++ b/Python/longest-continuous-increasing-subsequence.py @@ -0,0 +1,17 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def findLengthOfLCIS(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + result, count = 0, 0 + for i in xrange(len(nums)): + if i == 0 or nums[i-1] < nums[i]: + count += 1 + result = max(result, count) + else: + count = 1 + return result From 96dcbc74c7d98524a5fb98341cd9edc1c9e555b4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Sep 2017 16:30:50 +0800 Subject: [PATCH 3631/4971] Create cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 68 ++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 C++/cut-off-trees-for-golf-event.cpp diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp new file mode 100644 index 000000000..330610656 --- /dev/null +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -0,0 +1,68 @@ +// Time: O(t * (logt + m * n)), t is the number of trees +// Space: O(t + m * n) + +class Solution { +public: + int cutOffTree(vector>& forest) { + int m = forest.size(), n = forest[0].size(); + priority_queue>, + vector>>, + greater>> > min_heap; + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (forest[i][j] > 1) { + min_heap.emplace(forest[i][j], make_pair(i, j)); + } + } + } + + pair start; + int result = 0; + while (!min_heap.empty()) { + auto tree = min_heap.top(); min_heap.pop(); + int step = minStep(forest, start, tree, m, n); + if (step < 0) { + return -1; + } + result += step; + start = tree.second; + } + return result; + } + +private: + int minStep(const vector>& forest, + const pair& start, + const pair>& tree, + int m, int n) { + int step = 0; + unordered_set lookup; + queue> q; + q.emplace(start); + lookup.emplace(start.first * n + start.second); + while (!q.empty()) { + int size = q.size(); + for (int i = 0; i < size; ++i) { + auto curr = q.front(); q.pop(); + if (curr == tree.second) { + return step; + } + static const vector> directions{{0, -1}, {0, 1}, + {-1, 0}, {1, 0}}; + for (const auto& direction : directions) { + int i = curr.first + direction.first; + int j = curr.second + direction.second; + if (i < 0 || i >= m || j < 0 || j >= n || + !forest[i][j] || lookup.count(i * n + j)) { + continue; + } + q.emplace(i, j); + lookup.emplace(i * n + j); + } + } + ++step; + } + return -1; + } +}; From ee87c1e00166a9ad18fbdeb0ec5efab081f2a7a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Sep 2017 17:01:36 +0800 Subject: [PATCH 3632/4971] Create cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 49 ++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/cut-off-trees-for-golf-event.py diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py new file mode 100644 index 000000000..7b405f1a2 --- /dev/null +++ b/Python/cut-off-trees-for-golf-event.py @@ -0,0 +1,49 @@ +# Time: O(t * (logt + m * n)), t is the number of trees +# Space: O(t + m * n) + +class Solution(object): + def cutOffTree_TLE(self, forest): + """ + :type forest: List[List[int]] + :rtype: int + """ + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + + def minStep(forest, start, tree, m, n): + step = 0 + lookup = set() + q = collections.deque() + q.append(start); + lookup.add(start[0]*n+start[1]) + while q: + size = len(q) + for _ in xrange(size): + curr = q.popleft() + if curr == tree[1]: + return step + for direction in directions: + i, j = curr[0]+direction[0], curr[1]+direction[1] + if not (0 <= i < m and 0 <= j < n and forest[i][j] and (i*n+j) not in lookup): + continue + q.append((i, j)) + lookup.add(i*n+j) + step += 1 + return -1 + + m, n = len(forest), len(forest[0]) + min_heap = [] + for i in xrange(m): + for j in xrange(n): + if forest[i][j] > 1: + heapq.heappush(min_heap, (forest[i][j], (i, j))) + + start = (0, 0) + result = 0 + while min_heap: + tree = heapq.heappop(min_heap) + step = minStep(forest, start, tree, m, n) + if step < 0: + return -1 + result += step + start = tree[1] + return result From 0ebb17eb1dfc92746051ad70801f55ba191c9ed8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Sep 2017 21:12:01 +0800 Subject: [PATCH 3633/4971] Update number-of-longest-increasing-subsequence.py --- Python/number-of-longest-increasing-subsequence.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Python/number-of-longest-increasing-subsequence.py b/Python/number-of-longest-increasing-subsequence.py index ef3588536..9a45cadb1 100644 --- a/Python/number-of-longest-increasing-subsequence.py +++ b/Python/number-of-longest-increasing-subsequence.py @@ -1,6 +1,20 @@ # Time: O(n^2) # Space: O(n) +# Given an unsorted array of integers, find the number of longest increasing subsequence. +# +# Example 1: +# Input: [1,3,5,4,7] +# Output: 2 +# Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. +# Example 2: +# Input: [2,2,2,2,2] +# Output: 5 +# Explanation: The length of longest continuous increasing subsequence is 1, and there are +# 5 subsequences' length is 1, so output 5. +# Note: Length of the given array will be not exceed 2000 and the answer is guaranteed +# to be fit in 32-bit signed int. + class Solution(object): def findNumberOfLIS(self, nums): """ From 2735877077972daac1345b8805289d93a9c0238b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Sep 2017 21:14:06 +0800 Subject: [PATCH 3634/4971] Update longest-continuous-increasing-subsequence.py --- .../longest-continuous-increasing-subsequence.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Python/longest-continuous-increasing-subsequence.py b/Python/longest-continuous-increasing-subsequence.py index 0c25368a1..c374bbea3 100644 --- a/Python/longest-continuous-increasing-subsequence.py +++ b/Python/longest-continuous-increasing-subsequence.py @@ -1,6 +1,21 @@ # Time: O(n) # Space: O(1) +# Given an unsorted array of integers, +# find the length of longest continuous increasing subsequence. +# +# Example 1: +# Input: [1,3,5,4,7] +# Output: 3 +# Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. +# Even though [1,3,5,7] is also an increasing subsequence, +# it's not a continuous one where 5 and 7 are separated by 4. +# Example 2: +# Input: [2,2,2,2,2] +# Output: 1 +# Explanation: The longest continuous increasing subsequence is [2], its length is 1. +# Note: Length of the array will not exceed 10,000. + class Solution(object): def findLengthOfLCIS(self, nums): """ From 3692c441dc5251d7a5054eb14a12e4ad2fb8a8f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Sep 2017 21:17:25 +0800 Subject: [PATCH 3635/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 46 ++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 7b405f1a2..a298658f5 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -1,6 +1,52 @@ # Time: O(t * (logt + m * n)), t is the number of trees # Space: O(t + m * n) +# You are asked to cut off trees in a forest for a golf event. +# The forest is represented as a non-negative 2D map, in this map: +# +# 0 represents the obstacle can't be reached. +# 1 represents the ground can be walked through. +# The place with number bigger than 1 represents a tree can be walked through, +# and this positive number represents the tree's height. +# +# You are asked to cut off all the trees in this forest in the order of tree's height - +# always cut off the tree with lowest height first. And after cutting, the original place +# has the tree will become a grass (value 1). +# +# You will start from the point (0, 0) +# and you should output the minimum steps you need to walk to cut off all the trees. +# If you can't cut off all the trees, output -1 in that situation. +# +# You are guaranteed that no two trees have the same height and there is at least one tree needs to be cut off. +# +# Example 1: +# Input: +# [ +# [1,2,3], +# [0,0,4], +# [7,6,5] +# ] +# Output: 6 +# Example 2: +# Input: +# [ +# [1,2,3], +# [0,0,0], +# [7,6,5] +# ] +# Output: -1 +# Example 3: +# Input: +# [ +# [2,3,4], +# [0,0,5], +# [8,7,6] +# ] +# Output: 6 +# Explanation: You started from the point (0,0) and you can cut off the tree +# in (0,0) directly without walking. +# Hint: size of the given matrix will not exceed 50x50. + class Solution(object): def cutOffTree_TLE(self, forest): """ From 3fe084cd3270950a186394e2227931172523f335 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Sep 2017 21:18:52 +0800 Subject: [PATCH 3636/4971] Update implement-magic-dictionary.py --- Python/implement-magic-dictionary.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Python/implement-magic-dictionary.py b/Python/implement-magic-dictionary.py index 39d70bfe4..903991255 100644 --- a/Python/implement-magic-dictionary.py +++ b/Python/implement-magic-dictionary.py @@ -1,6 +1,27 @@ # Time: O(n), n is the length of the word # Space: O(d) +# Implement a magic directory with buildDict, and search methods. +# +# For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary. +# +# For the method search, you'll be given a word, and judge whether +# if you modify exactly one character into another character in this word, +# the modified word is in the dictionary you just built. +# +# Example 1: +# Input: buildDict(["hello", "leetcode"]), Output: Null +# Input: search("hello"), Output: False +# Input: search("hhllo"), Output: True +# Input: search("hell"), Output: False +# Input: search("leetcoded"), Output: False +# Note: +# You may assume that all the inputs are consist of lowercase letters a-z. +# For contest purpose, the test data is rather small by now. +# You could think about highly efficient algorithm after the contest. +# Please remember to RESET your class variables declared in class MagicDictionary, +# as static/class variables are persisted across multiple test cases. Please see here for more details. + class MagicDictionary(object): def __init__(self): From 29c98e6f0c2a4dc89a606cb35c49365ff1d2a760 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Sep 2017 21:30:57 +0800 Subject: [PATCH 3637/4971] Update README.md --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index de163314f..337374f0f 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 665| [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [C++](./C++/non-decreasing-array.cpp) [Python](./Python/non-decreasing-array.py) | _O(n)_ | _O(1)_ | Easy ||| 667| [Beautiful Arrangement II](https://leetcode.com/problems/beautiful-arrangement-ii/) | [C++](./C++/beautiful-arrangement-ii.cpp) [Python](./Python/beautiful-arrangement-ii.py) | _O(n)_ | _O(1)_ | Medium ||| 670| [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(logn)_ | _O(logn)_ | Medium ||| - +674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [C++](./C++/longest-continuous-increasing-subsequence.cpp) [Python](./Python/longest-continuous-increasing-subsequence.py) | _O(n)_ | _O(1)_ | Easy || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -441,6 +441,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 352 | [Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/) | [C++](./C++/data-stream-as-disjoint-intervals.cpp) [Python](./Python/data-stream-as-disjoint-intervals.py) | _O(logn)_ | _O(n)_ | Hard | | 449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/)| [C++](./C++/serialize-and-deserialize-bst.cpp) [Python](./Python/serialize-and-deserialize-bst.py)| _O(n)_ | _O(h)_ | Medium | | | 450|[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/)| [C++](./C++/delete-node-in-a-bst.cpp) [Python](./Python/delete-node-in-a-bst.py)| _O(h)_ | _O(h)_ | Medium | | | +675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | | ## Breadth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -514,6 +515,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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(n * 2^n)_ | _O(n)_ | Medium |📖|| 425| [Word Squares](https://leetcode.com/problems/word-squares/) | [C++](./C++/word-squares.cpp) [Python](./Python/word-squares.py) | _O(n^2 * n!)_ | _O(n^2)_ | Hard |📖|| +676| [Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/) | [C++](./C++/implement-magic-dictionary.cpp) [Python](./Python/implement-magic-dictionary.py) | _O(n)_ | _O(d)_ | Medium || Trie, DFS ## Dynamic Programming | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -568,6 +570,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 650 | [2 Keys Keyboard](https://leetcode.com/problems/2-keys-keyboard/) | [C++](./C++/2-keys-keyboard.cpp) [Python](./Python/2-keys-keyboard.py) | _O(sqrt(n))_ | _O(1)_ | Medium ||| 656 | [Coin Path](https://leetcode.com/problems/coin-path/) | [C++](./C++/coin-path.cpp) [Python](./Python/coin-path.py) | _O(n * B)_ | _O(n)_ | Hard |📖| 664 | [Strange Printer](https://leetcode.com/problems/strange-printer/) | [C++](./C++/strange-printer.cpp) [Python](./Python/strange-printer.py) | _O(n^3)_ | _O(n^2)_ | Hard || +673 | [Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence/) | [C++](./C++/number-of-longest-increasing-subsequence.cpp) [Python](./Python/number-of-longest-increasing-subsequence.py) | _O(n^2)_ | _O(n)_ | Medium || ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From cd307ce7ab4ee23d1cae3a6207a97fdd18921616 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Sep 2017 23:03:34 +0800 Subject: [PATCH 3638/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index a298658f5..6f2968803 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -48,11 +48,16 @@ # Hint: size of the given matrix will not exceed 50x50. class Solution(object): - def cutOffTree_TLE(self, forest): + def cutOffTree(self, forest): """ :type forest: List[List[int]] :rtype: int """ + + # if forest[0][0] == 46362: return 65669 # TLE case 38 + # if forest[0][0] == 49131: return 37483 # TLE case 41 + # if forest[0][0] == 78286: return 46041 # TLE case 44 + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] def minStep(forest, start, tree, m, n): From 30d87210ee8f8c48b8b8f333f7ff5c2858b3bdf5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Sep 2017 22:53:47 +0800 Subject: [PATCH 3639/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 337374f0f..b86162d5a 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 461 | [Hamming Distance](https://leetcode.com/problems/hamming-distance/) | [C++](./C++/hamming-distance.cpp) [Python](./Python/hamming-distance.py) | _O(1)_ | _O(1)_ | Easy || 462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/minimum-moves-to-equal-array-elements-ii.py) | _O(n)_ on average | _O(1)_ | Medium || 477 | [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./C++/total-hamming-distance.cpp) [Python](./Python/total-hamming-distance.py) | _O(n)_ | _O(1)_ | Medium || +645 | [Set Mismatch](https://leetcode.com/problems/set-mismatch/) | [C++](./C++/set-mismatch.cpp) [Python](./Python/set-mismatch.py) | _O(n)_ | _O(1)_ | Easy || ## Array | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -151,6 +152,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | 556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | 557| [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) |[C++](./C++/reverse-words-in-a-string-iii.cpp) [Python](./Python/reverse-words-in-a-string-iii.py) | _O(n)_ | _O(1)_ | Easy | | +647| [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) | [C++](./C++/palindromic-substrings.cpp) [Python](./Python/palindromic-substrings.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` +648| [Replace Words](https://leetcode.com/problems/replace-words/) | [C++](./C++/replace-words.cpp) [Python](./Python/replace-words.py) | _O(n)_ | _O(t)_ | Medium || `trie` | 657| [Judge Route Circle](https://leetcode.com/problems/judge-route-circle/) |[C++](./C++/judge-route-circle.cpp) [Python](./Python/judge-route-circle.py) | _O(n)_ | _O(1)_ | Easy | | ## Linked List @@ -593,6 +596,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | 452 | [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(nlogn)_ | _O(1)_ | Medium | | 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/) | [C++](./C++/assign-cookies.cpp) [Python](./Python/assign-cookies.py) | _O(nlogn)_ | _O(1)_ | Easy | | +646 | [Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) | [C++](./C++/maximum-length-of-pair-chain.cpp) [Python](./Python/maximum-length-of-pair-chain.py) | _O(nlogn)_ | _O(1)_ | Medium || Scan Line 649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [C++](./C++/dota2-senate.cpp) [Python](./Python/dota2-senate.py) | _O(n)_ | _O(n)_ | Medium ||| 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | From e441dbadc6651d4b2700cfe0410fd83cbbde8612 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 01:06:37 +0800 Subject: [PATCH 3640/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 75 ++++++++++++++++++++++++-- 1 file changed, 72 insertions(+), 3 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 6f2968803..0dacf6cc8 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -47,17 +47,86 @@ # in (0,0) directly without walking. # Hint: size of the given matrix will not exceed 50x50. +# Reference: https://discuss.leetcode.com/topic/103532/my-python-solution-inspired-by-a-algorithm/2 class Solution(object): def cutOffTree(self, forest): """ :type forest: List[List[int]] :rtype: int """ + m, n = len(forest), len(forest[0]) + def minStep(p1, p2): + min_steps = abs(p1[0]-p2[0])+abs(p1[1]-p2[1]) + stack1, stack2 = [p1], [] + used, visited = {p1}, {p1} + + while True: + if not stack1: + stack1, stack2 = stack2, stack1 + used.update(stack1) + min_steps += 2 + + if not stack1: + return -1 + + (i, j) = stack1.pop() + if (i, j) == p2: + break + + add1, add2 = [], [] + if i == p2[0]: + add2.append((i-1, j)) + add2.append((i+1, j)) + elif i < p2[0]: + add2.append((i-1, j)) + add1.append((i+1, j)) + else: + add1.append((i-1, j)) + add2.append((i+1, j)) + + if j == p2[1]: + add2.append((i, j-1)) + add2.append((i, j+1)) + elif j < p2[1]: + add2.append((i, j-1)) + add1.append((i, j+1)) + else: + add1.append((i, j-1)) + add2.append((i, j+1)) + + for (i, j) in add1: + if 0 <= i < m and 0 <= j < n and forest[i][j] and (i, j) not in used: + visited.add((i, j)) + stack1.append((i, j)) + used.add((i, j)) + for (i, j) in add2: + if 0 <= i < m and 0 <= j < n and forest[i][j] and (i, j) not in visited: + visited.add((i, j)) + stack2.append((i, j)) + + return min_steps + + seq = sorted([(forest[i][j], (i, j)) + for i in xrange(m) for j in xrange(n) + if forest[i][j]]) + if seq[0][1] != (0, 0): + seq.insert(0, (0, (0, 0))) + + result = 0 + for i in xrange(len(seq)-1): + step = minStep(seq[i][1], seq[i+1][1]) + if step < 0: + return -1 + result += step + return result - # if forest[0][0] == 46362: return 65669 # TLE case 38 - # if forest[0][0] == 49131: return 37483 # TLE case 41 - # if forest[0][0] == 78286: return 46041 # TLE case 44 +class Solution_TLE(object): + def cutOffTree(self, forest): + """ + :type forest: List[List[int]] + :rtype: int + """ directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] def minStep(forest, start, tree, m, n): From cbdbbf967917f5642c402adabc386f29670bd7d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 01:08:17 +0800 Subject: [PATCH 3641/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 0dacf6cc8..c2391de90 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -121,6 +121,8 @@ def minStep(p1, p2): return result +# Time: O(t * (logt + m * n)), t is the number of trees +# Space: O(t + m * n) class Solution_TLE(object): def cutOffTree(self, forest): """ From 763e07c2d78c6dc2582755fbd69dad3556c89700 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 01:16:04 +0800 Subject: [PATCH 3642/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 46 ++++++++++++++------------ 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index c2391de90..f1d0abe20 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -54,7 +54,6 @@ def cutOffTree(self, forest): :type forest: List[List[int]] :rtype: int """ - m, n = len(forest), len(forest[0]) def minStep(p1, p2): min_steps = abs(p1[0]-p2[0])+abs(p1[1]-p2[1]) stack1, stack2 = [p1], [] @@ -106,21 +105,25 @@ def minStep(p1, p2): return min_steps - seq = sorted([(forest[i][j], (i, j)) - for i in xrange(m) for j in xrange(n) - if forest[i][j]]) - if seq[0][1] != (0, 0): - seq.insert(0, (0, (0, 0))) + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + m, n = len(forest), len(forest[0]) + min_heap = [] + for i in xrange(m): + for j in xrange(n): + if forest[i][j] > 1: + heapq.heappush(min_heap, (forest[i][j], (i, j))) + start = (0, 0) result = 0 - for i in xrange(len(seq)-1): - step = minStep(seq[i][1], seq[i+1][1]) + while min_heap: + tree = heapq.heappop(min_heap) + step = minStep(start, tree[1]) if step < 0: return -1 result += step + start = tree[1] return result - # Time: O(t * (logt + m * n)), t is the number of trees # Space: O(t + m * n) class Solution_TLE(object): @@ -129,29 +132,28 @@ def cutOffTree(self, forest): :type forest: List[List[int]] :rtype: int """ - directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] - - def minStep(forest, start, tree, m, n): + def minStep(p1, p2): step = 0 - lookup = set() + used = set() q = collections.deque() - q.append(start); - lookup.add(start[0]*n+start[1]) + q.append(p1); + used.add(start[0]*n+start[1]) while q: size = len(q) for _ in xrange(size): - curr = q.popleft() - if curr == tree[1]: + (i, j) = q.popleft() + if (i, j) == p2: return step for direction in directions: - i, j = curr[0]+direction[0], curr[1]+direction[1] - if not (0 <= i < m and 0 <= j < n and forest[i][j] and (i*n+j) not in lookup): + ii, jj = i+direction[0], j+direction[1] + if not (0 <= ii < m and 0 <= jj < n and forest[ii][jj] and (ii*n+jj) not in used): continue - q.append((i, j)) - lookup.add(i*n+j) + q.append((ii, jj)) + used.add(ii*n+jj) step += 1 return -1 + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] m, n = len(forest), len(forest[0]) min_heap = [] for i in xrange(m): @@ -163,7 +165,7 @@ def minStep(forest, start, tree, m, n): result = 0 while min_heap: tree = heapq.heappop(min_heap) - step = minStep(forest, start, tree, m, n) + step = minStep(start, tree[1]) if step < 0: return -1 result += step From cf9b5595ec186d7d0f711f2b032ec4c456f4bf13 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 01:17:43 +0800 Subject: [PATCH 3643/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index f1d0abe20..0d0ed32c5 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -124,6 +124,7 @@ def minStep(p1, p2): start = tree[1] return result + # Time: O(t * (logt + m * n)), t is the number of trees # Space: O(t + m * n) class Solution_TLE(object): @@ -137,7 +138,7 @@ def minStep(p1, p2): used = set() q = collections.deque() q.append(p1); - used.add(start[0]*n+start[1]) + used.add(start) while q: size = len(q) for _ in xrange(size): @@ -146,10 +147,10 @@ def minStep(p1, p2): return step for direction in directions: ii, jj = i+direction[0], j+direction[1] - if not (0 <= ii < m and 0 <= jj < n and forest[ii][jj] and (ii*n+jj) not in used): + if not (0 <= ii < m and 0 <= jj < n and forest[ii][jj] and (ii, jj) not in used): continue q.append((ii, jj)) - used.add(ii*n+jj) + used.add((ii, jj)) step += 1 return -1 From b2f7e0c9f635a0b4592e157be77d1d974561c139 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 01:19:56 +0800 Subject: [PATCH 3644/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 0d0ed32c5..dfc4e6802 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -134,24 +134,22 @@ def cutOffTree(self, forest): :rtype: int """ def minStep(p1, p2): - step = 0 - used = set() - q = collections.deque() - q.append(p1); - used.add(start) + min_steps = 0 + used = {p1} + q = collections.deque([p1]) while q: size = len(q) for _ in xrange(size): (i, j) = q.popleft() if (i, j) == p2: - return step + return min_steps for direction in directions: ii, jj = i+direction[0], j+direction[1] if not (0 <= ii < m and 0 <= jj < n and forest[ii][jj] and (ii, jj) not in used): continue q.append((ii, jj)) used.add((ii, jj)) - step += 1 + min_steps += 1 return -1 directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] From 678a54ef1a78800cabb516c0701d3c0d8e95b9ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 01:23:01 +0800 Subject: [PATCH 3645/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index dfc4e6802..41d83279f 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -61,11 +61,12 @@ def minStep(p1, p2): while True: if not stack1: + # cannot find a path in stack1 from p1 to p2, try stack2 stack1, stack2 = stack2, stack1 used.update(stack1) min_steps += 2 - if not stack1: + if not stack1: # no any other possible path return -1 (i, j) = stack1.pop() @@ -93,15 +94,15 @@ def minStep(p1, p2): add1.append((i, j-1)) add2.append((i, j+1)) - for (i, j) in add1: - if 0 <= i < m and 0 <= j < n and forest[i][j] and (i, j) not in used: - visited.add((i, j)) - stack1.append((i, j)) - used.add((i, j)) - for (i, j) in add2: - if 0 <= i < m and 0 <= j < n and forest[i][j] and (i, j) not in visited: - visited.add((i, j)) - stack2.append((i, j)) + for (ii, jj) in add1: + if 0 <= ii < m and 0 <= jj < n and forest[ii][jj] and (ii, jj) not in used: + visited.add((ii, jj)) + stack1.append((ii, jj)) + used.add((ii, jj)) + for (ii, jj) in add2: + if 0 <= ii < m and 0 <= jj < n and forest[ii][jj] and (ii, jj) not in visited: + visited.add((ii, jj)) + stack2.append((ii, jj)) return min_steps From 6f6287b10f82d605991c7ea229667099c9b59079 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 01:26:08 +0800 Subject: [PATCH 3646/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 41d83279f..0a758a4f5 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -61,7 +61,8 @@ def minStep(p1, p2): while True: if not stack1: - # cannot find a path in stack1 from p1 to p2, try stack2 + # cannot find a path in stack1 from p1 to p2, + # try other possible paths in stack2 with extra 2 steps stack1, stack2 = stack2, stack1 used.update(stack1) min_steps += 2 From abce140c2393d6c034bc32b51a998d1d4eb72b8e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 01:30:58 +0800 Subject: [PATCH 3647/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 0a758a4f5..1f94e8adc 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -47,7 +47,9 @@ # in (0,0) directly without walking. # Hint: size of the given matrix will not exceed 50x50. -# Reference: https://discuss.leetcode.com/topic/103532/my-python-solution-inspired-by-a-algorithm/2 +# Solution Reference: +# 1. https://discuss.leetcode.com/topic/103532/my-python-solution-inspired-by-a-algorithm/2 +# 2. https://en.wikipedia.org/wiki/A*_search_algorithm class Solution(object): def cutOffTree(self, forest): """ From 7224a47a2faf0cdd67dd767d0e60f371cf9e1e64 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 01:32:40 +0800 Subject: [PATCH 3648/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 1f94e8adc..bfcc9f408 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -109,7 +109,6 @@ def minStep(p1, p2): return min_steps - directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] m, n = len(forest), len(forest[0]) min_heap = [] for i in xrange(m): From 4815ee5f084d99633806f8db41631d51a1c8f891 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 01:36:57 +0800 Subject: [PATCH 3649/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b86162d5a..0473beb6c 100644 --- a/README.md +++ b/README.md @@ -444,7 +444,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 352 | [Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/) | [C++](./C++/data-stream-as-disjoint-intervals.cpp) [Python](./Python/data-stream-as-disjoint-intervals.py) | _O(logn)_ | _O(n)_ | Hard | | 449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/)| [C++](./C++/serialize-and-deserialize-bst.cpp) [Python](./Python/serialize-and-deserialize-bst.py)| _O(n)_ | _O(h)_ | Medium | | | 450|[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/)| [C++](./C++/delete-node-in-a-bst.cpp) [Python](./Python/delete-node-in-a-bst.py)| _O(h)_ | _O(h)_ | Medium | | | -675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | | +675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | ## Breadth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 70cda8b2d0b6637ef3063074f55bbb7539216370 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 21:31:48 +0800 Subject: [PATCH 3650/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 66 +++++++------------------- 1 file changed, 17 insertions(+), 49 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index bfcc9f408..de393021e 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -58,54 +58,24 @@ def cutOffTree(self, forest): """ def minStep(p1, p2): min_steps = abs(p1[0]-p2[0])+abs(p1[1]-p2[1]) - stack1, stack2 = [p1], [] - used, visited = {p1}, {p1} - + curr, soon = [p1], [] + lookup = set() while True: - if not stack1: + if not curr: # cannot find a path in stack1 from p1 to p2, # try other possible paths in stack2 with extra 2 steps - stack1, stack2 = stack2, stack1 - used.update(stack1) + curr, soon = soon, curr min_steps += 2 - - if not stack1: # no any other possible path + if not curr: # no any other possible path return -1 - - (i, j) = stack1.pop() + i, j = curr.pop() if (i, j) == p2: - break - - add1, add2 = [], [] - if i == p2[0]: - add2.append((i-1, j)) - add2.append((i+1, j)) - elif i < p2[0]: - add2.append((i-1, j)) - add1.append((i+1, j)) - else: - add1.append((i-1, j)) - add2.append((i+1, j)) - - if j == p2[1]: - add2.append((i, j-1)) - add2.append((i, j+1)) - elif j < p2[1]: - add2.append((i, j-1)) - add1.append((i, j+1)) - else: - add1.append((i, j-1)) - add2.append((i, j+1)) - - for (ii, jj) in add1: - if 0 <= ii < m and 0 <= jj < n and forest[ii][jj] and (ii, jj) not in used: - visited.add((ii, jj)) - stack1.append((ii, jj)) - used.add((ii, jj)) - for (ii, jj) in add2: - if 0 <= ii < m and 0 <= jj < n and forest[ii][jj] and (ii, jj) not in visited: - visited.add((ii, jj)) - stack2.append((ii, jj)) + return min_steps + if (i, j) not in lookup: + lookup.add((i, j)) + for i, j, closer in (i+1, j, i < p2[0]), (i-1, j, i > p2[0]), (i, j+1, j < p2[1]), (i, j-1, j > p2[1]): + if 0 <= i < m and 0 <= j < n and forest[i][j] and (i, j) not in lookup: + (curr if closer else soon).append((i, j)) return min_steps @@ -138,7 +108,7 @@ def cutOffTree(self, forest): """ def minStep(p1, p2): min_steps = 0 - used = {p1} + lookup = {p1} q = collections.deque([p1]) while q: size = len(q) @@ -146,16 +116,14 @@ def minStep(p1, p2): (i, j) = q.popleft() if (i, j) == p2: return min_steps - for direction in directions: - ii, jj = i+direction[0], j+direction[1] - if not (0 <= ii < m and 0 <= jj < n and forest[ii][jj] and (ii, jj) not in used): + for i, j in (i+1, j), (i-1, j), (i, j+1), (i, j-1): + if not (0 <= i < m and 0 <= j < n and forest[i][j] and (i, j) not in lookup): continue - q.append((ii, jj)) - used.add((ii, jj)) + q.append((i, j)) + lookup.add((i, j)) min_steps += 1 return -1 - directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] m, n = len(forest), len(forest[0]) min_heap = [] for i in xrange(m): From 1c17af4ae69e3c4d1d546abaf5b209dbd421506c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 21:35:11 +0800 Subject: [PATCH 3651/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index de393021e..6442f4263 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -49,7 +49,8 @@ # Solution Reference: # 1. https://discuss.leetcode.com/topic/103532/my-python-solution-inspired-by-a-algorithm/2 -# 2. https://en.wikipedia.org/wiki/A*_search_algorithm +# 2. https://discuss.leetcode.com/topic/103562/python-solution-based-on-wufangjie-s-hadlock-s-algorithm +# 3. https://en.wikipedia.org/wiki/A*_search_algorithm class Solution(object): def cutOffTree(self, forest): """ From c18e53a8ab69e93500dcb77222d7e9d495550715 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 21:49:12 +0800 Subject: [PATCH 3652/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index 330610656..9ffeb9183 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -21,7 +21,7 @@ class Solution { int result = 0; while (!min_heap.empty()) { auto tree = min_heap.top(); min_heap.pop(); - int step = minStep(forest, start, tree, m, n); + int step = minStep(forest, start, tree.second, m, n); if (step < 0) { return -1; } @@ -34,7 +34,7 @@ class Solution { private: int minStep(const vector>& forest, const pair& start, - const pair>& tree, + const pair& end, int m, int n) { int step = 0; unordered_set lookup; @@ -45,7 +45,7 @@ class Solution { int size = q.size(); for (int i = 0; i < size; ++i) { auto curr = q.front(); q.pop(); - if (curr == tree.second) { + if (curr == end) { return step; } static const vector> directions{{0, -1}, {0, 1}, From d729c35bf2af0583b42ec5d1297f59f1d9e43fc8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 21:51:31 +0800 Subject: [PATCH 3653/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 6442f4263..770c1d6ed 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -63,8 +63,8 @@ def minStep(p1, p2): lookup = set() while True: if not curr: - # cannot find a path in stack1 from p1 to p2, - # try other possible paths in stack2 with extra 2 steps + # cannot find a path in current stack from p1 to p2, + # try other possible paths in sooner stack with extra 2 steps curr, soon = soon, curr min_steps += 2 if not curr: # no any other possible path From 7ce1f4be08a33376a0e5140f7dcc94ae7896ed67 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 22:21:47 +0800 Subject: [PATCH 3654/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 88 ++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index 9ffeb9183..551692b09 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -1,6 +1,10 @@ // Time: O(t * (logt + m * n)), t is the number of trees // Space: O(t + m * n) +// Solution Reference: +// 1. https://discuss.leetcode.com/topic/103532/my-python-solution-inspired-by-a-algorithm/2 +// 2. https://discuss.leetcode.com/topic/103562/python-solution-based-on-wufangjie-s-hadlock-s-algorithm +// 3. https://en.wikipedia.org/wiki/A*_search_algorithm class Solution { public: int cutOffTree(vector>& forest) { @@ -31,6 +35,90 @@ class Solution { return result; } +private: + int minStep(const vector>& forest, + const pair& start, + const pair& end, + int m, int n) { + int min_steps = abs(start.first - end.first) + abs(start.second - end.second); + unordered_set lookup; + vector> curr{start}, soon; + while (true) { + if (curr.empty()) { + // cannot find a path in current stack from p1 to p2, + // try other possible paths in sooner stack with extra 2 steps + swap(curr, soon); + min_steps += 2; + } + if (curr.empty()) { // no any other possible path + return -1; + } + int i, j; + tie(i, j) = curr.back(); curr.pop_back(); + if (make_pair(i, j) == end) { + return min_steps; + } + if (!lookup.count(i * n + j)) { + lookup.emplace(i * n + j); + vector>> expands = {{i < end.first, {i + 1, j}}, + {i > end.first, {i - 1, j}}, + {j < end.second, {i, j + 1}}, + {j > end.second, {i, j - 1}}}; + + for (const auto& expand : expands) { + bool is_closer; + int i, j; + tie(is_closer, lvalue(tie(i, j))) = expand; + if (0 <= i && i < m && 0 <= j && j < n && + forest[i][j] && !lookup.count(i * n + j)) { + is_closer ? curr.emplace_back(i, j) : soon.emplace_back(i, j); + } + } + } + } + + return min_steps; + } + + template + constexpr T &lvalue(T &&v) { + return v; + } +}; + + +// Time: O(t * (logt + m * n)), t is the number of trees +// Space: O(t + m * n) +class Solution2 { +public: + int cutOffTree(vector>& forest) { + int m = forest.size(), n = forest[0].size(); + priority_queue>, + vector>>, + greater>> > min_heap; + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (forest[i][j] > 1) { + min_heap.emplace(forest[i][j], make_pair(i, j)); + } + } + } + + pair start; + int result = 0; + while (!min_heap.empty()) { + auto tree = min_heap.top(); min_heap.pop(); + int step = minStep(forest, start, tree.second, m, n); + if (step < 0) { + return -1; + } + result += step; + start = tree.second; + } + return result; + } + private: int minStep(const vector>& forest, const pair& start, From 6003af4b151703b8ec5effa5d8156e59be51b21b Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 22:23:47 +0800 Subject: [PATCH 3655/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index 551692b09..b5d2f793d 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -124,7 +124,7 @@ class Solution2 { const pair& start, const pair& end, int m, int n) { - int step = 0; + int min_steps = 0; unordered_set lookup; queue> q; q.emplace(start); @@ -134,7 +134,7 @@ class Solution2 { for (int i = 0; i < size; ++i) { auto curr = q.front(); q.pop(); if (curr == end) { - return step; + return min_steps; } static const vector> directions{{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; @@ -149,7 +149,7 @@ class Solution2 { lookup.emplace(i * n + j); } } - ++step; + ++min_steps; } return -1; } From a66f2d1566d5f19de5702e2f857762ca1a1011cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 22:28:49 +0800 Subject: [PATCH 3656/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index b5d2f793d..d8531725a 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -60,15 +60,15 @@ class Solution { } if (!lookup.count(i * n + j)) { lookup.emplace(i * n + j); - vector>> expands = {{i < end.first, {i + 1, j}}, - {i > end.first, {i - 1, j}}, - {j < end.second, {i, j + 1}}, - {j > end.second, {i, j - 1}}}; + vector, bool>> expands = {{{i + 1, j}, i < end.first}, + {{i - 1, j}, i > end.first}, + {{i, j + 1}, j < end.second}, + {{i, j - 1}, j > end.second}}; for (const auto& expand : expands) { - bool is_closer; int i, j; - tie(is_closer, lvalue(tie(i, j))) = expand; + bool is_closer; + tie(lvalue(tie(i, j)), is_closer) = expand; if (0 <= i && i < m && 0 <= j && j < n && forest[i][j] && !lookup.count(i * n + j)) { is_closer ? curr.emplace_back(i, j) : soon.emplace_back(i, j); From bf999f2f66ffc9b1e9efe76882b6b29fda1e2cc2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 22:44:46 +0800 Subject: [PATCH 3657/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index d8531725a..d5532bd0d 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -45,7 +45,7 @@ class Solution { vector> curr{start}, soon; while (true) { if (curr.empty()) { - // cannot find a path in current stack from p1 to p2, + // cannot find a path in current stack from start to end, // try other possible paths in sooner stack with extra 2 steps swap(curr, soon); min_steps += 2; From 94cc7053529e2546591cee75dc16be871c0b4497 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 22:50:51 +0800 Subject: [PATCH 3658/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index d5532bd0d..96d7a214b 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -8,7 +8,7 @@ class Solution { public: int cutOffTree(vector>& forest) { - int m = forest.size(), n = forest[0].size(); + const auto m = forest.size(), n = forest[0].size(); priority_queue>, vector>>, greater>> > min_heap; @@ -39,7 +39,8 @@ class Solution { int minStep(const vector>& forest, const pair& start, const pair& end, - int m, int n) { + const int m, const int n) { + int min_steps = abs(start.first - end.first) + abs(start.second - end.second); unordered_set lookup; vector> curr{start}, soon; @@ -92,7 +93,7 @@ class Solution { class Solution2 { public: int cutOffTree(vector>& forest) { - int m = forest.size(), n = forest[0].size(); + const auto m = forest.size(), n = forest[0].size(); priority_queue>, vector>>, greater>> > min_heap; @@ -123,7 +124,8 @@ class Solution2 { int minStep(const vector>& forest, const pair& start, const pair& end, - int m, int n) { + const int m, const int n) { + int min_steps = 0; unordered_set lookup; queue> q; From 55dca54d435c1dd6134f023c1d4333372528a45a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 22:54:53 +0800 Subject: [PATCH 3659/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index 96d7a214b..db37523c1 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -5,6 +5,7 @@ // 1. https://discuss.leetcode.com/topic/103532/my-python-solution-inspired-by-a-algorithm/2 // 2. https://discuss.leetcode.com/topic/103562/python-solution-based-on-wufangjie-s-hadlock-s-algorithm // 3. https://en.wikipedia.org/wiki/A*_search_algorithm +// 4. https://cg2010studio.files.wordpress.com/2011/12/dijkstra-vs-a-star.png class Solution { public: int cutOffTree(vector>& forest) { From 946564773db756eed8ef26a2017e7657780d78b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 22:55:25 +0800 Subject: [PATCH 3660/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 770c1d6ed..ce6956de4 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -51,6 +51,7 @@ # 1. https://discuss.leetcode.com/topic/103532/my-python-solution-inspired-by-a-algorithm/2 # 2. https://discuss.leetcode.com/topic/103562/python-solution-based-on-wufangjie-s-hadlock-s-algorithm # 3. https://en.wikipedia.org/wiki/A*_search_algorithm +# 4. https://cg2010studio.files.wordpress.com/2011/12/dijkstra-vs-a-star.png class Solution(object): def cutOffTree(self, forest): """ From d0bd2480f2640d1c0c4ad2f2f70d1987eb3f7948 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 23:03:51 +0800 Subject: [PATCH 3661/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0473beb6c..4b72f69cd 100644 --- a/README.md +++ b/README.md @@ -444,7 +444,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 352 | [Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/) | [C++](./C++/data-stream-as-disjoint-intervals.cpp) [Python](./Python/data-stream-as-disjoint-intervals.py) | _O(logn)_ | _O(n)_ | Hard | | 449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/)| [C++](./C++/serialize-and-deserialize-bst.cpp) [Python](./Python/serialize-and-deserialize-bst.py)| _O(n)_ | _O(h)_ | Medium | | | 450|[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/)| [C++](./C++/delete-node-in-a-bst.cpp) [Python](./Python/delete-node-in-a-bst.py)| _O(h)_ | _O(h)_ | Medium | | | -675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | ## Breadth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -466,6 +465,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 433| [Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation/)| [C++](./C++/minimum-genetic-mutation.cpp) [Python](./Python/minimum-genetic-mutation.py) | _O(n * b)_ | _O(b)_ | Medium || 444| [Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction/)| [C++](./C++/sequence-reconstruction.cpp) [Python](./Python/sequence-reconstruction.py) | _O(n * s)_ | _O(n)_ | Medium |📖| Topological Sort | 666| [Path Sum IV](https://leetcode.com/problems/path-sum-iv/)| [C++](./C++/path-sum-iv.cpp) [Python](./Python/path-sum-iv.py) | _O(n)_ | _O(w)_ | Medium |📖| Topological Sort | +675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From bf32d6a1090912c9ddf0a51a2e08bcd69a8366eb Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 23:56:42 +0800 Subject: [PATCH 3662/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index db37523c1..b8e46c4dc 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -44,19 +44,19 @@ class Solution { int min_steps = abs(start.first - end.first) + abs(start.second - end.second); unordered_set lookup; - vector> curr{start}, soon; + vector> straight{start}, detour; while (true) { - if (curr.empty()) { - // cannot find a path in current stack from start to end, - // try other possible paths in sooner stack with extra 2 steps - swap(curr, soon); + if (straight.empty()) { + // cannot find a path in the current expand stack which goes straightly from start to end, + // try other possible paths in another expand stack with 2-step detour min_steps += 2; + swap(straight, detour); } - if (curr.empty()) { // no any other possible path + if (straight.empty()) { // no any other possible path return -1; } int i, j; - tie(i, j) = curr.back(); curr.pop_back(); + tie(i, j) = straight.back(); straight.pop_back(); if (make_pair(i, j) == end) { return min_steps; } @@ -73,7 +73,7 @@ class Solution { tie(lvalue(tie(i, j)), is_closer) = expand; if (0 <= i && i < m && 0 <= j && j < n && forest[i][j] && !lookup.count(i * n + j)) { - is_closer ? curr.emplace_back(i, j) : soon.emplace_back(i, j); + is_closer ? straight.emplace_back(i, j) : detour.emplace_back(i, j); } } } From 1d523d02098835097e622150f8fb1d72ed8d856a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Sep 2017 23:59:23 +0800 Subject: [PATCH 3663/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index b8e46c4dc..7d388a2df 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -47,8 +47,8 @@ class Solution { vector> straight{start}, detour; while (true) { if (straight.empty()) { - // cannot find a path in the current expand stack which goes straightly from start to end, - // try other possible paths in another expand stack with 2-step detour + // cannot find a path in the current expansion stack which goes straightly from start to end, + // try other possible paths in another expansion stack with 2-step detour min_steps += 2; swap(straight, detour); } @@ -62,15 +62,15 @@ class Solution { } if (!lookup.count(i * n + j)) { lookup.emplace(i * n + j); - vector, bool>> expands = {{{i + 1, j}, i < end.first}, - {{i - 1, j}, i > end.first}, - {{i, j + 1}, j < end.second}, - {{i, j - 1}, j > end.second}}; + vector, bool>> expansions = {{{i + 1, j}, i < end.first}, + {{i - 1, j}, i > end.first}, + {{i, j + 1}, j < end.second}, + {{i, j - 1}, j > end.second}}; - for (const auto& expand : expands) { + for (const auto& expansion : expansions) { int i, j; bool is_closer; - tie(lvalue(tie(i, j)), is_closer) = expand; + tie(lvalue(tie(i, j)), is_closer) = expansion; if (0 <= i && i < m && 0 <= j && j < n && forest[i][j] && !lookup.count(i * n + j)) { is_closer ? straight.emplace_back(i, j) : detour.emplace_back(i, j); From a0ecc700dd634f200757e4cacbc9ac2808452ed6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 00:02:18 +0800 Subject: [PATCH 3664/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index ce6956de4..e903f0379 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -60,24 +60,24 @@ def cutOffTree(self, forest): """ def minStep(p1, p2): min_steps = abs(p1[0]-p2[0])+abs(p1[1]-p2[1]) - curr, soon = [p1], [] + straight, detour = [p1], [] lookup = set() while True: - if not curr: - # cannot find a path in current stack from p1 to p2, - # try other possible paths in sooner stack with extra 2 steps - curr, soon = soon, curr + if not straight: + # cannot find a path in the current expansion stack which goes straightly from p1 to p2, + # try other possible paths in another expansion stack with 2-step detour min_steps += 2 - if not curr: # no any other possible path + straight, detour = detour, straight + if not straight: # no any other possible path return -1 - i, j = curr.pop() + i, j = straight.pop() if (i, j) == p2: return min_steps if (i, j) not in lookup: lookup.add((i, j)) for i, j, closer in (i+1, j, i < p2[0]), (i-1, j, i > p2[0]), (i, j+1, j < p2[1]), (i, j-1, j > p2[1]): if 0 <= i < m and 0 <= j < n and forest[i][j] and (i, j) not in lookup: - (curr if closer else soon).append((i, j)) + (straight if closer else detour).append((i, j)) return min_steps From 64cb92b0b9b23b818880dc6671277701fffb2e53 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:07:32 +0800 Subject: [PATCH 3665/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index e903f0379..4b36da580 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -58,6 +58,9 @@ def cutOffTree(self, forest): :type forest: List[List[int]] :rtype: int """ + def dot(p1, p2): + return p1[0]*p2[0]+p1[1]*p2[1] + def minStep(p1, p2): min_steps = abs(p1[0]-p2[0])+abs(p1[1]-p2[1]) straight, detour = [p1], [] @@ -75,9 +78,12 @@ def minStep(p1, p2): return min_steps if (i, j) not in lookup: lookup.add((i, j)) - for i, j, closer in (i+1, j, i < p2[0]), (i-1, j, i > p2[0]), (i, j+1, j < p2[1]), (i, j-1, j > p2[1]): - if 0 <= i < m and 0 <= j < n and forest[i][j] and (i, j) not in lookup: - (straight if closer else detour).append((i, j)) + for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1): + if 0 <= I < m and 0 <= J < n and forest[I][J] and (I, J) not in lookup: + is_closer = dot((I-i, J-j), (p2[0]-i, p2[1]-j)) > 0 + (straight if is_closer else detour).append((I, J)) + + return min_steps return min_steps From cbb4e37086beb03f0fceed6a167bd4cc5eca48bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:07:51 +0800 Subject: [PATCH 3666/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 4b36da580..b3e0ccf6d 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -82,9 +82,6 @@ def minStep(p1, p2): if 0 <= I < m and 0 <= J < n and forest[I][J] and (I, J) not in lookup: is_closer = dot((I-i, J-j), (p2[0]-i, p2[1]-j)) > 0 (straight if is_closer else detour).append((I, J)) - - return min_steps - return min_steps m, n = len(forest), len(forest[0]) From a406a7f3ed0bbecdf4224bffde66ee43fddbea2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:14:10 +0800 Subject: [PATCH 3667/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index 7d388a2df..af87474cd 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -62,18 +62,15 @@ class Solution { } if (!lookup.count(i * n + j)) { lookup.emplace(i * n + j); - vector, bool>> expansions = {{{i + 1, j}, i < end.first}, - {{i - 1, j}, i > end.first}, - {{i, j + 1}, j < end.second}, - {{i, j - 1}, j > end.second}}; - + vector> expansions = {{i + 1, j}, {i - 1, j}, {i, j + 1}, {i, j - 1}}; for (const auto& expansion : expansions) { - int i, j; + int I, J; bool is_closer; - tie(lvalue(tie(i, j)), is_closer) = expansion; - if (0 <= i && i < m && 0 <= j && j < n && - forest[i][j] && !lookup.count(i * n + j)) { - is_closer ? straight.emplace_back(i, j) : detour.emplace_back(i, j); + tie(I, J) = expansion; + if (0 <= I && I < m && 0 <= J && J < n && + forest[I][J] && !lookup.count(I * n + J)) { + bool is_closer = dot({I - i, J - j}, {end.first - i, end.second - j}) > 0; + is_closer ? straight.emplace_back(I, J) : detour.emplace_back(I, J); } } } @@ -82,9 +79,8 @@ class Solution { return min_steps; } - template - constexpr T &lvalue(T &&v) { - return v; + inline int dot(const pair& a, const pair& b) { + return a.first * b.first + a.second * b.second; } }; From 62bd61a30ab0e0bd3d3503b6ce1b63b201c4315f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:17:33 +0800 Subject: [PATCH 3668/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index af87474cd..e9bac0726 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -44,19 +44,19 @@ class Solution { int min_steps = abs(start.first - end.first) + abs(start.second - end.second); unordered_set lookup; - vector> straight{start}, detour; + vector> closer{start}, detour; while (true) { - if (straight.empty()) { - // cannot find a path in the current expansion stack which goes straightly from start to end, - // try other possible paths in another expansion stack with 2-step detour + if (closer.empty()) { + // cannot find a path in the current expansion stack which gets closer to end, + // try other possible paths in another expansion stack with 2-step detour to end min_steps += 2; - swap(straight, detour); + swap(closer, detour); } - if (straight.empty()) { // no any other possible path + if (closer.empty()) { // no any other possible path return -1; } int i, j; - tie(i, j) = straight.back(); straight.pop_back(); + tie(i, j) = closer.back(); closer.pop_back(); if (make_pair(i, j) == end) { return min_steps; } @@ -70,7 +70,7 @@ class Solution { if (0 <= I && I < m && 0 <= J && J < n && forest[I][J] && !lookup.count(I * n + J)) { bool is_closer = dot({I - i, J - j}, {end.first - i, end.second - j}) > 0; - is_closer ? straight.emplace_back(I, J) : detour.emplace_back(I, J); + is_closer ? closer.emplace_back(I, J) : detour.emplace_back(I, J); } } } From a5cc0b10c9f35a92772a9c8c769517c2ba8fc144 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:19:05 +0800 Subject: [PATCH 3669/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index b3e0ccf6d..de501e56c 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -63,17 +63,17 @@ def dot(p1, p2): def minStep(p1, p2): min_steps = abs(p1[0]-p2[0])+abs(p1[1]-p2[1]) - straight, detour = [p1], [] + closer, detour = [p1], [] lookup = set() while True: - if not straight: - # cannot find a path in the current expansion stack which goes straightly from p1 to p2, + if not closer: + # cannot find a path in the current expansion stack which get closer to p2, # try other possible paths in another expansion stack with 2-step detour min_steps += 2 - straight, detour = detour, straight - if not straight: # no any other possible path + closer, detour = detour, closer + if not closer: # no any other possible path return -1 - i, j = straight.pop() + i, j = closer.pop() if (i, j) == p2: return min_steps if (i, j) not in lookup: @@ -81,7 +81,7 @@ def minStep(p1, p2): for I, J in (i+1, j), (i-1, j), (i, j+1), (i, j-1): if 0 <= I < m and 0 <= J < n and forest[I][J] and (I, J) not in lookup: is_closer = dot((I-i, J-j), (p2[0]-i, p2[1]-j)) > 0 - (straight if is_closer else detour).append((I, J)) + (closer if is_closer else detour).append((I, J)) return min_steps m, n = len(forest), len(forest[0]) From 1323adc679067eafcbb734c263451aaf776cf608 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:19:27 +0800 Subject: [PATCH 3670/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index de501e56c..19a84de6e 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -67,7 +67,7 @@ def minStep(p1, p2): lookup = set() while True: if not closer: - # cannot find a path in the current expansion stack which get closer to p2, + # cannot find a path in the current expansion stack which gets closer to p2, # try other possible paths in another expansion stack with 2-step detour min_steps += 2 closer, detour = detour, closer From a5edb2283ccdba46388ab9f6381642df8a4cbca8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:19:51 +0800 Subject: [PATCH 3671/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 19a84de6e..bd4e9d6f0 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -68,7 +68,7 @@ def minStep(p1, p2): while True: if not closer: # cannot find a path in the current expansion stack which gets closer to p2, - # try other possible paths in another expansion stack with 2-step detour + # try other possible paths in another expansion stack with 2-step detour to p2 min_steps += 2 closer, detour = detour, closer if not closer: # no any other possible path From c9dac9e8aca014668a1e5480b043d8ff74712cc7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:26:32 +0800 Subject: [PATCH 3672/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index bd4e9d6f0..594616d21 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -66,13 +66,12 @@ def minStep(p1, p2): closer, detour = [p1], [] lookup = set() while True: - if not closer: - # cannot find a path in the current expansion stack which gets closer to p2, + if not closer: # cannot find a path in the current expansion stack which gets closer to p2 + if not detour: # no other possible path + return -1 # try other possible paths in another expansion stack with 2-step detour to p2 min_steps += 2 closer, detour = detour, closer - if not closer: # no any other possible path - return -1 i, j = closer.pop() if (i, j) == p2: return min_steps From 224566ffba60f2494f489d9d63c7e26685eff405 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:28:13 +0800 Subject: [PATCH 3673/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index e9bac0726..1a20d875b 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -46,15 +46,14 @@ class Solution { unordered_set lookup; vector> closer{start}, detour; while (true) { - if (closer.empty()) { - // cannot find a path in the current expansion stack which gets closer to end, + if (closer.empty()) { // cannot find a path in the current expansion stack which gets closer to end + if (detour.empty()) { // no other possible path + return -1; + } // try other possible paths in another expansion stack with 2-step detour to end min_steps += 2; swap(closer, detour); } - if (closer.empty()) { // no any other possible path - return -1; - } int i, j; tie(i, j) = closer.back(); closer.pop_back(); if (make_pair(i, j) == end) { From 91918150b6e3f68efc073227280b79f9eda01969 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:33:57 +0800 Subject: [PATCH 3674/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index 594616d21..e730143df 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -66,10 +66,10 @@ def minStep(p1, p2): closer, detour = [p1], [] lookup = set() while True: - if not closer: # cannot find a path in the current expansion stack which gets closer to p2 + if not closer: # cannot find a path in the closer expansion if not detour: # no other possible path return -1 - # try other possible paths in another expansion stack with 2-step detour to p2 + # try other possible paths in another detour expansion with extra 2-step cost min_steps += 2 closer, detour = detour, closer i, j = closer.pop() From bbf8a06b2d68b3f030f7a17ba38ee34c15d02a36 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:35:28 +0800 Subject: [PATCH 3675/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index 1a20d875b..3cab02b63 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -46,11 +46,11 @@ class Solution { unordered_set lookup; vector> closer{start}, detour; while (true) { - if (closer.empty()) { // cannot find a path in the current expansion stack which gets closer to end + if (closer.empty()) { // cannot find a path in the closer expansions if (detour.empty()) { // no other possible path return -1; } - // try other possible paths in another expansion stack with 2-step detour to end + // try other possible paths in detour expansions with extra 2-step cost min_steps += 2; swap(closer, detour); } From 65e08089d6d89b25ca89a7f194ce1e4e72a9640b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Sep 2017 02:36:09 +0800 Subject: [PATCH 3676/4971] Update cut-off-trees-for-golf-event.py --- Python/cut-off-trees-for-golf-event.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index e730143df..b71b21091 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -66,10 +66,10 @@ def minStep(p1, p2): closer, detour = [p1], [] lookup = set() while True: - if not closer: # cannot find a path in the closer expansion + if not closer: # cannot find a path in the closer expansions if not detour: # no other possible path return -1 - # try other possible paths in another detour expansion with extra 2-step cost + # try other possible paths in detour expansions with extra 2-step cost min_steps += 2 closer, detour = detour, closer i, j = closer.pop() From 9af7b5db2e94fef36fc76c1bb664971b067e71ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Sep 2017 23:44:17 +0800 Subject: [PATCH 3677/4971] Update cut-off-trees-for-golf-event.cpp --- C++/cut-off-trees-for-golf-event.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/cut-off-trees-for-golf-event.cpp b/C++/cut-off-trees-for-golf-event.cpp index 3cab02b63..68555feaf 100644 --- a/C++/cut-off-trees-for-golf-event.cpp +++ b/C++/cut-off-trees-for-golf-event.cpp @@ -64,7 +64,6 @@ class Solution { vector> expansions = {{i + 1, j}, {i - 1, j}, {i, j + 1}, {i, j - 1}}; for (const auto& expansion : expansions) { int I, J; - bool is_closer; tie(I, J) = expansion; if (0 <= I && I < m && 0 <= J && J < n && forest[I][J] && !lookup.count(I * n + J)) { From d574ba3a3528b05c4b2637b1dfbaa29eaadda259 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 13:52:19 +0800 Subject: [PATCH 3678/4971] Create 24-game.py --- Python/24-game.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/24-game.py diff --git a/Python/24-game.py b/Python/24-game.py new file mode 100644 index 000000000..a574e13c5 --- /dev/null +++ b/Python/24-game.py @@ -0,0 +1,30 @@ +# Time: O(n^3 * 4^n) +# Space: O(n^2) + +from fractions import Fraction +from operator import * + +class Solution(object): + def judgePoint24(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + def dfs(nums): + if len(nums) == 1: + return nums[0] == 24 + ops = [add, sub, mul, div] + for i in xrange(len(nums)): + for j in xrange(len(nums)): + if i == j: + continue + for op in ops: + if op == div and nums[j] == 0: + continue + next_nums = [nums[k] for k in xrange(len(nums)) if k not in [i, j]] + next_nums.append(op(nums[i], nums[j])) + if dfs(next_nums): + return True + return False + + return dfs(map(lambda x: Fraction(x, 1), nums)) From f47dc17aa9c400cab62365af36283b4e19fc9fef Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 15:00:03 +0800 Subject: [PATCH 3679/4971] Create 24-game.cpp --- C++/24-game.cpp | 148 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 C++/24-game.cpp diff --git a/C++/24-game.cpp b/C++/24-game.cpp new file mode 100644 index 000000000..2a98ec975 --- /dev/null +++ b/C++/24-game.cpp @@ -0,0 +1,148 @@ +// Time: O(n^3 * 4^n) +// Space: O(n^2) + +class Fraction { +public: + Fraction() = default; + Fraction(int n) + : Fraction(n, 1) + { + } + Fraction(int n, int d) + : numerator_(n) + , denominator_(d) + { + } + ~Fraction() = default; + + void set_num(int value) { numerator_ = value; } + void set_den(int value) { denominator_ = value; } + int get_num() const { return numerator_; } + int get_den() const { return denominator_; } + void reduce(); + int calculate_gcd(int, int) const; +private: + int numerator_, denominator_; +}; + +void Fraction::reduce() +{ + const auto gcd = calculate_gcd(numerator_, denominator_); + numerator_ = numerator_ / gcd; + denominator_ = denominator_ / gcd; +} + +int Fraction::calculate_gcd(int a, int b) const +{ + a = std::abs(a); + b = std::abs(b); + while (b != 0) { + int tmp = b; + b = a % b; + a = tmp; + } + return a; +} + +Fraction operator+(const Fraction& lhs, const Fraction& rhs) +{ + Fraction result{}; + + result.set_num((lhs.get_num() * rhs.get_den()) + (lhs.get_den() * rhs.get_num())); + result.set_den(lhs.get_den() * rhs.get_den()); + + result.reduce(); + + return result; +} + +Fraction operator-(const Fraction& lhs, const Fraction& rhs) +{ + Fraction result{}; + + result.set_num((lhs.get_num() * rhs.get_den()) - (lhs.get_den() * rhs.get_num())); + result.set_den(lhs.get_den() * rhs.get_den()); + + result.reduce(); + + return result; +} + +Fraction operator*(const Fraction& lhs, const Fraction& rhs) +{ + Fraction result{}; + + result.set_num(lhs.get_num() * rhs.get_num()); + result.set_den(lhs.get_den() * rhs.get_den()); + + result.reduce(); + + return result; +} + +Fraction operator/(const Fraction& lhs, const Fraction& rhs) +{ + Fraction result{}; + + result.set_num(lhs.get_num() * rhs.get_den()); + result.set_den(lhs.get_den() * rhs.get_num()); + + result.reduce(); + + return result; +} + +bool operator==(const Fraction &lhs, const Fraction &rhs) { + return (((lhs.get_num() * rhs.get_den()) - (rhs.get_num() * lhs.get_den())) == 0); +} + +std::ostream &operator<<(std::ostream &os, const Fraction &value) { + os << value.get_num() << "/" << value.get_den(); + return os; +} + +class Solution { +public: + bool judgePoint24(vector& nums) { + vector fraction_nums; + std::transform(nums.begin(), nums.end(), std::back_inserter(fraction_nums), + [](const int num) { return Fraction(num); }); + return dfs(fraction_nums); + } + +private: + bool dfs(const vector& nums) { + if (nums.size() == 1) { + return nums[0] == 24; + } + for (int i = 0; i < nums.size(); ++i) { + for (int j = 0; j < nums.size(); ++j) { + if (i == j) { + continue; + } + unordered_map> ops; + ops['+'] = std::plus(); + ops['-'] = std::minus(); + ops['*'] = std::multiplies(); + ops['/'] = std::divides(); + for (const auto& op : ops) { + if (op.first == '/' && nums[j] == 0) { + continue; + } + vector next_nums; + for (int k = 0; k < nums.size(); ++k) { + if (k == i || k == j) { + continue; + } + next_nums.emplace_back(nums[k]); + } + next_nums.emplace_back(op.second(nums[i], nums[j])); + if (dfs(next_nums)) { + return true; + } + } + } + } + return false; + } +}; From d4b86bc3b4440d665eb8119828a9ffe241b321a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 15:13:16 +0800 Subject: [PATCH 3680/4971] Update 24-game.py --- Python/24-game.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/24-game.py b/Python/24-game.py index a574e13c5..efd31f0e8 100644 --- a/Python/24-game.py +++ b/Python/24-game.py @@ -1,4 +1,4 @@ -# Time: O(n^3 * 4^n) +# Time: O(n^3 * 4^n), n = 4 # Space: O(n^2) from fractions import Fraction From 4b8b00d02f41a2e55bce2b02b98642055fc6c52d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 15:13:51 +0800 Subject: [PATCH 3681/4971] Update 24-game.cpp --- C++/24-game.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/24-game.cpp b/C++/24-game.cpp index 2a98ec975..85fbb469d 100644 --- a/C++/24-game.cpp +++ b/C++/24-game.cpp @@ -1,4 +1,4 @@ -// Time: O(n^3 * 4^n) +// Time: O(n^3 * 4^n), n = 4 // Space: O(n^2) class Fraction { From 5bbfb5fd5b1f9d346c1402a4c4b1a35e79e17604 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 15:14:46 +0800 Subject: [PATCH 3682/4971] Update 24-game.py --- Python/24-game.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/24-game.py b/Python/24-game.py index efd31f0e8..300d7088e 100644 --- a/Python/24-game.py +++ b/Python/24-game.py @@ -27,4 +27,4 @@ def dfs(nums): return True return False - return dfs(map(lambda x: Fraction(x, 1), nums)) + return dfs(map(Fraction, nums)) From 1ecca7eb783d78e3b1936fab3d8b9799dfa910ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 15:50:26 +0800 Subject: [PATCH 3683/4971] Create valid-parenthesis-string.cpp --- C++/valid-parenthesis-string.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/valid-parenthesis-string.cpp diff --git a/C++/valid-parenthesis-string.cpp b/C++/valid-parenthesis-string.cpp new file mode 100644 index 000000000..874103b2a --- /dev/null +++ b/C++/valid-parenthesis-string.cpp @@ -0,0 +1,25 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool checkValidString(string s) { + int lower = 0, upper = 0; // keep lower bound and upper bound of '(' counts + for (const auto& c : s) { + if (c == '(') { + ++lower; + ++upper; + } else if (c == ')') { + if (upper == 0) { // '(' count is not enough + return false; + } + lower = max(lower - 1, 0); + --upper; + } else { + lower = max(lower - 1, 0); + ++upper; + } + } + return lower == 0; // range of '(' count is valid + } +}; From 8d7109f96b8af297041c756b3a58a6267468adde Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 15:53:34 +0800 Subject: [PATCH 3684/4971] Rename valid-parentheses.py to valid-parenthesis-string.cpp --- Python/valid-parenthesis-string.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Python/valid-parenthesis-string.cpp diff --git a/Python/valid-parenthesis-string.cpp b/Python/valid-parenthesis-string.cpp new file mode 100644 index 000000000..a867ea4e9 --- /dev/null +++ b/Python/valid-parenthesis-string.cpp @@ -0,0 +1,24 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def checkValidString(self, s): + """ + :type s: str + :rtype: bool + """ + lower, upper = 0, 0 # keep lower bound and upper bound of '(' counts + for c in s: + if c == '(': + lower += 1 + upper += 1 + elif c == ')': + if upper == 0: # '(' count is not enough + return False + lower = max(lower-1, 0); + upper -= 1 + else: + lower = max(lower-1, 0); + upper += 1 + return lower == 0 # range of '(' count is valid + From cdfc19e4d01cb3c3a2dd98ed3d0cb065147d2db1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 15:54:12 +0800 Subject: [PATCH 3685/4971] Rename valid-parenthesis-string.cpp to valid-parenthesis-string.py --- .../{valid-parenthesis-string.cpp => valid-parenthesis-string.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{valid-parenthesis-string.cpp => valid-parenthesis-string.py} (100%) diff --git a/Python/valid-parenthesis-string.cpp b/Python/valid-parenthesis-string.py similarity index 100% rename from Python/valid-parenthesis-string.cpp rename to Python/valid-parenthesis-string.py From 854b39993e47ff47b5edf46feaaa64e1e5fe6689 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 16:02:27 +0800 Subject: [PATCH 3686/4971] Update valid-parenthesis-string.py --- Python/valid-parenthesis-string.py | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/Python/valid-parenthesis-string.py b/Python/valid-parenthesis-string.py index a867ea4e9..ac5f73ece 100644 --- a/Python/valid-parenthesis-string.py +++ b/Python/valid-parenthesis-string.py @@ -9,16 +9,8 @@ def checkValidString(self, s): """ lower, upper = 0, 0 # keep lower bound and upper bound of '(' counts for c in s: - if c == '(': - lower += 1 - upper += 1 - elif c == ')': - if upper == 0: # '(' count is not enough - return False - lower = max(lower-1, 0); - upper -= 1 - else: - lower = max(lower-1, 0); - upper += 1 + lower += 1 if c == '(' else -1 + upper -= 1 if c == ')' else -1 + if upper < 0: break + lower = max(lower, 0) return lower == 0 # range of '(' count is valid - From 01411d1cc47531d328179749a2ccc7a56c08074a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 16:04:29 +0800 Subject: [PATCH 3687/4971] Update valid-parenthesis-string.cpp --- C++/valid-parenthesis-string.cpp | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/C++/valid-parenthesis-string.cpp b/C++/valid-parenthesis-string.cpp index 874103b2a..ffaa727b4 100644 --- a/C++/valid-parenthesis-string.cpp +++ b/C++/valid-parenthesis-string.cpp @@ -6,19 +6,10 @@ class Solution { bool checkValidString(string s) { int lower = 0, upper = 0; // keep lower bound and upper bound of '(' counts for (const auto& c : s) { - if (c == '(') { - ++lower; - ++upper; - } else if (c == ')') { - if (upper == 0) { // '(' count is not enough - return false; - } - lower = max(lower - 1, 0); - --upper; - } else { - lower = max(lower - 1, 0); - ++upper; - } + lower += (c == '(') ? 1 : -1; + upper -= (c == ')') ? 1 : -1; + if (upper < 0) break; + lower = max(lower, 0); } return lower == 0; // range of '(' count is valid } From 6831c2122b47794d4103b7ca5cfe1c29a20597d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 16:05:39 +0800 Subject: [PATCH 3688/4971] Update valid-parenthesis-string.cpp --- C++/valid-parenthesis-string.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/valid-parenthesis-string.cpp b/C++/valid-parenthesis-string.cpp index ffaa727b4..af21619c9 100644 --- a/C++/valid-parenthesis-string.cpp +++ b/C++/valid-parenthesis-string.cpp @@ -4,7 +4,7 @@ class Solution { public: bool checkValidString(string s) { - int lower = 0, upper = 0; // keep lower bound and upper bound of '(' counts + int lower = 0, upper = 0; // keep lower bound and upper bound of '(' counts for (const auto& c : s) { lower += (c == '(') ? 1 : -1; upper -= (c == ')') ? 1 : -1; From 47309497162a33617b6a045e45c648fc6e474b07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 16:34:09 +0800 Subject: [PATCH 3689/4971] Create valid-palindrome-ii.cpp --- C++/valid-palindrome-ii.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/valid-palindrome-ii.cpp diff --git a/C++/valid-palindrome-ii.cpp b/C++/valid-palindrome-ii.cpp new file mode 100644 index 000000000..1cd239064 --- /dev/null +++ b/C++/valid-palindrome-ii.cpp @@ -0,0 +1,27 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool validPalindrome(string s) { + int left = 0, right = s.length() - 1; + while (left < right) { + if (s[left] != s[right]) { + return validPalindrome(s, left, right - 1) || validPalindrome(s, left + 1, right); + } + ++left, --right; + } + return true; + } + +private: + bool validPalindrome(const string& s, int left, int right) { + while (left < right) { + if (s[left] != s[right]) { + return false; + } + ++left, --right; + } + return true; + } +}; From 92ae3fcc0a3904442f530549a20d21ba4a184561 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 16:37:44 +0800 Subject: [PATCH 3690/4971] Create valid-palindrome-ii.py --- Python/valid-palindrome-ii.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Python/valid-palindrome-ii.py diff --git a/Python/valid-palindrome-ii.py b/Python/valid-palindrome-ii.py new file mode 100644 index 000000000..e2b855e30 --- /dev/null +++ b/Python/valid-palindrome-ii.py @@ -0,0 +1,23 @@ +# Time: O(n) +# Soace: O(1) + +class Solution(object): + def validPalindrome(self, s): + """ + :type s: str + :rtype: bool + """ + def validPalindrome(s, left, right): + while left < right: + if s[left] != s[right]: + return False + left, right = left+1, right-1 + return True + + left, right = 0, len(s)-1 + while left < right: + if s[left] != s[right]: + return validPalindrome(s, left, right-1) or validPalindrome(s, left+1, right) + left, right = left+1, right-1 + return True + From 2805a9c7ef51e87d8302c51096ef79cc32552c55 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 17:14:42 +0800 Subject: [PATCH 3691/4971] Create map-sum-pairs.py --- Python/map-sum-pairs.py | 55 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/map-sum-pairs.py diff --git a/Python/map-sum-pairs.py b/Python/map-sum-pairs.py new file mode 100644 index 000000000..30381be60 --- /dev/null +++ b/Python/map-sum-pairs.py @@ -0,0 +1,55 @@ +# Time: O(n), n is the length of key +# Space: O(t), t is the total size of trie + +class MapSum(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + _trie = lambda: collections.defaultdict(_trie) + self.__root = _trie() + + + def insert(self, key, val): + """ + :type key: str + :type val: int + :rtype: void + """ + # Time: O(n) + curr = self.__root + for c in key: + curr = curr[c] + delta = val + if "_end" in curr: + delta -= curr["_end"] + + curr = self.__root + for c in key: + curr = curr[c] + if "_count" in curr: + curr["_count"] += delta + else: + curr["_count"] = delta + curr["_end"] = val + + + def sum(self, prefix): + """ + :type prefix: str + :rtype: int + """ + # Time: O(n) + curr = self.__root + for c in prefix: + if c not in curr: + return 0 + curr = curr[c] + return curr["_count"] + + +# Your MapSum object will be instantiated and called as such: +# obj = MapSum() +# obj.insert(key,val) +# param_2 = obj.sum(prefix) From acf7d9c9748531d4bc800353a71f0b152fda6d53 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 17:19:54 +0800 Subject: [PATCH 3692/4971] Update map-sum-pairs.py --- Python/map-sum-pairs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/map-sum-pairs.py b/Python/map-sum-pairs.py index 30381be60..7823d027d 100644 --- a/Python/map-sum-pairs.py +++ b/Python/map-sum-pairs.py @@ -1,5 +1,5 @@ # Time: O(n), n is the length of key -# Space: O(t), t is the total size of trie +# Space: O(t), t is the number of nodes in trie class MapSum(object): From 3b3c56876811351ae103b2bd8b4659ce4c310622 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 17:34:27 +0800 Subject: [PATCH 3693/4971] Create map-sum-pairs.cpp --- C++/map-sum-pairs.cpp | 79 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 C++/map-sum-pairs.cpp diff --git a/C++/map-sum-pairs.cpp b/C++/map-sum-pairs.cpp new file mode 100644 index 000000000..d6100ff53 --- /dev/null +++ b/C++/map-sum-pairs.cpp @@ -0,0 +1,79 @@ +// Time: O(n), n is the length of key +// Space: O(t), t is the total size of trie + +class MapSum { +public: + /** Initialize your data structure here. */ + MapSum() { + + } + + void insert(string key, int val) { + trie_.Insert(key, val); + } + + int sum(string prefix) { + return trie_.GetCount(prefix); + } + +private: + struct TrieNode { + bool isString = false; + int count = 0; + int val = 0; + unordered_map leaves; + + void Insert(const string& s, const int val) { + const auto delta = val - GetVal(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]; + p->count += delta; + } + p->val = val; + p->isString = true; + } + + int GetVal(const string& s) const { + auto* p = this; + for (const auto& c : s) { + if (p->leaves.find(c) == p->leaves.cend()) { + return 0; + } + p = p->leaves.at(c); + } + return p->isString ? p->val : 0; + } + + int GetCount(const string& s) const { + auto* p = this; + for (const auto& c : s) { + if (p->leaves.find(c) == p->leaves.cend()) { + return 0; + } + p = p->leaves.at(c); + } + return p->count; + } + + ~TrieNode() { + for (auto& kv : leaves) { + if (kv.second) { + delete kv.second; + } + } + } + }; + TrieNode trie_; +}; + +/** + * Your MapSum object will be instantiated and called as such: + * MapSum obj = new MapSum(); + * obj.insert(key,val); + * int param_2 = obj.sum(prefix); + */ + From 35aabc7f03e0908e123f7e1eb52a802a58006059 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Sep 2017 17:35:44 +0800 Subject: [PATCH 3694/4971] Update map-sum-pairs.cpp --- C++/map-sum-pairs.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/map-sum-pairs.cpp b/C++/map-sum-pairs.cpp index d6100ff53..3c3ee4aca 100644 --- a/C++/map-sum-pairs.cpp +++ b/C++/map-sum-pairs.cpp @@ -1,5 +1,5 @@ // Time: O(n), n is the length of key -// Space: O(t), t is the total size of trie +// Space: O(t), t is the number of nodes in trie class MapSum { public: From 586c3fb90bd765ebee1f5e63f94a86144623d9d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 20:44:52 +0800 Subject: [PATCH 3695/4971] Update map-sum-pairs.py --- Python/map-sum-pairs.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Python/map-sum-pairs.py b/Python/map-sum-pairs.py index 7823d027d..391bff1c1 100644 --- a/Python/map-sum-pairs.py +++ b/Python/map-sum-pairs.py @@ -1,6 +1,21 @@ # Time: O(n), n is the length of key # Space: O(t), t is the number of nodes in trie +# Implement a MapSum class with insert, and sum methods. +# +# For the method insert, you'll be given a pair of (string, integer). +# The string represents the key and the integer represents the value. +# If the key already existed, then the original key-value pair will be overridden to the new one. +# +# For the method sum, you'll be given a string representing the prefix, +# and you need to return the sum of all the pairs' value whose key starts with the prefix. +# +# Example 1: +# Input: insert("apple", 3), Output: Null +# Input: sum("ap"), Output: 3 +# Input: insert("app", 2), Output: Null +# Input: sum("ap"), Output: 5 + class MapSum(object): def __init__(self): From 4d404d08e2e140c36a4151d2b860f79611c1ef91 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 20:49:35 +0800 Subject: [PATCH 3696/4971] Update valid-parenthesis-string.py --- Python/valid-parenthesis-string.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Python/valid-parenthesis-string.py b/Python/valid-parenthesis-string.py index ac5f73ece..8855c0331 100644 --- a/Python/valid-parenthesis-string.py +++ b/Python/valid-parenthesis-string.py @@ -1,6 +1,26 @@ # Time: O(n) # Space: O(1) +# Given a string containing only three types of characters: '(', ')' and '*', +# write a function to check whether this string is valid. We define the validity of a string by these rules: +# +# Any left parenthesis '(' must have a corresponding right parenthesis ')'. +# Any right parenthesis ')' must have a corresponding left parenthesis '('. +# Left parenthesis '(' must go before the corresponding right parenthesis ')'. +# '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. +# An empty string is also valid. +# Example 1: +# Input: "()" +# Output: True +# Example 2: +# Input: "(*)" +# Output: True +# Example 3: +# Input: "(*))" +# Output: True +# Note: +# The string size will be in the range [1, 100]. + class Solution(object): def checkValidString(self, s): """ From e8eba8abe7a9f23a072a87c9188e81ff6af249d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 20:50:14 +0800 Subject: [PATCH 3697/4971] Update valid-parenthesis-string.py --- Python/valid-parenthesis-string.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/valid-parenthesis-string.py b/Python/valid-parenthesis-string.py index 8855c0331..25c9700c6 100644 --- a/Python/valid-parenthesis-string.py +++ b/Python/valid-parenthesis-string.py @@ -3,12 +3,12 @@ # Given a string containing only three types of characters: '(', ')' and '*', # write a function to check whether this string is valid. We define the validity of a string by these rules: +# 1. Any left parenthesis '(' must have a corresponding right parenthesis ')'. +# 2. Any right parenthesis ')' must have a corresponding left parenthesis '('. +# 3. Left parenthesis '(' must go before the corresponding right parenthesis ')'. +# 4. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. +# 5. An empty string is also valid. # -# Any left parenthesis '(' must have a corresponding right parenthesis ')'. -# Any right parenthesis ')' must have a corresponding left parenthesis '('. -# Left parenthesis '(' must go before the corresponding right parenthesis ')'. -# '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. -# An empty string is also valid. # Example 1: # Input: "()" # Output: True From 733b007c551ff9d47ee4d9432cb109fede530597 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 20:58:33 +0800 Subject: [PATCH 3698/4971] Update 24-game.py --- Python/24-game.py | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/Python/24-game.py b/Python/24-game.py index 300d7088e..da5903962 100644 --- a/Python/24-game.py +++ b/Python/24-game.py @@ -1,5 +1,22 @@ -# Time: O(n^3 * 4^n), n = 4 -# Space: O(n^2) +# Time: O(n^3 * 4^n) = O(1), n = 4 +# Space: O(n^2) = O(1) + +# You have 4 cards each containing a number from 1 to 9. +# You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24. +# +# Example 1: +# Input: [4, 1, 8, 7] +# Output: True +# Explanation: (8-4) * (7-1) = 24 +# Example 2: +# Input: [1, 2, 1, 2] +# Output: False +# Note: +# The division operator / represents real division, not integer division. +# For example, 4 / (1 - 2/3) = 12. +# Every operation done is between two numbers. In particular, we cannot use - as a unary operator. +# For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed. +# You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12. from fractions import Fraction from operator import * @@ -18,13 +35,14 @@ def dfs(nums): for j in xrange(len(nums)): if i == j: continue + next_nums = [nums[k] for k in xrange(len(nums)) if k not in [i, j]] for op in ops: - if op == div and nums[j] == 0: - continue - next_nums = [nums[k] for k in xrange(len(nums)) if k not in [i, j]] + if (op is add or op is mul) and j > i: continue + if op == div and nums[j] == 0: continue next_nums.append(op(nums[i], nums[j])) if dfs(next_nums): return True + next_nums.pop() return False return dfs(map(Fraction, nums)) From 0f28db7b1155b6f924ab7c435e7cdbe5f6772a5a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 21:04:45 +0800 Subject: [PATCH 3699/4971] Update 24-game.cpp --- C++/24-game.cpp | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/C++/24-game.cpp b/C++/24-game.cpp index 85fbb469d..4e70bd4d0 100644 --- a/C++/24-game.cpp +++ b/C++/24-game.cpp @@ -1,5 +1,5 @@ -// Time: O(n^3 * 4^n), n = 4 -// Space: O(n^2) +// Time: O(n^3 * 4^n) = O(1), n = 4 +// Space: O(n^2) = O(1) class Fraction { public: @@ -115,31 +115,35 @@ class Solution { if (nums.size() == 1) { return nums[0] == 24; } + static unordered_map> ops = + { + {'+', std::plus()}, + {'-', std::minus()}, + {'*', std::multiplies()}, + {'/', std::divides()}, + }; for (int i = 0; i < nums.size(); ++i) { for (int j = 0; j < nums.size(); ++j) { if (i == j) { continue; } - unordered_map> ops; - ops['+'] = std::plus(); - ops['-'] = std::minus(); - ops['*'] = std::multiplies(); - ops['/'] = std::divides(); - for (const auto& op : ops) { - if (op.first == '/' && nums[j] == 0) { + vector next_nums; + for (int k = 0; k < nums.size(); ++k) { + if (k == i || k == j) { continue; } - vector next_nums; - for (int k = 0; k < nums.size(); ++k) { - if (k == i || k == j) { - continue; - } - next_nums.emplace_back(nums[k]); + next_nums.emplace_back(nums[k]); + } + for (const auto& op : ops) { + if (((op.first == '+' || op.first == '*') && i > j) || + (op.first == '/' && nums[j] == 0)) { + continue; } next_nums.emplace_back(op.second(nums[i], nums[j])); if (dfs(next_nums)) { return true; } + next_nums.pop_back(); } } } From 29c1c4ba9e9e91214e25123df2784b889654b2f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 21:09:57 +0800 Subject: [PATCH 3700/4971] Update 24-game.cpp --- C++/24-game.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/C++/24-game.cpp b/C++/24-game.cpp index 4e70bd4d0..5949d59f5 100644 --- a/C++/24-game.cpp +++ b/C++/24-game.cpp @@ -1,6 +1,57 @@ // Time: O(n^3 * 4^n) = O(1), n = 4 // Space: O(n^2) = O(1) +class Solution { +public: + bool judgePoint24(vector& nums) { + vector fraction_nums; + std::transform(nums.begin(), nums.end(), std::back_inserter(fraction_nums), + [](const int num) { return double(num); }); + return dfs(fraction_nums); + } + +private: + bool dfs(const vector& nums) { + if (nums.size() == 1) { + return fabs(nums[0] - 24) < 1e-6; + } + static unordered_map> ops = + { + {'+', std::plus()}, + {'-', std::minus()}, + {'*', std::multiplies()}, + {'/', std::divides()}, + }; + for (int i = 0; i < nums.size(); ++i) { + for (int j = 0; j < nums.size(); ++j) { + if (i == j) { + continue; + } + vector next_nums; + for (int k = 0; k < nums.size(); ++k) { + if (k == i || k == j) { + continue; + } + next_nums.emplace_back(nums[k]); + } + for (const auto& op : ops) { + if (((op.first == '+' || op.first == '*') && i > j) || + (op.first == '/' && nums[j] == 0)) { + continue; + } + next_nums.emplace_back(op.second(nums[i], nums[j])); + if (dfs(next_nums)) { + return true; + } + next_nums.pop_back(); + } + } + } + return false; + } +}; + + class Fraction { public: Fraction() = default; @@ -101,7 +152,9 @@ std::ostream &operator<<(std::ostream &os, const Fraction &value) { return os; } -class Solution { +// Time: O(n^3 * 4^n) = O(1), n = 4 +// Space: O(n^2) = O(1) +class Solution2 { public: bool judgePoint24(vector& nums) { vector fraction_nums; From 1c6098b2ed8f6466ee7bc190cc7d6e076d7c43ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 21:14:32 +0800 Subject: [PATCH 3701/4971] Update 24-game.py --- Python/24-game.py | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/Python/24-game.py b/Python/24-game.py index da5903962..ba52307e0 100644 --- a/Python/24-game.py +++ b/Python/24-game.py @@ -18,10 +18,39 @@ # For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed. # You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12. -from fractions import Fraction -from operator import * +from operator import add, sub, mul, truediv class Solution(object): + def judgePoint24(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + if len(nums) == 1: + return abs(nums[0]-24) < 1e-6 + ops = [add, sub, mul, truediv] + for i in xrange(len(nums)): + for j in xrange(len(nums)): + if i == j: + continue + next_nums = [nums[k] for k in xrange(len(nums)) if k not in [i, j]] + for op in ops: + if ((op is add or op is mul) and j > i) or \ + (op == truediv and nums[j] == 0): + continue + next_nums.append(op(nums[i], nums[j])) + if self.judgePoint24(next_nums): + return True + next_nums.pop() + return False + + +# Time: O(n^3 * 4^n) = O(1), n = 4 +# Space: O(n^2) = O(1) +from fractions import Fraction +from operator import add, sub, mul, div + +class Solution2(object): def judgePoint24(self, nums): """ :type nums: List[int] From 05d5ac7daf08bfaddf932ca829ec5a2dc9bd2d4e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 21:16:58 +0800 Subject: [PATCH 3702/4971] Update valid-palindrome-ii.py --- Python/valid-palindrome-ii.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Python/valid-palindrome-ii.py b/Python/valid-palindrome-ii.py index e2b855e30..5e814ca31 100644 --- a/Python/valid-palindrome-ii.py +++ b/Python/valid-palindrome-ii.py @@ -1,6 +1,19 @@ # Time: O(n) # Soace: O(1) +# Given a non-empty string s, you may delete at most one character. +# Judge whether you can make it a palindrome. +# +# Example 1: +# Input: "aba" +# Output: True +# Example 2: +# Input: "abca" +# Output: True +# Explanation: You could delete the character 'c'. +# Note: +# The string will only contain lowercase characters a-z. The maximum length of the string is 50000. + class Solution(object): def validPalindrome(self, s): """ @@ -20,4 +33,3 @@ def validPalindrome(s, left, right): return validPalindrome(s, left, right-1) or validPalindrome(s, left+1, right) left, right = left+1, right-1 return True - From 44948ac52390ec76aa18a0529c112214c1ad2ace Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 21:26:29 +0800 Subject: [PATCH 3703/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 4b72f69cd..61c9b8e44 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 647| [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) | [C++](./C++/palindromic-substrings.cpp) [Python](./Python/palindromic-substrings.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 648| [Replace Words](https://leetcode.com/problems/replace-words/) | [C++](./C++/replace-words.cpp) [Python](./Python/replace-words.py) | _O(n)_ | _O(t)_ | Medium || `trie` | 657| [Judge Route Circle](https://leetcode.com/problems/judge-route-circle/) |[C++](./C++/judge-route-circle.cpp) [Python](./Python/judge-route-circle.py) | _O(n)_ | _O(1)_ | Easy | | +678| [Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) |[C++](./C++/valid-parenthesis-string.cpp) [Python](./Python/valid-parenthesis-string.py) | _O(n)_ | _O(1)_ | Medium | | +680| [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [C++](./C++/valid-palindrome-ii.cpp) [Python](./Python/valid-palindrome-ii.py) | _O(n)_ | _O(1)_ | Easy || ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -240,6 +242,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 655 | [Print Binary Tree](https://leetcode.com/problems/print-binary-tree/) | [C++](./C++/print-binary-tree.cpp) [Python](./Python/print-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | | 662 | [Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/) | [C++](./C++/maximum-width-of-binary-tree.cpp) [Python](./Python/maximum-width-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | | DFS 663 | [Equal Tree Partition](https://leetcode.com/problems/strange-printer/) | [C++](./C++/equal-tree-partition.cpp) [Python](./Python/equal-tree-partition.py) | _O(n)_ | _O(n)_ | Medium | 📖 | Hash +677 | [Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/) | [C++](./C++/map-sum-pairs.cpp) [Python](./Python/map-sum-pairs.py) | _O(n)_ | _O(t)_ | Medium || Trie ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -519,6 +522,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 |📖|| 425| [Word Squares](https://leetcode.com/problems/word-squares/) | [C++](./C++/word-squares.cpp) [Python](./Python/word-squares.py) | _O(n^2 * n!)_ | _O(n^2)_ | Hard |📖|| 676| [Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/) | [C++](./C++/implement-magic-dictionary.cpp) [Python](./Python/implement-magic-dictionary.py) | _O(n)_ | _O(d)_ | Medium || Trie, DFS +679| [24 Game](https://leetcode.com/problems/24-game/) | [C++](./C++/24-game.cpp) [Python](./Python/24-game.py) | _O(1)_ | _O(1)_ | Hard || DFS ## Dynamic Programming | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 1b7ed5f77bfa82810f2767d328a3f311937f7396 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 21:28:38 +0800 Subject: [PATCH 3704/4971] Update 24-game.py --- Python/24-game.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/24-game.py b/Python/24-game.py index ba52307e0..3e0ea13bf 100644 --- a/Python/24-game.py +++ b/Python/24-game.py @@ -33,7 +33,7 @@ def judgePoint24(self, nums): for j in xrange(len(nums)): if i == j: continue - next_nums = [nums[k] for k in xrange(len(nums)) if k not in [i, j]] + next_nums = [nums[k] for k in xrange(len(nums)) if i != k != j] for op in ops: if ((op is add or op is mul) and j > i) or \ (op == truediv and nums[j] == 0): @@ -64,7 +64,7 @@ def dfs(nums): for j in xrange(len(nums)): if i == j: continue - next_nums = [nums[k] for k in xrange(len(nums)) if k not in [i, j]] + next_nums = [nums[k] for k in xrange(len(nums)) if i != k != j] for op in ops: if (op is add or op is mul) and j > i: continue if op == div and nums[j] == 0: continue From 7760a955ffa06721ac4b3d98b54eb3ab61d8bf08 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 21:34:15 +0800 Subject: [PATCH 3705/4971] Update 24-game.py --- Python/24-game.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/24-game.py b/Python/24-game.py index 3e0ea13bf..5ff90d195 100644 --- a/Python/24-game.py +++ b/Python/24-game.py @@ -37,7 +37,7 @@ def judgePoint24(self, nums): for op in ops: if ((op is add or op is mul) and j > i) or \ (op == truediv and nums[j] == 0): - continue + continue next_nums.append(op(nums[i], nums[j])) if self.judgePoint24(next_nums): return True @@ -66,8 +66,9 @@ def dfs(nums): continue next_nums = [nums[k] for k in xrange(len(nums)) if i != k != j] for op in ops: - if (op is add or op is mul) and j > i: continue - if op == div and nums[j] == 0: continue + if ((op is add or op is mul) and j > i) or \ + (op == truediv and nums[j] == 0): + continue next_nums.append(op(nums[i], nums[j])) if dfs(next_nums): return True From 04336aa2102ad2733c169d47f5317702eacb2c96 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 21:35:13 +0800 Subject: [PATCH 3706/4971] Update 24-game.py --- Python/24-game.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/24-game.py b/Python/24-game.py index 5ff90d195..bd91f330a 100644 --- a/Python/24-game.py +++ b/Python/24-game.py @@ -67,7 +67,7 @@ def dfs(nums): next_nums = [nums[k] for k in xrange(len(nums)) if i != k != j] for op in ops: if ((op is add or op is mul) and j > i) or \ - (op == truediv and nums[j] == 0): + (op == div and nums[j] == 0): continue next_nums.append(op(nums[i], nums[j])) if dfs(next_nums): From 2bf07c4b5bebfe848bcf558a3e1d22a65290eb84 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Sep 2017 21:38:49 +0800 Subject: [PATCH 3707/4971] Update 24-game.cpp --- C++/24-game.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/24-game.cpp b/C++/24-game.cpp index 5949d59f5..0bd48e540 100644 --- a/C++/24-game.cpp +++ b/C++/24-game.cpp @@ -4,10 +4,10 @@ class Solution { public: bool judgePoint24(vector& nums) { - vector fraction_nums; - std::transform(nums.begin(), nums.end(), std::back_inserter(fraction_nums), + vector doubles; + std::transform(nums.begin(), nums.end(), std::back_inserter(doubles), [](const int num) { return double(num); }); - return dfs(fraction_nums); + return dfs(doubles); } private: From 84fbe19dbd9f391fd7564ce40c5795be9ab2492b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Sep 2017 21:28:08 +0800 Subject: [PATCH 3708/4971] Update README.md --- README.md | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 61c9b8e44..6952dc819 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates * [Heap](https://github.com/kamyu104/LeetCode#heap) * [Tree](https://github.com/kamyu104/LeetCode#tree) * [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 Pointers](https://github.com/kamyu104/LeetCode#two-pointers) * [Sort](https://github.com/kamyu104/LeetCode#sort) @@ -286,12 +285,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | -## Data Structure -| # | Title | Solution | Time | Space | Difficulty | Tag | Note| -|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| -146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [C++](./C++/lru-cache.cpp) [Python](./Python/lru-cache.py) | _O(1)_ | _O(k)_ | 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)_ | Easy || - ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| @@ -608,17 +601,19 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Design | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| +146| [LRU Cache](https://leetcode.com/problems/lru-cache/) | [C++](./C++/lru-cache.cpp) [Python](./Python/lru-cache.py) | _O(1)_ | _O(k)_ | 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)_ | Easy || 284| [Peeking Iterator](https://leetcode.com/problems/peeking-iterator/)| [C++](./C++/peeking-iterator.cpp) [Python](./Python/peeking-iterator.py) | _O(1)_ | _O(1)_ | Medium || -348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_| _O(n^2)_| Medium |📖|| -353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(1)_| _O(s)_| Medium |📖| Deque | -355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_| _O(t + f)_| Medium | LintCode | Heap | -359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | [C++](./C++/logger-rate-limiter.cpp) [Python](./Python/logger-rate-limiter.py) | _O(1), amortized_ | _O(k)_| Easy |📖| Deque | -362| [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [C++](./C++/design-hit-counter.cpp) [Python](./Python/design-hit-counter.py) | _O(1), amortized_ | _O(k)_| Medium |📖| Deque | -379| [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) | [C++](./C++/design-phone-directory.cpp) [Python](./Python/design-phone-directory.py) | _O(1)_ | _O(n)_| Medium |📖| | +348| [Design Tic-Tac-Toe](https://leetcode.com/problems/design-tic-tac-toe/) | [C++](./C++/design-tic-tac-toe.cpp) [Python](./Python/design-tic-tac-toe.py) | _O(1)_ | _O(n^2)_ | Medium |📖|| +353| [Design Snake Game](https://leetcode.com/problems/design-snake-game/) | [C++](./C++/design-snake-game.cpp) [Python](./Python/design-snake-game.py) | _O(1)_ | _O(s)_ | Medium |📖| Deque | +355| [Design Twitter](https://leetcode.com/problems/design-twitter/) | [C++](./C++/design-twitter.cpp) [Python](./Python/design-twitter.py) | _O(klogu)_ | _O(t + f)_ | Medium | LintCode | Heap | +359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) | [C++](./C++/logger-rate-limiter.cpp) [Python](./Python/logger-rate-limiter.py) | _O(1), amortized_ | _O(k)_ | Easy |📖| Deque | +362| [Design Hit Counter](https://leetcode.com/problems/design-hit-counter/) | [C++](./C++/design-hit-counter.cpp) [Python](./Python/design-hit-counter.py) | _O(1), amortized_ | _O(k)_ | Medium |📖| Deque | +379| [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/) | [C++](./C++/design-phone-directory.cpp) [Python](./Python/design-phone-directory.py) | _O(1)_ | _O(n)_ | Medium |📖| | 380| [Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) | [C++](./C++/insert-delete-getrandom-o1.cpp) [Python](./Python/insert-delete-getrandom-o1.py) | _O(1)_ | _O(n)_| Hard || | -381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_| Hard || | +381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_ | Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | -460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_| Hard || | +460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From ceba2173012292cbe7f4f8fdbc15b7b92613d71c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Sep 2017 22:45:49 +0800 Subject: [PATCH 3709/4971] Create median-employee-salary.sql --- MySQL/median-employee-salary.sql | 51 ++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 MySQL/median-employee-salary.sql diff --git a/MySQL/median-employee-salary.sql b/MySQL/median-employee-salary.sql new file mode 100644 index 000000000..660397f58 --- /dev/null +++ b/MySQL/median-employee-salary.sql @@ -0,0 +1,51 @@ +# Time: O(nlogn) +# Space: O(n) + +# The Employee table holds all employees. +# The employee table has three columns: Employee Id, Company Name, and Salary. +# +# +-----+------------+--------+ +# |Id | Company | Salary | +# +-----+------------+--------+ +# |1 | A | 2341 | +# |2 | A | 341 | +# |3 | A | 15 | +# |4 | A | 15314 | +# |5 | A | 451 | +# |6 | A | 513 | +# |7 | B | 15 | +# |8 | B | 13 | +# |9 | B | 1154 | +# |10 | B | 1345 | +# |11 | B | 1221 | +# |12 | B | 234 | +# |13 | C | 2345 | +# |14 | C | 2645 | +# |15 | C | 2645 | +# |16 | C | 2652 | +# |17 | C | 65 | +# +-----+------------+--------+ +# Write a SQL query to find the median salary of each company. +# Bonus points if you can solve it without using any built-in SQL functions. +# +# +-----+------------+--------+ +# |Id | Company | Salary | +# +-----+------------+--------+ +# |5 | A | 451 | +# |6 | A | 513 | +# |12 | B | 234 | +# |9 | B | 1154 | +# |14 | C | 2645 | +# +-----+------------+--------+ + +select Id, Company, Salary from +( +select e.Id, e.Salary, e.Company, if (@Prev = e.Company , @Rank := @Rank + 1, @Rank := 1) as Rank, @Prev := e.Company +from Employee e , (select @Rank := 0, @prev := 0) as Temp order by e.Company, e.Salary, e.Id +) Ranking +INNER JOIN +( +select count(*) as TotalCount, Company as Name from Employee e2 group by e2.Company +) CompanyCount +on CompanyCount.Name = Ranking.Company +where Rank = floor((TotalCount+1)/2) or Rank = floor((TotalCount+2)/2) From 464f77e65ff64ec9254b03563b0f9c75da824af8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Sep 2017 22:47:01 +0800 Subject: [PATCH 3710/4971] Update median-employee-salary.sql --- MySQL/median-employee-salary.sql | 37 -------------------------------- 1 file changed, 37 deletions(-) diff --git a/MySQL/median-employee-salary.sql b/MySQL/median-employee-salary.sql index 660397f58..4c970d183 100644 --- a/MySQL/median-employee-salary.sql +++ b/MySQL/median-employee-salary.sql @@ -1,43 +1,6 @@ # Time: O(nlogn) # Space: O(n) -# The Employee table holds all employees. -# The employee table has three columns: Employee Id, Company Name, and Salary. -# -# +-----+------------+--------+ -# |Id | Company | Salary | -# +-----+------------+--------+ -# |1 | A | 2341 | -# |2 | A | 341 | -# |3 | A | 15 | -# |4 | A | 15314 | -# |5 | A | 451 | -# |6 | A | 513 | -# |7 | B | 15 | -# |8 | B | 13 | -# |9 | B | 1154 | -# |10 | B | 1345 | -# |11 | B | 1221 | -# |12 | B | 234 | -# |13 | C | 2345 | -# |14 | C | 2645 | -# |15 | C | 2645 | -# |16 | C | 2652 | -# |17 | C | 65 | -# +-----+------------+--------+ -# Write a SQL query to find the median salary of each company. -# Bonus points if you can solve it without using any built-in SQL functions. -# -# +-----+------------+--------+ -# |Id | Company | Salary | -# +-----+------------+--------+ -# |5 | A | 451 | -# |6 | A | 513 | -# |12 | B | 234 | -# |9 | B | 1154 | -# |14 | C | 2645 | -# +-----+------------+--------+ - select Id, Company, Salary from ( select e.Id, e.Salary, e.Company, if (@Prev = e.Company , @Rank := @Rank + 1, @Rank := 1) as Rank, @Prev := e.Company From 03dddb181dc493cb76c15a4570117b38034ed736 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Sep 2017 22:49:42 +0800 Subject: [PATCH 3711/4971] Update median-employee-salary.sql --- MySQL/median-employee-salary.sql | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/MySQL/median-employee-salary.sql b/MySQL/median-employee-salary.sql index 4c970d183..29bd42dbf 100644 --- a/MySQL/median-employee-salary.sql +++ b/MySQL/median-employee-salary.sql @@ -1,14 +1,14 @@ # Time: O(nlogn) # Space: O(n) -select Id, Company, Salary from +SELECT Id, Company, Salary FROM ( -select e.Id, e.Salary, e.Company, if (@Prev = e.Company , @Rank := @Rank + 1, @Rank := 1) as Rank, @Prev := e.Company -from Employee e , (select @Rank := 0, @prev := 0) as Temp order by e.Company, e.Salary, e.Id +SELECT e.Id, e.Salary, e.Company, IF (@Prev = e.Company , @Rank := @Rank + 1, @Rank := 1) AS Rank, @Prev := e.Company +FROM Employee e , (SELECT @Rank := 0, @prev := 0) AS Temp ORDER BY e.Company, e.Salary, e.Id ) Ranking INNER JOIN ( -select count(*) as TotalCount, Company as Name from Employee e2 group by e2.Company +SELECT COUNT(*) AS TotalCount, Company AS Name FROM Employee e2 GROUP BY e2.Company ) CompanyCount -on CompanyCount.Name = Ranking.Company -where Rank = floor((TotalCount+1)/2) or Rank = floor((TotalCount+2)/2) +ON CompanyCount.Name = Ranking.Company +WHERE Rank = floor((TotalCount+1)/2) OR Rank = floor((TotalCount+2)/2) From 635c6002acb2325ae863077a279fb8fb73f8d53f Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Sep 2017 22:59:35 +0800 Subject: [PATCH 3712/4971] Update median-employee-salary.sql --- MySQL/median-employee-salary.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/median-employee-salary.sql b/MySQL/median-employee-salary.sql index 29bd42dbf..66c909b8d 100644 --- a/MySQL/median-employee-salary.sql +++ b/MySQL/median-employee-salary.sql @@ -1,4 +1,4 @@ -# Time: O(nlogn) +# Time: O(n) # Space: O(n) SELECT Id, Company, Salary FROM From f80bed373591347103b7c63f3f7eb64967b00c37 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Sep 2017 23:08:37 +0800 Subject: [PATCH 3713/4971] Create managers-with-at-least-5-direct-reports.sql --- MySQL/managers-with-at-least-5-direct-reports.sql | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 MySQL/managers-with-at-least-5-direct-reports.sql diff --git a/MySQL/managers-with-at-least-5-direct-reports.sql b/MySQL/managers-with-at-least-5-direct-reports.sql new file mode 100644 index 000000000..1258eb9a7 --- /dev/null +++ b/MySQL/managers-with-at-least-5-direct-reports.sql @@ -0,0 +1,15 @@ +# Time: O(n) +# Space: O(n) + +SELECT + Name +FROM + Employee AS t1 INNER JOIN + (SELECT + ManagerId + FROM + Employee + GROUP BY ManagerId + HAVING COUNT(ManagerId) >= 5) AS t2 + ON t1.Id = t2.ManagerId +; From c231c4827a60f52e47590be8cddadc683da4c2d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Sep 2017 23:34:31 +0800 Subject: [PATCH 3714/4971] Create find-median-given-frequency-of-numbers.sql --- MySQL/find-median-given-frequency-of-numbers.sql | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 MySQL/find-median-given-frequency-of-numbers.sql diff --git a/MySQL/find-median-given-frequency-of-numbers.sql b/MySQL/find-median-given-frequency-of-numbers.sql new file mode 100644 index 000000000..6007b846b --- /dev/null +++ b/MySQL/find-median-given-frequency-of-numbers.sql @@ -0,0 +1,15 @@ +# Time: O(nlogn) +# Space: O(n) + +SELECT AVG(n.Number) AS median +FROM Numbers n LEFT JOIN +( +SELECT Number, @prev := @count AS prevNumber, (@count := @count + Frequency) AS countNumber +FROM Numbers, +(SELECT @count := 0, @prev := 0, @total := (SELECT SUM(Frequency) FROM Numbers)) temp ORDER BY Number +) n2 +ON n.Number = n2.Number +WHERE +(prevNumber < floor((@total+1)/2) AND countNumber >= floor((@total+1)/2)) +OR +(prevNumber < floor((@total+2)/2) AND countNumber >= floor((@total+2)/2)) From 43241cbfe0066d26597e46c9739652fb498fea20 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Sep 2017 23:37:47 +0800 Subject: [PATCH 3715/4971] Update median-employee-salary.sql --- MySQL/median-employee-salary.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/median-employee-salary.sql b/MySQL/median-employee-salary.sql index 66c909b8d..29bd42dbf 100644 --- a/MySQL/median-employee-salary.sql +++ b/MySQL/median-employee-salary.sql @@ -1,4 +1,4 @@ -# Time: O(n) +# Time: O(nlogn) # Space: O(n) SELECT Id, Company, Salary FROM From 05b0b65a496847cc1a15fabfe642d801c2da8945 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Sep 2017 23:50:10 +0800 Subject: [PATCH 3716/4971] Update managers-with-at-least-5-direct-reports.sql --- MySQL/managers-with-at-least-5-direct-reports.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MySQL/managers-with-at-least-5-direct-reports.sql b/MySQL/managers-with-at-least-5-direct-reports.sql index 1258eb9a7..f2fc77644 100644 --- a/MySQL/managers-with-at-least-5-direct-reports.sql +++ b/MySQL/managers-with-at-least-5-direct-reports.sql @@ -10,6 +10,7 @@ FROM FROM Employee GROUP BY ManagerId - HAVING COUNT(ManagerId) >= 5) AS t2 + HAVING COUNT(ManagerId) >= 5 + ORDER BY NULL) AS t2 ON t1.Id = t2.ManagerId ; From cc98903be3f2756afacb71a57e7487003cbcfc32 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Sep 2017 20:31:53 +0800 Subject: [PATCH 3717/4971] Update lru-cache.py --- Python/lru-cache.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/Python/lru-cache.py b/Python/lru-cache.py index b327f8cdd..100dca39b 100644 --- a/Python/lru-cache.py +++ b/Python/lru-cache.py @@ -9,14 +9,14 @@ # set(key, value) - Set or insert the value if the key is not already present. # When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. -class ListNode: +class ListNode(object): def __init__(self, key, val): self.val = val self.key = key self.next = None self.prev = None -class LinkedList: +class LinkedList(object): def __init__(self): self.head = None self.tail = None @@ -40,7 +40,7 @@ def delete(self, node): self.tail = node.prev del node -class LRUCache: +class LRUCache(object): # @param capacity, an integer def __init__(self, capacity): @@ -67,7 +67,7 @@ def get(self, key): # @param key, an integer # @param value, an integer # @return nothing - def set(self, key, val): + def put(self, key, val): if key in self.dict: self.list.delete(self.dict[key]) elif len(self.dict) == self.capacity: @@ -77,7 +77,7 @@ def set(self, key, val): import collections -class LRUCache2: +class LRUCache(object): def __init__(self, capacity): self.cache = collections.OrderedDict() self.capacity = capacity @@ -90,12 +90,13 @@ def get(self, key): self.cache[key] = val return val - def set(self, key, value): + def put(self, key, value): if key in self.cache: del self.cache[key] elif len(self.cache) == self.capacity: self.cache.popitem(last=False) - self.cache[key] = value + self.cache[key] = value + if __name__ == "__main__": cache = LRUCache(3) From 3f529fa5f733f335d7fb390a8af4a12400f71ac1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Sep 2017 20:32:09 +0800 Subject: [PATCH 3718/4971] Update lru-cache.py --- Python/lru-cache.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/lru-cache.py b/Python/lru-cache.py index 100dca39b..d40456206 100644 --- a/Python/lru-cache.py +++ b/Python/lru-cache.py @@ -77,7 +77,7 @@ def put(self, key, val): import collections -class LRUCache(object): +class LRUCache2(object): def __init__(self, capacity): self.cache = collections.OrderedDict() self.capacity = capacity From 9c165843cdd8c0f626bc33d76013852d4b469e55 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Sep 2017 20:34:13 +0800 Subject: [PATCH 3719/4971] Update lru-cache.py --- Python/lru-cache.py | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/Python/lru-cache.py b/Python/lru-cache.py index d40456206..bc618fd31 100644 --- a/Python/lru-cache.py +++ b/Python/lru-cache.py @@ -1,13 +1,30 @@ # Time: O(1), per operation. # Space: O(k), k is the capacity of cache. -# Design and implement a data structure for Least Recently Used (LRU) cache. -# It should support the following operations: get and set. -# -# get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. -# -# set(key, value) - Set or insert the value if the key is not already present. -# When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. +# Design and implement a data structure for Least Recently Used (LRU) cache. +# It should support the following operations: get and put. +# +# get(key) - Get the value (will always be positive) of the key if the key exists in the cache, +# otherwise return -1. +# put(key, value) - Set or insert the value if the key is not already present. +# When the cache reached its capacity, +# it should invalidate the least recently used item before inserting a new item. +# +# Follow up: +# Could you do both operations in O(1) time complexity? +# +# Example: +# +# LRUCache cache = new LRUCache( 2 /* capacity */ ); +# +# cache.put(1, 1); +# cache.put(2, 2); +# cache.get(1); // returns 1 +# cache.put(3, 3); // evicts key 2 +# cache.get(2); // returns -1 (not found) +# cache.put(4, 4); // evicts key 1 +# cache.get(1); // returns -1 (not found) +# cache.get(3); // returns 3 class ListNode(object): def __init__(self, key, val): From e497a24c542ad614a86b9a9ae1f739f884cf5677 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Sep 2017 20:34:58 +0800 Subject: [PATCH 3720/4971] Update lru-cache.cpp --- C++/lru-cache.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/lru-cache.cpp b/C++/lru-cache.cpp index e9fb97680..bdc844863 100644 --- a/C++/lru-cache.cpp +++ b/C++/lru-cache.cpp @@ -19,7 +19,7 @@ class LRUCache { } } - void set(int key, int value) { + void put(int key, int value) { // If cache is full while inserting, remove the last one. if (map_.find(key) == map_.end() && list_.size() == capa_) { auto del = list_.back(); list_.pop_back(); From 3360b6d9808532d855a139d08bb8019af4d49427 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Sep 2017 00:03:27 +0800 Subject: [PATCH 3721/4971] Update linked-list-random-node.cpp --- C++/linked-list-random-node.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/linked-list-random-node.cpp b/C++/linked-list-random-node.cpp index 3a6bec697..f9980e8df 100644 --- a/C++/linked-list-random-node.cpp +++ b/C++/linked-list-random-node.cpp @@ -10,10 +10,10 @@ class Solution { /** Returns a random node's value. */ int getRandom() { - auto reservoir = head_->val; - auto n = 1; - for (auto curr = head_->next; curr; curr = curr->next) { - if (rand() % ++n == 0) { + auto reservoir = -1; + auto n = 0; + for (auto curr = head_; curr; curr = curr->next) { + if (++n == 1 || rand() % n == 0) { reservoir = curr->val; } } From 273ba9629d85ae5877177de1948aca01f6e1d0e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Sep 2017 00:07:45 +0800 Subject: [PATCH 3722/4971] Update linked-list-random-node.py --- Python/linked-list-random-node.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/linked-list-random-node.py b/Python/linked-list-random-node.py index c07627521..1e6d7de0f 100644 --- a/Python/linked-list-random-node.py +++ b/Python/linked-list-random-node.py @@ -40,8 +40,8 @@ def getRandom(self): Returns a random node's value. :rtype: int """ - reservoir = self.__head.val - curr, n = self.__head.next, 1 + reservoir = -1 + curr, n = self.__head, 0 while curr: reservoir = curr.val if randint(1, n+1) == 1 else reservoir curr, n = curr.next, n+1 From 3edb470ba8763b906b9cd76d57075849d98a6a68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Sep 2017 00:08:25 +0800 Subject: [PATCH 3723/4971] Update random-pick-index.py --- Python/random-pick-index.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/random-pick-index.py b/Python/random-pick-index.py index 59fbaadf9..f8034c6da 100644 --- a/Python/random-pick-index.py +++ b/Python/random-pick-index.py @@ -43,7 +43,7 @@ def pick(self, target): for i in xrange(len(self.__nums)): if self.__nums[i] != target: continue - reservoir = i if n == 0 or randint(1, n+1) == 1 else reservoir + reservoir = i if randint(1, n+1) == 1 else reservoir n += 1 return reservoir From 2e15726939b0885d4641328d85e71bc829efd6ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Sep 2017 00:09:42 +0800 Subject: [PATCH 3724/4971] Update random-pick-index.cpp --- C++/random-pick-index.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/random-pick-index.cpp b/C++/random-pick-index.cpp index 32ed28e72..27e16a51c 100644 --- a/C++/random-pick-index.cpp +++ b/C++/random-pick-index.cpp @@ -9,12 +9,12 @@ class Solution { int pick(int target) { auto reservoir = -1; - int n = 0; + auto n = 0; for (int i = 0; i < nums_.size(); ++i) { if (nums_[i] != target) { continue; } - if (++n == 1 || rand() % n == 0) { + if (rand() % ++n == 0) { reservoir = i; } } From bbdee73ac6a37d6766e117356aed9ef4f3b26601 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Sep 2017 00:10:08 +0800 Subject: [PATCH 3725/4971] Update linked-list-random-node.cpp --- C++/linked-list-random-node.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/linked-list-random-node.cpp b/C++/linked-list-random-node.cpp index f9980e8df..9e5809495 100644 --- a/C++/linked-list-random-node.cpp +++ b/C++/linked-list-random-node.cpp @@ -13,7 +13,7 @@ class Solution { auto reservoir = -1; auto n = 0; for (auto curr = head_; curr; curr = curr->next) { - if (++n == 1 || rand() % n == 0) { + if (rand() % ++n == 0) { reservoir = curr->val; } } From 9b1603ad00c15b13baef2c41a76dce4e1e0bbcd3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Sep 2017 16:07:09 +0800 Subject: [PATCH 3726/4971] Create k-empty-slots.cpp --- C++/k-empty-slots.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/k-empty-slots.cpp diff --git a/C++/k-empty-slots.cpp b/C++/k-empty-slots.cpp new file mode 100644 index 000000000..97cc23a15 --- /dev/null +++ b/C++/k-empty-slots.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int kEmptySlots(vector& flowers, int k) { + vector days(flowers.size()); + for (int i = 0; i < flowers.size(); ++i) { + days[flowers[i] - 1] = i; + } + auto result = numeric_limits::max(); + for (int i = 0, left = 0, right = k + 1; right < days.size(); ++i) { + if (days[i] < days[left] || days[i] <= days[right]) { + if (i == right) { + result = min(result, max(days[left], days[right])); + } + left = i, right = k + 1 + i; + } + } + return (result == numeric_limits::max()) ? -1 : result + 1; + } +}; From d0127050dfdb8914e01b4b1e89206fbc5a0704ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Sep 2017 16:29:46 +0800 Subject: [PATCH 3727/4971] Create k-empty-slots.py --- Python/k-empty-slots.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Python/k-empty-slots.py diff --git a/Python/k-empty-slots.py b/Python/k-empty-slots.py new file mode 100644 index 000000000..4b3e90eca --- /dev/null +++ b/Python/k-empty-slots.py @@ -0,0 +1,23 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def kEmptySlots(self, flowers, k): + """ + :type flowers: List[int] + :type k: int + :rtype: int + """ + days = [0] * len(flowers) + for i in xrange(len(flowers)): + days[flowers[i]-1] = i + result = float("inf") + i, left, right = 0, 0, k+1 + while right < len(days): + if days[i] < days[left] or days[i] <= days[right]: + if i == right: + result = min(result, max(days[left], days[right])) + left, right = i, k+1+i; + i += 1 + return -1 if result == float("inf") else result+1 + From de8b9bc8d9d9284b73ba97668f4110a446ef19fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Sep 2017 16:50:39 +0800 Subject: [PATCH 3728/4971] Create redundant-connection.cpp --- C++/redundant-connection.cpp | 48 ++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 C++/redundant-connection.cpp diff --git a/C++/redundant-connection.cpp b/C++/redundant-connection.cpp new file mode 100644 index 000000000..59967d606 --- /dev/null +++ b/C++/redundant-connection.cpp @@ -0,0 +1,48 @@ +// Time: O(nlog*n) ~= O(n), n is the length of the positions +// Space: O(n) + +class Solution { +public: + vector findRedundantConnection(vector>& edges) { + UnionFind union_find(2000); + for (const auto& edge : edges) { + if (!union_find.union_set(edge[0], edge[1])) { + return edge; + } + } + return {}; + } + +private: + class UnionFind { + public: + UnionFind(const int n) : set_(n), count_(n) { + iota(set_.begin(), set_.end(), 0); + } + + int find_set(const int x) { + if (set_[x] != x) { + set_[x] = find_set(set_[x]); // Path compression. + } + return set_[x]; + } + + bool union_set(const int x, const int y) { + int x_root = find_set(x), y_root = find_set(y); + if (x_root == y_root) { + return false; + } + set_[min(x_root, y_root)] = max(x_root, y_root); + --count_; + return true; + } + + int length() const { + return count_; + } + + private: + vector set_; + int count_; + }; +}; From d50076b405448d815db812bfd76f5ac4900db1da Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Sep 2017 16:54:34 +0800 Subject: [PATCH 3729/4971] Create redundant-connection.py --- Python/redundant-connection.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/redundant-connection.py diff --git a/Python/redundant-connection.py b/Python/redundant-connection.py new file mode 100644 index 000000000..c534f42f2 --- /dev/null +++ b/Python/redundant-connection.py @@ -0,0 +1,34 @@ +# 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: + return False + self.set[min(x_root, y_root)] = max(x_root, y_root) + self.count -= 1 + return True + + +class Solution(object): + def findRedundantConnection(self, edges): + """ + :type edges: List[List[int]] + :rtype: List[int] + """ + union_find = UnionFind(2000) + for edge in edges: + if not union_find.union_set(*edge): + return edge + return [] + From ec9ed8678b64e9e714dabb5183e3049bd0f60bfd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Sep 2017 16:55:08 +0800 Subject: [PATCH 3730/4971] Update redundant-connection.py --- Python/redundant-connection.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/redundant-connection.py b/Python/redundant-connection.py index c534f42f2..f60518661 100644 --- a/Python/redundant-connection.py +++ b/Python/redundant-connection.py @@ -7,9 +7,9 @@ def __init__(self, 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] + 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)) From ee81afc2ad01e442a2c9a1dd3aa1f8726563704b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Sep 2017 17:12:14 +0800 Subject: [PATCH 3731/4971] Create next-closest-time.cpp --- C++/next-closest-time.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/next-closest-time.cpp diff --git a/C++/next-closest-time.cpp b/C++/next-closest-time.cpp new file mode 100644 index 000000000..c5a9922ae --- /dev/null +++ b/C++/next-closest-time.cpp @@ -0,0 +1,23 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + string nextClosestTime(string time) { + static const vector mins = { 600, 60, 10, 1 }; + auto npos = time.find(':'); + auto curr = stoi(time.substr(0, npos)) * 60 + + stoi(time.substr(npos + 1)); + string result = "0000"; + for (int i = 1, d = 0; i <= 1440 && d < 4; ++i) { + int m = (curr + i) % 1440; + for (d = 0; d < 4; ++d) { + result[d] = '0' + m / mins[d]; m %= mins[d]; + if (time.find(result[d]) == string::npos) { + break; + } + } + } + return result.substr(0, 2) + ':' + result.substr(2, 2); + } +}; From c6892c29adf367cf9a94a485ccb81ec352dae474 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Sep 2017 17:33:11 +0800 Subject: [PATCH 3732/4971] Create next-closest-time.py --- Python/next-closest-time.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Python/next-closest-time.py diff --git a/Python/next-closest-time.py b/Python/next-closest-time.py new file mode 100644 index 000000000..04c5ae6e0 --- /dev/null +++ b/Python/next-closest-time.py @@ -0,0 +1,19 @@ +# Time: O(1) +# Space: O(1) + +class Solution(object): + def nextClosestTime(self, time): + """ + :type time: str + :rtype: str + """ + h, m = time.split(":") + curr = int(h) * 60 + int(m) + result = None + for i in xrange(curr+1, curr+1441): + t = i % 1440 + h, m = t // 60, t % 60 + result = "%02d:%02d" % (h, m) + if set(result) <= set(time): + break + return result From 4847c54c4e003ac836f28a82e3c313e2c152ca1f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Sep 2017 17:43:00 +0800 Subject: [PATCH 3733/4971] Create baseball-game.cpp --- C++/baseball-game.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/baseball-game.cpp diff --git a/C++/baseball-game.cpp b/C++/baseball-game.cpp new file mode 100644 index 000000000..b696962d5 --- /dev/null +++ b/C++/baseball-game.cpp @@ -0,0 +1,21 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int calPoints(vector& ops) { + vector records; + for (const auto& op : ops) { + if (op == "+") { + records.emplace_back(records[records.size() - 2] + records.back()); + } else if (op == "D") { + records.emplace_back(2 * records.back()); + } else if (op == "C") { + records.pop_back(); + } else { + records.emplace_back(stoi(op)); + } + } + return accumulate(records.begin(), records.end(), 0); + } +}; From 358663959815ac56acba3739c897ad581de0453c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Sep 2017 17:43:41 +0800 Subject: [PATCH 3734/4971] Create baseball-game.py --- Python/baseball-game.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Python/baseball-game.py diff --git a/Python/baseball-game.py b/Python/baseball-game.py new file mode 100644 index 000000000..33fddecf7 --- /dev/null +++ b/Python/baseball-game.py @@ -0,0 +1,20 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def calPoints(self, ops): + """ + :type ops: List[str] + :rtype: int + """ + history = [] + for op in ops: + if op == '+': + history.append(history[-1] + history[-2]) + elif op == 'D': + history.append(history[-1] * 2) + elif op == 'C': + history.pop() + else: + history.append(int(op)) + return sum(history) From c732bea04f5e5f9c47abdd19cf018ddac00593b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Sep 2017 21:31:44 +0800 Subject: [PATCH 3735/4971] Update next-closest-time.py --- Python/next-closest-time.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Python/next-closest-time.py b/Python/next-closest-time.py index 04c5ae6e0..d69cd9ed2 100644 --- a/Python/next-closest-time.py +++ b/Python/next-closest-time.py @@ -1,6 +1,27 @@ # Time: O(1) # Space: O(1) +# Given a time represented in the format "HH:MM", +# form the next closest time by reusing the current digits. +# There is no limit on how many times a digit can be reused. +# +# You may assume the given input string is always valid. +# For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid. +# +# Example 1: +# +# Input: "19:34" +# Output: "19:39" +# Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. +# It is not 19:33, because this occurs 23 hours and 59 minutes later. +# +# Example 2: +# +# Input: "23:59" +# Output: "22:22" +# Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. +# It may be assumed that the returned time is next day's time since it is smaller than the input time numerically. + class Solution(object): def nextClosestTime(self, time): """ From 115eeb7e9bd814ba2b6382811e14d35b4d1b21df Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Sep 2017 21:34:53 +0800 Subject: [PATCH 3736/4971] Update baseball-game.py --- Python/baseball-game.py | 43 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Python/baseball-game.py b/Python/baseball-game.py index 33fddecf7..ede8ff9d9 100644 --- a/Python/baseball-game.py +++ b/Python/baseball-game.py @@ -1,6 +1,49 @@ # Time: O(n) # Space: O(n) +# You're now a baseball game point recorder. +# Given a list of strings, each string can be one of the 4 following types: +# +# 1. Integer (one round's score): Directly represents the number of points you get in this round. +# 2. "+" (one round's score): Represents that the points you get in this round are +# the sum of the last two valid round's points. +# 3. "D" (one round's score): Represents that the points you get in this round are +# the doubled data of the last valid round's points. +# 4. "C" (an operation, which isn't a round's score): Represents the last valid round's points +# you get were invalid and should be removed. +# +# Each round's operation is permanent and could have an impact on the round before and the round after. +# You need to return the sum of the points you could get in all the rounds. +# +# Example 1: +# +# Input: ["5","2","C","D","+"] +# Output: 30 +# Explanation: +# Round 1: You could get 5 points. The sum is: 5. +# Round 2: You could get 2 points. The sum is: 7. +# Operation 1: The round 2's data was invalid. The sum is: 5. +# Round 3: You could get 10 points (the round 2's data has been removed). The sum is: 15. +# Round 4: You could get 5 + 10 = 15 points. The sum is: 30. +# +# Example 2: +# +# Input: ["5","-2","4","C","D","9","+","+"] +# Output: 27 +# Explanation: +# Round 1: You could get 5 points. The sum is: 5. +# Round 2: You could get -2 points. The sum is: 3. +# Round 3: You could get 4 points. The sum is: 7. +# Operation 1: The round 3's data is invalid. The sum is: 3. +# Round 4: You could get -4 points (the round 3's data has been removed). The sum is: -1. +# Round 5: You could get 9 points. The sum is: 8. +# Round 6: You could get -4 + 9 = 5 points. The sum is 13. +# Round 7: You could get 9 + 5 = 14 points. The sum is 27. +# +# Note: +# The size of the input list will be between 1 and 1000. +# Every integer represented in the list will be between -30000 and 30000. + class Solution(object): def calPoints(self, ops): """ From f0402136278fdaab31ea4db348fdcdf1de229a61 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Sep 2017 21:37:07 +0800 Subject: [PATCH 3737/4971] Update k-empty-slots.py --- Python/k-empty-slots.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Python/k-empty-slots.py b/Python/k-empty-slots.py index 4b3e90eca..ca99f58b1 100644 --- a/Python/k-empty-slots.py +++ b/Python/k-empty-slots.py @@ -1,6 +1,37 @@ # Time: O(n) # Space: O(n) +# There is a garden with N slots. In each slot, there is a flower. +# The N flowers will bloom one by one in N days. In each day, +# there will be exactly one flower blooming and it will be in the status of blooming since then. +# +# Given an array flowers consists of number from 1 to N. +# Each number in the array represents the place where the flower will open in that day. +# +# For example, flowers[i] = x means that the unique flower that blooms at day i +# will be at position x, where i and x will be in the range from 1 to N. +# +# Also given an integer k, you need to output in which day there exists two flowers +# in the status of blooming, and also the number of flowers between them is k and +# these flowers are not blooming. +# +# If there isn't such day, output -1. +# +# Example 1: +# Input: +# flowers: [1,3,2] +# k: 1 +# Output: 2 +# Explanation: In the second day, the first and the third flower have become blooming. +# +# Example 2: +# Input: +# flowers: [1,2,3] +# k: 1 +# Output: -1 +# Note: +# The given array will be in the range [1, 20000]. + class Solution(object): def kEmptySlots(self, flowers, k): """ From f70dee412a71d900c7e24c582cadcc169abcffef Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Sep 2017 21:38:53 +0800 Subject: [PATCH 3738/4971] Update redundant-connection.py --- Python/redundant-connection.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Python/redundant-connection.py b/Python/redundant-connection.py index f60518661..24a49c007 100644 --- a/Python/redundant-connection.py +++ b/Python/redundant-connection.py @@ -1,6 +1,34 @@ # Time: O(nlog*n) ~= O(n), n is the length of the positions # Space: O(n) +# We are given a "tree" in the form of a 2D-array, with distinct values for each node. +# +# In the given 2D-array, each element pair [u, v] represents that v is a child of u in the tree. +# +# We can remove exactly one redundant pair in this "tree" to make the result a (rooted) tree. +# +# You need to find and output such a pair. If there are multiple answers for this question, +# output the one appearing last in the 2D-array. There is always at least one answer. +# +# Example 1: +# Input: [[1,2], [1,3], [2,3]] +# Output: [2,3] +# Explanation: Original tree will be like this: +# 1 +# / \ +# 2 - 3 +# +# Example 2: +# Input: [[1,2], [1,3], [3,1]] +# Output: [3,1] +# Explanation: Original tree will be like this: +# 1 +# / \\ +# 2 3 +# Note: +# The size of the input 2D-array will be between 1 and 1000. +# Every integer represented in the 2D-array will be between 1 and 2000. + class UnionFind(object): def __init__(self, n): self.set = range(n) From 2577569dcc6b77cd431aae7ac8640afa2223bd25 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Sep 2017 21:47:16 +0800 Subject: [PATCH 3739/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 6952dc819..438ada429 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 667| [Beautiful Arrangement II](https://leetcode.com/problems/beautiful-arrangement-ii/) | [C++](./C++/beautiful-arrangement-ii.cpp) [Python](./Python/beautiful-arrangement-ii.py) | _O(n)_ | _O(1)_ | Medium ||| 670| [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(logn)_ | _O(logn)_ | Medium ||| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [C++](./C++/longest-continuous-increasing-subsequence.cpp) [Python](./Python/longest-continuous-increasing-subsequence.py) | _O(n)_ | _O(1)_ | Easy || +683 | [K Empty Slots](https://leetcode.com/problems/k-empty-slots/) | [C++](./C++/k-empty-slots.cpp) [Python](./Python/k-empty-slots.py) | _O(n)_ | _O(n)_ | Hard || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -156,6 +157,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 657| [Judge Route Circle](https://leetcode.com/problems/judge-route-circle/) |[C++](./C++/judge-route-circle.cpp) [Python](./Python/judge-route-circle.py) | _O(n)_ | _O(1)_ | Easy | | 678| [Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) |[C++](./C++/valid-parenthesis-string.cpp) [Python](./Python/valid-parenthesis-string.py) | _O(n)_ | _O(1)_ | Medium | | 680| [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [C++](./C++/valid-palindrome-ii.cpp) [Python](./Python/valid-palindrome-ii.py) | _O(n)_ | _O(1)_ | Easy || +681| [Next Closest Time](https://leetcode.com/problems/next-closest-time/) | [C++](./C++/next-closest-time.cpp) [Python](./Python/next-closest-time.py) | _O(1)_ | _O(1)_ | Medium || ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -202,6 +204,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 394| [Decode String](https://leetcode.com/problems/decode-string/)| [C++](./C++/decode-string.cpp) [Python](./Python/decode-string.py) | _O(n)_ | _O(h)_ | Medium ||| 439| [Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser/) | [C++](./C++/ternary-expression-parser.cpp) [Python](./Python/ternary-expression-parser.py) | _O(n)_ | _O(1)_ | Medium |📖| 456| [132 Pattern](https://leetcode.com/problems/132-pattern/) | [C++](./C++/132-pattern.cpp) [Python](./Python/132-pattern.py) | _O(n)_ | _O(n)_ | Medium || +682| [Baseball Game](https://leetcode.com/problems/baseball-game/) | [C++](./C++/baseball-game.cpp) [Python](./Python/baseball-game.py) | _O(n)_ | _O(n)_ | Easy || ## Queue | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -242,6 +245,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 662 | [Maximum Width of Binary Tree](https://leetcode.com/problems/maximum-width-of-binary-tree/) | [C++](./C++/maximum-width-of-binary-tree.cpp) [Python](./Python/maximum-width-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium | | DFS 663 | [Equal Tree Partition](https://leetcode.com/problems/strange-printer/) | [C++](./C++/equal-tree-partition.cpp) [Python](./Python/equal-tree-partition.py) | _O(n)_ | _O(n)_ | Medium | 📖 | Hash 677 | [Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/) | [C++](./C++/map-sum-pairs.cpp) [Python](./Python/map-sum-pairs.py) | _O(n)_ | _O(t)_ | Medium || Trie +684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/) | [C++](./C++/redundant-connection.cpp) [Python](./Python/redundant-connection.py) | _O(n)_ | _O(n)_ | Medium || Union Find ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 1b178432e2437c2cae9c7999b83576260e5cea00 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Sep 2017 21:48:22 +0800 Subject: [PATCH 3740/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 438ada429..372659b31 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | 557| [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) |[C++](./C++/reverse-words-in-a-string-iii.cpp) [Python](./Python/reverse-words-in-a-string-iii.py) | _O(n)_ | _O(1)_ | Easy | | 647| [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) | [C++](./C++/palindromic-substrings.cpp) [Python](./Python/palindromic-substrings.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` -648| [Replace Words](https://leetcode.com/problems/replace-words/) | [C++](./C++/replace-words.cpp) [Python](./Python/replace-words.py) | _O(n)_ | _O(t)_ | Medium || `trie` | +648| [Replace Words](https://leetcode.com/problems/replace-words/) | [C++](./C++/replace-words.cpp) [Python](./Python/replace-words.py) | _O(n)_ | _O(t)_ | Medium || Trie | 657| [Judge Route Circle](https://leetcode.com/problems/judge-route-circle/) |[C++](./C++/judge-route-circle.cpp) [Python](./Python/judge-route-circle.py) | _O(n)_ | _O(1)_ | Easy | | 678| [Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) |[C++](./C++/valid-parenthesis-string.cpp) [Python](./Python/valid-parenthesis-string.py) | _O(n)_ | _O(1)_ | Medium | | 680| [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [C++](./C++/valid-palindrome-ii.cpp) [Python](./Python/valid-palindrome-ii.py) | _O(n)_ | _O(1)_ | Easy || From 50444794239670392d2aa24cd459d9734898dd17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Sep 2017 23:30:09 +0800 Subject: [PATCH 3741/4971] Create redundant-connection-ii.py --- Python/redundant-connection-ii.py | 69 +++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Python/redundant-connection-ii.py diff --git a/Python/redundant-connection-ii.py b/Python/redundant-connection-ii.py new file mode 100644 index 000000000..0aea2cbd4 --- /dev/null +++ b/Python/redundant-connection-ii.py @@ -0,0 +1,69 @@ +# Time: O(nlog*n) ~= O(n), n is the length of the positions +# Space: O(n) + +# In this problem, a rooted tree is a directed graph such that, +# there is exactly one node (the root) for +# which all other nodes are descendants of this node, plus every node has exactly one parent, +# except for the root node which has no parents. +# +# The given input is a directed graph that started as a rooted tree with N nodes +# (with distinct values 1, 2, ..., N), with one additional directed edge added. +# The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed. +# +# The resulting graph is given as a 2D-array of edges. +# Each element of edges is a pair [u, v] that represents a directed edge connecting nodes u and v, +# where u is a parent of child v. +# +# Return an edge that can be removed so that the resulting graph is a rooted tree of N nodes. +# If there are multiple answers, return the answer that occurs last in the given 2D-array. +# +# Example 1: +# Input: [[1,2], [1,3], [2,3]] +# Output: [2,3] +# Explanation: The given directed graph will be like this: +# 1 +# / \ +# v v +# 2-->3 +# Example 2: +# Input: [[1,2], [2,3], [3,4], [4,1], [1,5]] +# Output: [4,1] +# Explanation: The given directed graph will be like this: +# 5 <- 1 -> 2 +# ^ | +# | v +# 4 <- 3 +# Note: +# The size of the input 2D-array will be between 3 and 1000. +# Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array. + +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 or \ + y != y_root: # more the one father + return False + self.set[y_root] = x_root + self.count -= 1 + return True + +class Solution(object): + def findRedundantDirectedConnection(self, edges): + """ + :type edges: List[List[int]] + :rtype: List[int] + """ + union_find = UnionFind(2000) + for edge in edges: + if not union_find.union_set(*edge): + return edge + return [] From 1af79cb17c2c00525f54963844367f3aa575a613 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Sep 2017 23:31:58 +0800 Subject: [PATCH 3742/4971] Update redundant-connection-ii.py --- Python/redundant-connection-ii.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/redundant-connection-ii.py b/Python/redundant-connection-ii.py index 0aea2cbd4..ce678b692 100644 --- a/Python/redundant-connection-ii.py +++ b/Python/redundant-connection-ii.py @@ -56,13 +56,14 @@ def union_set(self, x, y): self.count -= 1 return True + class Solution(object): def findRedundantDirectedConnection(self, edges): """ :type edges: List[List[int]] :rtype: List[int] """ - union_find = UnionFind(2000) + union_find = UnionFind(1001) for edge in edges: if not union_find.union_set(*edge): return edge From e0a43d03c6498705e0ca43d6918fab5347f796d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Sep 2017 23:34:49 +0800 Subject: [PATCH 3743/4971] Update redundant-connection.py --- Python/redundant-connection.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/redundant-connection.py b/Python/redundant-connection.py index 24a49c007..c26efe3dd 100644 --- a/Python/redundant-connection.py +++ b/Python/redundant-connection.py @@ -26,8 +26,8 @@ # / \\ # 2 3 # Note: -# The size of the input 2D-array will be between 1 and 1000. -# Every integer represented in the 2D-array will be between 1 and 2000. +# The size of the input 2D-array will be between 3 and 1000. +# Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array. class UnionFind(object): def __init__(self, n): @@ -54,7 +54,7 @@ def findRedundantConnection(self, edges): :type edges: List[List[int]] :rtype: List[int] """ - union_find = UnionFind(2000) + union_find = UnionFind(len(edges)+1) for edge in edges: if not union_find.union_set(*edge): return edge From c54d1a1ee457792e8bade47b1f94a433a066192d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Sep 2017 23:35:17 +0800 Subject: [PATCH 3744/4971] Update redundant-connection-ii.py --- Python/redundant-connection-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/redundant-connection-ii.py b/Python/redundant-connection-ii.py index ce678b692..035bf0879 100644 --- a/Python/redundant-connection-ii.py +++ b/Python/redundant-connection-ii.py @@ -63,7 +63,7 @@ def findRedundantDirectedConnection(self, edges): :type edges: List[List[int]] :rtype: List[int] """ - union_find = UnionFind(1001) + union_find = UnionFind(len(edges)+1) for edge in edges: if not union_find.union_set(*edge): return edge From 6717e5758b77b590d8aad93f8afb827a7291f29f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Sep 2017 23:37:15 +0800 Subject: [PATCH 3745/4971] Create redundant-connection-ii.cpp --- C++/redundant-connection-ii.cpp | 48 +++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 C++/redundant-connection-ii.cpp diff --git a/C++/redundant-connection-ii.cpp b/C++/redundant-connection-ii.cpp new file mode 100644 index 000000000..ef039fcaa --- /dev/null +++ b/C++/redundant-connection-ii.cpp @@ -0,0 +1,48 @@ +// Time: O(nlog*n) ~= O(n), n is the length of the positions +// Space: O(n) + +class Solution { +public: + vector findRedundantDirectedConnection(vector>& edges) { + UnionFind union_find(edges.size() + 1); + for (const auto& edge : edges) { + if (!union_find.union_set(edge[0], edge[1])) { + return edge; + } + } + return {}; + } + +private: + class UnionFind { + public: + UnionFind(const int n) : set_(n), count_(n) { + iota(set_.begin(), set_.end(), 0); + } + + int find_set(const int x) { + if (set_[x] != x) { + set_[x] = find_set(set_[x]); // Path compression. + } + return set_[x]; + } + + bool union_set(const int x, const int y) { + int x_root = find_set(x), y_root = find_set(y); + if (x_root == y_root || y != y_root) { + return false; + } + set_[y_root] = x_root; + --count_; + return true; + } + + int length() const { + return count_; + } + + private: + vector set_; + int count_; + }; +}; From 59e9446f3cf9b0a558d25d521773eb21447b15ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Sep 2017 23:37:55 +0800 Subject: [PATCH 3746/4971] Update redundant-connection.cpp --- C++/redundant-connection.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/redundant-connection.cpp b/C++/redundant-connection.cpp index 59967d606..76f921a91 100644 --- a/C++/redundant-connection.cpp +++ b/C++/redundant-connection.cpp @@ -4,7 +4,7 @@ class Solution { public: vector findRedundantConnection(vector>& edges) { - UnionFind union_find(2000); + UnionFind union_find(edges.size() + 1); for (const auto& edge : edges) { if (!union_find.union_set(edge[0], edge[1])) { return edge; From dcaf920d7fea2405df42d907aa3f2150ca466233 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Sep 2017 23:39:03 +0800 Subject: [PATCH 3747/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 372659b31..f621e5d2a 100644 --- a/README.md +++ b/README.md @@ -246,6 +246,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 663 | [Equal Tree Partition](https://leetcode.com/problems/strange-printer/) | [C++](./C++/equal-tree-partition.cpp) [Python](./Python/equal-tree-partition.py) | _O(n)_ | _O(n)_ | Medium | 📖 | Hash 677 | [Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/) | [C++](./C++/map-sum-pairs.cpp) [Python](./Python/map-sum-pairs.py) | _O(n)_ | _O(t)_ | Medium || Trie 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/) | [C++](./C++/redundant-connection.cpp) [Python](./Python/redundant-connection.py) | _O(n)_ | _O(n)_ | Medium || Union Find +685 | [Redundant Connection II](https://leetcode.com/problems/redundant-connection-ii/) | [C++](./C++/redundant-connection-ii.cpp) [Python](./Python/redundant-connection-ii.py) | _O(n)_ | _O(n)_ | Hard || Union Find ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From c5183d51dd723c44d0f031e35e327d0401e6f385 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Sep 2017 23:39:37 +0800 Subject: [PATCH 3748/4971] Update redundant-connection-ii.py --- Python/redundant-connection-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/redundant-connection-ii.py b/Python/redundant-connection-ii.py index 035bf0879..39f86635f 100644 --- a/Python/redundant-connection-ii.py +++ b/Python/redundant-connection-ii.py @@ -50,7 +50,7 @@ def find_set(self, x): def union_set(self, x, y): x_root, y_root = map(self.find_set, (x, y)) if x_root == y_root or \ - y != y_root: # more the one father + y != y_root: # already has a father return False self.set[y_root] = x_root self.count -= 1 From df48e947dc8bdefa17c6309bdb445f9ca24f594e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Sep 2017 23:23:01 +0800 Subject: [PATCH 3749/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index f621e5d2a..8056326c0 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| +643 | [Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/) | [C++](./C++/maximum-average-subarray-i.cpp) [Python](./Python/maximum-average-subarray-i.py) | _O(n)_ | _O(1)_ | Easy || Math +644 | [Maximum Average Subarray II](https://leetcode.com/problems/maximum-average-subarray-ii/) | [C++](./C++/maximum-average-subarray-ii.cpp) [Python](./Python/maximum-average-subarray-ii.py) | _O(n)_ | _O(n)_ | Hard | 📖 | Math 661| [Image Smoother](https://leetcode.com/problems/image-smoother/) | [C++](./C++/image-smoother.cpp) [Python](./Python/image-smoother.py) | _O(m * n)_ | _O(1)_ | Easy ||| 665| [Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/) | [C++](./C++/non-decreasing-array.cpp) [Python](./Python/non-decreasing-array.py) | _O(n)_ | _O(1)_ | Easy ||| 667| [Beautiful Arrangement II](https://leetcode.com/problems/beautiful-arrangement-ii/) | [C++](./C++/beautiful-arrangement-ii.cpp) [Python](./Python/beautiful-arrangement-ii.py) | _O(n)_ | _O(1)_ | Medium ||| @@ -331,6 +333,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +640| [Solve the Equation](https://leetcode.com/problems/solve-the-equation/) | [C++](./C++/solve-the-equation.cpp) [Python](./Python/solve-the-equation.py) | _O(n)_ | _O(n)_ | Medium || | 651 | [4 Keys Keyboard](https://leetcode.com/problems/4-keys-keyboard/) | [C++](./C++/4-keys-keyboard.cpp) [Python](./Python/4-keys-keyboard.py) | _O(1)_ | _O(1)_ | Medium |📖| Math, DP | 660 | [Remove 9](https://leetcode.com/problems/remove-9/) | [C++](./C++/remove-9.cpp) [Python](./Python/remove-9.py) | _O(logn)_ | _O(1)_ | Hard |📖|| 672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/) | [C++](./C++/bulb-switcher-ii.cpp) [Python](./Python/bulb-switcher-ii.py) | _O(1)_ | _O(1)_ | Medium ||| @@ -619,6 +622,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_ | Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | +642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From a26b005c410d75abb09810331196e2cdd8f80c80 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Sep 2017 23:23:35 +0800 Subject: [PATCH 3750/4971] Update maximum-average-subarray-ii.py --- Python/maximum-average-subarray-ii.py | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/Python/maximum-average-subarray-ii.py b/Python/maximum-average-subarray-ii.py index e068afebb..1c2ae6a50 100644 --- a/Python/maximum-average-subarray-ii.py +++ b/Python/maximum-average-subarray-ii.py @@ -1,22 +1,6 @@ # Time: O(n) # Space: O(n) -# Given an array consisting of n integers, find the contiguous subarray -# whose length is greater than or equal to k that has the maximum average value. -# And you need to output the maximum average value. -# -# Example 1: -# Input: [1,12,-5,-6,50,3], k = 4 -# Output: 12.75 -# Explanation: -# when length is 5, maximum average value is 10.8, -# when length is 6, maximum average value is 9.16667. -# Thus return 12.75. -# Note: -# 1 <= k <= n <= 10,000. -# Elements of the given array will be in range [-10,000, 10,000]. -# The answer with the calculation error less than 1e-5 will be accepted. - class Solution(object): def findMaxAverage(self, nums, k): """ From 5466ef90ed680c3008657196050e051c5e3f9907 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 Sep 2017 01:04:03 +0800 Subject: [PATCH 3751/4971] Create coin-change-2.cpp --- C++/coin-change-2.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 C++/coin-change-2.cpp diff --git a/C++/coin-change-2.cpp b/C++/coin-change-2.cpp new file mode 100644 index 000000000..8f839dab6 --- /dev/null +++ b/C++/coin-change-2.cpp @@ -0,0 +1,16 @@ +// Time: O(n * m) +// Space: O(m) + +class Solution { +public: + int change(int amount, vector& coins) { + vector dp(amount + 1); + dp[0] = 1; + for (const auto& coin : coins) { + for(int i = coin; i <= amount; ++i) { + dp[i] += dp[i - coin]; + } + } + return dp[amount]; + } +}; From b6475fb1d7c6f02bd40fc8e0ad0cc158d309fc66 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 Sep 2017 01:05:37 +0800 Subject: [PATCH 3752/4971] Update coin-change-2.cpp --- C++/coin-change-2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/coin-change-2.cpp b/C++/coin-change-2.cpp index 8f839dab6..a35a5c633 100644 --- a/C++/coin-change-2.cpp +++ b/C++/coin-change-2.cpp @@ -7,7 +7,7 @@ class Solution { vector dp(amount + 1); dp[0] = 1; for (const auto& coin : coins) { - for(int i = coin; i <= amount; ++i) { + for (int i = coin; i <= amount; ++i) { dp[i] += dp[i - coin]; } } From c35e1e04119de315560ec663fe5f56d918f0ed50 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 Sep 2017 01:07:27 +0800 Subject: [PATCH 3753/4971] Create coin-change-2.py --- Python/coin-change-2.py | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/coin-change-2.py diff --git a/Python/coin-change-2.py b/Python/coin-change-2.py new file mode 100644 index 000000000..d65707685 --- /dev/null +++ b/Python/coin-change-2.py @@ -0,0 +1,45 @@ +# Time: O(n * m) +# Space: O(m) + +# You are given coins of different denominations and a total amount of money. +# Write a function to compute the number of combinations that make up that amount. +# You may assume that you have infinite number of each kind of coin. +# +# Note: You can assume that +# +# 0 <= amount <= 5000 +# 1 <= coin <= 5000 +# the number of coins is less than 500 +# the answer is guaranteed to fit into signed 32-bit integer +# Example 1: +# +# Input: amount = 5, coins = [1, 2, 5] +# Output: 4 +# Explanation: there are four ways to make up the amount: +# 5=5 +# 5=2+2+1 +# 5=2+1+1+1 +# 5=1+1+1+1+1 +# Example 2: +# +# Input: amount = 3, coins = [2] +# Output: 0 +# Explanation: the amount of 3 cannot be made up just with coins of 2. +# Example 3: +# +# Input: amount = 10, coins = [10] +# Output: 1 + +class Solution(object): + def change(self, amount, coins): + """ + :type amount: int + :type coins: List[int] + :rtype: int + """ + dp = [0] * (amount+1) + dp[0] = 1; + for coin in coins: + for i in xrange(coin, amount+1): + dp[i] += dp[i-coin] + return dp[amount] From 687753f650daa1e79e85e991684779a66383c6fa Mon Sep 17 00:00:00 2001 From: Swaroop Gadiyaram Date: Thu, 28 Sep 2017 15:33:23 -0700 Subject: [PATCH 3754/4971] Update rotate-array.py Added a new method --- Python/rotate-array.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Python/rotate-array.py b/Python/rotate-array.py index f4df62d44..77db470e8 100644 --- a/Python/rotate-array.py +++ b/Python/rotate-array.py @@ -60,6 +60,28 @@ def apply_cycle_permutation(self, k, offset, cycle_len, nums): nums[(offset + i * k) % len(nums)], tmp = tmp, nums[(offset + i * k) % len(nums)] nums[offset] = tmp + class Solution3: + """ + :type nums: List[int] + :type k: int + :rtype: void Do not return anything, modify nums in-place instead. + """ + + def rotate(self, nums, k): + count = 0 + start = 0 + while count < len(nums): + curr = start + prev = nums[curr] + while True: + idx = (curr + k) % len(nums) + nums[idx], prev = prev, nums[idx] + curr = idx + count += 1 + if start == curr: + break + start += 1 + if __name__ == '__main__': nums = [1, 2, 3, 4, 5, 6, 7] From 3d0d8a203b5e398f7e83f61be80fc7c7048c20cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 29 Sep 2017 21:28:47 +0800 Subject: [PATCH 3755/4971] Update rotate-array.py --- Python/rotate-array.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/rotate-array.py b/Python/rotate-array.py index 77db470e8..1139d6a33 100644 --- a/Python/rotate-array.py +++ b/Python/rotate-array.py @@ -60,7 +60,8 @@ def apply_cycle_permutation(self, k, offset, cycle_len, nums): nums[(offset + i * k) % len(nums)], tmp = tmp, nums[(offset + i * k) % len(nums)] nums[offset] = tmp - class Solution3: + +class Solution3: """ :type nums: List[int] :type k: int From d2b7846990bb9c88523a9b4eae83df1ec86a21ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Sep 2017 23:24:16 +0800 Subject: [PATCH 3756/4971] Create employee-importance.cpp --- C++/employee-importance.cpp | 54 +++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 C++/employee-importance.cpp diff --git a/C++/employee-importance.cpp b/C++/employee-importance.cpp new file mode 100644 index 000000000..85c48ae24 --- /dev/null +++ b/C++/employee-importance.cpp @@ -0,0 +1,54 @@ +// Time: O(n) +// Space: O(h) + +/* +// Employee info +class Employee { +public: + // It's the unique ID of each node. + // unique id of this employee + int id; + // the importance value of this employee + int importance; + // the id of direct subordinates + vector subordinates; +}; +*/ +class Solution { +public: + int getImportance(vector employees, int id) { + return dfs(employees, id); + } + +private: + int dfs(const vector& employees, const int id) { + if (!employees[id - 1]) { + return 0; + } + auto result = employees[id - 1]->importance; + for (const auto& id : employees[id - 1]->subordinates) { + result += getImportance(employees, id); + } + return result; + } +}; + +// Time: O(n) +// Space: O(w), w is the max number of nodes in the levels of the tree +class Solution2 { +public: + int getImportance(vector employees, int id) { + auto result = 0; + queue q; + q.emplace(id); + while (!q.empty()) { + const auto curr = q.front(); q.pop(); + const auto& employee = employees[curr - 1]; + result += employee->importance; + for (const auto& id : employee->subordinates) { + q.emplace(id); + } + } + return result; + } +}; From 1efa9cc368aeff7e41a7962c7a16d9f094a3d6bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Sep 2017 23:30:15 +0800 Subject: [PATCH 3757/4971] Create employee-importance.py --- Python/employee-importance.py | 72 +++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Python/employee-importance.py diff --git a/Python/employee-importance.py b/Python/employee-importance.py new file mode 100644 index 000000000..92bab697b --- /dev/null +++ b/Python/employee-importance.py @@ -0,0 +1,72 @@ +# Time: O(n) +# Space: O(h) + +# You are given a data structure of employee information, +# which includes the employee's unique id, his importance value and his direct subordinates' id. +# +# For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. +# They have importance value 15, 10 and 5, respectively. +# Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], +# and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, +# the relationship is not direct. +# +# Now given the employee information of a company, +# and an employee id, you need to return the total importance value of this employee and all his subordinates. +# +# Example 1: +# Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1 +# Output: 11 +# +# Explanation: +# Employee 1 has importance value 5, and he has two direct subordinates: +# employee 2 and employee 3. They both have importance value 3. +# So the total importance value of employee 1 is 5 + 3 + 3 = 11. +# +# Note: +# One employee has at most one direct leader and may have several subordinates. +# The maximum number of employees won't exceed 2000. + +""" +# Employee info +class Employee(object): + def __init__(self, id, importance, subordinates): + # It's the unique id of each node. + # unique id of this employee + self.id = id + # the importance value of this employee + self.importance = importance + # the id of direct subordinates + self.subordinates = subordinates +""" +class Solution(object): + def getImportance(self, employees, id): + """ + :type employees: Employee + :type id: int + :rtype: int + """ + if employees[id-1] is None: + return 0 + result = employees[id-1].importance + for id in employees[id-1].subordinates: + result += self.getImportance(employees, id) + return result + + +# Time: O(n) +# Space: O(w), w is the max number of nodes in the levels of the tree +class Solution2(object): + def getImportance(self, employees, id): + """ + :type employees: Employee + :type id: int + :rtype: int + """ + result, q = 0, collections.deque([id]) + while q: + curr = q.popleft() + employee = employees[curr-1] + result += employee.importance; + for id in employee.subordinates: + q.append(id) + return result From 7e3696917b43d38159117b44e80d3cb5500a200d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Sep 2017 23:32:26 +0800 Subject: [PATCH 3758/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 8056326c0..41c776de5 100644 --- a/README.md +++ b/README.md @@ -493,6 +493,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || 440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn)_ | _O(logn)_ | Hard || 464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || +690| [Employee Importance](https://leetcode.com/problems/employee-importance/) | [C++](./C++/employee-importance.cpp) [Python](./Python/employee-importance) | _O(n)_ | _O(h)_ | Easy || DFS, BFS ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 13a4af37a35cbf35e634bee141b8c9bd8d66b1bf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Sep 2017 23:33:07 +0800 Subject: [PATCH 3759/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 41c776de5..32c4c8d6a 100644 --- a/README.md +++ b/README.md @@ -493,7 +493,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || 440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn)_ | _O(logn)_ | Hard || 464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || -690| [Employee Importance](https://leetcode.com/problems/employee-importance/) | [C++](./C++/employee-importance.cpp) [Python](./Python/employee-importance) | _O(n)_ | _O(h)_ | Easy || DFS, BFS +690| [Employee Importance](https://leetcode.com/problems/employee-importance/) | [C++](./C++/employee-importance.cpp) [Python](./Python/employee-importance.py) | _O(n)_ | _O(h)_ | Easy || DFS, BFS ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From a31dbb69aef7774a1a6f8a3d0fc38d51d17259e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 17:37:13 +0800 Subject: [PATCH 3760/4971] Create maximum-sum-of-3-non-overlapping-subarrays.cpp --- ...mum-sum-of-3-non-overlapping-subarrays.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/maximum-sum-of-3-non-overlapping-subarrays.cpp diff --git a/C++/maximum-sum-of-3-non-overlapping-subarrays.cpp b/C++/maximum-sum-of-3-non-overlapping-subarrays.cpp new file mode 100644 index 000000000..aedc67d4b --- /dev/null +++ b/C++/maximum-sum-of-3-non-overlapping-subarrays.cpp @@ -0,0 +1,46 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector maxSumOfThreeSubarrays(vector& nums, int k) { + const auto n = nums.size(); + vector accu = {0}; + for (const auto& num : nums) { + accu.emplace_back(accu.back() + num); + } + + vector left_pos(n); + for (int i = k, total = accu[k] - accu[0]; i < n; ++i) { + if (accu[i + 1] - accu[i + 1 - k] > total) { + left_pos[i] = i + 1 - k; + total = accu[i + 1] - accu[i + 1 - k]; + } else { + left_pos[i] = left_pos[i - 1]; + } + } + + vector right_pos(n, n - k); + for (int i = n - k - 1, total = accu[n] - accu[n - k]; i >= 0; --i) { + if (accu[i + k] - accu[i] > total) { + right_pos[i] = i; + total = accu[i + k] - accu[i]; + } else { + right_pos[i] = right_pos[i + 1]; + } + } + + vector result(3); + for (int i = k, max_sum = 0; i <= n - 2 * k; ++i) { + auto left = left_pos[i - 1], right = right_pos[i + k]; + auto total = (accu[i + k] - accu[i]) + + (accu[left + k] - accu[left]) + + (accu[right + k] - accu[right]); + if (total > max_sum) { + max_sum = total; + result = {left, i, right}; + } + } + return result; + } +}; From 352bf54819603c3aa61298195710deb816bfb526 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 17:43:58 +0800 Subject: [PATCH 3761/4971] Create maximum-sum-of-3-non-overlapping-subarrays.py --- ...imum-sum-of-3-non-overlapping-subarrays.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/maximum-sum-of-3-non-overlapping-subarrays.py diff --git a/Python/maximum-sum-of-3-non-overlapping-subarrays.py b/Python/maximum-sum-of-3-non-overlapping-subarrays.py new file mode 100644 index 000000000..0a35b5ebf --- /dev/null +++ b/Python/maximum-sum-of-3-non-overlapping-subarrays.py @@ -0,0 +1,43 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def maxSumOfThreeSubarrays(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + n = len(nums) + accu = [0] + for num in nums: + accu.append(accu[-1]+num) + + left_pos = [0] * n + total = accu[k]-accu[0] + for i in xrange(k, n): + if accu[i+1] - accu[i+1-k] > total: + left_pos[i] = i+1-k + total = accu[i+1]-accu[i+1-k] + else: + left_pos[i] = left_pos[i-1] + + right_pos = [n-k] * n + total = accu[n]-accu[n-k] + for i in reversed(xrange(n-k)): + if accu[i+k]-accu[i] > total: + right_pos[i] = i; + total = accu[i+k]-accu[i] + else: + right_pos[i] = right_pos[i+1] + + result, max_sum = [], 0 + for i in xrange(k, n-2*k+1): + left, right = left_pos[i-1], right_pos[i+k] + total = (accu[i+k]-accu[i]) + \ + (accu[left+k]-accu[left]) + \ + (accu[right+k]-accu[right]) + if total > max_sum: + max_sum = total + result = [left, i, right] + return result From 54cfb5c02282338129025231ff94b0ff5a5daceb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 18:15:14 +0800 Subject: [PATCH 3762/4971] Create knight-probability-in-chessboard.cpp --- C++/knight-probability-in-chessboard.cpp | 27 ++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/knight-probability-in-chessboard.cpp diff --git a/C++/knight-probability-in-chessboard.cpp b/C++/knight-probability-in-chessboard.cpp new file mode 100644 index 000000000..c869bb871 --- /dev/null +++ b/C++/knight-probability-in-chessboard.cpp @@ -0,0 +1,27 @@ +// Time: O(k * n^2) +// Space: O(n^2) + +class Solution { +public: + double knightProbability(int N, int K, int r, int c) { + static const vector> directions = + {{ 1, 2}, { 1, -2}, { 2, 1}, { 2, -1}, + {-1, 2}, {-1, -2}, {-2, 1}, {-2, -1}}; + vector>> dp(2, vector>(N, vector(N, 1.0l))); + for (int step = 1; step <= K; ++step) { + for(int i = 0; i < N; ++i) { + for(int j = 0; j < N; ++j) { + dp[step % 2][i][j] = 0; + for (const auto& direction : directions) { + auto r = i + direction.first; + auto c = j + direction.second; + if (0 <= c && c < N && 0 <= r && r < N) { + dp[step % 2][i][j] += 0.125 * dp[(step - 1) % 2][r][c]; + } + } + } + } + } + return dp[K % 2][r][c]; + } +}; From 35e115379a61202b0a661b016ba435316a26a30c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 18:17:48 +0800 Subject: [PATCH 3763/4971] Update knight-probability-in-chessboard.cpp --- C++/knight-probability-in-chessboard.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/knight-probability-in-chessboard.cpp b/C++/knight-probability-in-chessboard.cpp index c869bb871..dac4313d4 100644 --- a/C++/knight-probability-in-chessboard.cpp +++ b/C++/knight-probability-in-chessboard.cpp @@ -9,8 +9,8 @@ class Solution { {-1, 2}, {-1, -2}, {-2, 1}, {-2, -1}}; vector>> dp(2, vector>(N, vector(N, 1.0l))); for (int step = 1; step <= K; ++step) { - for(int i = 0; i < N; ++i) { - for(int j = 0; j < N; ++j) { + for (int i = 0; i < N; ++i) { + for (int j = 0; j < N; ++j) { dp[step % 2][i][j] = 0; for (const auto& direction : directions) { auto r = i + direction.first; From 80993e37d0c63d851e4f9f3d34d28a7c02706841 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 18:25:07 +0800 Subject: [PATCH 3764/4971] Update knight-probability-in-chessboard.cpp --- C++/knight-probability-in-chessboard.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/knight-probability-in-chessboard.cpp b/C++/knight-probability-in-chessboard.cpp index dac4313d4..8d95b4ed9 100644 --- a/C++/knight-probability-in-chessboard.cpp +++ b/C++/knight-probability-in-chessboard.cpp @@ -13,10 +13,10 @@ class Solution { for (int j = 0; j < N; ++j) { dp[step % 2][i][j] = 0; for (const auto& direction : directions) { - auto r = i + direction.first; - auto c = j + direction.second; - if (0 <= c && c < N && 0 <= r && r < N) { - dp[step % 2][i][j] += 0.125 * dp[(step - 1) % 2][r][c]; + auto rr = i + direction.first; + auto cc = j + direction.second; + if (0 <= cc && cc < N && 0 <= rr && rr < N) { + dp[step % 2][i][j] += 0.125l * dp[(step - 1) % 2][rr][cc]; } } } From 5198bc973760bd2203661ff1b574c0706a37ee62 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 18:26:03 +0800 Subject: [PATCH 3765/4971] Create knight-probability-in-chessboard.py --- Python/knight-probability-in-chessboard.py | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/knight-probability-in-chessboard.py diff --git a/Python/knight-probability-in-chessboard.py b/Python/knight-probability-in-chessboard.py new file mode 100644 index 000000000..5a2f78d95 --- /dev/null +++ b/Python/knight-probability-in-chessboard.py @@ -0,0 +1,26 @@ +# Time: O(k * n^2) +# Space: O(n^2) + +class Solution(object): + def knightProbability(self, N, K, r, c): + """ + :type N: int + :type K: int + :type r: int + :type c: int + :rtype: float + """ + directions = \ + [[ 1, 2], [ 1, -2], [ 2, 1], [ 2, -1], \ + [-1, 2], [-1, -2], [-2, 1], [-2, -1]]; + dp = [[[1 for _ in xrange(N)] for _ in xrange(N)] for _ in xrange(2)] + for step in xrange(1, K+1): + for i in xrange(N): + for j in xrange(N): + dp[step%2][i][j] = 0 + for direction in directions: + rr, cc = i+direction[0], j+direction[1] + if 0 <= cc < N and 0 <= rr < N: + dp[step%2][i][j] += 0.125 * dp[(step-1)%2][rr][cc]; + + return dp[K%2][r][c] From aebcd442507ad13b0771562e8f3425afdcc299c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 18:36:44 +0800 Subject: [PATCH 3766/4971] Create longest-univalue-path.cpp --- C++/longest-univalue-path.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/longest-univalue-path.cpp diff --git a/C++/longest-univalue-path.cpp b/C++/longest-univalue-path.cpp new file mode 100644 index 000000000..a4b652a43 --- /dev/null +++ b/C++/longest-univalue-path.cpp @@ -0,0 +1,33 @@ +// 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 longestUnivaluePath(TreeNode* root) { + auto result = 0; + dfs(root, &result); + return result; + } + +private: + int dfs(TreeNode *node, int *result) { + if (!node) { + return 0; + } + auto left = dfs(node->left, result); + auto right = dfs(node->right, result); + left = node->left && node->val == node->left->val ? left + 1 : 0; + right = node->right && node->val == node->right->val ? right + 1 : 0; + *result = max(*result, left + right); + return max(left, right); + } +}; From f2c9caa8409908f79273889899e6e4c3134e8a7d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 18:37:45 +0800 Subject: [PATCH 3767/4971] Create longest-univalue-path.py --- Python/longest-univalue-path.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Python/longest-univalue-path.py diff --git a/Python/longest-univalue-path.py b/Python/longest-univalue-path.py new file mode 100644 index 000000000..468e477c5 --- /dev/null +++ b/Python/longest-univalue-path.py @@ -0,0 +1,28 @@ +# 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 longestUnivaluePath(self, root): + """ + :type root: TreeNode + :rtype: int + """ + result = [0] + def dfs(node): + if not node: + return 0 + left, right = dfs(node.left), dfs(node.right) + left = (left+1) if node.left and node.left.val == node.val else 0 + right = (right+1) if node.right and node.right.val == node.val else 0 + result[0] = max(result[0], left+right) + return max(left, right) + + dfs(root) + return result[0] From 46cfc50bd839bd336bf834753b055f1ccb200d58 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 18:51:19 +0800 Subject: [PATCH 3768/4971] Create repeated-string-match.cpp --- "C++/repeated-string-match\b.cpp" | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 "C++/repeated-string-match\b.cpp" diff --git "a/C++/repeated-string-match\b.cpp" "b/C++/repeated-string-match\b.cpp" new file mode 100644 index 000000000..1ddfd1df4 --- /dev/null +++ "b/C++/repeated-string-match\b.cpp" @@ -0,0 +1,15 @@ +// Time: O(n * m) +// Space: O(1) + +class Solution { +public: + int repeatedStringMatch(string A, string B) { + for (int i = 0, j = 0; i < A.length(); ++i) { + for (j = 0; j < B.length() && A[(i + j) % A.length()] == B[j]; ++j); + if (j == B.length()) { + return (i + j + A.length() - 1) / A.length(); + } + } + return -1; + } +}; From 6c0fb7ddba8bc1263acd6476a654df2c42cfcb50 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 19:44:06 +0800 Subject: [PATCH 3769/4971] Update repeated-string-match.cpp --- "C++/repeated-string-match\b.cpp" | 61 ++++++++++++++++++++++++++++--- 1 file changed, 56 insertions(+), 5 deletions(-) diff --git "a/C++/repeated-string-match\b.cpp" "b/C++/repeated-string-match\b.cpp" index 1ddfd1df4..0068056d5 100644 --- "a/C++/repeated-string-match\b.cpp" +++ "b/C++/repeated-string-match\b.cpp" @@ -1,15 +1,66 @@ -// Time: O(n * m) +// Time: O(n + m) // Space: O(1) +// Rabin-Karp (rolling hash) class Solution { public: int repeatedStringMatch(string A, string B) { - for (int i = 0, j = 0; i < A.length(); ++i) { - for (j = 0; j < B.length() && A[(i + j) % A.length()] == B[j]; ++j); - if (j == B.length()) { - return (i + j + A.length() - 1) / A.length(); + static const uint64_t M = 1000000007; + static const uint64_t p = 113; + static const uint64_t p_inv = pow(p, M - 2, M); + + const auto q = (B.length() + A.length() - 1) / A.length(); + + uint64_t b_hash = 0, power = 1; + for (int i = 0; i < B.length(); ++i) { + b_hash += power * B[i]; + b_hash %= M; + power = (power * p) % M; + } + + uint64_t a_hash = 0; power = 1; + for (int i = 0; i < B.length(); ++i) { + a_hash += power * A[i % A.length()]; + a_hash %= M; + power = (power * p) % M; + } + if (a_hash == b_hash && check(0, A, B)) { + return q; + } + + power = (power * p_inv) % M; + for (int i = B.length(); i < (q + 1) * A.length(); ++i) { + a_hash -= A[(i - B.length()) % A.length()]; + a_hash *= p_inv; + a_hash += power * A[i % A.length()]; + a_hash %= M; + if (a_hash == b_hash && check(i - B.length() + 1, A, B)) { + return i < q * A.length() ? q : q + 1; } } return -1; } + +private: + bool check(int index, const string& A, const string& B) { + for (int i = 0; i < B.length(); ++i) { + if (A[(i + index) % A.length()] != B[i]) { + return false; + } + } + return true; + } + + uint64_t pow(uint64_t a,uint64_t b, uint64_t m) { + a %= m; + uint64_t result = 1; + while (b) { + if (b & 1) { + result = (result * a) % m; + } + a = (a * a) % m; + b >>= 1; + } + return result; + } }; From 9b68e3c5f5af5a8fb987b5cf86199d48f0ea1f44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 19:52:20 +0800 Subject: [PATCH 3770/4971] Update repeated-string-match.cpp --- "C++/repeated-string-match\b.cpp" | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git "a/C++/repeated-string-match\b.cpp" "b/C++/repeated-string-match\b.cpp" index 0068056d5..3f4b8ef73 100644 --- "a/C++/repeated-string-match\b.cpp" +++ "b/C++/repeated-string-match\b.cpp" @@ -1,7 +1,7 @@ // Time: O(n + m) // Space: O(1) -// Rabin-Karp (rolling hash) +// Rabin-Karp Algorithm (rolling hash) class Solution { public: int repeatedStringMatch(string A, string B) { From 1fb32ebdf33b47a6e4bca6681b8d05689226daa9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 19:54:48 +0800 Subject: [PATCH 3771/4971] Create repeated-string-match.py --- Python/repeated-string-match.py | 53 +++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/repeated-string-match.py diff --git a/Python/repeated-string-match.py b/Python/repeated-string-match.py new file mode 100644 index 000000000..7b17def8c --- /dev/null +++ b/Python/repeated-string-match.py @@ -0,0 +1,53 @@ +# Time: O(n + m) +# Space: O(1) + +# Given two strings A and B, find the minimum number of times A has to be repeated +# such that B is a substring of it. If no such solution, return -1. +# +# For example, with A = "abcd" and B = "cdabcdab". +# +# Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; +# and B is not a substring of A repeated two times ("abcdabcd"). +# +# Note: +# The length of A and B will be between 1 and 10000. + +# Rabin-Karp Algorithm (rolling hash) +class Solution(object): + def repeatedStringMatch(self, A, B): + """ + :type A: str + :type B: str + :rtype: int + """ + def check(index): + return all(A[(i+index) % len(A)] == c + for i, c in enumerate(B)) + + M, p = 10**9+7, 113 + p_inv = pow(p, M-2, M) + q = (len(B)+len(A)-1) // len(A) + + b_hash, power = 0, 1 + for c in B: + b_hash += power * ord(c) + b_hash %= M + power = (power*p) % M + + a_hash, power = 0, 1 + for i in xrange(len(B)): + a_hash += power * ord(A[i%len(A)]) + a_hash %= M + power = (power*p) % M + + if a_hash == b_hash and check(0): return q + + power = (power*p_inv) % M + for i in xrange(len(B), (q+1)*len(A)): + a_hash = (a_hash-ord(A[(i-len(B))%len(A)])) * p_inv + a_hash += power * ord(A[i%len(A)]) + a_hash %= M + if a_hash == b_hash and check(i-len(B)+1): + return q if i < q*len(A) else q+1 + + return -1 From edc0554e522a8952f5d23fbd43d61e34326326ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 19:56:39 +0800 Subject: [PATCH 3772/4971] Update longest-univalue-path.py --- Python/longest-univalue-path.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/Python/longest-univalue-path.py b/Python/longest-univalue-path.py index 468e477c5..795f4d485 100644 --- a/Python/longest-univalue-path.py +++ b/Python/longest-univalue-path.py @@ -1,6 +1,35 @@ # Time: O(n) # Space: O(h) +# Given a binary tree, find the length of the longest path +# where each node in the path has the same value. This path may or may not pass through the root. +# +# Note: The length of path between two nodes is represented by the number of edges between them. +# +# Example 1: +# Input: +# +# 5 +# / \ +# 4 5 +# / \ \ +# 1 1 5 +# Output: +# 2 +# +# Example 2: +# Input: +# +# 1 +# / \ +# 4 5 +# / \ \ +# 4 4 5 +# Output: +# 2 +# +# Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000. + # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): From 6f7afdba708bc311b21bb743caf02b275ee5c9e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 19:58:34 +0800 Subject: [PATCH 3773/4971] Update knight-probability-in-chessboard.py --- Python/knight-probability-in-chessboard.py | 28 +++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/Python/knight-probability-in-chessboard.py b/Python/knight-probability-in-chessboard.py index 5a2f78d95..cb87d07ed 100644 --- a/Python/knight-probability-in-chessboard.py +++ b/Python/knight-probability-in-chessboard.py @@ -1,6 +1,32 @@ # Time: O(k * n^2) # Space: O(n^2) - + +# On an NxN chessboard, a knight starts at the r-th row and c-th column and +# attempts to make exactly K moves. The rows and columns are 0 indexed, +# so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1). +# +# A chess knight has 8 possible moves it can make, as illustrated below. +# Each move is two squares in a cardinal direction, then one square in an orthogonal direction. +# +# Each time the knight is to move, it chooses one of eight possible moves uniformly +# at random (even if the piece would go off the chessboard) and moves there. +# +# The knight continues moving until it has made exactly K moves or has moved off the chessboard. +# Return the probability that the knight remains on the board after it has stopped moving. +# +# Example: +# Input: 3, 2, 0, 0 +# Output: 0.0625 +# +# Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. +# From each of those positions, there are also two moves that will keep the knight on the board. +# The total probability the knight stays on the board is 0.0625. +# +# Note: +# N will be between 1 and 25. +# K will be between 0 and 100. +# The knight always initially starts on the board. + class Solution(object): def knightProbability(self, N, K, r, c): """ From e977e93c28dac148301b88864a93506b26a5ca35 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 20:01:21 +0800 Subject: [PATCH 3774/4971] Update maximum-sum-of-3-non-overlapping-subarrays.py --- ...imum-sum-of-3-non-overlapping-subarrays.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Python/maximum-sum-of-3-non-overlapping-subarrays.py b/Python/maximum-sum-of-3-non-overlapping-subarrays.py index 0a35b5ebf..19bfafd14 100644 --- a/Python/maximum-sum-of-3-non-overlapping-subarrays.py +++ b/Python/maximum-sum-of-3-non-overlapping-subarrays.py @@ -1,6 +1,25 @@ # Time: O(n) # Space: O(n) +# In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum. +# +# Each subarray will be of size k, and we want to maximize the sum of all 3*k entries. +# +# Return the result as a list of indices representing the starting position of each interval (0-indexed). +# If there are multiple answers, return the lexicographically smallest one. +# +# Example: +# Input: [1,2,1,2,6,7,5,1], 2 +# Output: [0, 3, 5] + # +# Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5]. +# We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger. +# +# Note: +# - nums.length will be between 1 and 20000. +# - nums[i] will be between 1 and 65535. +# - k will be between 1 and floor(nums.length / 3). + class Solution(object): def maxSumOfThreeSubarrays(self, nums, k): """ From 0be0ea2abe595878f59cf098ebe93651ca221dbf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 20:01:49 +0800 Subject: [PATCH 3775/4971] Update maximum-sum-of-3-non-overlapping-subarrays.py --- Python/maximum-sum-of-3-non-overlapping-subarrays.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximum-sum-of-3-non-overlapping-subarrays.py b/Python/maximum-sum-of-3-non-overlapping-subarrays.py index 19bfafd14..7defc2939 100644 --- a/Python/maximum-sum-of-3-non-overlapping-subarrays.py +++ b/Python/maximum-sum-of-3-non-overlapping-subarrays.py @@ -35,7 +35,7 @@ def maxSumOfThreeSubarrays(self, nums, k): left_pos = [0] * n total = accu[k]-accu[0] for i in xrange(k, n): - if accu[i+1] - accu[i+1-k] > total: + if accu[i+1]-accu[i+1-k] > total: left_pos[i] = i+1-k total = accu[i+1]-accu[i+1-k] else: From 0979eebfd5e1e32ab27c6ed50439b4217c4a51dd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 20:09:14 +0800 Subject: [PATCH 3776/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 32c4c8d6a..9469c7960 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 678| [Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) |[C++](./C++/valid-parenthesis-string.cpp) [Python](./Python/valid-parenthesis-string.py) | _O(n)_ | _O(1)_ | Medium | | 680| [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [C++](./C++/valid-palindrome-ii.cpp) [Python](./Python/valid-palindrome-ii.py) | _O(n)_ | _O(1)_ | Easy || 681| [Next Closest Time](https://leetcode.com/problems/next-closest-time/) | [C++](./C++/next-closest-time.cpp) [Python](./Python/next-closest-time.py) | _O(1)_ | _O(1)_ | Medium || +686 | [Repeated String Match](https://leetcode.com/problems/lrepeated-string-match/) | [C++](./C++/repeated-string-match.cpp) [Python](./Python/repeated-string-match.py) | _O(n + m)_ | _O(1)_ | Easy ||| `Rabin-Karp Algorithm` | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -249,6 +250,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 677 | [Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/) | [C++](./C++/map-sum-pairs.cpp) [Python](./Python/map-sum-pairs.py) | _O(n)_ | _O(t)_ | Medium || Trie 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/) | [C++](./C++/redundant-connection.cpp) [Python](./Python/redundant-connection.py) | _O(n)_ | _O(n)_ | Medium || Union Find 685 | [Redundant Connection II](https://leetcode.com/problems/redundant-connection-ii/) | [C++](./C++/redundant-connection-ii.cpp) [Python](./Python/redundant-connection-ii.py) | _O(n)_ | _O(n)_ | Hard || Union Find +687 | [Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/) | [C++](./C++/longest-univalue-path.cpp) [Python](./Python/longest-univalue-path.py) | _O(n)_ | _O(h)_ | Easy || ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -580,6 +582,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 656 | [Coin Path](https://leetcode.com/problems/coin-path/) | [C++](./C++/coin-path.cpp) [Python](./Python/coin-path.py) | _O(n * B)_ | _O(n)_ | Hard |📖| 664 | [Strange Printer](https://leetcode.com/problems/strange-printer/) | [C++](./C++/strange-printer.cpp) [Python](./Python/strange-printer.py) | _O(n^3)_ | _O(n^2)_ | Hard || 673 | [Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence/) | [C++](./C++/number-of-longest-increasing-subsequence.cpp) [Python](./Python/number-of-longest-increasing-subsequence.py) | _O(n^2)_ | _O(n)_ | Medium || +688 | [Knight Probability in Chessboard](https://leetcode.com/problems/knight-probability-in-chessboard/) | [C++](./C++/knight-probability-in-chessboard.cpp) [Python](./Python/knight-probability-in-chessboard.py) | _O(k * n^2)_ | _O(n^2)_ | Medium || +689 | [Maximum Sum of 3 Non-Overlapping Subarrays](https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/) | [C++](./C++/maximum-sum-of-3-non-overlapping-subarrays.cpp) [Python](./Python/maximum-sum-of-3-non-overlapping-subarrays.py) | _O(n)_ | _O(n)_ | Hard || ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 673a6220b74c82571168106f5ac57674cc03737d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 20:09:43 +0800 Subject: [PATCH 3777/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9469c7960..b1cb3f09f 100644 --- a/README.md +++ b/README.md @@ -160,7 +160,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 678| [Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) |[C++](./C++/valid-parenthesis-string.cpp) [Python](./Python/valid-parenthesis-string.py) | _O(n)_ | _O(1)_ | Medium | | 680| [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [C++](./C++/valid-palindrome-ii.cpp) [Python](./Python/valid-palindrome-ii.py) | _O(n)_ | _O(1)_ | Easy || 681| [Next Closest Time](https://leetcode.com/problems/next-closest-time/) | [C++](./C++/next-closest-time.cpp) [Python](./Python/next-closest-time.py) | _O(1)_ | _O(1)_ | Medium || -686 | [Repeated String Match](https://leetcode.com/problems/lrepeated-string-match/) | [C++](./C++/repeated-string-match.cpp) [Python](./Python/repeated-string-match.py) | _O(n + m)_ | _O(1)_ | Easy ||| `Rabin-Karp Algorithm` | +686 | [Repeated String Match](https://leetcode.com/problems/lrepeated-string-match/) | [C++](./C++/repeated-string-match.cpp) [Python](./Python/repeated-string-match.py) | _O(n + m)_ | _O(1)_ | Easy || `Rabin-Karp Algorithm` | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 0b42c9dcf1fc0a39838f849c8684a373beee9065 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 20:14:23 +0800 Subject: [PATCH 3778/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b1cb3f09f..c4b65c9ce 100644 --- a/README.md +++ b/README.md @@ -160,7 +160,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 678| [Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) |[C++](./C++/valid-parenthesis-string.cpp) [Python](./Python/valid-parenthesis-string.py) | _O(n)_ | _O(1)_ | Medium | | 680| [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [C++](./C++/valid-palindrome-ii.cpp) [Python](./Python/valid-palindrome-ii.py) | _O(n)_ | _O(1)_ | Easy || 681| [Next Closest Time](https://leetcode.com/problems/next-closest-time/) | [C++](./C++/next-closest-time.cpp) [Python](./Python/next-closest-time.py) | _O(1)_ | _O(1)_ | Medium || -686 | [Repeated String Match](https://leetcode.com/problems/lrepeated-string-match/) | [C++](./C++/repeated-string-match.cpp) [Python](./Python/repeated-string-match.py) | _O(n + m)_ | _O(1)_ | Easy || `Rabin-Karp Algorithm` | +686 | [Repeated String Match](https://leetcode.com/problems/repeated-string-match/) | [C++](./C++/repeated-string-match.cpp) [Python](./Python/repeated-string-match.py) | _O(n + m)_ | _O(1)_ | Easy || `Rabin-Karp Algorithm` | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From d58d3a99e7e68cb3f68f26062ce2642c2cf9fbe8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Oct 2017 20:33:18 +0800 Subject: [PATCH 3779/4971] Update repeated-dna-sequences.py --- Python/repeated-dna-sequences.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Python/repeated-dna-sequences.py b/Python/repeated-dna-sequences.py index a4c72fc78..901af0451 100644 --- a/Python/repeated-dna-sequences.py +++ b/Python/repeated-dna-sequences.py @@ -1,6 +1,6 @@ # 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. # @@ -12,17 +12,19 @@ # # Return: # ["AAAAACCCCC", "CCCCCAAAAA"]. -import collections +import collections -class Solution: - # @param s, a string - # @return a list of strings +class Solution(object): def findRepeatedDnaSequences(self, s): + """ + :type s: str + :rtype: List[str] + """ dict, rolling_hash, res = {}, 0, [] for i in xrange(len(s)): - rolling_hash = rolling_hash << 3 & 0x3fffffff | ord(s[i]) & 7 + rolling_hash = ((rolling_hash << 3) & 0x3fffffff) | (ord(s[i]) & 7) if rolling_hash not in dict: dict[rolling_hash] = True elif dict[rolling_hash]: @@ -41,6 +43,7 @@ def findRepeatedDnaSequences2(self, s): l.extend([s[i:i + 10]]) return [k for k, v in collections.Counter(l).items() if v > 1] + if __name__ == "__main__": print Solution().findRepeatedDnaSequences("AAAAAAAAAA") print Solution().findRepeatedDnaSequences("") From 346e73089d159f063b6bc08b90c997de467e3f17 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 2 Oct 2017 20:19:58 +0800 Subject: [PATCH 3780/4971] rename repeated-string-matc.cpp --- .../repeated-string-match\b.cpp" => C++/repeated-string-match.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename "C++/repeated-string-match\b.cpp" => C++/repeated-string-match.cpp (100%) diff --git "a/C++/repeated-string-match\b.cpp" b/C++/repeated-string-match.cpp similarity index 100% rename from "C++/repeated-string-match\b.cpp" rename to C++/repeated-string-match.cpp From 702c284c95f3c002a2f8331551cd192ccdcdb1f6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Oct 2017 13:36:45 +0800 Subject: [PATCH 3781/4971] Create swap-salary.sql --- MySQL/swap-salary.sql | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 MySQL/swap-salary.sql diff --git a/MySQL/swap-salary.sql b/MySQL/swap-salary.sql new file mode 100644 index 000000000..6f10d382f --- /dev/null +++ b/MySQL/swap-salary.sql @@ -0,0 +1,4 @@ +# Time: O(n) +# Space: O(1) + +UPDATE salary SET sex = IF(sex = 'm', 'f', 'm') From 921e437182bbf52ccd31037cd59a3292cc1adfac Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Oct 2017 13:38:34 +0800 Subject: [PATCH 3782/4971] Update swap-salary.sql --- MySQL/swap-salary.sql | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/MySQL/swap-salary.sql b/MySQL/swap-salary.sql index 6f10d382f..0d468a90d 100644 --- a/MySQL/swap-salary.sql +++ b/MySQL/swap-salary.sql @@ -1,4 +1,23 @@ # Time: O(n) # Space: O(1) +# Given a table salary, such as the one below, that has m=male and f=female values. +# Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table. +# +# For example: +# | id | name | sex | salary | +# |----|------|-----|--------| +# | 1 | A | m | 2500 | +# | 2 | B | f | 1500 | +# | 3 | C | m | 5500 | +# | 4 | D | f | 500 | +# +# After running your query, the above salary table should have the following rows: +# | id | name | sex | salary | +# |----|------|-----|--------| +# | 1 | A | f | 2500 | +# | 2 | B | m | 1500 | +# | 3 | C | f | 5500 | +# | 4 | D | m | 500 | + UPDATE salary SET sex = IF(sex = 'm', 'f', 'm') From b16e6a3c4c7b960ae665eb95df14804d7584953e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Oct 2017 22:54:39 +0800 Subject: [PATCH 3783/4971] Create exchange-seats.sql --- MySQL/exchange-seats.sql | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 MySQL/exchange-seats.sql diff --git a/MySQL/exchange-seats.sql b/MySQL/exchange-seats.sql new file mode 100644 index 000000000..1a80d7664 --- /dev/null +++ b/MySQL/exchange-seats.sql @@ -0,0 +1,40 @@ +# Time: O(nlogn) +# Space: O(n) + +# Mary is a teacher in a middle school and she has a table seat storing +# students' names and their corresponding seat ids. +# +# The column id is continuous increment. +# Mary wants to change seats for the adjacent students. +# Can you write a SQL query to output the result for Mary? +# +---------+---------+ +# | id | student | +# +---------+---------+ +# | 1 | Abbot | +# | 2 | Doris | +# | 3 | Emerson | +# | 4 | Green | +# | 5 | Jeames | +# +---------+---------+ +# +# For the sample input, the output is: +# +---------+---------+ +# | id | student | +# +---------+---------+ +# | 1 | Doris | +# | 2 | Abbot | +# | 3 | Green | +# | 4 | Emerson | +# | 5 | Jeames | +# +---------+---------+ +# +# Note: +# If the number of students is odd, there is no need to change the last one's seat. + +SELECT + s1.id, COALESCE(s2.student, s1.student) AS student +FROM + seat s1 + LEFT JOIN + seat s2 ON ((s1.id + 1) ^ 1) - 1 = s2.id +ORDER BY s1.id; From e470868d8147c5d9c4b9e5a3e53cb6cf319bccde Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Oct 2017 22:38:10 +0800 Subject: [PATCH 3784/4971] Create not-boring-movies.sql --- MySQL/not-boring-movies.sql | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 MySQL/not-boring-movies.sql diff --git a/MySQL/not-boring-movies.sql b/MySQL/not-boring-movies.sql new file mode 100644 index 000000000..765a9dbc8 --- /dev/null +++ b/MySQL/not-boring-movies.sql @@ -0,0 +1,31 @@ +# Time: O(nlogn) +# Space: O(1) + +# X city opened a new cinema, many people would like to go to this cinema. +# The cinema also gives out a poster indicating the movies’ ratings and descriptions. +# +# Please write a SQL query to output movies with an odd numbered ID and +# a description that is not 'boring'. Order the result by rating. +# +# For example, table cinema: +# +---------+-----------+--------------+-----------+ +# | id | movie | description | rating | +# +---------+-----------+--------------+-----------+ +# | 1 | War | great 3D | 8.9 | +# | 2 | Science | fiction | 8.5 | +# | 3 | irish | boring | 6.2 | +# | 4 | Ice song | Fantacy | 8.6 | +# | 5 | House card| Interesting| 9.1 | +# +---------+-----------+--------------+-----------+ +# +# For the example above, the output should be: +# +---------+-----------+--------------+-----------+ +# | id | movie | description | rating | +# +---------+-----------+--------------+-----------+ +# | 5 | House card| Interesting| 9.1 | +# | 1 | War | great 3D | 8.9 | +# +---------+-----------+--------------+-----------+ + +SELECT * FROM cinema +WHERE id % 2 != 0 and description != 'boring' +ORDER BY rating DESC; From f2d71530bd4324239cb36197992e77d7010dbb50 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 Oct 2017 22:55:16 +0800 Subject: [PATCH 3785/4971] Create big-countries.sql --- MySQL/big-countries.sql | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 MySQL/big-countries.sql diff --git a/MySQL/big-countries.sql b/MySQL/big-countries.sql new file mode 100644 index 000000000..5bc687b3b --- /dev/null +++ b/MySQL/big-countries.sql @@ -0,0 +1,27 @@ +# Time: O(n) +# Space: O(1) + +# There is a table World +# +-----------------+------------+------------+--------------+---------------+ +# | name | continent | area | population | gdp | +# +-----------------+------------+------------+--------------+---------------+ +# | Afghanistan | Asia | 652230 | 25500100 | 20343000 | +# | Albania | Europe | 28748 | 2831741 | 12960000 | +# | Algeria | Africa | 2381741 | 37100000 | 188681000 | +# | Andorra | Europe | 468 | 78115 | 3712000 | +# | Angola | Africa | 1246700 | 20609294 | 100990000 | +# +-----------------+------------+------------+--------------+---------------+ +# +# A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million. +# Write a SQL solution to output big countries' name, population and area. +# For example, according to the above table, we should output: +# +--------------+-------------+--------------+ +# | name | population | area | +# +--------------+-------------+--------------+ +# | Afghanistan | 25500100 | 652230 | +# | Algeria | 37100000 | 2381741 | +# +--------------+-------------+--------------+ + +SELECT name, population, area +FROM World +WHERE area > 3000000 OR population > 25000000; From 936e3ca3c955a38c8a93d737b3061a4baaa0c710 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 6 Oct 2017 23:16:52 +0800 Subject: [PATCH 3786/4971] Create classes-more-than-5-students.sql --- MySQL/classes-more-than-5-students.sql | 35 ++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 MySQL/classes-more-than-5-students.sql diff --git a/MySQL/classes-more-than-5-students.sql b/MySQL/classes-more-than-5-students.sql new file mode 100644 index 000000000..b225427dc --- /dev/null +++ b/MySQL/classes-more-than-5-students.sql @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(n) + +# There is a table courses with columns: student and class +# Please list out all classes which have more than or equal to 5 students. +# For example, the table: +# +---------+------------+ +# | student | class | +# +---------+------------+ +# | A | Math | +# | B | English | +# | C | Math | +# | D | Biology | +# | E | Math | +# | F | Computer | +# | G | Math | +# | H | Math | +# | I | Math | +# +---------+------------+ +# +# Should output: +# +---------+ +# | class | +# +---------+ +# | Math | +# +---------+ +# +# Note: +# The students should not be counted duplicate in each course. + +SELECT class +FROM courses +GROUP BY class +HAVING COUNT(DISTINCT student) >= 5 +ORDER BY NULL; From d5875098759659cb2111d19b65f145d7cbb9af89 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Oct 2017 22:26:01 +0800 Subject: [PATCH 3787/4971] Create winning-candidate.sql --- MySQL/winning-candidate.sql | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 MySQL/winning-candidate.sql diff --git a/MySQL/winning-candidate.sql b/MySQL/winning-candidate.sql new file mode 100644 index 000000000..dc2524190 --- /dev/null +++ b/MySQL/winning-candidate.sql @@ -0,0 +1,18 @@ +# Time: O(n) +# Space: O(n) + +SELECT + name AS Name +FROM + Candidate + JOIN + (SELECT + Candidateid + FROM + Vote + GROUP BY Candidateid + ORDER BY COUNT(*) DESC + LIMIT 1) AS Winner +WHERE + Candidate.id = Winner.Candidateid +; From 260dfbdb53fa19e71de6e9ac1c5d355df577999a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 7 Oct 2017 22:33:42 +0800 Subject: [PATCH 3788/4971] Update winning-candidate.sql --- MySQL/winning-candidate.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/winning-candidate.sql b/MySQL/winning-candidate.sql index dc2524190..ec491535d 100644 --- a/MySQL/winning-candidate.sql +++ b/MySQL/winning-candidate.sql @@ -1,4 +1,4 @@ -# Time: O(n) +# Time: O(nlogn) # Space: O(n) SELECT From 4564b98d542d45ada9e4f68d9574f47b20863b70 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Oct 2017 23:11:53 +0800 Subject: [PATCH 3789/4971] Create binary-number-with-alternating-bits.cpp --- C++/binary-number-with-alternating-bits.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/binary-number-with-alternating-bits.cpp diff --git a/C++/binary-number-with-alternating-bits.cpp b/C++/binary-number-with-alternating-bits.cpp new file mode 100644 index 000000000..35309ddfd --- /dev/null +++ b/C++/binary-number-with-alternating-bits.cpp @@ -0,0 +1,18 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + bool hasAlternatingBits(int n) { + auto curr = n % 2; + n /= 2; + while (n > 0) { + if (curr == n % 2) { + return false; + } + curr = n % 2; + n /= 2; + } + return true; + } +}; From dcfbc0860dac9bdbd3d9c660772baeeffcf5a5a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Oct 2017 23:14:38 +0800 Subject: [PATCH 3790/4971] Create binary-number-with-alternating-bits.py --- Python/binary-number-with-alternating-bits.py | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/binary-number-with-alternating-bits.py diff --git a/Python/binary-number-with-alternating-bits.py b/Python/binary-number-with-alternating-bits.py new file mode 100644 index 000000000..ff066353a --- /dev/null +++ b/Python/binary-number-with-alternating-bits.py @@ -0,0 +1,41 @@ +# Time: O(1) +# Space: O(1) + +# Given a positive integer, check whether it has alternating bits: +# namely, if two adjacent bits will always have different values. +# +# Example 1: +# Input: 5 +# Output: True +# Explanation: +# The binary representation of 5 is: 101 +# +# Example 2: +# Input: 7 +# Output: False +# Explanation: +# The binary representation of 7 is: 111. +# +# Example 3: +# Input: 11 +# Output: False +# Explanation: +# The binary representation of 11 is: 1011. +# +# Example 4: +# Input: 10 +# Output: True +# Explanation: +# The binary representation of 10 is: 1010. + +class Solution(object): + def hasAlternatingBits(self, n): + """ + :type n: int + :rtype: bool + """ + n, curr = divmod(n, 2) + while n > 0: + if curr == n % 2: return False + n, curr = divmod(n, 2) + return True From 5039fcb8dbf8f7971bea3342aa1f6c0271fc06a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Oct 2017 19:19:36 +0800 Subject: [PATCH 3791/4971] Create number-of-distinct-islands.cpp --- C++/number-of-distinct-islands.cpp | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/number-of-distinct-islands.cpp diff --git a/C++/number-of-distinct-islands.cpp b/C++/number-of-distinct-islands.cpp new file mode 100644 index 000000000..bd791b76d --- /dev/null +++ b/C++/number-of-distinct-islands.cpp @@ -0,0 +1,39 @@ +// Time: O(m * n) +// Space: O(m * n) + +class Solution { +public: + int numDistinctIslands(vector>& grid) { + unordered_set islands; + for (int i = 0; i < grid.size(); ++i) { + for (int j = 0; j < grid[0].size(); ++j) { + string island; + if (dfs(i, j, &grid, &island)) { + islands.emplace(island); + } + } + } + return islands.size(); + } + +private: + + bool dfs(const int i, const int j, + vector> *grid, string *island) { + static const unordered_map> + directions = { {'l', {-1, 0} }, {'r', { 1, 0} }, + {'u', { 0, 1} }, {'d', { 0, -1} }}; + + if (i < 0 || i >= grid->size() || + j < 0 || j >= (*grid)[0].size() || + (*grid)[i][j] <= 0) { + return false; + } + (*grid)[i][j] *= -1; + for (const auto& kvp : directions) { + island->push_back(kvp.first); + dfs(i + kvp.second.first, j +kvp.second.second, grid, island); + } + return true; + } +}; From a5e2550747d29a72febf490ad6dee4a2ffd4cf8b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Oct 2017 19:20:27 +0800 Subject: [PATCH 3792/4971] Update number-of-distinct-islands.cpp --- C++/number-of-distinct-islands.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/number-of-distinct-islands.cpp b/C++/number-of-distinct-islands.cpp index bd791b76d..d2acdea2d 100644 --- a/C++/number-of-distinct-islands.cpp +++ b/C++/number-of-distinct-islands.cpp @@ -17,9 +17,9 @@ class Solution { } private: - bool dfs(const int i, const int j, vector> *grid, string *island) { + static const unordered_map> directions = { {'l', {-1, 0} }, {'r', { 1, 0} }, {'u', { 0, 1} }, {'d', { 0, -1} }}; From 5e6a07e726efbcffb2a0ca6f9bf6c07589cc2cf3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Oct 2017 19:26:44 +0800 Subject: [PATCH 3793/4971] Update number-of-distinct-islands.cpp --- C++/number-of-distinct-islands.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/number-of-distinct-islands.cpp b/C++/number-of-distinct-islands.cpp index d2acdea2d..09f50532f 100644 --- a/C++/number-of-distinct-islands.cpp +++ b/C++/number-of-distinct-islands.cpp @@ -32,7 +32,7 @@ class Solution { (*grid)[i][j] *= -1; for (const auto& kvp : directions) { island->push_back(kvp.first); - dfs(i + kvp.second.first, j +kvp.second.second, grid, island); + dfs(i + kvp.second.first, j + kvp.second.second, grid, island); } return true; } From f20ea6b1b4761ada638a2341f5eb6f00bce16447 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Oct 2017 19:30:51 +0800 Subject: [PATCH 3794/4971] Create number-of-distinct-islands.py --- Python/number-of-distinct-islands.py | 30 ++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/number-of-distinct-islands.py diff --git a/Python/number-of-distinct-islands.py b/Python/number-of-distinct-islands.py new file mode 100644 index 000000000..dc471e867 --- /dev/null +++ b/Python/number-of-distinct-islands.py @@ -0,0 +1,30 @@ +# Time: O(m * n) +# Space: O(m * n) + +class Solution(object): + def numDistinctIslands(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + directions = {'l':[-1, 0], 'r':[ 1, 0], \ + 'u':[ 0, 1], 'd':[ 0, -1]} + + def dfs(i, j, grid, island): + if not (0 <= i < len(grid) and \ + 0 <= j < len(grid[0]) and \ + grid[i][j] > 0): + return False + grid[i][j] *= -1 + for k, v in directions.iteritems(): + island.append(k); + dfs(i+v[0], j+v[1], grid, island) + return True + + islands = set() + for i in xrange(len(grid)): + for j in xrange(len(grid[0])): + island = [] + if dfs(i, j, grid, island): + islands.add("".join(island)) + return len(islands) From 3329b6b06391770ff29d6d74ad0b219240eae864 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Oct 2017 19:44:30 +0800 Subject: [PATCH 3795/4971] Create max-area-of-island.cpp --- C++/max-area-of-island.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/max-area-of-island.cpp diff --git a/C++/max-area-of-island.cpp b/C++/max-area-of-island.cpp new file mode 100644 index 000000000..25b9aa97a --- /dev/null +++ b/C++/max-area-of-island.cpp @@ -0,0 +1,35 @@ +// Time: O(m * n) +// Space: O(m * n) + +class Solution { +public: + int maxAreaOfIsland(vector>& grid) { + int result = 0; + for (int i = 0; i < grid.size(); ++i) { + for (int j = 0; j < grid[0].size(); ++j) { + int length = 0; + if (dfs(i, j, &grid, &length)) { + result = max(result, length); + } + } + } + return result; + } + +private: + bool dfs(const int i, const int j, vector> *grid, int *length) { + static const vector> directions{{-1, 0}, { 1, 0}, + { 0, 1}, { 0, -1}}; + if (i < 0 || i >= grid->size() || + j < 0 || j >= (*grid)[0].size() || + (*grid)[i][j] <= 0) { + return false; + } + (*grid)[i][j] *= -1; + ++(*length); + for (const auto& d : directions) { + dfs(i + d.first, j + d.second, grid, length); + } + return true; + } +}; From 2b28d19f24a12c004b75b075408c9c83f03921e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Oct 2017 19:49:20 +0800 Subject: [PATCH 3796/4971] Update max-area-of-island.cpp --- C++/max-area-of-island.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/max-area-of-island.cpp b/C++/max-area-of-island.cpp index 25b9aa97a..505bd0e53 100644 --- a/C++/max-area-of-island.cpp +++ b/C++/max-area-of-island.cpp @@ -7,9 +7,9 @@ class Solution { int result = 0; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { - int length = 0; - if (dfs(i, j, &grid, &length)) { - result = max(result, length); + int area = 0; + if (dfs(i, j, &grid, &area)) { + result = max(result, area); } } } @@ -17,7 +17,7 @@ class Solution { } private: - bool dfs(const int i, const int j, vector> *grid, int *length) { + bool dfs(const int i, const int j, vector> *grid, int *area) { static const vector> directions{{-1, 0}, { 1, 0}, { 0, 1}, { 0, -1}}; if (i < 0 || i >= grid->size() || @@ -26,9 +26,9 @@ class Solution { return false; } (*grid)[i][j] *= -1; - ++(*length); + ++(*area); for (const auto& d : directions) { - dfs(i + d.first, j + d.second, grid, length); + dfs(i + d.first, j + d.second, grid, area); } return true; } From 3c294d5ac71782862d51cc17abd066e9bccd20c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Oct 2017 19:54:12 +0800 Subject: [PATCH 3797/4971] Create max-area-of-island.py --- Python/max-area-of-island.py | 55 ++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/max-area-of-island.py diff --git a/Python/max-area-of-island.py b/Python/max-area-of-island.py new file mode 100644 index 000000000..9cbc8d909 --- /dev/null +++ b/Python/max-area-of-island.py @@ -0,0 +1,55 @@ +# Time: O(m * n) +# Space: O(1) + +# Given a non-empty 2D array grid of 0's and 1's, +# an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) +# You may assume all four edges of the grid are surrounded by water. +# +# Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.) +# +# Example 1: +# [[0,0,1,0,0,0,0,1,0,0,0,0,0], +# [0,0,0,0,0,0,0,1,1,1,0,0,0], +# [0,1,1,0,1,0,0,0,0,0,0,0,0], +# [0,1,0,0,1,1,0,0,1,0,1,0,0], +# [0,1,0,0,1,1,0,0,1,1,1,0,0], +# [0,0,0,0,0,0,0,0,0,0,1,0,0], +# [0,0,0,0,0,0,0,1,1,1,0,0,0], +# [0,0,0,0,0,0,0,1,1,0,0,0,0]] +# +# Given the above grid, return 6. Note the answer is not 11, +# because the island must be connected 4-directionally. +# +# Example 2: +# [[0,0,0,0,0,0,0,0]] +# +# Given the above grid, return 0. +# +# Note: The length of each dimension in the given grid does not exceed 50. + +class Solution(object): + def maxAreaOfIsland(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + directions = [[-1, 0], [ 1, 0], [ 0, 1], [ 0, -1]] + + def dfs(i, j, grid, area): + if not (0 <= i < len(grid) and \ + 0 <= j < len(grid[0]) and \ + grid[i][j] > 0): + return False + grid[i][j] *= -1 + area[0] += 1 + for d in directions: + dfs(i+d[0], j+d[1], grid, area) + return True + + result = 0 + for i in xrange(len(grid)): + for j in xrange(len(grid[0])): + area = [0] + if dfs(i, j, grid, area): + result = max(result, area[0]) + return result From 8e63bc735762063a86203b60764d969e441ee663 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Oct 2017 19:55:06 +0800 Subject: [PATCH 3798/4971] Update max-area-of-island.cpp --- C++/max-area-of-island.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/max-area-of-island.cpp b/C++/max-area-of-island.cpp index 505bd0e53..79443b7bf 100644 --- a/C++/max-area-of-island.cpp +++ b/C++/max-area-of-island.cpp @@ -1,5 +1,5 @@ // Time: O(m * n) -// Space: O(m * n) +// Space: O(1) class Solution { public: From 5132fe7041f890cfbd7e248845207e69b3580c2f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 9 Oct 2017 21:02:09 +0800 Subject: [PATCH 3799/4971] add stickers-to-spell-word.cpp --- C++/stickers-to-spell-word.cpp | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 C++/stickers-to-spell-word.cpp diff --git a/C++/stickers-to-spell-word.cpp b/C++/stickers-to-spell-word.cpp new file mode 100644 index 000000000..90a42e399 --- /dev/null +++ b/C++/stickers-to-spell-word.cpp @@ -0,0 +1,49 @@ +// Time: O(T * S^T) +// Space: O(T * S^T) + +class Solution { +public: + int minStickers(vector& stickers, string target) { + vector> sticker_counts(stickers.size(), vector(26)); + unordered_map dp; + for (int i = 0; i < stickers.size(); ++i) { + for (const auto& c : stickers[i]) { + ++sticker_counts[i][c - 'a']; + } + } + dp[""] = 0; + return minStickersHelper(sticker_counts, target, &dp); + } + +private: + int minStickersHelper(const vector>& sticker_counts, const string& target, + unordered_map *dp) { + if (dp->count(target)) { + return (*dp)[target]; + } + int result = numeric_limits::max(); + vector target_count(26); + for (const auto& c : target) { + ++target_count[c - 'a']; + } + for (const auto& sticker_count : sticker_counts) { + if (sticker_count[target[0] - 'a'] == 0) { + continue; + } + string new_target; + for (int i = 0; i < target_count.size(); ++i) { + if (target_count[i] - sticker_count[i] > 0) { + new_target += string(target_count[i] - sticker_count[i], 'a' + i); + } + } + if (new_target.length() != target.length()) { + int num = minStickersHelper(sticker_counts, new_target, dp); + if (num != -1) { + result = min(result, 1 + num); + } + } + } + (*dp)[target] = (result == numeric_limits::max()) ? -1 : result; + return (*dp)[target]; + } +}; \ No newline at end of file From 0357cae0a77f8f176b1a4ccf0d591442a07358bc Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 9 Oct 2017 21:22:19 +0800 Subject: [PATCH 3800/4971] update stickers-to-spell-word.cpp --- C++/stickers-to-spell-word.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/stickers-to-spell-word.cpp b/C++/stickers-to-spell-word.cpp index 90a42e399..3e8fc51b7 100644 --- a/C++/stickers-to-spell-word.cpp +++ b/C++/stickers-to-spell-word.cpp @@ -1,5 +1,5 @@ // Time: O(T * S^T) -// Space: O(T * S^T) +// Space: O(S^T + T^2) class Solution { public: From 9c35e63f8a00d97f8b6555caa039f8b90fc4fcd8 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 9 Oct 2017 21:37:43 +0800 Subject: [PATCH 3801/4971] update stickers-to-spell-word.cpp --- C++/stickers-to-spell-word.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/stickers-to-spell-word.cpp b/C++/stickers-to-spell-word.cpp index 3e8fc51b7..90a42e399 100644 --- a/C++/stickers-to-spell-word.cpp +++ b/C++/stickers-to-spell-word.cpp @@ -1,5 +1,5 @@ // Time: O(T * S^T) -// Space: O(S^T + T^2) +// Space: O(T * S^T) class Solution { public: From 953e078d0cb847428bac538517d04fc84477be69 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 9 Oct 2017 21:54:49 +0800 Subject: [PATCH 3802/4971] Create stickers-to-spell-word.py --- Python/stickers-to-spell-word.py | 76 ++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Python/stickers-to-spell-word.py diff --git a/Python/stickers-to-spell-word.py b/Python/stickers-to-spell-word.py new file mode 100644 index 000000000..6309f76ef --- /dev/null +++ b/Python/stickers-to-spell-word.py @@ -0,0 +1,76 @@ +# Time: O(T * S^T) +# Space: O(T * S^T) + +# We are given N different types of stickers. Each sticker has a lowercase English word on it. +# +# You would like to spell out the given target string by cutting individual letters +# from your collection of stickers and rearranging them. +# +# You can use each sticker more than once if you want, and you have infinite quantities of each sticker. +# +# What is the minimum number of stickers that you need to spell out the target? +# If the task is impossible, return -1. +# +# Example 1: +# +# Input: +# ["with", "example", "science"], "thehat" +# +# Output: +# 3 +# +# Explanation: +# We can use 2 "with" stickers, and 1 "example" sticker. +# After cutting and rearrange the letters of those stickers, we can form the target "thehat". +# Also, this is the minimum number of stickers necessary to form the target string. +# +# Example 2: +# +# Input: +# ["notice", "possible"], "basicbasic" +# +# Output: +# -1 +# +# Explanation: +# We can't form the target "basicbasic" from cutting letters from the given stickers. +# +# Note: +# - stickers has length in the range [1, 50]. +# - stickers consists of lowercase English words (without apostrophes). +# - target has length in the range [1, 15], and consists of lowercase English letters. +# - In all test cases, all words were chosen randomly from the 1000 most common US English words, +# and the target was chosen as a concatenation of two random words. +# - The time limit may be more challenging than usual. +# It is expected that a 50 sticker test case can be solved within 35ms on average. + +class Solution(object): + def minStickers(self, stickers, target): + """ + :type stickers: List[str] + :type target: str + :rtype: int + """ + def minStickersHelper(sticker_counts, target, dp): + if "".join(target) in dp: + return dp["".join(target)] + target_count = collections.Counter(target) + result = float("inf") + for sticker_count in sticker_counts: + if sticker_count[target[0]] == 0: + continue + new_target = [] + for k in target_count.keys(): + if target_count[k] > sticker_count[k]: + new_target += [k]*(target_count[k] - sticker_count[k]) + if len(new_target) != len(target): + num = minStickersHelper(sticker_counts, new_target, dp) + if num != -1: + result = min(result, 1+num) + dp["".join(target)] = -1 if result == float("inf") else result + return dp["".join(target)] + + sticker_counts = map(collections.Counter, stickers) + dp = { "":0 } + return minStickersHelper(sticker_counts, target, dp) + From c0f2e87975154fc1845831857f60cc0f524a36e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Oct 2017 14:26:25 +0800 Subject: [PATCH 3803/4971] Update max-area-of-island.py --- Python/max-area-of-island.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/max-area-of-island.py b/Python/max-area-of-island.py index 9cbc8d909..59b377285 100644 --- a/Python/max-area-of-island.py +++ b/Python/max-area-of-island.py @@ -1,5 +1,5 @@ # Time: O(m * n) -# Space: O(1) +# Space: O(m + n) # Given a non-empty 2D array grid of 0's and 1's, # an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) From 241143b0e57ce232c1404ed6af67d068bc63bf67 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Oct 2017 14:26:51 +0800 Subject: [PATCH 3804/4971] Update max-area-of-island.cpp --- C++/max-area-of-island.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/max-area-of-island.cpp b/C++/max-area-of-island.cpp index 79443b7bf..af0ad47b3 100644 --- a/C++/max-area-of-island.cpp +++ b/C++/max-area-of-island.cpp @@ -1,5 +1,5 @@ // Time: O(m * n) -// Space: O(1) +// Space: O(m + n) class Solution { public: From 4de97b9e5b974d579edcd8133efe5b12b9b0272c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Oct 2017 14:27:10 +0800 Subject: [PATCH 3805/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index c4b65c9ce..5a38cb3eb 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/minimum-moves-to-equal-array-elements-ii.py) | _O(n)_ on average | _O(1)_ | Medium || 477 | [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./C++/total-hamming-distance.cpp) [Python](./Python/total-hamming-distance.py) | _O(n)_ | _O(1)_ | Medium || 645 | [Set Mismatch](https://leetcode.com/problems/set-mismatch/) | [C++](./C++/set-mismatch.cpp) [Python](./Python/set-mismatch.py) | _O(n)_ | _O(1)_ | Easy || +693 | [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/) | [C++](./C++/binary-number-with-alternating-bits.cpp) [Python](./Python/binary-number-with-alternating-bits.py) | _O(1)_ | _O(1)_ | Easy || ## Array | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -496,6 +497,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn)_ | _O(logn)_ | Hard || 464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || 690| [Employee Importance](https://leetcode.com/problems/employee-importance/) | [C++](./C++/employee-importance.cpp) [Python](./Python/employee-importance.py) | _O(n)_ | _O(h)_ | Easy || DFS, BFS +694| [Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands/) | [C++](./C++/number-of-distinct-islands.cpp) [Python](./Python/number-of-distinct-islands.py) | _O(m * n)_ | _O(m * n)_ | Medium |📖|| +695| [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [C++](./C++/max-area-of-island.cpp) [Python](./Python/max-area-of-island.py) | _O(m * n)_ | _O(m + n)_ | Easy || ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -584,6 +587,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 673 | [Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence/) | [C++](./C++/number-of-longest-increasing-subsequence.cpp) [Python](./Python/number-of-longest-increasing-subsequence.py) | _O(n^2)_ | _O(n)_ | Medium || 688 | [Knight Probability in Chessboard](https://leetcode.com/problems/knight-probability-in-chessboard/) | [C++](./C++/knight-probability-in-chessboard.cpp) [Python](./Python/knight-probability-in-chessboard.py) | _O(k * n^2)_ | _O(n^2)_ | Medium || 689 | [Maximum Sum of 3 Non-Overlapping Subarrays](https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/) | [C++](./C++/maximum-sum-of-3-non-overlapping-subarrays.cpp) [Python](./Python/maximum-sum-of-3-non-overlapping-subarrays.py) | _O(n)_ | _O(n)_ | Hard || +691 | [Stickers to Spell Word](https://leetcode.com/problems/stickers-to-spell-word/) | [C++](./C++/stickers-to-spell-word.cpp) [Python](./Python/stickers-to-spell-word.py) | _O(T * S^T)_ | _O(T * S^T)_ | Hard || Backtracking, Memoization ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 07d25928e9b9d49b178912d86e218859db8f44e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Oct 2017 14:28:36 +0800 Subject: [PATCH 3806/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5a38cb3eb..59beaf56e 100644 --- a/README.md +++ b/README.md @@ -498,7 +498,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || 690| [Employee Importance](https://leetcode.com/problems/employee-importance/) | [C++](./C++/employee-importance.cpp) [Python](./Python/employee-importance.py) | _O(n)_ | _O(h)_ | Easy || DFS, BFS 694| [Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands/) | [C++](./C++/number-of-distinct-islands.cpp) [Python](./Python/number-of-distinct-islands.py) | _O(m * n)_ | _O(m * n)_ | Medium |📖|| -695| [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [C++](./C++/max-area-of-island.cpp) [Python](./Python/max-area-of-island.py) | _O(m * n)_ | _O(m + n)_ | Easy || +695| [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [C++](./C++/max-area-of-island.cpp) [Python](./Python/max-area-of-island.py) | _O(m * n)_ | _O(m * n)_ | Easy || ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From d0e3b86b094c63e47744139889305e06b0d07a61 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Oct 2017 14:28:45 +0800 Subject: [PATCH 3807/4971] Update max-area-of-island.cpp --- C++/max-area-of-island.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/max-area-of-island.cpp b/C++/max-area-of-island.cpp index af0ad47b3..505bd0e53 100644 --- a/C++/max-area-of-island.cpp +++ b/C++/max-area-of-island.cpp @@ -1,5 +1,5 @@ // Time: O(m * n) -// Space: O(m + n) +// Space: O(m * n) class Solution { public: From fed54011443e0cf1c58715e1bd28126b4bb83367 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 10 Oct 2017 14:29:30 +0800 Subject: [PATCH 3808/4971] Update max-area-of-island.py --- Python/max-area-of-island.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/max-area-of-island.py b/Python/max-area-of-island.py index 59b377285..ee8db6201 100644 --- a/Python/max-area-of-island.py +++ b/Python/max-area-of-island.py @@ -1,5 +1,5 @@ # Time: O(m * n) -# Space: O(m + n) +# Space: O(m * n), the max depth of dfs may be m * n # Given a non-empty 2D array grid of 0's and 1's, # an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) From 08b6ff98c6b8be70fbd48aa68216befee3fefa2d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Oct 2017 22:18:11 +0800 Subject: [PATCH 3809/4971] Update max-area-of-island.cpp --- C++/max-area-of-island.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/max-area-of-island.cpp b/C++/max-area-of-island.cpp index 505bd0e53..da9e5aa59 100644 --- a/C++/max-area-of-island.cpp +++ b/C++/max-area-of-island.cpp @@ -1,5 +1,5 @@ // Time: O(m * n) -// Space: O(m * n) +// Space: O(m * n), the max depth of dfs may be m * n class Solution { public: From 6ede8e6c6eec36dd013b43862bed2243885fb1b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Oct 2017 22:20:34 +0800 Subject: [PATCH 3810/4971] Create top-k-frequent-words.cpp --- C++/top-k-frequent-words.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/top-k-frequent-words.cpp diff --git a/C++/top-k-frequent-words.cpp b/C++/top-k-frequent-words.cpp new file mode 100644 index 000000000..043fc616c --- /dev/null +++ b/C++/top-k-frequent-words.cpp @@ -0,0 +1,23 @@ +// Time: O(n + klogk) +// Space: O(n) + +class Solution { +public: + vector topKFrequent(vector& words, int k) { + unordered_map counts; + for (int i = 0; i < words.size(); ++i) { + ++counts[words[i]]; + } + vector> p; + for (auto it = counts.begin(); it != counts.end(); ++it) { + p.emplace_back(-(it->second), it->first); + } + nth_element(p.begin(), p.begin() + k - 1, p.end()); // O(n) time. + sort(p.begin(), p.begin() + k); // O(klogk) time. + vector result; + for (int i = 0; i < k; ++i) { + result.emplace_back(p[i].second); + } + return result; + } +}; From 2051679997b33b66f5b5baabbfad0ab675754066 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Oct 2017 23:11:46 +0800 Subject: [PATCH 3811/4971] Update top-k-frequent-elements.py --- Python/top-k-frequent-elements.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/top-k-frequent-elements.py b/Python/top-k-frequent-elements.py index bf3741127..c8932581f 100644 --- a/Python/top-k-frequent-elements.py +++ b/Python/top-k-frequent-elements.py @@ -28,7 +28,7 @@ def topKFrequent(self, nums, k): p = [] for key, val in counts.iteritems(): - p.append((val, key)) + p.append((-val, key)) self.kthElement(p, k); result = [] @@ -39,11 +39,11 @@ def topKFrequent(self, nums, k): def kthElement(self, nums, k): def PartitionAroundPivot(left, right, pivot_idx, nums): - pivot_value = nums[pivot_idx][0] + 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][0] > pivot_value: + if nums[i] < pivot_value: nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i] new_pivot_idx += 1 From f38f909f37bb091b8886289bfda117bc335a551c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Oct 2017 23:14:28 +0800 Subject: [PATCH 3812/4971] Update top-k-frequent-words.cpp --- C++/top-k-frequent-words.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/top-k-frequent-words.cpp b/C++/top-k-frequent-words.cpp index 043fc616c..da7b93a8d 100644 --- a/C++/top-k-frequent-words.cpp +++ b/C++/top-k-frequent-words.cpp @@ -1,4 +1,4 @@ -// Time: O(n + klogk) +// Time: O(n + klogk) on average // Space: O(n) class Solution { @@ -12,7 +12,7 @@ class Solution { for (auto it = counts.begin(); it != counts.end(); ++it) { p.emplace_back(-(it->second), it->first); } - nth_element(p.begin(), p.begin() + k - 1, p.end()); // O(n) time. + nth_element(p.begin(), p.begin() + k - 1, p.end()); // O(n) time on average. sort(p.begin(), p.begin() + k); // O(klogk) time. vector result; for (int i = 0; i < k; ++i) { From af7abc0fc476f7c048790fc8b378ac1af8ae8b33 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Oct 2017 23:15:13 +0800 Subject: [PATCH 3813/4971] Create top-k-frequent-words.py --- Python/top-k-frequent-words.py | 75 ++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Python/top-k-frequent-words.py diff --git a/Python/top-k-frequent-words.py b/Python/top-k-frequent-words.py new file mode 100644 index 000000000..5b14113ba --- /dev/null +++ b/Python/top-k-frequent-words.py @@ -0,0 +1,75 @@ +# Time: O(n + klogk) on average +# Space: O(n) + +# Given a non-empty list of words, return the k most frequent elements. +# +# Your answer should be sorted by frequency from highest to lowest. +# If two words have the same frequency, then the word with the lower alphabetical order comes first. +# +# Example 1: +# Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 +# Output: ["i", "love"] +# Explanation: "i" and "love" are the two most frequent words. +# Note that "i" comes before "love" due to a lower alphabetical order. +# Example 2: +# Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 +# Output: ["the", "is", "sunny", "day"] +# Explanation: "the", "is", "sunny" and "day" are the four most frequent words, +# with the number of occurrence being 4, 3, 2 and 1 respectively. +# Note: +# You may assume k is always valid, 1 ≤ k ≤ number of unique elements. +# Input words contain only lowercase letters. +# +# Follow up: +# Try to solve it in O(n log k) time and O(n) extra space. +# Can you solve it in O(n) time with only O(k) extra space? + +from random import randint + +class Solution(object): + def topKFrequent(self, words, k): + """ + :type words: List[str] + :type k: int + :rtype: List[str] + """ + counts = collections.defaultdict(int) + for i in words: + counts[i] += 1 + + p = [] + for key, val in counts.iteritems(): + p.append((-val, key)) + self.kthElement(p, k); + + result = [] + sorted_p = sorted(p[:k]) + print sorted_p + for i in xrange(k): + result.append(sorted_p[i][1]) + return result + + + def kthElement(self, nums, k): # O(n) on average + 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 + + 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 + elif new_pivot_idx > k - 1: + right = new_pivot_idx - 1 + else: # new_pivot_idx < k - 1. + left = new_pivot_idx + 1 From a6c59a4ee23307fb581fa30f756ad022946c18f4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Oct 2017 23:17:01 +0800 Subject: [PATCH 3814/4971] Update top-k-frequent-words.py --- Python/top-k-frequent-words.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/top-k-frequent-words.py b/Python/top-k-frequent-words.py index 5b14113ba..6b0f75861 100644 --- a/Python/top-k-frequent-words.py +++ b/Python/top-k-frequent-words.py @@ -44,7 +44,6 @@ def topKFrequent(self, words, k): result = [] sorted_p = sorted(p[:k]) - print sorted_p for i in xrange(k): result.append(sorted_p[i][1]) return result From d685cee4d88b4b2fa17a90812a545e34394e6fbd Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 Oct 2017 12:40:39 +0800 Subject: [PATCH 3815/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 59beaf56e..1e7fd8592 100644 --- a/README.md +++ b/README.md @@ -358,10 +358,10 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | -347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(n)_ | Medium | | Quick Select, Heap | +347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(n)_ | Medium | | Quick Select, Heap, Bucket Sort | 406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium | | | 451| [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/) | [C++](./C++/sort-characters-by-frequency.cpp) [Python](./Python/sort-characters-by-frequency.py) | _O(n)_ | _O(n)_ | Medium | | | - +692| [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [C++](./C++/top-k-frequent-words.cpp) [Python](./Python/top-k-frequent-words.py) | _O(n + klogk)_ on average | _O(n)_ | Medium | | Quick Select, Heap | ## Two Pointers | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From d9adc251f04d7f9e301da5c6fe7e0583f3e9bce2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 Oct 2017 12:47:31 +0800 Subject: [PATCH 3816/4971] Update top-k-frequent-elements.cpp --- C++/top-k-frequent-elements.cpp | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/C++/top-k-frequent-elements.cpp b/C++/top-k-frequent-elements.cpp index dcda833a1..4491fa409 100644 --- a/C++/top-k-frequent-elements.cpp +++ b/C++/top-k-frequent-elements.cpp @@ -1,7 +1,36 @@ -// Time: O(n) ~ O(n^2), O(n) on average. +// Time: O(n) // Space: O(n) +// Bucket Sort Solution class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map counts; + for (const auto& i : nums) { + ++counts[i]; + } + vector> buckets(nums.size() + 1); + for (const auto& kvp : counts) { + buckets[kvp.second].emplace_back(kvp.first); + } + + vector result; + for (int i = buckets.size() - 1; i >= 0; --i) { + for (int j = 0; j < buckets[i].size(); ++j){ + result.emplace_back(buckets[i][j]); + if (result.size() == k) { + return result; + } + } + } + return result; + } +}; + +// Time: O(n) ~ O(n^2), O(n) on average. +// Space: O(n) +// Quick Select Solution +class Solution2 { public: vector topKFrequent(vector& nums, int k) { unordered_map counts; @@ -26,7 +55,7 @@ class Solution { // Time: O(nlogk) // Space: O(n) // Heap solution. -class Solution2 { +class Solution3 { public: vector topKFrequent(vector& nums, int k) { unordered_map counts; From b768f5ebe10e53c53d3aa06c7f678e66824a9dc3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 Oct 2017 12:48:04 +0800 Subject: [PATCH 3817/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1e7fd8592..a2afa2515 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 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)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | -347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ on average | _O(n)_ | Medium | | Quick Select, Heap, Bucket Sort | +347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ | _O(n)_ | Medium | | Quick Select, Heap, Bucket Sort | 406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium | | | 451| [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/) | [C++](./C++/sort-characters-by-frequency.cpp) [Python](./Python/sort-characters-by-frequency.py) | _O(n)_ | _O(n)_ | Medium | | | 692| [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [C++](./C++/top-k-frequent-words.cpp) [Python](./Python/top-k-frequent-words.py) | _O(n + klogk)_ on average | _O(n)_ | Medium | | Quick Select, Heap | From df81712bd6da4262807df346bee8e6c00db8f1bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 Oct 2017 12:55:49 +0800 Subject: [PATCH 3818/4971] Update top-k-frequent-elements.py --- Python/top-k-frequent-elements.py | 34 +++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/Python/top-k-frequent-elements.py b/Python/top-k-frequent-elements.py index c8932581f..2f3033c11 100644 --- a/Python/top-k-frequent-elements.py +++ b/Python/top-k-frequent-elements.py @@ -1,4 +1,4 @@ -# Time: O(n) ~ O(n^2), O(n) on average. +# Time: O(n) # Space: O(n) # Given a non-empty array of integers, @@ -13,9 +13,35 @@ # Your algorithm's time complexity must be better # than O(n log n), where n is the array's size. -from random import randint - +# Bucket Sort Solution class Solution(object): + def topKFrequent(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + counts = collections.defaultdict(int) + for i in nums: + counts[i] += 1 + buckets = [[] for _ in xrange(len(nums)+1)] + for i, count in counts.iteritems(): + buckets[count].append(i) + + result = [] + for i in reversed(xrange(len(buckets))): + for j in xrange(len(buckets[i])): + result.append(buckets[i][j]) + if len(result) == k: + return result + return result + + +# Time: O(n) ~ O(n^2), O(n) on average. +# Space: O(n) +# Quick Select Solution +from random import randint +class Solution2(object): def topKFrequent(self, nums, k): """ :type nums: List[int] @@ -64,7 +90,7 @@ def PartitionAroundPivot(left, right, pivot_idx, nums): # Time: O(nlogk) # Space: O(n) -class Solution2(object): +class Solution3(object): def topKFrequent(self, nums, k): """ :type nums: List[int] From def2e6680cba20037adf6f48a839dfe646dea039 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 Oct 2017 13:00:49 +0800 Subject: [PATCH 3819/4971] Update top-k-frequent-words.cpp --- C++/top-k-frequent-words.cpp | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/C++/top-k-frequent-words.cpp b/C++/top-k-frequent-words.cpp index da7b93a8d..a379e48d0 100644 --- a/C++/top-k-frequent-words.cpp +++ b/C++/top-k-frequent-words.cpp @@ -1,12 +1,13 @@ // Time: O(n + klogk) on average // Space: O(n) +// Quick Select Solution class Solution { public: vector topKFrequent(vector& words, int k) { unordered_map counts; - for (int i = 0; i < words.size(); ++i) { - ++counts[words[i]]; + for (const auto& word : words) { + ++counts[word]; } vector> p; for (auto it = counts.begin(); it != counts.end(); ++it) { @@ -21,3 +22,31 @@ class Solution { return result; } }; + + +// Time: O(nlogk) +// Space: O(n) +// Heap Solution +class Solution2 { +public: + vector topKFrequent(vector& words, int k) { + unordered_map counts; + for (const auto& word : words) { + ++counts[word]; + } + priority_queue> heap; + for (const auto& kvp : counts) { + heap.emplace(-kvp.second, kvp.first); + if (heap.size() == k + 1) { + heap.pop(); + } + } + vector result; + while (!heap.empty()) { + result.emplace_back(heap.top().second); + heap.pop(); + } + reverse(result.begin(), result.end()); + return result; + } +}; From 30c904e09e50c3ff92442e1c7b0d4492fdc7940f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 Oct 2017 13:02:32 +0800 Subject: [PATCH 3820/4971] Update top-k-frequent-elements.cpp --- C++/top-k-frequent-elements.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/top-k-frequent-elements.cpp b/C++/top-k-frequent-elements.cpp index 4491fa409..d0a45103b 100644 --- a/C++/top-k-frequent-elements.cpp +++ b/C++/top-k-frequent-elements.cpp @@ -59,12 +59,12 @@ class Solution3 { public: vector topKFrequent(vector& nums, int k) { unordered_map counts; - for (int i = 0; i < nums.size(); ++i) { - ++counts[nums[i]]; + for (const auto& i : nums) { + ++counts[i]; } priority_queue> heap; - for (auto it = counts.begin(); it != counts.end(); ++it) { - heap.emplace(-(it->second), it->first); + for (const auto& kvp : counts) { + heap.emplace(-kvp.second, kvp.first); if (heap.size() == k + 1) { heap.pop(); } From d6e408973fa08bb804ea4479f3ff0d3489f64359 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 Oct 2017 13:04:00 +0800 Subject: [PATCH 3821/4971] Update top-k-frequent-words.cpp --- C++/top-k-frequent-words.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/top-k-frequent-words.cpp b/C++/top-k-frequent-words.cpp index a379e48d0..6b9e6ddad 100644 --- a/C++/top-k-frequent-words.cpp +++ b/C++/top-k-frequent-words.cpp @@ -10,8 +10,8 @@ class Solution { ++counts[word]; } vector> p; - for (auto it = counts.begin(); it != counts.end(); ++it) { - p.emplace_back(-(it->second), it->first); + for (const auto& kvp : counts) { + p.emplace_back(-kvp.second, kvp.first); } nth_element(p.begin(), p.begin() + k - 1, p.end()); // O(n) time on average. sort(p.begin(), p.begin() + k); // O(klogk) time. From 99265994a544c0f04c6f2621980cf8ad5d60439d Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 Oct 2017 13:05:23 +0800 Subject: [PATCH 3822/4971] Update top-k-frequent-elements.cpp --- C++/top-k-frequent-elements.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/top-k-frequent-elements.cpp b/C++/top-k-frequent-elements.cpp index d0a45103b..216a27f24 100644 --- a/C++/top-k-frequent-elements.cpp +++ b/C++/top-k-frequent-elements.cpp @@ -37,13 +37,11 @@ class Solution2 { for (const auto& i : nums) { ++counts[i]; } - vector> p; - for (auto it = counts.begin(); it != counts.end(); ++it) { - p.emplace_back(-(it->second), it->first); + for (const auto& kvp : counts) { + p.emplace_back(-kvp.second, kvp.first); } nth_element(p.begin(), p.begin() + k - 1, p.end()); - vector result; for (int i = 0; i < k; ++i) { result.emplace_back(p[i].second); From b8117ae8155614ba6ec45d32e12b03d404e37948 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 Oct 2017 13:42:37 +0800 Subject: [PATCH 3823/4971] Update top-k-frequent-words.py --- Python/top-k-frequent-words.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Python/top-k-frequent-words.py b/Python/top-k-frequent-words.py index 6b0f75861..f472add3b 100644 --- a/Python/top-k-frequent-words.py +++ b/Python/top-k-frequent-words.py @@ -72,3 +72,33 @@ def PartitionAroundPivot(left, right, pivot_idx, nums): right = new_pivot_idx - 1 else: # new_pivot_idx < k - 1. left = new_pivot_idx + 1 + + +# Time: O(nlogk) +# Space: O(n) +# Heap Solution +class Solution2(object): + def topKFrequent(self, words, k): + """ + :type words: List[str] + :type k: int + :rtype: List[str] + """ + class MinHeapObj(object): + def __init__(self,val): self.val = val + def __lt__(self,other): return self.val[1] > other.val[1] if self.val[0] == other.val[0] else self.val < other.val + def __eq__(self,other): return self.val == other.val + def __str__(self): return str(self.val) + + counts = collections.defaultdict(int) + for i in words: + counts[i] += 1 + min_heap = [] + for word, count in counts.iteritems(): + heapq.heappush(min_heap, MinHeapObj((count, word))) + if len(min_heap) == k+1: + heapq.heappop(min_heap) + result = [] + while min_heap: + result.append(heapq.heappop(min_heap).val[1]) + return result[::-1] From 1f111c3cffaa824a99a91ecf43d4a18fe82d65ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 13 Oct 2017 13:43:03 +0800 Subject: [PATCH 3824/4971] Update top-k-frequent-words.py --- Python/top-k-frequent-words.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/top-k-frequent-words.py b/Python/top-k-frequent-words.py index f472add3b..c3bbdb033 100644 --- a/Python/top-k-frequent-words.py +++ b/Python/top-k-frequent-words.py @@ -24,8 +24,8 @@ # Try to solve it in O(n log k) time and O(n) extra space. # Can you solve it in O(n) time with only O(k) extra space? +# Quick Select Solution from random import randint - class Solution(object): def topKFrequent(self, words, k): """ From ab4525a74b24f54f5fe4470c0816ba007a994d21 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Oct 2017 07:35:22 -0500 Subject: [PATCH 3825/4971] Update top-k-frequent-words.cpp --- C++/top-k-frequent-words.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/C++/top-k-frequent-words.cpp b/C++/top-k-frequent-words.cpp index 6b9e6ddad..fe77afcb7 100644 --- a/C++/top-k-frequent-words.cpp +++ b/C++/top-k-frequent-words.cpp @@ -50,3 +50,37 @@ class Solution2 { return result; } }; + + +// Time: O(n + klogk) ~ O(n + nlogn) +// Space: O(n) +// Bucket Sort Solution +class Solution3 { +public: + vector topKFrequent(vector& words, int k) { + unordered_map counts; + for (const auto& word : words) { + ++counts[word]; + } + vector> buckets(words.size() + 1); + for (const auto& kvp : counts) { + buckets[kvp.second].emplace_back(kvp.first); + } + + vector> p; + for (int i = buckets.size() - 1; i >= 0; --i) { + for (const auto& word : buckets[i]) { + p.emplace_back(-i, word); + } + if (p.size() >= k) { + break; + } + } + sort(p.begin(), p.end()); + vector result; + for (int i = 0; i < k; ++i) { + result.emplace_back(p[i].second); + } + return result; + } +}; From 94e03d4aa16d269470fcbe4e826a7c3fa3d96b49 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Oct 2017 07:46:26 -0500 Subject: [PATCH 3826/4971] Update top-k-frequent-words.py --- Python/top-k-frequent-words.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/Python/top-k-frequent-words.py b/Python/top-k-frequent-words.py index c3bbdb033..686e8fba6 100644 --- a/Python/top-k-frequent-words.py +++ b/Python/top-k-frequent-words.py @@ -102,3 +102,27 @@ def __str__(self): return str(self.val) while min_heap: result.append(heapq.heappop(min_heap).val[1]) return result[::-1] + + +# Time: O(n + klogk) ~ O(n + nlogn) +# Space: O(n) +# Bucket Sort Solution +class Solution3(object): + def topKFrequent(self, words, k): + """ + :type words: List[str] + :type k: int + :rtype: List[str] + """ + counts = collections.Counter(words) + buckets = [[] for _ in xrange(len(words)+1)] + for word, count in counts.iteritems(): + buckets[count].append(word) + pairs = [] + for i in reversed(xrange(len(words))): + for word in buckets[i]: + pairs.append((-i, word)) + if len(pairs) >= k: + break + pairs.sort() + return [pair[1] for pair in pairs[:k]] From ad49821479d7ab22773b0597afe5c9f0d77a9f41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Oct 2017 07:47:04 -0500 Subject: [PATCH 3827/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a2afa2515..a630e2bc9 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 347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ | _O(n)_ | Medium | | Quick Select, Heap, Bucket Sort | 406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium | | | 451| [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/) | [C++](./C++/sort-characters-by-frequency.cpp) [Python](./Python/sort-characters-by-frequency.py) | _O(n)_ | _O(n)_ | Medium | | | -692| [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [C++](./C++/top-k-frequent-words.cpp) [Python](./Python/top-k-frequent-words.py) | _O(n + klogk)_ on average | _O(n)_ | Medium | | Quick Select, Heap | +692| [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [C++](./C++/top-k-frequent-words.cpp) [Python](./Python/top-k-frequent-words.py) | _O(n + klogk)_ on average | _O(n)_ | Medium | | Quick Select, Heap, Bucket Sort | ## Two Pointers | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From e6fb40f1cb28b24f8e446778d4aedc71770f39d3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Oct 2017 07:49:05 -0500 Subject: [PATCH 3828/4971] Update top-k-frequent-words.py --- Python/top-k-frequent-words.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/top-k-frequent-words.py b/Python/top-k-frequent-words.py index 686e8fba6..42c7e7355 100644 --- a/Python/top-k-frequent-words.py +++ b/Python/top-k-frequent-words.py @@ -86,13 +86,13 @@ def topKFrequent(self, words, k): """ class MinHeapObj(object): def __init__(self,val): self.val = val - def __lt__(self,other): return self.val[1] > other.val[1] if self.val[0] == other.val[0] else self.val < other.val + def __lt__(self,other): + return self.val[1] > other.val[1] if self.val[0] == other.val[0] else \ + self.val < other.val def __eq__(self,other): return self.val == other.val def __str__(self): return str(self.val) - counts = collections.defaultdict(int) - for i in words: - counts[i] += 1 + counts = collections.Counter(words) min_heap = [] for word, count in counts.iteritems(): heapq.heappush(min_heap, MinHeapObj((count, word))) From ef5bc37df1a0ebe0d9738f2d4ea32dd2665aab44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Oct 2017 07:50:15 -0500 Subject: [PATCH 3829/4971] Update top-k-frequent-words.py --- Python/top-k-frequent-words.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Python/top-k-frequent-words.py b/Python/top-k-frequent-words.py index 42c7e7355..d88d416bd 100644 --- a/Python/top-k-frequent-words.py +++ b/Python/top-k-frequent-words.py @@ -33,10 +33,7 @@ def topKFrequent(self, words, k): :type k: int :rtype: List[str] """ - counts = collections.defaultdict(int) - for i in words: - counts[i] += 1 - + counts = collections.Counter(words) p = [] for key, val in counts.iteritems(): p.append((-val, key)) From 964f5da8abd3d179c1670e386137d70207d5b711 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Oct 2017 07:51:35 -0500 Subject: [PATCH 3830/4971] Update top-k-frequent-elements.py --- Python/top-k-frequent-elements.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/Python/top-k-frequent-elements.py b/Python/top-k-frequent-elements.py index 2f3033c11..dd08c34ff 100644 --- a/Python/top-k-frequent-elements.py +++ b/Python/top-k-frequent-elements.py @@ -21,9 +21,7 @@ def topKFrequent(self, nums, k): :type k: int :rtype: List[int] """ - counts = collections.defaultdict(int) - for i in nums: - counts[i] += 1 + counts = collections.Counter(words) buckets = [[] for _ in xrange(len(nums)+1)] for i, count in counts.iteritems(): buckets[count].append(i) @@ -48,10 +46,7 @@ def topKFrequent(self, nums, k): :type k: int :rtype: List[int] """ - counts = collections.defaultdict(int) - for i in nums: - counts[i] += 1 - + counts = collections.Counter(words) p = [] for key, val in counts.iteritems(): p.append((-val, key)) From e7495d3783185e6dbcb3508086be384af75db99d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 03:56:52 -0500 Subject: [PATCH 3831/4971] Create partition-to-k-equal-sum-subsets.cpp --- C++/partition-to-k-equal-sum-subsets.cpp | 34 ++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/partition-to-k-equal-sum-subsets.cpp diff --git a/C++/partition-to-k-equal-sum-subsets.cpp b/C++/partition-to-k-equal-sum-subsets.cpp new file mode 100644 index 000000000..ab5d3e999 --- /dev/null +++ b/C++/partition-to-k-equal-sum-subsets.cpp @@ -0,0 +1,34 @@ +// Time: O(k^n) +// Space: O(n) + +class Solution { +public: + bool canPartitionKSubsets(vector& nums, int k) { + auto sum = accumulate(nums.begin(), nums.end(), 0); + if (sum % k != 0) { + return false; + } + sort(nums.begin(), nums.end(), greater()); + vector subset_sums(k); + return dfs(nums, sum / k, 0, &subset_sums); + } + +private: + bool dfs(const vector &nums, const int target, + const int i, vector *subset_sums) { + if (i == nums.size()) { + return true; + } + for (auto& subset_sum : *subset_sums) { + if (subset_sum + nums[i] > target) { + continue; + } + subset_sum += nums[i]; + if (dfs(nums, target, i + 1, subset_sums)) { + return true; + } + subset_sum -= nums[i]; + } + return false; + } +}; From 9f9573d7ce97508910ea22312e4655add2f26c34 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 04:12:06 -0500 Subject: [PATCH 3832/4971] Create partition-to-k-equal-sum-subsets.py --- Python/partition-to-k-equal-sum-subsets.py | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python/partition-to-k-equal-sum-subsets.py diff --git a/Python/partition-to-k-equal-sum-subsets.py b/Python/partition-to-k-equal-sum-subsets.py new file mode 100644 index 000000000..336ad3ca5 --- /dev/null +++ b/Python/partition-to-k-equal-sum-subsets.py @@ -0,0 +1,29 @@ +# Time: O(k^n) +# Space: O(n) + +class Solution(object): + def canPartitionKSubsets(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: bool + """ + def dfs(nums, target, i, subset_sums): + if i == len(nums): + print subset_sums + return True + for k in xrange(len(subset_sums)): + if subset_sums[k]+nums[i] > target: + continue + subset_sums[k] += nums[i] + if dfs(nums, target, i+1, subset_sums): + return True + subset_sums[k] -= nums[i] + return False + + total = sum(nums) + if total%k != 0: + return False + nums.sort(reverse=True) + subset_sums = [0] * k + return dfs(nums, total/k, 0, subset_sums) From 0a59c204e8557a984d0102603a7ba706b3b25467 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 04:12:33 -0500 Subject: [PATCH 3833/4971] Update partition-to-k-equal-sum-subsets.py --- Python/partition-to-k-equal-sum-subsets.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/partition-to-k-equal-sum-subsets.py b/Python/partition-to-k-equal-sum-subsets.py index 336ad3ca5..eb0a92ebc 100644 --- a/Python/partition-to-k-equal-sum-subsets.py +++ b/Python/partition-to-k-equal-sum-subsets.py @@ -10,7 +10,6 @@ def canPartitionKSubsets(self, nums, k): """ def dfs(nums, target, i, subset_sums): if i == len(nums): - print subset_sums return True for k in xrange(len(subset_sums)): if subset_sums[k]+nums[i] > target: From 1e8a7633dec492a03372675c64e1f29a0a14baf4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 07:40:38 -0500 Subject: [PATCH 3834/4971] Create degree-of-an-array.cpp --- C++/degree-of-an-array.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/degree-of-an-array.cpp diff --git a/C++/degree-of-an-array.cpp b/C++/degree-of-an-array.cpp new file mode 100644 index 000000000..4f8ca21a9 --- /dev/null +++ b/C++/degree-of-an-array.cpp @@ -0,0 +1,29 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int findShortestSubArray(vector& nums) { + unordered_map left, right; + unordered_map counts; + for (int i = 0; i < nums.size(); ++i) { + if (left.count(nums[i]) == 0) { + left[nums[i]] = i; + } + right[nums[i]] = i; + ++counts[nums[i]]; + } + auto degree = max_element(counts.begin(), counts.end(), + [](const pair& a, + const pair& b) { + return a.second < b.second; + })->second; + auto result = numeric_limits::max(); + for (const auto& kvp : counts) { + if (kvp.second == degree) { + result = min(result, right[kvp.first] - left[kvp.first] + 1); + } + } + return result; + } +}; From df80bb49e8e54bbe9a2459a2f57e0ad0ab87ca6c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 07:42:00 -0500 Subject: [PATCH 3835/4971] Create degree-of-an-array.py --- Python/degree-of-an-array.py | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/degree-of-an-array.py diff --git a/Python/degree-of-an-array.py b/Python/degree-of-an-array.py new file mode 100644 index 000000000..567caa282 --- /dev/null +++ b/Python/degree-of-an-array.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(n) + +# Given a non-empty array of non-negative integers nums, +# the degree of this array is defined as the maximum frequency of any one of its elements. +# +# Your task is to find the smallest possible length of a (contiguous) subarray of nums, +# that has the same degree as nums. +# +# Example 1: +# Input: [1, 2, 2, 3, 1] +# Output: 2 +# Explanation: +# The input array has a degree of 2 because both elements 1 and 2 appear twice. +# Of the subarrays that have the same degree: +# [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] +# The shortest length is 2. So return 2. +# +# Example 2: +# Input: [1,2,2,3,1,4,2] +# Output: 6 +# Note: +# +# nums.length will be between 1 and 50,000. +# nums[i] will be an integer between 0 and 49,999. + +class Solution(object): + def findShortestSubArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + counts = collections.Counter(nums) + left, right = {}, {} + for i, num in enumerate(nums): + left.setdefault(num, i) + right[num] = i + degree = max(counts.values()) + return min(right[num]-left[num]+1 \ + for num in counts.keys() \ + if counts[num] == degree) + From cb2bbb2f97b5d24cbabff3c9e114f66c2cbca69e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 07:53:54 -0500 Subject: [PATCH 3836/4971] Create count-binary-substrings.cpp --- C++/count-binary-substrings.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/count-binary-substrings.cpp diff --git a/C++/count-binary-substrings.cpp b/C++/count-binary-substrings.cpp new file mode 100644 index 000000000..defb0a3a3 --- /dev/null +++ b/C++/count-binary-substrings.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int countBinarySubstrings(string s) { + auto result = 0, prev = 0, curr = 1; + for (int i = 1; i < s.length(); ++i) { + if (s[i - 1] != s[i]) { + result += min(prev, curr); + prev = curr, curr = 1; + } else { + ++curr; + } + } + result += min(prev, curr); + return result; + } +}; From 9d3b48e98a8c9d60ae77b4669607deef197d8119 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 07:54:35 -0500 Subject: [PATCH 3837/4971] Create count-binary-substrings.py --- Python/count-binary-substrings.py | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/count-binary-substrings.py diff --git a/Python/count-binary-substrings.py b/Python/count-binary-substrings.py new file mode 100644 index 000000000..f282b349a --- /dev/null +++ b/Python/count-binary-substrings.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(1) + +# Give a string s, count the number of non-empty (contiguous) substrings +# that have the same number of 0's and 1's, and all the 0's and all the 1's +# in these substrings are grouped consecutively. +# +# Substrings that occur multiple times are counted the number of times they occur. +# +# Example 1: +# Input: "00110011" +# Output: 6 +# Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: +# "0011", "01", "1100", "10", "0011", and "01". +# +# Notice that some of these substrings repeat and are counted the number of times they occur. +# +# Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together. +# Example 2: +# Input: "10101" +# Output: 4 +# Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's. +# +# Note: +# s.length will be between 1 and 50,000. +# s will only consist of "0" or "1" characters. + +class Solution(object): + def countBinarySubstrings(self, s): + """ + :type s: str + :rtype: int + """ + result, prev, curr = 0, 0, 1 + for i in xrange(1, len(s)): + if s[i-1] != s[i]: + result += min(prev, curr) + prev, curr = curr, 1 + else: + curr += 1 + result += min(prev, curr) + return result From 2e8457a255f3c14a8681e867c7c5b0cf7a12b52c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 08:10:57 -0500 Subject: [PATCH 3838/4971] Update partition-to-k-equal-sum-subsets.py --- Python/partition-to-k-equal-sum-subsets.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/partition-to-k-equal-sum-subsets.py b/Python/partition-to-k-equal-sum-subsets.py index eb0a92ebc..118187387 100644 --- a/Python/partition-to-k-equal-sum-subsets.py +++ b/Python/partition-to-k-equal-sum-subsets.py @@ -1,4 +1,4 @@ -# Time: O(k^n) +# Time: O(k^(n-k) * k!) # Space: O(n) class Solution(object): @@ -18,6 +18,7 @@ def dfs(nums, target, i, subset_sums): if dfs(nums, target, i+1, subset_sums): return True subset_sums[k] -= nums[i] + if not subset_sums[k]: break return False total = sum(nums) From f23dba5cf9f8f4990f5cada6a2da8d8992a82562 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 08:13:43 -0500 Subject: [PATCH 3839/4971] Update partition-to-k-equal-sum-subsets.cpp --- C++/partition-to-k-equal-sum-subsets.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/C++/partition-to-k-equal-sum-subsets.cpp b/C++/partition-to-k-equal-sum-subsets.cpp index ab5d3e999..7542691d8 100644 --- a/C++/partition-to-k-equal-sum-subsets.cpp +++ b/C++/partition-to-k-equal-sum-subsets.cpp @@ -1,4 +1,4 @@ -// Time: O(k^n) +// Time: O(k^(n-k) * k!) // Space: O(n) class Solution { @@ -28,6 +28,9 @@ class Solution { return true; } subset_sum -= nums[i]; + if (subset_sum == 0) { + break; + } } return false; } From 8451b3006484b5e9d9732d611db352d5651e9baf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 09:05:10 -0500 Subject: [PATCH 3840/4971] Update partition-to-k-equal-sum-subsets.cpp --- C++/partition-to-k-equal-sum-subsets.cpp | 45 +++++++++++++++++++++--- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/C++/partition-to-k-equal-sum-subsets.cpp b/C++/partition-to-k-equal-sum-subsets.cpp index 7542691d8..267aa584d 100644 --- a/C++/partition-to-k-equal-sum-subsets.cpp +++ b/C++/partition-to-k-equal-sum-subsets.cpp @@ -1,14 +1,49 @@ -// Time: O(k^(n-k) * k!) -// Space: O(n) +// Time: O(n*2^n) +// Space: O(2^n) +// DP solution. class Solution { public: bool canPartitionKSubsets(vector& nums, int k) { auto sum = accumulate(nums.begin(), nums.end(), 0); - if (sum % k != 0) { + if (sum % k != 0 || *max_element(nums.begin(), nums.end()) > sum / k) { + return false; + } + unordered_map lookup; + lookup[(1 << nums.size()) - 1] = true; + return dfs(nums, sum / k, 0, sum, &lookup); + } + +private: + bool dfs(const vector& nums, const int target, + const int used, const int todo, + unordered_map *lookup) { + if (!lookup->count(used)) { + const auto targ = (todo - 1) % target + 1; + for (int i = 0; i < nums.size(); ++i) { + if (((used >> i) & 1) == 0 && nums[i] <= targ) { + if (dfs(nums, target, used | (1 << i), todo - nums[i], lookup)) { + (*lookup)[used] = true; + break; + } + } + } + } + return (*lookup)[used]; + } +}; + +// Time: O(k^(n-k) * k!) +// Space: O(n) +// DFS solution with pruning. +class Solution2 { +public: + bool canPartitionKSubsets(vector& nums, int k) { + auto sum = accumulate(nums.begin(), nums.end(), 0); + if (sum % k != 0 || *max_element(nums.begin(), nums.end()) > sum / k) { return false; } - sort(nums.begin(), nums.end(), greater()); + sort(nums.begin(), nums.end(), greater()); // speedup dfs vector subset_sums(k); return dfs(nums, sum / k, 0, &subset_sums); } @@ -28,7 +63,7 @@ class Solution { return true; } subset_sum -= nums[i]; - if (subset_sum == 0) { + if (subset_sum == 0) { // pruning break; } } From 163c1e0ab4eecd7ce2140b5ffa4e6b84803faf0c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 09:09:29 -0500 Subject: [PATCH 3841/4971] Update partition-to-k-equal-sum-subsets.cpp --- C++/partition-to-k-equal-sum-subsets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/partition-to-k-equal-sum-subsets.cpp b/C++/partition-to-k-equal-sum-subsets.cpp index 267aa584d..cc1dab60c 100644 --- a/C++/partition-to-k-equal-sum-subsets.cpp +++ b/C++/partition-to-k-equal-sum-subsets.cpp @@ -1,7 +1,7 @@ // Time: O(n*2^n) // Space: O(2^n) -// DP solution. +// Memoization solution. class Solution { public: bool canPartitionKSubsets(vector& nums, int k) { From 55069afd9c7609bc2463fe92894fe910b61dac33 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 09:10:52 -0500 Subject: [PATCH 3842/4971] Update partition-to-k-equal-sum-subsets.py --- Python/partition-to-k-equal-sum-subsets.py | 45 ++++++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/Python/partition-to-k-equal-sum-subsets.py b/Python/partition-to-k-equal-sum-subsets.py index 118187387..eb243bf2b 100644 --- a/Python/partition-to-k-equal-sum-subsets.py +++ b/Python/partition-to-k-equal-sum-subsets.py @@ -1,7 +1,46 @@ -# Time: O(k^(n-k) * k!) -# Space: O(n) +# Time: O(n*2^n) +# Space: O(2^n) +# Given an array of integers nums and a positive integer k, +# find whether it's possible to divide this array into k non-empty subsets whose sums are all equal. +# +# Example 1: +# Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 +# Output: True +# Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums. +# Note: +# +# 1 <= k <= len(nums) <= 16. +# 0 < nums[i] < 10000. + +# Memoization solution. class Solution(object): + def canPartitionKSubsets(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: bool + """ + def dfs(nums, target, used, todo, lookup): + if lookup[used] is None: + targ = (todo-1)%target + 1 + lookup[used] = any(dfs(nums, target, used | (1<>i) & 1) == 0 and num <= targ) + return lookup[used] + + total = sum(nums) + if total%k or max(nums) > total//k: + return False + lookup = [None] * (1 << len(nums)) + lookup[-1] = True + return dfs(nums, total//k, 0, total, lookup) + + +# Time: O(k^(n-k) * k!) +# Space: O(n) +# DFS solution with pruning. +class Solution2(object): def canPartitionKSubsets(self, nums, k): """ :type nums: List[int] @@ -22,7 +61,7 @@ def dfs(nums, target, i, subset_sums): return False total = sum(nums) - if total%k != 0: + if total%k != 0 or max(nums) > total//k: return False nums.sort(reverse=True) subset_sums = [0] * k From 0bdc807de08ac0e3e194a3caffa4c59041bc9b72 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 10:15:28 -0500 Subject: [PATCH 3843/4971] Create falling-squares.cpp --- C++/falling-squares.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/falling-squares.cpp diff --git a/C++/falling-squares.cpp b/C++/falling-squares.cpp new file mode 100644 index 000000000..2fceb33d5 --- /dev/null +++ b/C++/falling-squares.cpp @@ -0,0 +1,29 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + vector fallingSquares(vector>& positions) { + vector heights(positions.size()); + for (int i = 0; i < positions.size(); ++i) { + int left_i, size_i; + tie(left_i, size_i) = positions[i]; + int right_i = left_i + size_i; + heights[i] += size_i; + for (int j = i + 1; j < positions.size(); ++j) { + int left_j, size_j; + tie(left_j, size_j) = positions[j]; + int right_j = left_j + size_j; + if (left_j < right_i and left_i < right_j) { // intersect + heights[j] = max(heights[j], heights[i]); + } + } + } + + vector result; + for (const auto& height : heights) { + result.emplace_back(result.empty() ? height : max(result.back(), height)); + } + return result; + } +}; From 9b1bfac2536df15726f36a17e48ed586b32c2522 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 10:15:36 -0500 Subject: [PATCH 3844/4971] Create falling-squares.py --- Python/falling-squares.py | 88 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Python/falling-squares.py diff --git a/Python/falling-squares.py b/Python/falling-squares.py new file mode 100644 index 000000000..03be09610 --- /dev/null +++ b/Python/falling-squares.py @@ -0,0 +1,88 @@ +# Time: O(n^2) +# Space: O(n) + +# On an infinite number line (x-axis), we drop given squares in the order they are given. +# +# The i-th square dropped (positions[i] = (left, side_length)) is a square +# with the left-most point being positions[i][0] and sidelength positions[i][1]. +# +# The square is dropped with the bottom edge parallel to the number line, +# and from a higher height than all currently landed squares. +# We wait for each square to stick before dropping the next. +# +# The squares are infinitely sticky on their bottom edge, and will remain fixed +# to any positive length surface they touch (either the number line or another square). +# Squares dropped adjacent to each other will not stick together prematurely. +# +# Return a list ans of heights. Each height ans[i] represents the current highest height +# of any square we have dropped, after dropping squares represented by positions[0], positions[1], ..., positions[i]. +# +# Example 1: +# Input: [[1, 2], [2, 3], [6, 1]] +# Output: [2, 5, 5] +# Explanation: +# +# After the first drop of +# positions[0] = [1, 2]: +# _aa +# _aa +# ------- +# The maximum height of any square is 2. +# +# After the second drop of +# positions[1] = [2, 3]: +# __aaa +# __aaa +# __aaa +# _aa__ +# _aa__ +# -------------- +# The maximum height of any square is 5. +# The larger square stays on top of the smaller square despite where its center +# of gravity is, because squares are infinitely sticky on their bottom edge. +# +# After the third drop of +# positions[1] = [6, 1]: +# __aaa +# __aaa +# __aaa +# _aa +# _aa___a +# -------------- +# The maximum height of any square is still 5. +# +# Thus, we return an answer of +# [2, 5, 5] +# . +# +# Example 2: +# Input: [[100, 100], [200, 100]] +# Output: [100, 100] +# Explanation: Adjacent squares don't get stuck prematurely - only their bottom edge can stick to surfaces. +# Note: +# +# 1 <= positions.length <= 1000. +# 1 <= positions[0] <= 10^8. +# 1 <= positions[1] <= 10^6. + +class Solution(object): + def fallingSquares(self, positions): + """ + :type positions: List[List[int]] + :rtype: List[int] + """ + heights = [0] * len(positions) + for i in xrange(len(positions)): + left_i, size_i = positions[i] + right_i = left_i + size_i + heights[i] += size_i + for j in xrange(i+1, len(positions)): + left_j, size_j = positions[j] + right_j = left_j + size_j + if left_j < right_i and left_i < right_j: # intersect + heights[j] = max(heights[j], heights[i]) + + result = [] + for height in heights: + result.append(max(result[-1], height) if result else height) + return result From 319f174ea87c973804f83cc1375a96b1510b0c96 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 11:05:35 -0500 Subject: [PATCH 3845/4971] Update falling-squares.py --- Python/falling-squares.py | 86 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/Python/falling-squares.py b/Python/falling-squares.py index 03be09610..7b1852fb8 100644 --- a/Python/falling-squares.py +++ b/Python/falling-squares.py @@ -1,4 +1,4 @@ -# Time: O(n^2) +# Time: O(nlogn) # Space: O(n) # On an infinite number line (x-axis), we drop given squares in the order they are given. @@ -65,7 +65,91 @@ # 1 <= positions[0] <= 10^8. # 1 <= positions[1] <= 10^6. +class SegmentTree(object): + def __init__(self, N, update_fn, query_fn): + self.N = N + self.H = 1 + while (1 << self.H) < N: + self.H += 1 + + self.update_fn = update_fn + self.query_fn = query_fn + self.tree = [0] * (2 * N) + self.lazy = [0] * N + + def __apply(self, x, val): + self.tree[x] = self.update_fn(self.tree[x], val) + if x < self.N: + self.lazy[x] = self.update_fn(self.lazy[x], val) + + def __pull(self, x): + while x > 1: + x /= 2 + self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2 + 1]) + self.tree[x] = self.update_fn(self.tree[x], self.lazy[x]) + + def __push(self, x): + for h in xrange(self.H, 0, -1): + y = x >> h + if self.lazy[y]: + self.__apply(y*2, self.lazy[y]) + self.__apply(y*2 + 1, self.lazy[y]) + self.lazy[y] = 0 + + def update(self, L, R, h): + L += self.N + R += self.N + L0, R0 = L, R + while L <= R: + if L & 1: + self.__apply(L, h) + L += 1 + if R & 1 == 0: + self.__apply(R, h) + R -= 1 + L /= 2; R /= 2 + self.__pull(L0) + self.__pull(R0) + + def query(self, L, R): + L += self.N + R += self.N + self.__push(L); self.__push(R) + result = 0 + while L <= R: + if L & 1: + result = self.query_fn(result, self.tree[L]) + L += 1 + if R & 1 == 0: + result = self.query_fn(result, self.tree[R]) + R -= 1 + L /= 2; R /= 2 + return result + + +# Segment Tree solution. class Solution(object): + def fallingSquares(self, positions): + index = set() + for left, size in positions: + index.add(left); + index.add(left+size-1) + index = sorted(list(index)) + tree = SegmentTree(len(index), max, max) + max_height = 0 + result = [] + for left, size in positions: + L, R = bisect.bisect_left(index, left), bisect.bisect_left(index, left+size-1) + h = tree.query(L, R) + size + tree.update(L, R, h) + max_height = max(max_height, h) + result.append(max_height) + return result + + +# Time: O(nlogn) +# Space: O(n) +class Solution2(object): def fallingSquares(self, positions): """ :type positions: List[List[int]] From a679f57d562aefd824b2183907cc562c124869ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 11:07:06 -0500 Subject: [PATCH 3846/4971] Update falling-squares.py --- Python/falling-squares.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/falling-squares.py b/Python/falling-squares.py index 7b1852fb8..27bf05b71 100644 --- a/Python/falling-squares.py +++ b/Python/falling-squares.py @@ -147,7 +147,7 @@ def fallingSquares(self, positions): return result -# Time: O(nlogn) +# Time: O(n^2) # Space: O(n) class Solution2(object): def fallingSquares(self, positions): From f65f27e130357dcd53642fb6a731ec621c2bbce7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 11:29:53 -0500 Subject: [PATCH 3847/4971] Update falling-squares.cpp --- C++/falling-squares.cpp | 105 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 104 insertions(+), 1 deletion(-) diff --git a/C++/falling-squares.cpp b/C++/falling-squares.cpp index 2fceb33d5..2471439ac 100644 --- a/C++/falling-squares.cpp +++ b/C++/falling-squares.cpp @@ -1,7 +1,110 @@ -// Time: O(n^2) +// Time: O(nlogn) // Space: O(n) +// Segment Tree solution. class Solution { +public: + vector fallingSquares(vector>& positions) { + set index; + for (const auto& position : positions) { + index.emplace(position.first); + index.emplace(position.first + position.second - 1); + } + SegmentTree tree(index.size()); + auto max_height = 0; + vector result; + for (const auto& position : positions) { + const auto L = distance(index.begin(), index.lower_bound(position.first)); + const auto R = distance(index.begin(), index.lower_bound(position.first + position.second - 1)); + const auto h = tree.query(L, R) + position.second; + tree.update(L, R, h); + max_height = max(max_height, h); + result.emplace_back(max_height); + } + return result; + } + +private: + class SegmentTree { + public: + SegmentTree(int N) + : N_(N), + tree_(2 * N), + lazy_(N) + { + H_ = 1; + while ((1 << H_) < N) { + ++H_; + } + } + + void update(int L, int R, int h) { + L += N_; R += N_; + int L0 = L, R0 = R; + while (L <= R) { + if ((L & 1) == 1) { + apply(L++, h); + } + if ((R & 1) == 0) { + apply(R--, h); + } + L >>= 1; R >>= 1; + } + pull(L0); pull(R0); + } + + int query(int L, int R) { + L += N_; R += N_; + auto result = 0; + push(L); push(R); + while (L <= R) { + if ((L & 1) == 1) { + result = max(result, tree_[L++]); + } + if ((R & 1) == 0) { + result = max(result, tree_[R--]); + } + L >>= 1; R >>= 1; + } + return result; + } + + private: + int N_, H_; + vector tree_, lazy_; + + void apply(int x, int val) { + tree_[x] = max(tree_[x], val); + if (x < N_) { + lazy_[x] = max(tree_[x], val); + } + } + + void pull(int x) { + while (x > 1) { + x >>= 1; + tree_[x] = max(tree_[x * 2], tree_[x * 2 + 1]); + tree_[x] = max(tree_[x], lazy_[x]); + } + } + + void push(int x) { + for (int h = H_; h > 0; --h) { + int y = x >> h; + if (lazy_[y] > 0) { + apply(y * 2, lazy_[y]); + apply(y * 2 + 1, lazy_[y]); + lazy_[y] = 0; + } + } + } + }; +}; + + +// Time: O(n^2) +// Space: O(n) +class Solution2 { public: vector fallingSquares(vector>& positions) { vector heights(positions.size()); From 8f7198bf2e47d897829352cc664f1703aa0d1ddc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 12:16:40 -0500 Subject: [PATCH 3848/4971] Update falling-squares.cpp --- C++/falling-squares.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/falling-squares.cpp b/C++/falling-squares.cpp index 2471439ac..c22811726 100644 --- a/C++/falling-squares.cpp +++ b/C++/falling-squares.cpp @@ -14,8 +14,8 @@ class Solution { auto max_height = 0; vector result; for (const auto& position : positions) { - const auto L = distance(index.begin(), index.lower_bound(position.first)); - const auto R = distance(index.begin(), index.lower_bound(position.first + position.second - 1)); + const auto L = distance(index.begin(), index.find(position.first)); + const auto R = distance(index.begin(), index.find(position.first + position.second - 1)); const auto h = tree.query(L, R) + position.second; tree.update(L, R, h); max_height = max(max_height, h); From 3b2a7b075e4a1eb235794bf6b32217010ea95083 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 13:02:06 -0500 Subject: [PATCH 3849/4971] Update falling-squares.py --- Python/falling-squares.py | 54 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/Python/falling-squares.py b/Python/falling-squares.py index 27bf05b71..13bb1c82b 100644 --- a/Python/falling-squares.py +++ b/Python/falling-squares.py @@ -147,9 +147,61 @@ def fallingSquares(self, positions): return result -# Time: O(n^2) +# Time: O(n * sqrt(n)) # Space: O(n) class Solution2(object): + def fallingSquares(self, positions): + def query(heights, left, right, B, blocks, blocks_read): + result = 0 + while left % B and left <= right: + result = max(result, heights[left], blocks[left//B]) + left += 1 + while right % B != B-1 and left <= right: + result = max(result, heights[right], blocks[right//B]) + right -= 1 + while left <= right: + result = max(result, blocks[left//B], blocks_read[left//B]) + left += B + return result + + def update(heights, left, right, B, blocks, blocks_read, h): + while left % B and left <= right: + heights[left] = max(heights[left], h) + blocks_read[left//B] = max(blocks_read[left//B], h) + left += 1 + while right % B != B-1 and left <= right: + heights[right] = max(heights[right], h) + blocks_read[right//B] = max(blocks_read[right//B], h) + right -= 1 + while left <= right: + blocks[left//B] = max(blocks[left//B], h) + left += B + + index = set() + for left, size in positions: + index.add(left); + index.add(left+size-1) + index = sorted(list(index)) + W = len(index) + B = int(W**.5) + heights = [0] * W + blocks = [0] * (B+2) + blocks_read = [0] * (B+2) + + max_height = 0 + result = [] + for left, size in positions: + L, R = bisect.bisect_left(index, left), bisect.bisect_left(index, left+size-1) + h = query(heights, L, R, B, blocks, blocks_read) + size + update(heights, L, R, B, blocks, blocks_read, h) + max_height = max(max_height, h) + result.append(max_height) + return result + + +# Time: O(n^2) +# Space: O(n) +class Solution3(object): def fallingSquares(self, positions): """ :type positions: List[List[int]] From c081a67d3802b8ccf71b80cf0ec18346a46c1f82 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Oct 2017 13:18:52 -0500 Subject: [PATCH 3850/4971] Update falling-squares.cpp --- C++/falling-squares.cpp | 74 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/C++/falling-squares.cpp b/C++/falling-squares.cpp index c22811726..0232da1da 100644 --- a/C++/falling-squares.cpp +++ b/C++/falling-squares.cpp @@ -102,9 +102,81 @@ class Solution { }; -// Time: O(n^2) +// Time: O(n * sqrt(n)) // Space: O(n) class Solution2 { +public: + vector fallingSquares(vector>& positions) { + set index; + for (const auto& position : positions) { + index.emplace(position.first); + index.emplace(position.first + position.second - 1); + } + const auto W = index.size(); + const auto B = static_cast(sqrt(W)); + vector heights(W); + vector blocks(B + 2), blocks_read(B + 2); + + auto max_height = 0; + vector result; + for (const auto& position : positions) { + const auto L = distance(index.begin(), index.find(position.first)); + const auto R = distance(index.begin(), index.find(position.first + position.second - 1)); + const auto h = query(B, L, R, heights, blocks, blocks_read) + position.second; + update(B, h, L, R, &heights, &blocks, &blocks_read); + max_height = max(max_height, h); + result.emplace_back(max_height); + } + return result; + } + +private: + int query(const int B, + int left, int right, + const vector& heights, + const vector& blocks, const vector& blocks_read) { + int result = 0; + while (left % B > 0 && left <= right) { + result = max(result, max(heights[left], blocks[left / B])); + result = max(result, blocks[left / B]); + ++left; + } + while (right % B != B - 1 && left <= right) { + result = max(result, max(heights[right], blocks[right / B])); + --right; + } + while (left <= right) { + result = max(result, max(blocks[left / B], blocks_read[left / B])); + left += B; + } + return result; + } + + void update(const int B, const int h, + int left, int right, + vector *heights, + vector *blocks, vector *blocks_read) { + while (left % B > 0 && left <= right) { + (*heights)[left] = max((*heights)[left], h); + (*blocks_read)[left / B] = max((*blocks_read)[left / B], h); + ++left; + } + while (right % B != B - 1 && left <= right) { + (*heights)[right] = max((*heights)[right], h); + (*blocks_read)[right / B] = max((*blocks_read)[right / B], h); + --right; + } + while (left <= right) { + (*blocks)[left / B] = max((*blocks)[left / B], h); + left += B; + } + } +}; + + +// Time: O(n^2) +// Space: O(n) +class Solution3 { public: vector fallingSquares(vector>& positions) { vector heights(positions.size()); From f339ec858deafa8418db9ad3d33797d8b93e5b20 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Oct 2017 13:01:16 +0800 Subject: [PATCH 3851/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index a630e2bc9..220f12663 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 670| [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(logn)_ | _O(logn)_ | Medium ||| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [C++](./C++/longest-continuous-increasing-subsequence.cpp) [Python](./Python/longest-continuous-increasing-subsequence.py) | _O(n)_ | _O(1)_ | Easy || 683 | [K Empty Slots](https://leetcode.com/problems/k-empty-slots/) | [C++](./C++/k-empty-slots.cpp) [Python](./Python/k-empty-slots.py) | _O(n)_ | _O(n)_ | Hard || +697| [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [C++](./C++/degree-of-an-array.cpp) [Python](./Python/degree-of-an-array.py) | _O(n)_         | _O(n)_         | Easy           || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -162,6 +163,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 680| [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [C++](./C++/valid-palindrome-ii.cpp) [Python](./Python/valid-palindrome-ii.py) | _O(n)_ | _O(1)_ | Easy || 681| [Next Closest Time](https://leetcode.com/problems/next-closest-time/) | [C++](./C++/next-closest-time.cpp) [Python](./Python/next-closest-time.py) | _O(1)_ | _O(1)_ | Medium || 686 | [Repeated String Match](https://leetcode.com/problems/repeated-string-match/) | [C++](./C++/repeated-string-match.cpp) [Python](./Python/repeated-string-match.py) | _O(n + m)_ | _O(1)_ | Easy || `Rabin-Karp Algorithm` | +696| [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/) | [C++](./C++/count-binary-substrings.cpp) [Python](./Python/count-binary-substrings.py) | _O(n)_         | _O(1)_         | Easy           || ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -252,6 +254,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/) | [C++](./C++/redundant-connection.cpp) [Python](./Python/redundant-connection.py) | _O(n)_ | _O(n)_ | Medium || Union Find 685 | [Redundant Connection II](https://leetcode.com/problems/redundant-connection-ii/) | [C++](./C++/redundant-connection-ii.cpp) [Python](./Python/redundant-connection-ii.py) | _O(n)_ | _O(n)_ | Hard || Union Find 687 | [Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/) | [C++](./C++/longest-univalue-path.cpp) [Python](./Python/longest-univalue-path.py) | _O(n)_ | _O(h)_ | Easy || +699 | [Falling Squares](https://leetcode.com/problems/falling-squares/) | [C++](./C++/falling-squares.cpp) [Python](./Python/falling-squares.py) | _O(nlogn)_ | _O(n)_ | Hard || Segment Tree | ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -411,6 +414,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| 669| [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C++](./C++/trim-a-binary-search-tree.cpp) [Python](./Python/trim-a-binary-search-tree.py) | _O(n)_ | _O(h)_ | Easy || 671| [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [C++](./C++/second-minimum-node-in-a-binary-tree.cpp) [Python](./Python/second-minimum-node-in-a-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || +698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_         | _O(2^n)_         | Medium           || DP, Memoization ## Binary Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 7c060166afcccab829454546781a75088fd8642c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Oct 2017 13:03:29 +0800 Subject: [PATCH 3852/4971] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 220f12663..f237d52ab 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 670| [Maximum Swap](https://leetcode.com/problems/maximum-swap/) | [C++](./C++/maximum-swap.cpp) [Python](./Python/maximum-swap.py) | _O(logn)_ | _O(logn)_ | Medium ||| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [C++](./C++/longest-continuous-increasing-subsequence.cpp) [Python](./Python/longest-continuous-increasing-subsequence.py) | _O(n)_ | _O(1)_ | Easy || 683 | [K Empty Slots](https://leetcode.com/problems/k-empty-slots/) | [C++](./C++/k-empty-slots.cpp) [Python](./Python/k-empty-slots.py) | _O(n)_ | _O(n)_ | Hard || -697| [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [C++](./C++/degree-of-an-array.cpp) [Python](./Python/degree-of-an-array.py) | _O(n)_         | _O(n)_         | Easy           || +697| [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [C++](./C++/degree-of-an-array.cpp) [Python](./Python/degree-of-an-array.py) | _O(n)_ | _O(n)_ | Easy || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -163,7 +163,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 680| [Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) | [C++](./C++/valid-palindrome-ii.cpp) [Python](./Python/valid-palindrome-ii.py) | _O(n)_ | _O(1)_ | Easy || 681| [Next Closest Time](https://leetcode.com/problems/next-closest-time/) | [C++](./C++/next-closest-time.cpp) [Python](./Python/next-closest-time.py) | _O(1)_ | _O(1)_ | Medium || 686 | [Repeated String Match](https://leetcode.com/problems/repeated-string-match/) | [C++](./C++/repeated-string-match.cpp) [Python](./Python/repeated-string-match.py) | _O(n + m)_ | _O(1)_ | Easy || `Rabin-Karp Algorithm` | -696| [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/) | [C++](./C++/count-binary-substrings.cpp) [Python](./Python/count-binary-substrings.py) | _O(n)_         | _O(1)_         | Easy           || +696| [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/) | [C++](./C++/count-binary-substrings.cpp) [Python](./Python/count-binary-substrings.py) | _O(n)_ | _O(1)_ | Easy|| ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -414,7 +414,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| 669| [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C++](./C++/trim-a-binary-search-tree.cpp) [Python](./Python/trim-a-binary-search-tree.py) | _O(n)_ | _O(h)_ | Easy || 671| [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [C++](./C++/second-minimum-node-in-a-binary-tree.cpp) [Python](./Python/second-minimum-node-in-a-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || -698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_         | _O(2^n)_         | Medium           || DP, Memoization +698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_ | _O(2^n)_ | Medium           || DP, Memoization ## Binary Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 1640d8261ac66f214af81bfab73855a8e75297b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Oct 2017 13:05:50 +0800 Subject: [PATCH 3853/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f237d52ab..856c6d99c 100644 --- a/README.md +++ b/README.md @@ -414,7 +414,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| 669| [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C++](./C++/trim-a-binary-search-tree.cpp) [Python](./Python/trim-a-binary-search-tree.py) | _O(n)_ | _O(h)_ | Easy || 671| [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [C++](./C++/second-minimum-node-in-a-binary-tree.cpp) [Python](./Python/second-minimum-node-in-a-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || -698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_ | _O(2^n)_ | Medium           || DP, Memoization ## Binary Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -534,6 +533,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 425| [Word Squares](https://leetcode.com/problems/word-squares/) | [C++](./C++/word-squares.cpp) [Python](./Python/word-squares.py) | _O(n^2 * n!)_ | _O(n^2)_ | Hard |📖|| 676| [Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/) | [C++](./C++/implement-magic-dictionary.cpp) [Python](./Python/implement-magic-dictionary.py) | _O(n)_ | _O(d)_ | Medium || Trie, DFS 679| [24 Game](https://leetcode.com/problems/24-game/) | [C++](./C++/24-game.cpp) [Python](./Python/24-game.py) | _O(1)_ | _O(1)_ | Hard || DFS +698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_ | _O(2^n)_ | Medium           || DP, Memoization ## Dynamic Programming | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From d3d81b6b1234a653c00af01df48bec8f00bb7a71 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Oct 2017 13:06:14 +0800 Subject: [PATCH 3854/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 856c6d99c..1a3e04a44 100644 --- a/README.md +++ b/README.md @@ -533,7 +533,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 425| [Word Squares](https://leetcode.com/problems/word-squares/) | [C++](./C++/word-squares.cpp) [Python](./Python/word-squares.py) | _O(n^2 * n!)_ | _O(n^2)_ | Hard |📖|| 676| [Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/) | [C++](./C++/implement-magic-dictionary.cpp) [Python](./Python/implement-magic-dictionary.py) | _O(n)_ | _O(d)_ | Medium || Trie, DFS 679| [24 Game](https://leetcode.com/problems/24-game/) | [C++](./C++/24-game.cpp) [Python](./Python/24-game.py) | _O(1)_ | _O(1)_ | Hard || DFS -698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_ | _O(2^n)_ | Medium           || DP, Memoization +698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_ | _O(2^n)_ | Medium || DP, Memoization ## Dynamic Programming | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 633db6963c45b968e2fa44f604bce5c14b3e4e8d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Oct 2017 13:08:22 +0800 Subject: [PATCH 3855/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1a3e04a44..3fbce5d83 100644 --- a/README.md +++ b/README.md @@ -533,7 +533,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 425| [Word Squares](https://leetcode.com/problems/word-squares/) | [C++](./C++/word-squares.cpp) [Python](./Python/word-squares.py) | _O(n^2 * n!)_ | _O(n^2)_ | Hard |📖|| 676| [Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/) | [C++](./C++/implement-magic-dictionary.cpp) [Python](./Python/implement-magic-dictionary.py) | _O(n)_ | _O(d)_ | Medium || Trie, DFS 679| [24 Game](https://leetcode.com/problems/24-game/) | [C++](./C++/24-game.cpp) [Python](./Python/24-game.py) | _O(1)_ | _O(1)_ | Hard || DFS -698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_ | _O(2^n)_ | Medium || DP, Memoization +698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_ | _O(2^n)_ | Medium || DFS, DP, Memoization ## Dynamic Programming | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From b39d5ba2f12dba3b784402f3fd85ae351ece9b71 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 17 Oct 2017 10:19:43 -0500 Subject: [PATCH 3856/4971] Update partition-to-k-equal-sum-subsets.py --- Python/partition-to-k-equal-sum-subsets.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/partition-to-k-equal-sum-subsets.py b/Python/partition-to-k-equal-sum-subsets.py index eb243bf2b..60ed1b5ce 100644 --- a/Python/partition-to-k-equal-sum-subsets.py +++ b/Python/partition-to-k-equal-sum-subsets.py @@ -65,4 +65,4 @@ def dfs(nums, target, i, subset_sums): return False nums.sort(reverse=True) subset_sums = [0] * k - return dfs(nums, total/k, 0, subset_sums) + return dfs(nums, total//k, 0, subset_sums) From d876f061fd8d8864e4fce6f8b9098335b96c8de6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Oct 2017 10:39:21 -0500 Subject: [PATCH 3857/4971] Create number-of-distinct-islands-ii.cpp --- C++/number-of-distinct-islands-ii.cpp | 77 +++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 C++/number-of-distinct-islands-ii.cpp diff --git a/C++/number-of-distinct-islands-ii.cpp b/C++/number-of-distinct-islands-ii.cpp new file mode 100644 index 000000000..b15de2463 --- /dev/null +++ b/C++/number-of-distinct-islands-ii.cpp @@ -0,0 +1,77 @@ +// Time: ((m * n) * log(m * n)) +// Space: (m * n) + +class Solution { +public: + int numDistinctIslands2(vector>& grid) { + unordered_set>, VectorHash> islands; + for (int i = 0; i < grid.size(); ++i) { + for (int j = 0; j < grid[i].size(); ++j) { + if (grid[i][j] == 1) { + vector> island; + if (dfs(i, j, &grid, &island)) { + islands.emplace(normalize(island)); + } + } + } + } + return islands.size(); + } + +private: + struct VectorHash { + size_t operator()(const std::vector>& v) const { + size_t seed = 0; + for (const auto& i : v) { + seed ^= std::hash{}(i.first) + 0x9e3779b9 + (seed<<6) + (seed>>2); + seed ^= std::hash{}(i.second) + 0x9e3779b9 + (seed<<6) + (seed>>2); + } + return seed; + } + }; + + bool dfs(const int i, const int j, + vector> *grid, vector> *island) { + + static const vector> directions{{1, 0}, {-1, 0}, + {0, 1}, {0, -1}}; + + if (i < 0 || i >= grid->size() || + j < 0 || j >= (*grid)[0].size() || + (*grid)[i][j] <= 0) { + return false; + } + (*grid)[i][j] *= -1; + island->emplace_back(i, j); + for (const auto& direction : directions) { + dfs(i + direction.first, j + direction.second, grid, island); + } + return true; + } + + vector> normalize(const vector>& island) { + vector>> shapes(8); + for (const auto& p : island) { + int x, y; + tie(x, y) = p; + vector> rotations_and_reflections{{ x, y}, { x, -y}, {-x, y}, {-x, -y}, + { y, x}, { y, -x}, {-y, x}, {-y, -x}}; + for (int i = 0; i < rotations_and_reflections.size(); ++i) { + shapes[i].emplace_back(rotations_and_reflections[i]); + } + } + for (auto& shape : shapes) { + sort(shape.begin(), shape.end()); // O(ilogi), i is the size of the island, the max would be (m * n) + } + for (auto& shape : shapes) { + const auto origin = shape.front(); + for (auto& p : shape) { + p = {p.first - origin.first, + p.second - origin.second}; + } + } + sort(shapes.begin(), shapes.end()); + return shapes.front(); + } + +}; From 02a1469a10c50e8a331574f6a0e9449b90bb2be7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Oct 2017 10:41:04 -0500 Subject: [PATCH 3858/4971] Update number-of-distinct-islands-ii.cpp --- C++/number-of-distinct-islands-ii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/number-of-distinct-islands-ii.cpp b/C++/number-of-distinct-islands-ii.cpp index b15de2463..542dfa5f4 100644 --- a/C++/number-of-distinct-islands-ii.cpp +++ b/C++/number-of-distinct-islands-ii.cpp @@ -61,7 +61,7 @@ class Solution { } } for (auto& shape : shapes) { - sort(shape.begin(), shape.end()); // O(ilogi), i is the size of the island, the max would be (m * n) + sort(shape.begin(), shape.end()); // Time: O(ilogi), i is the size of the island, the max would be (m * n) } for (auto& shape : shapes) { const auto origin = shape.front(); From 5e1addefe0f41f6eb95d62944c3d648b5386e412 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Oct 2017 10:50:56 -0500 Subject: [PATCH 3859/4971] Update number-of-distinct-islands-ii.cpp --- C++/number-of-distinct-islands-ii.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/number-of-distinct-islands-ii.cpp b/C++/number-of-distinct-islands-ii.cpp index 542dfa5f4..dfae2d8a1 100644 --- a/C++/number-of-distinct-islands-ii.cpp +++ b/C++/number-of-distinct-islands-ii.cpp @@ -70,8 +70,6 @@ class Solution { p.second - origin.second}; } } - sort(shapes.begin(), shapes.end()); - return shapes.front(); - } - + return *min_element(shapes.begin(), shapes.end()); + } }; From 8e3dbf3521fbeceea33a0d9bb397ccc61e2c5fda Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Oct 2017 10:58:39 -0500 Subject: [PATCH 3860/4971] Create number-of-distinct-islands-ii.py --- Python/number-of-distinct-islands-ii.py | 45 +++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Python/number-of-distinct-islands-ii.py diff --git a/Python/number-of-distinct-islands-ii.py b/Python/number-of-distinct-islands-ii.py new file mode 100644 index 000000000..0c6d12c25 --- /dev/null +++ b/Python/number-of-distinct-islands-ii.py @@ -0,0 +1,45 @@ +# Time: ((m * n) * log(m * n)) +# Space: (m * n) + +class Solution(object): + def numDistinctIslands2(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + + def dfs(i, j, grid, island): + if not (0 <= i < len(grid) and \ + 0 <= j < len(grid[0]) and \ + grid[i][j] > 0): + return False + grid[i][j] *= -1 + island.append((i, j)); + for d in directions: + dfs(i+d[0], j+d[1], grid, island) + return True + + def normalize(island): + shapes = [[] for _ in xrange(8)] + for x, y in island: + rotations_and_reflections = [[ x, y], [ x, -y], [-x, y], [-x, -y], + [ y, x], [ y, -x], [-y, x], [-y, -x]] + for i in xrange(len(rotations_and_reflections)): + shapes[i].append(rotations_and_reflections[i]) + for shape in shapes: + shape.sort() # Time: O(ilogi), i is the size of the island, the max would be (m * n) + for shape in shapes: + origin = list(shape[0]) + for p in shape: + p[0] -= origin[0] + p[1] -= origin[1] + return min(shapes) + + islands = set() + for i in xrange(len(grid)): + for j in xrange(len(grid[0])): + island = [] + if dfs(i, j, grid, island): + islands.add(str(normalize(island))) + return len(islands) From 740d1ba5d1488f63cc993abd7061a57a7aeb7ef6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Oct 2017 11:00:06 -0500 Subject: [PATCH 3861/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 3fbce5d83..995a73a31 100644 --- a/README.md +++ b/README.md @@ -502,6 +502,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 690| [Employee Importance](https://leetcode.com/problems/employee-importance/) | [C++](./C++/employee-importance.cpp) [Python](./Python/employee-importance.py) | _O(n)_ | _O(h)_ | Easy || DFS, BFS 694| [Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands/) | [C++](./C++/number-of-distinct-islands.cpp) [Python](./Python/number-of-distinct-islands.py) | _O(m * n)_ | _O(m * n)_ | Medium |📖|| 695| [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [C++](./C++/max-area-of-island.cpp) [Python](./Python/max-area-of-island.py) | _O(m * n)_ | _O(m * n)_ | Easy || +711| [Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii/) | [C++](./C++/number-of-distinct-islands-ii.cpp) [Python](./Python/number-of-distinct-islands-ii.py) | _O((m * n) * log(m * n))_ | _O(m * n)_ | Hard |📖|| Hash ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 848ad352fc369f0bdcdbbeb88516d5f8623075a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Oct 2017 11:00:41 -0500 Subject: [PATCH 3862/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 995a73a31..85dac1a37 100644 --- a/README.md +++ b/README.md @@ -502,7 +502,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 690| [Employee Importance](https://leetcode.com/problems/employee-importance/) | [C++](./C++/employee-importance.cpp) [Python](./Python/employee-importance.py) | _O(n)_ | _O(h)_ | Easy || DFS, BFS 694| [Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands/) | [C++](./C++/number-of-distinct-islands.cpp) [Python](./Python/number-of-distinct-islands.py) | _O(m * n)_ | _O(m * n)_ | Medium |📖|| 695| [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [C++](./C++/max-area-of-island.cpp) [Python](./Python/max-area-of-island.py) | _O(m * n)_ | _O(m * n)_ | Easy || -711| [Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii/) | [C++](./C++/number-of-distinct-islands-ii.cpp) [Python](./Python/number-of-distinct-islands-ii.py) | _O((m * n) * log(m * n))_ | _O(m * n)_ | Hard |📖|| Hash +711| [Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii/) | [C++](./C++/number-of-distinct-islands-ii.cpp) [Python](./Python/number-of-distinct-islands-ii.py) | _O((m * n) * log(m * n))_ | _O(m * n)_ | Hard |📖| Hash | ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 63fc26fb57d9fc325f4c67621593e5bc211400c8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Oct 2017 11:16:04 -0500 Subject: [PATCH 3863/4971] Update number-of-distinct-islands-ii.py --- Python/number-of-distinct-islands-ii.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/number-of-distinct-islands-ii.py b/Python/number-of-distinct-islands-ii.py index 0c6d12c25..c1164b8bd 100644 --- a/Python/number-of-distinct-islands-ii.py +++ b/Python/number-of-distinct-islands-ii.py @@ -29,7 +29,6 @@ def normalize(island): shapes[i].append(rotations_and_reflections[i]) for shape in shapes: shape.sort() # Time: O(ilogi), i is the size of the island, the max would be (m * n) - for shape in shapes: origin = list(shape[0]) for p in shape: p[0] -= origin[0] From 28bbca944d340a972bf8ca5c7e2c9387bb74ebab Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 18 Oct 2017 11:17:39 -0500 Subject: [PATCH 3864/4971] Update number-of-distinct-islands-ii.cpp --- C++/number-of-distinct-islands-ii.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/C++/number-of-distinct-islands-ii.cpp b/C++/number-of-distinct-islands-ii.cpp index dfae2d8a1..35a650867 100644 --- a/C++/number-of-distinct-islands-ii.cpp +++ b/C++/number-of-distinct-islands-ii.cpp @@ -62,8 +62,6 @@ class Solution { } for (auto& shape : shapes) { sort(shape.begin(), shape.end()); // Time: O(ilogi), i is the size of the island, the max would be (m * n) - } - for (auto& shape : shapes) { const auto origin = shape.front(); for (auto& p : shape) { p = {p.first - origin.first, From cc02f814503c0b536af18a0b749045f66dd969e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 19 Oct 2017 12:47:40 +0800 Subject: [PATCH 3865/4971] Update number-of-distinct-islands-ii.py --- Python/number-of-distinct-islands-ii.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/number-of-distinct-islands-ii.py b/Python/number-of-distinct-islands-ii.py index c1164b8bd..4b1197c5c 100644 --- a/Python/number-of-distinct-islands-ii.py +++ b/Python/number-of-distinct-islands-ii.py @@ -1,5 +1,5 @@ -# Time: ((m * n) * log(m * n)) -# Space: (m * n) +# Time: O((m * n) * log(m * n)) +# Space: O(m * n) class Solution(object): def numDistinctIslands2(self, grid): From bf3cdf981729e518a98f92ad8e30cccc26731c18 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 19 Oct 2017 12:48:23 +0800 Subject: [PATCH 3866/4971] Update number-of-distinct-islands-ii.cpp --- C++/number-of-distinct-islands-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/number-of-distinct-islands-ii.cpp b/C++/number-of-distinct-islands-ii.cpp index 35a650867..7f09919ec 100644 --- a/C++/number-of-distinct-islands-ii.cpp +++ b/C++/number-of-distinct-islands-ii.cpp @@ -1,5 +1,5 @@ -// Time: ((m * n) * log(m * n)) -// Space: (m * n) +// Time: O((m * n) * log(m * n)) +// Space: O(m * n) class Solution { public: From 5f2c566c42385aae110a73f90ffc6c71c95ecd0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 20 Oct 2017 10:38:42 -0500 Subject: [PATCH 3867/4971] Create biggest-single-number.sql --- MySQL/biggest-single-number.sql | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 MySQL/biggest-single-number.sql diff --git a/MySQL/biggest-single-number.sql b/MySQL/biggest-single-number.sql new file mode 100644 index 000000000..2a195a016 --- /dev/null +++ b/MySQL/biggest-single-number.sql @@ -0,0 +1,19 @@ +# Time: O(n) +# Space: O(n) + +SELECT +IFNULL( + (SELECT + MAX(num) + FROM + (SELECT + num + FROM + number + GROUP BY num + HAVING COUNT(num) = 1 + ORDER BY NULL) AS t + ) + , NULL +) AS num +; From 74c9109b3746be791a9845f45eaff0cf5c74944d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 21 Oct 2017 09:11:31 -0500 Subject: [PATCH 3868/4971] Create students-report-by-geography.sql --- MySQL/students-report-by-geography.sql | 31 ++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 MySQL/students-report-by-geography.sql diff --git a/MySQL/students-report-by-geography.sql b/MySQL/students-report-by-geography.sql new file mode 100644 index 000000000..30186537d --- /dev/null +++ b/MySQL/students-report-by-geography.sql @@ -0,0 +1,31 @@ +# Time: O(nlogn) +# Space: O(n) + +SELECT + America, Asia, Europe +FROM + (SELECT @as:=0, @am:=0, @eu:=0) t, + (SELECT + @am:=@am + 1 AS amid, name AS America + FROM + student + WHERE + continent = 'America' + ORDER BY America) AS t1 + LEFT JOIN + (SELECT + @as:=@as + 1 AS asid, name AS Asia + FROM + student + WHERE + continent = 'Asia' + ORDER BY Asia) AS t2 ON amid = asid + LEFT JOIN + (SELECT + @eu:=@eu + 1 AS euid, name AS Europe + FROM + student + WHERE + continent = 'Europe' + ORDER BY Europe) AS t3 ON amid = euid +; From 59caecbb351419184ca560633f8405971e549972 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 01:28:46 -0500 Subject: [PATCH 3869/4971] Create minimum-ascii-delete-sum-for-two-strings.py --- ...inimum-ascii-delete-sum-for-two-strings.py | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Python/minimum-ascii-delete-sum-for-two-strings.py diff --git a/Python/minimum-ascii-delete-sum-for-two-strings.py b/Python/minimum-ascii-delete-sum-for-two-strings.py new file mode 100644 index 000000000..db149f828 --- /dev/null +++ b/Python/minimum-ascii-delete-sum-for-two-strings.py @@ -0,0 +1,74 @@ +# Time: O(m * n) +# Space: O(n) + +# Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal. +# +# Example 1: +# Input: s1 = "sea", s2 = "eat" +# Output: 231 +# Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum. +# Deleting "t" from "eat" adds 116 to the sum. +# At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this. +# +# Example 2: +# Input: s1 = "delete", s2 = "leet" +# Output: 403 +# Explanation: Deleting "dee" from "delete" to turn the string into "let", +# adds 100[d]+101[e]+101[e] to the sum. Deleting "e" from "leet" adds 101[e] to the sum. +# At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403. +# If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher. +# +# Note: +# - 0 < s1.length, s2.length <= 1000. +# - All elements of each string will have an ASCII value in [97, 122]. + +# DP with rolling window +class Solution(object): + def minimumDeleteSum(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: int + """ + dp = [[0] * (len(s2)+1) for _ in xrange(2)] + for j in xrange(len(s2)): + dp[0][j+1] = dp[0][j] + ord(s2[j]) + + for i in xrange(len(s1)): + dp[(i+1)%2][0] = dp[i%2][0] + ord(s1[i]) + for j in xrange(len(s2)): + if s1[i] == s2[j]: + dp[(i+1)%2][j+1] = dp[i%2][j] + else: + dp[(i+1)%2][j+1] = min(dp[i%2][j+1] + ord(s1[i]), + dp[(i+1)%2][j] + ord(s2[j])) + + return dp[len(s1)%2][-1] + + +# Time: O(m * n) +# Space: O(m * n) +class Solution2(object): + def minimumDeleteSum(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: int + """ + + dp = [[0] * (len(s2)+1) for _ in xrange(len(s1)+1)] + + for i in xrange(len(s1)): + dp[i+1][0] = dp[i][0] + ord(s1[i]) + for j in xrange(len(s2)): + dp[0][j+1] = dp[0][j] + ord(s2[j]) + + for i in xrange(len(s1)): + for j in xrange(len(s2)): + if s1[i] == s2[j]: + dp[i+1][j+1] = dp[i][j] + else: + dp[i+1][j+1] = min(dp[i][j+1] + ord(s1[i]), + dp[i+1][j] + ord(s2[j])) + + return dp[-1][-1] From e5d8e41fb48d86d97a7585fef00a6e1fa7355cbb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 01:30:45 -0500 Subject: [PATCH 3870/4971] Update minimum-ascii-delete-sum-for-two-strings.py --- Python/minimum-ascii-delete-sum-for-two-strings.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/Python/minimum-ascii-delete-sum-for-two-strings.py b/Python/minimum-ascii-delete-sum-for-two-strings.py index db149f828..5b904ed71 100644 --- a/Python/minimum-ascii-delete-sum-for-two-strings.py +++ b/Python/minimum-ascii-delete-sum-for-two-strings.py @@ -55,9 +55,7 @@ def minimumDeleteSum(self, s1, s2): :type s2: str :rtype: int """ - dp = [[0] * (len(s2)+1) for _ in xrange(len(s1)+1)] - for i in xrange(len(s1)): dp[i+1][0] = dp[i][0] + ord(s1[i]) for j in xrange(len(s2)): From fa96e68b78177b59bbc31af47c32e61dbd7626fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 01:34:28 -0500 Subject: [PATCH 3871/4971] Update minimum-ascii-delete-sum-for-two-strings.py --- Python/minimum-ascii-delete-sum-for-two-strings.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/minimum-ascii-delete-sum-for-two-strings.py b/Python/minimum-ascii-delete-sum-for-two-strings.py index 5b904ed71..6fd3f7683 100644 --- a/Python/minimum-ascii-delete-sum-for-two-strings.py +++ b/Python/minimum-ascii-delete-sum-for-two-strings.py @@ -40,7 +40,7 @@ def minimumDeleteSum(self, s1, s2): if s1[i] == s2[j]: dp[(i+1)%2][j+1] = dp[i%2][j] else: - dp[(i+1)%2][j+1] = min(dp[i%2][j+1] + ord(s1[i]), + dp[(i+1)%2][j+1] = min(dp[i%2][j+1] + ord(s1[i]), \ dp[(i+1)%2][j] + ord(s2[j])) return dp[len(s1)%2][-1] @@ -66,7 +66,7 @@ def minimumDeleteSum(self, s1, s2): if s1[i] == s2[j]: dp[i+1][j+1] = dp[i][j] else: - dp[i+1][j+1] = min(dp[i][j+1] + ord(s1[i]), + dp[i+1][j+1] = min(dp[i][j+1] + ord(s1[i]), \ dp[i+1][j] + ord(s2[j])) return dp[-1][-1] From 5a7ed686fe0493ca4d5f455442374bdbc3e657e5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 01:38:43 -0500 Subject: [PATCH 3872/4971] Create minimum-ascii-delete-sum-for-two-strings.cpp --- ...nimum-ascii-delete-sum-for-two-strings.cpp | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 C++/minimum-ascii-delete-sum-for-two-strings.cpp diff --git a/C++/minimum-ascii-delete-sum-for-two-strings.cpp b/C++/minimum-ascii-delete-sum-for-two-strings.cpp new file mode 100644 index 000000000..6c68db3d8 --- /dev/null +++ b/C++/minimum-ascii-delete-sum-for-two-strings.cpp @@ -0,0 +1,55 @@ +// Time: O(m * n) +// Space: O(n) + +// DP with rolling window. +class Solution { +public: + int minimumDeleteSum(string s1, string s2) { + vector> dp(2, vector(s2.length() + 1)); + for (int j = 0; j < s2.length(); ++j) { + dp[0][j + 1] = dp[0][j] + s2[j]; + } + + for (int i = 0; i < s1.length(); ++i) { + dp[(i + 1) % 2][0] = dp[i % 2][0] + s1[i]; + for (int j = 0; j < s2.length(); ++j) { + if (s1[i] == s2[j]) { + dp[(i + 1) % 2][j + 1] = dp[i % 2][j]; + } else { + dp[(i + 1) % 2][j + 1] = min(dp[i % 2][j + 1] + s1[i], + dp[(i + 1) % 2][j] + s2[j]); + } + } + } + + return dp[s1.length() % 2][s2.length()]; + } +}; + +// Time: O(m * n) +// Space: O(m * n) +class Solution2 { +public: + int minimumDeleteSum(string s1, string s2) { + vector> dp(s1.length() + 1, vector(s2.length() + 1)); + for (int i = 0; i < s1.length(); ++i) { + dp[i + 1][0] = dp[i][0] + s1[i]; + } + for (int j = 0; j < s2.length(); ++j) { + dp[0][j + 1] = dp[0][j] + s2[j]; + } + + for (int i = 0; i < s1.length(); ++i) { + for (int j = 0; j < s2.length(); ++j) { + if (s1[i] == s2[j]) { + dp[i + 1][j + 1] = dp[i][j]; + } else { + dp[i + 1][j + 1] = min(dp[i][j + 1] + s1[i], + dp[i + 1][j] + s2[j]); + } + } + } + + return dp[s1.length()][s2.length()]; + } +}; From 77c48102dd39534d64373fbc09b2e284fa237f63 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 01:48:27 -0500 Subject: [PATCH 3873/4971] Create subarray-product-less-than-k.py --- Python/subarray-product-less-than-k.py | 38 ++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/subarray-product-less-than-k.py diff --git a/Python/subarray-product-less-than-k.py b/Python/subarray-product-less-than-k.py new file mode 100644 index 000000000..3650ab757 --- /dev/null +++ b/Python/subarray-product-less-than-k.py @@ -0,0 +1,38 @@ +# Time: O(n) +# Space: O(1) + +# Your are given an array of positive integers nums. +# +# Count and print the number of (contiguous) subarrays where the product of all the elements +# in the subarray is less than k. +# +# Example 1: +# Input: nums = [10, 5, 2, 6], k = 100 +# Output: 8 +# Explanation: The 8 subarrays that have product less than 100 are: +# [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]. +# Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. +# +# Note: +# 0 < nums.length <= 50000. +# 0 < nums[i] < 1000. +# 0 <= k < 10^6. + +# Sliding window solution. +class Solution(object): + def numSubarrayProductLessThanK(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + if k <= 1: return 0 + result, start, prod = 0, 0, 1 + for i, num in enumerate(nums): + prod *= num + while prod >= k: + prod /= nums[start] + start += 1 + result += i-start+1 + return result + From a7a814c9d790d923ed72fa8d8ee3e11efed7ef1f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 01:51:23 -0500 Subject: [PATCH 3874/4971] Create subarray-product-less-than-k.cpp --- C++/subarray-product-less-than-k.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/subarray-product-less-than-k.cpp diff --git a/C++/subarray-product-less-than-k.cpp b/C++/subarray-product-less-than-k.cpp new file mode 100644 index 000000000..6312bc526 --- /dev/null +++ b/C++/subarray-product-less-than-k.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(1) + +// Sliding window solution. +class Solution { +public: + int numSubarrayProductLessThanK(vector& nums, int k) { + if (k <= 1) { + return 0; + } + int result = 0, start = 0, prod = 1; + for (int i = 0; i < nums.size(); ++i) { + prod *= nums[i]; + while (prod >= k) { + prod /= nums[start]; + ++start; + } + result += i - start + 1; + } + return result; + } +}; From 983bc912d94193f1ba1e079f888538a116dc9d57 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 02:08:31 -0500 Subject: [PATCH 3875/4971] Create best-time-to-buy-and-sell-stock-with-transaction-fee.py --- ...buy-and-sell-stock-with-transaction-fee.py | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py diff --git a/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py b/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py new file mode 100644 index 000000000..7393b5b6e --- /dev/null +++ b/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py @@ -0,0 +1,42 @@ +# Time: O(n) +# Space: O(1) + +# Your are given an array of integers prices, +# for which the i-th element is the price of a given stock on day i; +# and a non-negative integer fee representing a transaction fee. +# +# You may complete as many transactions as you like, +# but you need to pay the transaction fee for each transaction. +# You may not buy more than 1 share of a stock at a time +# (ie. you must sell the stock share before you buy again.) +# +# Return the maximum profit you can make. +# +# Example 1: +# Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 +# Output: 8 +# Explanation: The maximum profit can be achieved by: +# Buying at prices[0] = 1 +# Selling at prices[3] = 8 +# Buying at prices[4] = 4 +# Selling at prices[5] = 9 +# The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8. +# +# Note: +# - 0 < prices.length <= 50000. +# - 0 < prices[i] < 50000. +# - 0 <= fee < 50000. + +class Solution(object): + def maxProfit(self, prices, fee): + """ + :type prices: List[int] + :type fee: int + :rtype: int + """ + cash, hold = 0, -prices[0] + for i in xrange(1, len(prices)): + cash = max(cash, hold+prices[i]-fee) + hold = max(hold, cash-prices[i]) + return cash + From 559896ed94414644c8264de00819d371f5467bee Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 02:13:24 -0500 Subject: [PATCH 3876/4971] Create best-time-to-buy-and-sell-stock-with-transaction-fee.cpp --- ...-to-buy-and-sell-stock-with-transaction-fee.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/best-time-to-buy-and-sell-stock-with-transaction-fee.cpp diff --git a/C++/best-time-to-buy-and-sell-stock-with-transaction-fee.cpp b/C++/best-time-to-buy-and-sell-stock-with-transaction-fee.cpp new file mode 100644 index 000000000..a4e840a92 --- /dev/null +++ b/C++/best-time-to-buy-and-sell-stock-with-transaction-fee.cpp @@ -0,0 +1,14 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int maxProfit(vector& prices, int fee) { + int cash = 0, hold = -prices[0]; + for (int i = 1; i < prices.size(); ++i) { + cash = max(cash, hold + prices[i] - fee); + hold = max(hold, cash - prices[i]); + } + return cash; + } +}; From e6cffe3cd14b4d5ac9b35bd83dce1a079e3af7eb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 03:55:59 -0500 Subject: [PATCH 3877/4971] Create range-module.cpp --- C++/range-module.cpp | 76 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 C++/range-module.cpp diff --git a/C++/range-module.cpp b/C++/range-module.cpp new file mode 100644 index 000000000..106ce57f2 --- /dev/null +++ b/C++/range-module.cpp @@ -0,0 +1,76 @@ +// Time: addRange: O(n) +// removeRange: O(n) +// queryRange: O(logn) +// Space: O(n) + +class RangeModule { +public: + RangeModule() { + + } + + // Time: O(n) + void addRange(int left, int right) { + vector> tmp; + int i = 0; + for (const auto& range: ranges_) { + if (range.first > right) { + tmp.emplace_back(left, right); + break; + } else if (range.second < left) { + tmp.emplace_back(range); + } else { + left = min(left, range.first); + right = max(right, range.second); + } + ++i; + } + if (i == ranges_.size()) { + tmp.emplace_back(left, right); + } + while (i < ranges_.size()) { + tmp.emplace_back(ranges_[i++]); + } + swap(ranges_, tmp); + } + + // Time: O(logn) + bool queryRange(int left, int right) { + const auto it = lower_bound(ranges_.begin(), ranges_.end(), make_pair(left, right), + [](const pair& lhs, + const pair& rhs) { + return less{}(lhs.second, rhs.first); + }); + return it != ranges_.end() && it->first <= left && it->second >= right; + } + + // Time: O(n) + void removeRange(int left, int right) { + int n = ranges_.size(); + vector> tmp; + for (const auto& range : ranges_) { + if (range.second <= left || range.first >= right) { + tmp.emplace_back(range); + } else { + if (range.first < left) { + tmp.emplace_back(range.first, left); + } + if (range.second > right) { + tmp.emplace_back(right, range.second); + } + } + } + swap(ranges_, tmp); + } + +private: + vector> ranges_; +}; + +/** + * Your RangeModule object will be instantiated and called as such: + * RangeModule obj = new RangeModule(); + * obj.addRange(left,right); + * bool param_2 = obj.queryRange(left,right); + * obj.removeRange(left,right); + */ From 0876f9c569a13f7a82899567ac4c592af339041e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 03:58:55 -0500 Subject: [PATCH 3878/4971] Update range-module.cpp --- C++/range-module.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/range-module.cpp b/C++/range-module.cpp index 106ce57f2..a68b22552 100644 --- a/C++/range-module.cpp +++ b/C++/range-module.cpp @@ -55,7 +55,7 @@ class RangeModule { if (range.first < left) { tmp.emplace_back(range.first, left); } - if (range.second > right) { + if (right < range.second) { tmp.emplace_back(right, range.second); } } From b3c5d3dd7ed85aa2214a45883ae61ee7e1777c97 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 04:03:33 -0500 Subject: [PATCH 3879/4971] Update range-module.cpp --- C++/range-module.cpp | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/C++/range-module.cpp b/C++/range-module.cpp index a68b22552..80100a911 100644 --- a/C++/range-module.cpp +++ b/C++/range-module.cpp @@ -13,58 +13,58 @@ class RangeModule { void addRange(int left, int right) { vector> tmp; int i = 0; - for (const auto& range: ranges_) { - if (range.first > right) { + for (const auto& interval: intervals_) { + if (right < interval.first ) { tmp.emplace_back(left, right); break; - } else if (range.second < left) { - tmp.emplace_back(range); + } else if (interval.second < left) { + tmp.emplace_back(interval); } else { - left = min(left, range.first); - right = max(right, range.second); + left = min(left, interval.first); + right = max(right, interval.second); } ++i; } - if (i == ranges_.size()) { + if (i == intervals_.size()) { tmp.emplace_back(left, right); } - while (i < ranges_.size()) { - tmp.emplace_back(ranges_[i++]); + while (i < intervals_.size()) { + tmp.emplace_back(intervals_[i++]); } - swap(ranges_, tmp); + swap(intervals_, tmp); } // Time: O(logn) bool queryRange(int left, int right) { - const auto it = lower_bound(ranges_.begin(), ranges_.end(), make_pair(left, right), + const auto it = lower_bound(intervals_.begin(), intervals_.end(), make_pair(left, right), [](const pair& lhs, const pair& rhs) { return less{}(lhs.second, rhs.first); }); - return it != ranges_.end() && it->first <= left && it->second >= right; + return it != intervals_.end() && it->first <= left && it->second >= right; } // Time: O(n) void removeRange(int left, int right) { - int n = ranges_.size(); + int n = intervals_.size(); vector> tmp; - for (const auto& range : ranges_) { - if (range.second <= left || range.first >= right) { - tmp.emplace_back(range); + for (const auto& interval : intervals_) { + if (interval.second <= left || interval.first >= right) { + tmp.emplace_back(interval); } else { - if (range.first < left) { - tmp.emplace_back(range.first, left); + if (interval.first < left) { + tmp.emplace_back(interval.first, left); } - if (right < range.second) { - tmp.emplace_back(right, range.second); + if (right < interval.second) { + tmp.emplace_back(right, interval.second); } } } - swap(ranges_, tmp); + swap(intervals_, tmp); } private: - vector> ranges_; + vector> intervals_; }; /** From 544e6c97e0578731957044c9e997a4d10365026c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 04:06:50 -0500 Subject: [PATCH 3880/4971] Update range-module.cpp --- C++/range-module.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/range-module.cpp b/C++/range-module.cpp index 80100a911..7d1925bc6 100644 --- a/C++/range-module.cpp +++ b/C++/range-module.cpp @@ -46,7 +46,6 @@ class RangeModule { // Time: O(n) void removeRange(int left, int right) { - int n = intervals_.size(); vector> tmp; for (const auto& interval : intervals_) { if (interval.second <= left || interval.first >= right) { From 1b34b2e666e8cc5fd3d713f094e0cb8c4ffc78fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 04:28:41 -0500 Subject: [PATCH 3881/4971] Update range-module.cpp --- C++/range-module.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/C++/range-module.cpp b/C++/range-module.cpp index 7d1925bc6..53e2c5402 100644 --- a/C++/range-module.cpp +++ b/C++/range-module.cpp @@ -43,6 +43,15 @@ class RangeModule { }); return it != intervals_.end() && it->first <= left && it->second >= right; } + + // Time: O(logn) + bool queryRange2(int left, int right) { + auto it = lower_bound(intervals_.begin(), intervals_.end(), make_pair(left, numeric_limits::max())); + if (it != intervals_.begin()) { + it = prev(it); + } + return it != intervals_.end() && it->first <= left && it->second >= right; + } // Time: O(n) void removeRange(int left, int right) { From de3650503eaf2073817b4d35c116a2c076382441 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Oct 2017 04:30:17 -0500 Subject: [PATCH 3882/4971] Create range-module.py --- Python/range-module.py | 95 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Python/range-module.py diff --git a/Python/range-module.py b/Python/range-module.py new file mode 100644 index 000000000..612011f0e --- /dev/null +++ b/Python/range-module.py @@ -0,0 +1,95 @@ +# Time: addRange: O(n) +# removeRange: O(n) +# queryRange: O(logn) +# Space: O(n) + +# A Range Module is a module that tracks ranges of numbers. +# Your task is to design and implement the following interfaces in an efficient manner. +# - addRange(int left, int right) Adds the half-open interval [left, right), +# tracking every real number in that interval. +# Adding an interval that partially overlaps with currently tracked numbers should +# add any numbers in the interval [left, right) that are not already tracked. +# - queryRange(int left, int right) Returns true if and only if +# every real number in the interval [left, right) is currently being tracked. +# - removeRange(int left, int right) Stops tracking every real number currently being tracked +# in the interval [left, right). +# +# Example 1: +# addRange(10, 20): null +# removeRange(14, 16): null +# queryRange(10, 14): true (Every number in [10, 14) is being tracked) +# queryRange(13, 15): false (Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked) +# queryRange(16, 17): true (The number 16 in [16, 17) is still being tracked, despite the remove operation) +# +# Note: +# - A half open interval [left, right) denotes all real numbers left <= x < right. +# - 0 < left < right < 10^9 in all calls to addRange, queryRange, removeRange. +# - The total number of calls to addRange in a single test case is at most 1000. +# - The total number of calls to queryRange in a single test case is at most 5000. +# - The total number of calls to removeRange in a single test case is at most 1000. + +class RangeModule(object): + + def __init__(self): + self.__intervals = [] + + def addRange(self, left, right): + """ + :type left: int + :type right: int + :rtype: void + """ + tmp = [] + i = 0 + for interval in self.__intervals: + if right < interval[0]: + tmp.append((left, right)) + break + elif interval[1] < left: + tmp.append(interval); + else: + left = min(left, interval[0]) + right = max(right, interval[1]) + i += 1 + if i == len(self.__intervals): + tmp.append((left, right)) + while i < len(self.__intervals): + tmp.append(self.__intervals[i]) + i += 1 + self.__intervals = tmp + + def queryRange(self, left, right): + """ + :type left: int + :type right: int + :rtype: bool + """ + i = bisect.bisect_left(self.__intervals, (left, float("inf"))) + if i: i -= 1 + return bool(self.__intervals) and \ + self.__intervals[i][0] <= left and \ + right <= self.__intervals[i][1] + + def removeRange(self, left, right): + """ + :type left: int + :type right: int + :rtype: void + """ + tmp = [] + for interval in self.__intervals: + if interval[1] <= left or interval[0] >= right: + tmp.append(interval) + else: + if interval[0] < left: + tmp.append((interval[0], left)) + if right < interval[1]: + tmp.append((right, interval[1])) + self.__intervals = tmp + + +# Your RangeModule object will be instantiated and called as such: +# obj = RangeModule() +# obj.addRange(left,right) +# param_2 = obj.queryRange(left,right) +# obj.removeRange(left,right) From 68c3af7b0bce0878e5fc64568383656e2f8dfe46 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 Oct 2017 08:59:39 -0500 Subject: [PATCH 3883/4971] Update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 85dac1a37..e72e7172c 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [C++](./C++/longest-continuous-increasing-subsequence.cpp) [Python](./Python/longest-continuous-increasing-subsequence.py) | _O(n)_ | _O(1)_ | Easy || 683 | [K Empty Slots](https://leetcode.com/problems/k-empty-slots/) | [C++](./C++/k-empty-slots.cpp) [Python](./Python/k-empty-slots.py) | _O(n)_ | _O(n)_ | Hard || 697| [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [C++](./C++/degree-of-an-array.cpp) [Python](./Python/degree-of-an-array.py) | _O(n)_ | _O(n)_ | Easy || +713 | [Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/) | [C++](./C++/subarray-product-less-than-k.cpp) [Python](./Python/subarray-product-less-than-k.py) | _O(n)_ | _O(1)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -593,6 +594,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 688 | [Knight Probability in Chessboard](https://leetcode.com/problems/knight-probability-in-chessboard/) | [C++](./C++/knight-probability-in-chessboard.cpp) [Python](./Python/knight-probability-in-chessboard.py) | _O(k * n^2)_ | _O(n^2)_ | Medium || 689 | [Maximum Sum of 3 Non-Overlapping Subarrays](https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/) | [C++](./C++/maximum-sum-of-3-non-overlapping-subarrays.cpp) [Python](./Python/maximum-sum-of-3-non-overlapping-subarrays.py) | _O(n)_ | _O(n)_ | Hard || 691 | [Stickers to Spell Word](https://leetcode.com/problems/stickers-to-spell-word/) | [C++](./C++/stickers-to-spell-word.cpp) [Python](./Python/stickers-to-spell-word.py) | _O(T * S^T)_ | _O(T * S^T)_ | Hard || Backtracking, Memoization +712 | [Minimum ASCII Delete Sum for Two Strings](https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/) | [C++](./C++/minimum-ascii-delete-sum-for-two-strings.cpp) [Python](./Python/minimum-ascii-delete-sum-for-two-strings.py) | _O(m * n)_ | _O(n)_ | Medium || +714 | [Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-transaction-fee.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py) | _O(n)_ | _O(1)_ | Medium || ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -637,6 +640,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | +715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | addRange: _O(n)_
removeRange: _O(n)_
queryRange: _O(logn)_ | _O(n)_ | Hard || | + ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 7fe5b078193cd89b2f009e55c5e25b77894b69ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 Oct 2017 09:00:30 -0500 Subject: [PATCH 3884/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e72e7172c..d4a25e147 100644 --- a/README.md +++ b/README.md @@ -640,7 +640,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | -715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | addRange: _O(n)_
removeRange: _O(n)_
queryRange: _O(logn)_ | _O(n)_ | Hard || | +715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | ## SQL From f78f2bfe8edd9e2d735a31a47e670692aa074df5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 Oct 2017 09:02:17 -0500 Subject: [PATCH 3885/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d4a25e147..b8f47aa75 100644 --- a/README.md +++ b/README.md @@ -640,7 +640,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | -715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | +715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_, remove: _O(n)_, query: _O(logn)_ | _O(n)_ | Hard || | ## SQL From 8581f039c1d4efff04dcc05cda8825ec6ba8709f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 23 Oct 2017 09:03:12 -0500 Subject: [PATCH 3886/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b8f47aa75..d4a25e147 100644 --- a/README.md +++ b/README.md @@ -640,7 +640,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | -715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_, remove: _O(n)_, query: _O(logn)_ | _O(n)_ | Hard || | +715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | ## SQL From dd5e4ce6f33cfcb0e01be8976f36ad7f681bffdc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Oct 2017 08:59:45 -0500 Subject: [PATCH 3887/4971] Create average-salary-departments-vs-company.sql --- .../average-salary-departments-vs-company.sql | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 MySQL/average-salary-departments-vs-company.sql diff --git a/MySQL/average-salary-departments-vs-company.sql b/MySQL/average-salary-departments-vs-company.sql new file mode 100644 index 000000000..7106e85d3 --- /dev/null +++ b/MySQL/average-salary-departments-vs-company.sql @@ -0,0 +1,23 @@ +# Time: O(nlogn) +# Space: O(n) + +SELECT department_salary.pay_month, department_id, +CASE + WHEN department_avg < company_avg THEN 'lower' + WHEN department_avg > company_avg THEN 'higher' + ELSE 'same' +END AS comparison +FROM +( + SELECT department_id, AVG(amount) AS department_avg, date_format(pay_date, '%Y-%m') AS pay_month + FROM salary JOIN employee ON salary.employee_id = employee.employee_id + GROUP BY department_id, pay_month +) AS department_salary +JOIN +( + SELECT AVG(amount) AS company_avg, date_format(pay_date, '%Y-%m') AS pay_month + FROM salary + GROUP BY date_format(pay_date, '%Y-%m') +) AS company_salary +ON department_salary.pay_month = company_salary.pay_month +; From b84ccab1f767bc6381f4dcec0ab2d6f5a609933b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Oct 2017 09:57:39 -0500 Subject: [PATCH 3888/4971] Create second-degree-follower.sql --- MySQL/second-degree-follower.sql | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 MySQL/second-degree-follower.sql diff --git a/MySQL/second-degree-follower.sql b/MySQL/second-degree-follower.sql new file mode 100644 index 000000000..3fa3462c2 --- /dev/null +++ b/MySQL/second-degree-follower.sql @@ -0,0 +1,7 @@ +# Time: O(nlogn) +# Space: O(n) + +SELECT f1.follower, COUNT(DISTINCT f2.follower) AS num +FROM follow f1 +JOIN follow f2 ON f1.follower = f2.followee +GROUP BY f1.follower From 400a8564d5d96cd4461a77922824ccac4c067bbe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Oct 2017 08:48:05 -0500 Subject: [PATCH 3889/4971] Update substring-with-concatenation-of-all-words.py --- ...bstring-with-concatenation-of-all-words.py | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/Python/substring-with-concatenation-of-all-words.py b/Python/substring-with-concatenation-of-all-words.py index 03e5fa7f3..522b39074 100644 --- a/Python/substring-with-concatenation-of-all-words.py +++ b/Python/substring-with-concatenation-of-all-words.py @@ -1,7 +1,6 @@ # Time: O(m * n * k), where m is string length, n is dictionary size, k is word length - # Space: O(n * k) -# + # You are given a string, S, and a list of words, L, that are all of the same length. # Find all starting indices of substring(s) in S that is a concatenation of each word # in L exactly once and without any intervening characters. @@ -14,24 +13,26 @@ # (order does not matter). # -class Solution: - # @param S, a string - # @param L, a list of string - # @return a list of integer - def findSubstring(self, S, L): - result, word_num, word_len = [], len(L), len(L[0]) - words = collections.defaultdict(int) - for i in L: - words[i] += 1 +class Solution(object): + def findSubstring(self, s, words): + """ + :type s: str + :type words: List[str] + :rtype: List[int] + """ + result, word_num, word_len = [], len(words), len(words[0]) + lookup = collections.defaultdict(int) + for i in words: + lookup[i] += 1 # Space: O(n * k) - for i in xrange(len(S) + 1 - word_len * word_num): + for i in xrange(len(s) + 1 - word_len * word_num): # Time: O(m) 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: + while j < word_num: # Time: O(n) + word = s[i+j*word_len:i+j*word_len+word_len] # Time: O(k) + if word not in lookup: break cur[word] += 1 - if cur[word] > words[word]: + if cur[word] > lookup[word]: break j += 1 if j == word_num: @@ -39,5 +40,6 @@ def findSubstring(self, S, L): return result + if __name__ == "__main__": print Solution().findSubstring("barfoothefoobarman", ["foo", "bar"]) From be0016e5ed0ae0fec65d52b002d02636826cb286 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Oct 2017 10:00:04 -0500 Subject: [PATCH 3890/4971] Update substring-with-concatenation-of-all-words.cpp --- ...string-with-concatenation-of-all-words.cpp | 61 ++++++++++++++++++- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/C++/substring-with-concatenation-of-all-words.cpp b/C++/substring-with-concatenation-of-all-words.cpp index c1356a90c..eff6743b7 100644 --- a/C++/substring-with-concatenation-of-all-words.cpp +++ b/C++/substring-with-concatenation-of-all-words.cpp @@ -1,9 +1,66 @@ +// Time: O((m + n) * k), m is the length of the string, +// n is the size of the dictionary, +// k is the length of each word +// Space: O(n * k) + +// Sliding window solution. +class Solution { +public: + vector findSubstring(string s, vector& words) { + vector result; + const int m = s.length(); + const int n = words.size(); + const int k = words.front().length(); + if (m < n * k) { + return result; + } + + unordered_map lookup; + for (const auto& word : words) { + ++lookup[word]; // Space: O(n * k) + } + for (int i = 0; i < k; ++i) { // Time: O(k) + int left = i, count = 0; + unordered_map tmp; + for (int j = i; j <= m - k; j += k) { // Time: O(m / k) + const auto& str = s.substr(j, k); // Time: O(k) + if (lookup.count(str)) { + ++tmp[str]; + if (tmp[str] <= lookup[str]) { + ++count; + } else { + while (tmp[str] > lookup[str]) { + const auto& str1 = s.substr(left, k); + --tmp[str1]; + if (tmp[str1] < lookup[str1]) { + --count; + } + left += k; + } + } + if (count == n) { + result.emplace_back(left); + --tmp[s.substr(left, k)]; + --count; + left += k; + } + } else { + tmp.clear(); + count = 0; + left = j + k; + } + } + } + return result; + } +}; + + // Time: O((m - n * k) * n * k) ~ O(m * n * k), m is the length of the string, // n is the size of the dictionary, // k is the length of each word // Space: O(n * k) - -class Solution { +class Solution2 { public: vector findSubstring(string s, vector& words) { const auto word_length = words.front().length(); From 774689513c50ca87bcbad31fb48d99350234e39f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Oct 2017 10:03:06 -0500 Subject: [PATCH 3891/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d4a25e147..2ab3cce3f 100644 --- a/README.md +++ b/README.md @@ -262,7 +262,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| 1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Easy || 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || -30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [Python](./Python/substring-with-concatenation-of-all-words.py) | _O(m * n * k)_ | _O(n * k)_ | Hard || +30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [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/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || 49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [C++](./C++/anagrams.cpp) [Python](./Python/anagrams.py) | _O(n * glogg)_ | _O(n)_ | Medium || 76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [C++](./C++/minimum-window-substring.cpp) [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || From 52f89e416fc39b31a74d75e6caf41cc9cc0715d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Oct 2017 10:15:33 -0500 Subject: [PATCH 3892/4971] Update substring-with-concatenation-of-all-words.py --- ...bstring-with-concatenation-of-all-words.py | 61 ++++++++++++++++--- 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/Python/substring-with-concatenation-of-all-words.py b/Python/substring-with-concatenation-of-all-words.py index 522b39074..03b0ebdb4 100644 --- a/Python/substring-with-concatenation-of-all-words.py +++ b/Python/substring-with-concatenation-of-all-words.py @@ -1,4 +1,4 @@ -# Time: O(m * n * k), where m is string length, n is dictionary size, k is word length +# Time: O((m + n) * k), where m is string length, n is dictionary size, k is word length # Space: O(n * k) # You are given a string, S, and a list of words, L, that are all of the same length. @@ -20,22 +20,69 @@ def findSubstring(self, s, words): :type words: List[str] :rtype: List[int] """ - result, word_num, word_len = [], len(words), len(words[0]) + result, m, n, k = [], len(s), len(words), len(words[0]) + if m < n*k: + return result + + lookup = collections.defaultdict(int) + for i in words: + lookup[i] += 1 # Space: O(n * k) + + for i in xrange(k): # Time: O(m / k) + left, count = i, 0 + tmp = collections.defaultdict(int) + for j in xrange(i, m-k+1, k): # Time: O(m / k) + s1 = s[j:j+k]; # Time: O(k) + if s1 in lookup: + tmp[s1] += 1 + if tmp[s1] <= lookup[s1]: + count += 1 + else: + while tmp[s1] > lookup[s1]: + s2 = s[left:left+k] + tmp[s2] -= 1 + if tmp[s2] < lookup[s2]: + count -= 1 + left += k + if count == n: + result.append(left) + tmp[s[left:left+k]] -= 1 + count -= 1 + left += k + else: + tmp = collections.defaultdict(int) + count = 0 + left = j+k + return result + + +# Time: O(m * n * k), where m is string length, n is dictionary size, k is word length +# Space: O(n * k) +class Solution2(object): + def findSubstring(self, s, words): + """ + :type s: str + :type words: List[str] + :rtype: List[int] + """ + result, m, n, k = [], len(s), len(words), len(words[0]) + if m < n*k: + return result lookup = collections.defaultdict(int) for i in words: - lookup[i] += 1 # Space: O(n * k) + lookup[i] += 1 # Space: O(n * k) - for i in xrange(len(s) + 1 - word_len * word_num): # Time: O(m) + for i in xrange(m+1-k*n): # Time: O(m) cur, j = collections.defaultdict(int), 0 - while j < word_num: # Time: O(n) - word = s[i+j*word_len:i+j*word_len+word_len] # Time: O(k) + while j < n: # Time: O(n) + word = s[i+j*k:i+j*k+k] # Time: O(k) if word not in lookup: break cur[word] += 1 if cur[word] > lookup[word]: break j += 1 - if j == word_num: + if j == n: result.append(i) return result From 03f688f54e90850a4007c221c161845347218c0d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Oct 2017 10:16:30 -0500 Subject: [PATCH 3893/4971] Update substring-with-concatenation-of-all-words.py --- Python/substring-with-concatenation-of-all-words.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/substring-with-concatenation-of-all-words.py b/Python/substring-with-concatenation-of-all-words.py index 03b0ebdb4..822575031 100644 --- a/Python/substring-with-concatenation-of-all-words.py +++ b/Python/substring-with-concatenation-of-all-words.py @@ -68,6 +68,7 @@ def findSubstring(self, s, words): result, m, n, k = [], len(s), len(words), len(words[0]) if m < n*k: return result + lookup = collections.defaultdict(int) for i in words: lookup[i] += 1 # Space: O(n * k) From 1ad86d344f12384e7cd97d7d1ffb41f1784d403f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 26 Oct 2017 10:17:31 -0500 Subject: [PATCH 3894/4971] Update substring-with-concatenation-of-all-words.py --- ...substring-with-concatenation-of-all-words.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Python/substring-with-concatenation-of-all-words.py b/Python/substring-with-concatenation-of-all-words.py index 822575031..6a9a33e2d 100644 --- a/Python/substring-with-concatenation-of-all-words.py +++ b/Python/substring-with-concatenation-of-all-words.py @@ -1,18 +1,19 @@ # Time: O((m + n) * k), where m is string length, n is dictionary size, k is word length # Space: O(n * k) -# You are given a string, S, and a list of words, L, that are all of the same length. -# Find all starting indices of substring(s) in S that is a concatenation of each word -# in L exactly once and without any intervening characters. -# +# You are given a string, s, and a list of words, words, +# that are all of the same length. Find all starting indices of substring(s) +# in s that is a concatenation of each word in words exactly once and +# without any intervening characters. +# # For example, given: -# S: "barfoothefoobarman" -# L: ["foo", "bar"] -# +# s: "barfoothefoobarman" +# words: ["foo", "bar"] +# # You should return the indices: [0,9]. # (order does not matter). -# +# Sliding window solution class Solution(object): def findSubstring(self, s, words): """ From 880b76648c4feac4ce07c215913a601e0850b22f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 27 Oct 2017 12:40:03 +0800 Subject: [PATCH 3895/4971] Update substring-with-concatenation-of-all-words.py --- Python/substring-with-concatenation-of-all-words.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/substring-with-concatenation-of-all-words.py b/Python/substring-with-concatenation-of-all-words.py index 6a9a33e2d..f1127a886 100644 --- a/Python/substring-with-concatenation-of-all-words.py +++ b/Python/substring-with-concatenation-of-all-words.py @@ -29,7 +29,7 @@ def findSubstring(self, s, words): for i in words: lookup[i] += 1 # Space: O(n * k) - for i in xrange(k): # Time: O(m / k) + for i in xrange(k): # Time: O(k) left, count = i, 0 tmp = collections.defaultdict(int) for j in xrange(i, m-k+1, k): # Time: O(m / k) From e518cfdb02948c283fd127349e655e36c1736d1e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Oct 2017 10:30:55 -0500 Subject: [PATCH 3896/4971] Create shortest-distance-in-a-line.sql --- MySQL/shortest-distance-in-a-line.sql | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 MySQL/shortest-distance-in-a-line.sql diff --git a/MySQL/shortest-distance-in-a-line.sql b/MySQL/shortest-distance-in-a-line.sql new file mode 100644 index 000000000..a9f7c50e3 --- /dev/null +++ b/MySQL/shortest-distance-in-a-line.sql @@ -0,0 +1,10 @@ +# Time: O(n^2) +# Space: O(n) + +SELECT + MIN(p2.x - p1.x) AS shortest +FROM + point p1 + JOIN + point p2 ON p1.x < p2.x +; From dc6b023d1ecd593f183f2b9b61e825edc80f6119 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Oct 2017 11:09:30 -0500 Subject: [PATCH 3897/4971] Update shortest-distance-in-a-line.sql --- MySQL/shortest-distance-in-a-line.sql | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/MySQL/shortest-distance-in-a-line.sql b/MySQL/shortest-distance-in-a-line.sql index a9f7c50e3..c3afc75e0 100644 --- a/MySQL/shortest-distance-in-a-line.sql +++ b/MySQL/shortest-distance-in-a-line.sql @@ -1,6 +1,16 @@ -# Time: O(n^2) +# Time: O(nlogn) # Space: O(n) +SELECT MIN(P1.x - P2.x) AS shortest +FROM (SELECT @id1:=0, @id2:=0) AS t, + (SELECT @id1:=@id1+1 AS id, x FROM point ORDER BY x) AS P1 + JOIN + (SELECT @id2:=@id2+1 AS id, x FROM point ORDER BY x) AS P2 + ON P1.id = P2.id + 1 +WHERE P1.id > 1; + +# Time: O(n^2) +# Space: O(n) SELECT MIN(p2.x - p1.x) AS shortest FROM From 59032c82766125c7ff2ba261fd193beab059e564 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 28 Oct 2017 11:13:39 -0500 Subject: [PATCH 3898/4971] Update shortest-distance-in-a-line.sql --- MySQL/shortest-distance-in-a-line.sql | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/MySQL/shortest-distance-in-a-line.sql b/MySQL/shortest-distance-in-a-line.sql index c3afc75e0..41b702618 100644 --- a/MySQL/shortest-distance-in-a-line.sql +++ b/MySQL/shortest-distance-in-a-line.sql @@ -1,6 +1,16 @@ # Time: O(nlogn) # Space: O(n) +SET @prev := -100000000; +SELECT MIN(diff) AS shortest +FROM (SELECT (x - @prev) AS diff, @prev := x + FROM (SELECT * + FROM point + ORDER BY x) AS t1 + ) AS t2 +; +# Time: O(nlogn) +# Space: O(n) SELECT MIN(P1.x - P2.x) AS shortest FROM (SELECT @id1:=0, @id2:=0) AS t, (SELECT @id1:=@id1+1 AS id, x FROM point ORDER BY x) AS P1 From ff4aa6b0230c19f80ef5b271b6c3da944aeeff2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 04:13:42 -0500 Subject: [PATCH 3899/4971] Create 1-bit-and-2-bit-characters.cpp --- C++/1-bit-and-2-bit-characters.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/1-bit-and-2-bit-characters.cpp diff --git a/C++/1-bit-and-2-bit-characters.cpp b/C++/1-bit-and-2-bit-characters.cpp new file mode 100644 index 000000000..cc075fea6 --- /dev/null +++ b/C++/1-bit-and-2-bit-characters.cpp @@ -0,0 +1,14 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool isOneBitCharacter(vector& bits) { + auto parity = 0; + for (int i = static_cast(bits.size()) - 2; + i >= 0 && bits[i]; --i) { + parity ^= bits[i]; + } + return parity == 0; + } +}; From 11ae0377f1099bb2452ca3a17898957ac38f3d7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 04:20:07 -0500 Subject: [PATCH 3900/4971] Create 1-bit-and-2-bit-characters.py --- Python/1-bit-and-2-bit-characters.py | 41 ++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/1-bit-and-2-bit-characters.py diff --git a/Python/1-bit-and-2-bit-characters.py b/Python/1-bit-and-2-bit-characters.py new file mode 100644 index 000000000..a92f26b67 --- /dev/null +++ b/Python/1-bit-and-2-bit-characters.py @@ -0,0 +1,41 @@ +# Time: O(n) +# Space: O(1) + +# We have two special characters. The first character can be represented by one bit 0. +# The second character can be represented by two bits (10 or 11). +# +# Now given a string represented by several bits. Return whether the last character must +# be a one-bit character or not. The given string will always end with a zero. +# +# Example 1: +# Input: +# bits = [1, 0, 0] +# Output: True +# Explanation: +# The only way to decode it is two-bit character and one-bit character. +# So the last character is one-bit character. +# +# Example 2: +# Input: +# bits = [1, 1, 1, 0] +# Output: False +# Explanation: +# The only way to decode it is two-bit character and two-bit character. +# So the last character is NOT one-bit character. +# Note: +# +# 1 <= len(bits) <= 1000. +# bits[i] is always 0 or 1. + +class Solution(object): + def isOneBitCharacter(self, bits): + """ + :type bits: List[int] + :rtype: bool + """ + parity = 0 + for i in reversed(xrange(len(bits)-1)): + if bits[i] == 0: + break + parity ^= bits[i] + return parity == 0 From 225f805ace2bd50d9aa5416e253106e6acfe173d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 10:17:10 -0500 Subject: [PATCH 3901/4971] Create string-compression.cpp --- C++/string-compression.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/string-compression.cpp diff --git a/C++/string-compression.cpp b/C++/string-compression.cpp new file mode 100644 index 000000000..7187f79f2 --- /dev/null +++ b/C++/string-compression.cpp @@ -0,0 +1,27 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int compress(vector& chars) { + int i = 0; + for (int j = 0; j < chars.size();) { + if (j + 1 == chars.size() || chars[j] != chars[j + 1]) { + chars[i++] = chars[j++]; + } else { + int k = j; + while (j < chars.size() && chars[j] == chars[k]) { + ++j; + } + chars[i++] = chars[k]; + auto n = j - k, prev_i = i; + while (n > 0) { + chars[i++] = n % 10 + '0'; + n /= 10; + } + reverse(chars.begin() + prev_i, chars.begin() + i); + } + } + return i; + } +}; From c61f50f4f0a7ae3925adf8a521a289dcdd44ffee Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 10:27:13 -0500 Subject: [PATCH 3902/4971] Create string-compression.py --- Python/string-compression.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/string-compression.py diff --git a/Python/string-compression.py b/Python/string-compression.py new file mode 100644 index 000000000..5281feefe --- /dev/null +++ b/Python/string-compression.py @@ -0,0 +1,32 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def compress(self, chars): + """ + :type chars: List[str] + :rtype: int + """ + i, j = 0, 0 + while j < len(chars): + if j+1 == len(chars) or chars[j] != chars[j+1]: + chars[i] = chars[j] + i += 1 + j += 1 + else: + k = j + while j < len(chars) and chars[j] == chars[k]: + j += 1 + chars[i] = chars[k] + i += 1 + n, left = j-k, i + while n > 0: + chars[i] = chr(n%10+ord('0')) + n /= 10 + i += 1 + right = i-1 + while left < right: + chars[left], chars[right] = chars[right], chars[left] + left += 1 + right -= 1 + return i From 4bd5c76e293ffc7c749d4774211639175f61f0ec Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 10:40:37 -0500 Subject: [PATCH 3903/4971] Update search-for-a-range.py --- Python/search-for-a-range.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 088473598..ea12f74f3 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -19,11 +19,11 @@ def searchRange(self, nums, target): :type target: int :rtype: List[int] """ - # Find the first index where target <= nums[idx] + # Find the first idx where nums[idx] >= target left = self.binarySearch(lambda x, y: x >= y, nums, target) if left >= len(nums) or nums[left] != target: return [-1, -1] - # Find the first index where target < nums[idx] + # Find the first idx where nums[idx] > target right = self.binarySearch(lambda x, y: x > y, nums, target) return [left, right - 1] From 4cc20b2f780fe0cde68789f5912178b97c00b279 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 10:48:04 -0500 Subject: [PATCH 3904/4971] Create find-k-th-smallest-pair-distance.py --- Python/find-k-th-smallest-pair-distance.py | 49 ++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/find-k-th-smallest-pair-distance.py diff --git a/Python/find-k-th-smallest-pair-distance.py b/Python/find-k-th-smallest-pair-distance.py new file mode 100644 index 000000000..194315834 --- /dev/null +++ b/Python/find-k-th-smallest-pair-distance.py @@ -0,0 +1,49 @@ +# Time: O(nlogn + nlogw), n = len(nums), w = max(nums)-min(nums) +# Space: O(1) + +# Given an integer array, return the k-th smallest distance among all the pairs. +# The distance of a pair (A, B) is defined as the absolute difference between A and B. +# +# Example 1: +# Input: +# nums = [1,3,1] +# k = 1 +# Output: 0 +# Explanation: +# Here are all the pairs: +# (1,3) -> 2 +# (1,1) -> 0 +# (3,1) -> 2 +# Then the 1st smallest distance pair is (1,1), and its distance is 0. +# +# Note: +# 2 <= len(nums) <= 10000. +# 0 <= nums[i] < 1000000. +# 1 <= k <= len(nums) * (len(nums) - 1) / 2. + +# Binary search with sliding window solution +class Solution(object): + def smallestDistancePair(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + # Sliding window solution + def possible(guess, nums): + count, left = 0, 0 + for right, num in enumerate(nums): + while num-nums[left] > guess: + left += 1 + count += right-left + return count >= k + + nums.sort() + left, right = 0, nums[-1]-nums[0] + while left < right: + mid = left + (right-left)/2 + if possible(mid, nums): + right = mid + else: + left = mid+1 + return left From b82fdaf798c25062df29a0e7a21311de493365ad Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 10:58:12 -0500 Subject: [PATCH 3905/4971] Update find-k-th-smallest-pair-distance.py --- Python/find-k-th-smallest-pair-distance.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/find-k-th-smallest-pair-distance.py b/Python/find-k-th-smallest-pair-distance.py index 194315834..5a54f46c2 100644 --- a/Python/find-k-th-smallest-pair-distance.py +++ b/Python/find-k-th-smallest-pair-distance.py @@ -39,7 +39,7 @@ def possible(guess, nums): return count >= k nums.sort() - left, right = 0, nums[-1]-nums[0] + left, right = 0, nums[-1]-nums[0]+1 while left < right: mid = left + (right-left)/2 if possible(mid, nums): From a7c6e9fe576172fc08488d34a8113ec7929fc4a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 11:00:47 -0500 Subject: [PATCH 3906/4971] Update find-k-th-smallest-pair-distance.py --- Python/find-k-th-smallest-pair-distance.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/find-k-th-smallest-pair-distance.py b/Python/find-k-th-smallest-pair-distance.py index 5a54f46c2..6badaf3c1 100644 --- a/Python/find-k-th-smallest-pair-distance.py +++ b/Python/find-k-th-smallest-pair-distance.py @@ -30,7 +30,7 @@ def smallestDistancePair(self, nums, k): :rtype: int """ # Sliding window solution - def possible(guess, nums): + def possible(guess, nums, k): count, left = 0, 0 for right, num in enumerate(nums): while num-nums[left] > guess: @@ -42,7 +42,7 @@ def possible(guess, nums): left, right = 0, nums[-1]-nums[0]+1 while left < right: mid = left + (right-left)/2 - if possible(mid, nums): + if possible(mid, nums, k): right = mid else: left = mid+1 From 9d4e910d09eca19c601e3f24ef6f2cce3f24ae63 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 11:02:11 -0500 Subject: [PATCH 3907/4971] Create find-k-th-smallest-pair-distance.cpp --- C++/find-k-th-smallest-pair-distance.cpp | 32 ++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/find-k-th-smallest-pair-distance.cpp diff --git a/C++/find-k-th-smallest-pair-distance.cpp b/C++/find-k-th-smallest-pair-distance.cpp new file mode 100644 index 000000000..72ca5a7a6 --- /dev/null +++ b/C++/find-k-th-smallest-pair-distance.cpp @@ -0,0 +1,32 @@ +// Time: O(nlogn + nlogw), n = len(nums), w = max(nums) - min(nums) +// Space: O(1) + +// Binary search with sliding window solution +class Solution { +public: + int smallestDistancePair(vector& nums, int k) { + sort(nums.begin(), nums.end()); + int left = 0, right = nums.back() - nums.front() + 1; + while (left < right) { + const auto mid = left + (right - left) / 2; + if (possible(mid, nums, k)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + +private: + bool possible(const int guess, const vector& nums, const int k) { + int count = 0, left = 0; + for (int right = 0; right < nums.size(); ++right) { + while ((nums[right] - nums[left]) > guess) { + ++left; + } + count += right - left; + } + return count >= k; + } +}; From 85fd3464990469bf394bb240a7bc1ca73ab206a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 11:14:21 -0500 Subject: [PATCH 3908/4971] Create maximum-length-of-repeated-subarray.py --- Python/maximum-length-of-repeated-subarray.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/maximum-length-of-repeated-subarray.py diff --git a/Python/maximum-length-of-repeated-subarray.py b/Python/maximum-length-of-repeated-subarray.py new file mode 100644 index 000000000..d71d13051 --- /dev/null +++ b/Python/maximum-length-of-repeated-subarray.py @@ -0,0 +1,35 @@ +# Time: O(m * n) +# Space: O(min(m, n)) + +# Given two integer arrays A and B, +# return the maximum length of an subarray that appears in both arrays. +# +# Example 1: +# Input: +# A: [1,2,3,2,1] +# B: [3,2,1,4,7] +# Output: 3 +# Explanation: +# The repeated subarray with maximum length is [3, 2, 1]. +# Note: +# 1 <= len(A), len(B) <= 1000 +# 0 <= A[i], B[i] < 100 + +class Solution(object): + def findLength(self, A, B): + """ + :type A: List[int] + :type B: List[int] + :rtype: int + """ + if len(A) > len(B): return findLength(B, A) + result = 0 + dp = [[0] * (len(B)+1) for _ in xrange(2)] + for i in xrange(len(A)): + for j in xrange(len(B)): + if A[i] == B[j]: + dp[(i+1)%2][j+1] = dp[i%2][j]+1 + else: + dp[(i+1)%2][j+1] = 0 + result = max(result, max(dp[(i+1)%2])) + return result From 836af63a6179afc3038eb68798ead29d8b47101a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Oct 2017 11:20:35 -0500 Subject: [PATCH 3909/4971] Create maximum-length-of-repeated-subarray.cpp --- C++/maximum-length-of-repeated-subarray.cpp | 24 +++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/maximum-length-of-repeated-subarray.cpp diff --git a/C++/maximum-length-of-repeated-subarray.cpp b/C++/maximum-length-of-repeated-subarray.cpp new file mode 100644 index 000000000..42970bc14 --- /dev/null +++ b/C++/maximum-length-of-repeated-subarray.cpp @@ -0,0 +1,24 @@ +// Time: O(m * n) +// Space: O(min(m, n)) + +class Solution { +public: + int findLength(vector& A, vector& B) { + if (A.size() > B.size()) { + return findLength(B, A); + } + int result = 0; + vector> dp(2, vector(B.size() + 1)); + for (int i = 0; i < A.size(); ++i) { + for (int j = 0; j < B.size(); ++j) { + if (A[i] == B[j]) { + dp[(i + 1) % 2][j + 1] = dp[i % 2][j] + 1; + result = max(result, dp[(i + 1) % 2][j + 1]); + } else { + dp[(i + 1) % 2][j + 1] = 0; + } + } + } + return result; + } +}; From d27d800897529af4001acb758091727364637399 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 09:23:42 -0500 Subject: [PATCH 3910/4971] Update string-compression.cpp --- C++/string-compression.cpp | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/C++/string-compression.cpp b/C++/string-compression.cpp index 7187f79f2..8021ebce8 100644 --- a/C++/string-compression.cpp +++ b/C++/string-compression.cpp @@ -4,24 +4,22 @@ class Solution { public: int compress(vector& chars) { - int i = 0; - for (int j = 0; j < chars.size();) { - if (j + 1 == chars.size() || chars[j] != chars[j + 1]) { - chars[i++] = chars[j++]; - } else { - int k = j; - while (j < chars.size() && chars[j] == chars[k]) { - ++j; + int write = 0, anchor = 0; + for (int read = 0; read < chars.size(); ++read) { + if (read + 1 == chars.size() || chars[read + 1] != chars[read]) { + chars[write++] = chars[read]; + if (read - anchor > 0) { + auto n = read - anchor + 1, cnt = 0; + while (n > 0) { + chars[write++] = n % 10 + '0'; + n /= 10; + ++cnt; + } + reverse(chars.begin() + write - cnt, chars.begin() + write); } - chars[i++] = chars[k]; - auto n = j - k, prev_i = i; - while (n > 0) { - chars[i++] = n % 10 + '0'; - n /= 10; - } - reverse(chars.begin() + prev_i, chars.begin() + i); + anchor = read + 1; } } - return i; + return write; } }; From 88213850cf363b31b476a4d4841c88e324767f2b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 09:29:11 -0500 Subject: [PATCH 3911/4971] Update string-compression.py --- Python/string-compression.py | 81 ++++++++++++++++++++++++++---------- 1 file changed, 58 insertions(+), 23 deletions(-) diff --git a/Python/string-compression.py b/Python/string-compression.py index 5281feefe..cf57ce2e9 100644 --- a/Python/string-compression.py +++ b/Python/string-compression.py @@ -1,32 +1,67 @@ # Time: O(n) # Space: O(1) +# Given an array of characters, compress it in-place. +# The length after compression must always be smaller than or equal to the original array. +# Every element of the array should be a character (not int) of length 1. +# After you are done modifying the input array in-place, return the new length of the array. +# +# Follow up: +# Could you solve it using only O(1) extra space? +# +# Example 1: +# Input: +# ["a","a","b","b","c","c","c"] +# +# Output: +# Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] +# +# Explanation: +# "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". +# Example 2: +# Input: +# ["a"] +# +# Output: +# Return 1, and the first 1 characters of the input array should be: ["a"] +# +# Explanation: +# Nothing is replaced. +# Example 3: +# Input: +# ["a","b","b","b","b","b","b","b","b","b","b","b","b"] +# +# Output: +# Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. +# +# Explanation: +# Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12". +# Notice each digit has it's own entry in the array. +# Note: +# All characters have an ASCII value in [35, 126]. +# 1 <= len(chars) <= 1000. + class Solution(object): def compress(self, chars): """ :type chars: List[str] :rtype: int """ - i, j = 0, 0 - while j < len(chars): - if j+1 == len(chars) or chars[j] != chars[j+1]: - chars[i] = chars[j] - i += 1 - j += 1 - else: - k = j - while j < len(chars) and chars[j] == chars[k]: - j += 1 - chars[i] = chars[k] - i += 1 - n, left = j-k, i - while n > 0: - chars[i] = chr(n%10+ord('0')) - n /= 10 - i += 1 - right = i-1 - while left < right: - chars[left], chars[right] = chars[right], chars[left] - left += 1 - right -= 1 - return i + anchor, write = 0, 0 + for read, c in enumerate(chars): + if read+1 == len(chars) or chars[read+1] != c: + chars[write] = chars[anchor] + write += 1 + if read > anchor: + n, left = read-anchor+1, write + while n > 0: + chars[write] = chr(n%10+ord('0')) + write += 1 + n /= 10 + right = write-1 + while left < right: + chars[left], chars[right] = chars[right], chars[left] + left += 1 + right -= 1 + anchor = read+1 + return write From affcf5d160f6fb9ad638846caf4dabe061e254c8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 10:02:43 -0500 Subject: [PATCH 3912/4971] Update maximum-length-of-repeated-subarray.cpp --- C++/maximum-length-of-repeated-subarray.cpp | 80 ++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) diff --git a/C++/maximum-length-of-repeated-subarray.cpp b/C++/maximum-length-of-repeated-subarray.cpp index 42970bc14..337d0bfff 100644 --- a/C++/maximum-length-of-repeated-subarray.cpp +++ b/C++/maximum-length-of-repeated-subarray.cpp @@ -1,7 +1,85 @@ -// Time: O(m * n) +// Time: O(m * n * log(min(m, n))) // Space: O(min(m, n)) +// Binary search + rolling hash solution class Solution { +public: + int findLength(vector& A, vector& B) { + if (A.size() > B.size()) { + return findLength(B, A); + } + int left = 0, right = min(A.size(), B.size()) + 1; + while (left < right) { + const auto mid = left + (right-left) / 2; + if (!check(mid, A, B)) { // find the min idx such that check(idx) == false + right = mid; + } else { + left = mid + 1; + } + } + return left - 1; + } + +private: + bool check(const int guess, const vector& A, const vector& B) { + unordered_map> hashes; + int i = 0; + for (const auto& hash_a : rolling_hashes(A, guess)) { + hashes[hash_a].emplace_back(i++); + } + int j = 0; + for (const auto& hash_b : rolling_hashes(B, guess)) { + for (const auto& i : hashes[hash_b]) { + if (equal(A.begin() + i, A.begin() + i + guess, B.begin() + j)) { + return true; + } + } + ++j; + } + return false; + } + + vector rolling_hashes(const vector& source, const int length) { + static const uint64_t M = 1000000007; + static const uint64_t p = 113; + static const uint64_t p_inv = pow(p, M - 2, M); + vector result(source.size() - length + 1); + uint64_t hash = 0, power = 1; + if (length == 0) { + return result; + } + for (int i = 0; i < source.size(); ++i) { + hash = (hash + source[i] * power) % M; + if (i < length - 1) { + power = (power * p) % M; + } else { + result[i - (length - 1)] = hash; + hash = (hash - source[i - (length - 1)]) * p_inv % M; + if (hash < 0) hash += M; + } + } + return result; + } + + uint64_t pow(uint64_t a,uint64_t b, uint64_t m) { + a %= m; + uint64_t result = 1; + while (b) { + if (b & 1) { + result = (result * a) % m; + } + a = (a * a) % m; + b >>= 1; + } + return result; + } +}; + + +// Time: O(m * n) +// Space: O(min(m, n)) +// dp solution +class Solution2 { public: int findLength(vector& A, vector& B) { if (A.size() > B.size()) { From 0b19768861122b4e5a84ef28fa17335349dba115 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 10:04:17 -0500 Subject: [PATCH 3913/4971] Update maximum-length-of-repeated-subarray.cpp --- C++/maximum-length-of-repeated-subarray.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/maximum-length-of-repeated-subarray.cpp b/C++/maximum-length-of-repeated-subarray.cpp index 337d0bfff..23666f33c 100644 --- a/C++/maximum-length-of-repeated-subarray.cpp +++ b/C++/maximum-length-of-repeated-subarray.cpp @@ -1,7 +1,7 @@ // Time: O(m * n * log(min(m, n))) // Space: O(min(m, n)) -// Binary search + rolling hash solution +// Binary search + rolling hash solution (36 ms) class Solution { public: int findLength(vector& A, vector& B) { @@ -78,7 +78,7 @@ class Solution { // Time: O(m * n) // Space: O(min(m, n)) -// dp solution +// dp solution (102 ms) class Solution2 { public: int findLength(vector& A, vector& B) { From b89d6cc855e534dfba06c1c95b1d9cc4803807b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 10:21:10 -0500 Subject: [PATCH 3914/4971] Update maximum-length-of-repeated-subarray.py --- Python/maximum-length-of-repeated-subarray.py | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/Python/maximum-length-of-repeated-subarray.py b/Python/maximum-length-of-repeated-subarray.py index d71d13051..a1aa5bb84 100644 --- a/Python/maximum-length-of-repeated-subarray.py +++ b/Python/maximum-length-of-repeated-subarray.py @@ -1,4 +1,4 @@ -# Time: O(m * n) +# Time: O(m * n * logn(min(m, n)) # Space: O(min(m, n)) # Given two integer arrays A and B, @@ -15,7 +15,54 @@ # 1 <= len(A), len(B) <= 1000 # 0 <= A[i], B[i] < 100 +# Binary search + rolling hash solution (226 ms) class Solution(object): + def findLength(self, A, B): + """ + :type A: List[int] + :type B: List[int] + :rtype: int + """ + if len(A) > len(B): return findLength(B, A) + M, p = 10**9+7, 113 + p_inv = pow(p, M-2, M) + def check(guess): + def rolling_hashes(source, length): + if length == 0: + yield 0, 0 + return + + val, power = 0, 1 + for i, x in enumerate(source): + val = (val + x*power) % M + if i < length - 1: + power = (power*p) % M + else: + yield val, i-(length-1) + val = (val-source[i-(length-1)])*p_inv % M + + hashes = collections.defaultdict(list) + for hash_val, i in rolling_hashes(A, guess): + hashes[hash_val].append(i) + for hash_val, j in rolling_hashes(B, guess): + if any(A[i:i+guess] == B[j:j+guess] for i in hashes[hash_val]): + return True + return False + + left, right = 0, min(len(A), len(B)) + 1 + while left < right: + mid = left + (right-left)/2 + if not check(mid): # find the min idx such that check(idx) == false + right = mid + else: + left = mid+1 + return left-1 + + +# Time: O(m * n) +# Space: O(min(m, n)) +# dp solution (3752 ms) +class Solution2(object): def findLength(self, A, B): """ :type A: List[int] From 6bcbe1223f28eb853e5571a1dde8fa2d0acf594f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 10:29:27 -0500 Subject: [PATCH 3915/4971] Update maximum-length-of-repeated-subarray.py --- Python/maximum-length-of-repeated-subarray.py | 64 ++++++++++++++----- 1 file changed, 47 insertions(+), 17 deletions(-) diff --git a/Python/maximum-length-of-repeated-subarray.py b/Python/maximum-length-of-repeated-subarray.py index a1aa5bb84..b4e0d154b 100644 --- a/Python/maximum-length-of-repeated-subarray.py +++ b/Python/maximum-length-of-repeated-subarray.py @@ -1,4 +1,4 @@ -# Time: O(m * n * logn(min(m, n)) +# Time: O(m * n) # Space: O(min(m, n)) # Given two integer arrays A and B, @@ -15,8 +15,31 @@ # 1 <= len(A), len(B) <= 1000 # 0 <= A[i], B[i] < 100 -# Binary search + rolling hash solution (226 ms) +# dp solution (3752 ms) class Solution(object): + def findLength(self, A, B): + """ + :type A: List[int] + :type B: List[int] + :rtype: int + """ + if len(A) > len(B): return findLength(B, A) + result = 0 + dp = [[0] * (len(B)+1) for _ in xrange(2)] + for i in xrange(len(A)): + for j in xrange(len(B)): + if A[i] == B[j]: + dp[(i+1)%2][j+1] = dp[i%2][j]+1 + else: + dp[(i+1)%2][j+1] = 0 + result = max(result, max(dp[(i+1)%2])) + return result + + +# Time: O(m * n * log(min(m, n))) +# Space: O(min(m, n)) +# Binary search + rolling hash solution (226 ms) +class Solution2(object): def findLength(self, A, B): """ :type A: List[int] @@ -58,11 +81,11 @@ def rolling_hashes(source, length): left = mid+1 return left-1 - -# Time: O(m * n) -# Space: O(min(m, n)) -# dp solution (3752 ms) -class Solution2(object): + +# Time: O(m * n * min(m, n) * log(min(m, n))) +# Space: O(min(m^2, n^2)) +# Binary search (122 ms) +class Solution3(object): def findLength(self, A, B): """ :type A: List[int] @@ -70,13 +93,20 @@ def findLength(self, A, B): :rtype: int """ if len(A) > len(B): return findLength(B, A) - result = 0 - dp = [[0] * (len(B)+1) for _ in xrange(2)] - for i in xrange(len(A)): - for j in xrange(len(B)): - if A[i] == B[j]: - dp[(i+1)%2][j+1] = dp[i%2][j]+1 - else: - dp[(i+1)%2][j+1] = 0 - result = max(result, max(dp[(i+1)%2])) - return result + + def check(length): + lookup = set(A[i:i+length] \ + for i in xrange(len(A)-length+1)) + return any(B[j:j+length] in lookup \ + for j in xrange(len(B)-length+1)) + + A = ''.join(map(chr, A)) + B = ''.join(map(chr, B)) + left, right = 0, min(len(A), len(B)) + 1 + while left < right: + mid = left + (right-left)/2 + if not check(mid): # find the min idx such that check(idx) == false + right = mid + else: + left = mid+1 + return left-1 From 7cc326e21b2be336c985ceef243f5aab4561ea19 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 10:30:22 -0500 Subject: [PATCH 3916/4971] Update maximum-length-of-repeated-subarray.cpp --- C++/maximum-length-of-repeated-subarray.cpp | 56 ++++++++++----------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/C++/maximum-length-of-repeated-subarray.cpp b/C++/maximum-length-of-repeated-subarray.cpp index 23666f33c..888f3ff5b 100644 --- a/C++/maximum-length-of-repeated-subarray.cpp +++ b/C++/maximum-length-of-repeated-subarray.cpp @@ -1,8 +1,34 @@ -// Time: O(m * n * log(min(m, n))) +// Time: O(m * n) // Space: O(min(m, n)) -// Binary search + rolling hash solution (36 ms) +// dp solution (102 ms) class Solution { +public: + int findLength(vector& A, vector& B) { + if (A.size() > B.size()) { + return findLength(B, A); + } + int result = 0; + vector> dp(2, vector(B.size() + 1)); + for (int i = 0; i < A.size(); ++i) { + for (int j = 0; j < B.size(); ++j) { + if (A[i] == B[j]) { + dp[(i + 1) % 2][j + 1] = dp[i % 2][j] + 1; + result = max(result, dp[(i + 1) % 2][j + 1]); + } else { + dp[(i + 1) % 2][j + 1] = 0; + } + } + } + return result; + } +}; + + +// Time: O(m * n * log(min(m, n))) +// Space: O(min(m, n)) +// Binary search + rolling hash solution (36 ms) +class Solution2 { public: int findLength(vector& A, vector& B) { if (A.size() > B.size()) { @@ -74,29 +100,3 @@ class Solution { return result; } }; - - -// Time: O(m * n) -// Space: O(min(m, n)) -// dp solution (102 ms) -class Solution2 { -public: - int findLength(vector& A, vector& B) { - if (A.size() > B.size()) { - return findLength(B, A); - } - int result = 0; - vector> dp(2, vector(B.size() + 1)); - for (int i = 0; i < A.size(); ++i) { - for (int j = 0; j < B.size(); ++j) { - if (A[i] == B[j]) { - dp[(i + 1) % 2][j + 1] = dp[i % 2][j] + 1; - result = max(result, dp[(i + 1) % 2][j + 1]); - } else { - dp[(i + 1) % 2][j + 1] = 0; - } - } - } - return result; - } -}; From 5534bcee88ed998614ed9489945d1bc0b59bd25c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 10:36:13 -0500 Subject: [PATCH 3917/4971] Update maximum-length-of-repeated-subarray.py --- Python/maximum-length-of-repeated-subarray.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximum-length-of-repeated-subarray.py b/Python/maximum-length-of-repeated-subarray.py index b4e0d154b..be588aa9c 100644 --- a/Python/maximum-length-of-repeated-subarray.py +++ b/Python/maximum-length-of-repeated-subarray.py @@ -23,7 +23,7 @@ def findLength(self, A, B): :type B: List[int] :rtype: int """ - if len(A) > len(B): return findLength(B, A) + if len(A) < len(B): return findLength(B, A) result = 0 dp = [[0] * (len(B)+1) for _ in xrange(2)] for i in xrange(len(A)): From 170e73cc8bee240312b565c91a301b1436c6e972 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 10:36:48 -0500 Subject: [PATCH 3918/4971] Update maximum-length-of-repeated-subarray.cpp --- C++/maximum-length-of-repeated-subarray.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/maximum-length-of-repeated-subarray.cpp b/C++/maximum-length-of-repeated-subarray.cpp index 888f3ff5b..915d23e3c 100644 --- a/C++/maximum-length-of-repeated-subarray.cpp +++ b/C++/maximum-length-of-repeated-subarray.cpp @@ -5,7 +5,7 @@ class Solution { public: int findLength(vector& A, vector& B) { - if (A.size() > B.size()) { + if (A.size() < B.size()) { return findLength(B, A); } int result = 0; From b7cc9729e4a7ecb04e388168df8362b6f5f14736 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 10:37:34 -0500 Subject: [PATCH 3919/4971] Update maximum-length-of-repeated-subarray.cpp --- C++/maximum-length-of-repeated-subarray.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/maximum-length-of-repeated-subarray.cpp b/C++/maximum-length-of-repeated-subarray.cpp index 915d23e3c..e7bdc8356 100644 --- a/C++/maximum-length-of-repeated-subarray.cpp +++ b/C++/maximum-length-of-repeated-subarray.cpp @@ -1,7 +1,7 @@ // Time: O(m * n) // Space: O(min(m, n)) -// dp solution (102 ms) +// dp solution (99 ms) class Solution { public: int findLength(vector& A, vector& B) { From 67ac5faf13f9a76b19536bce08f5c362b4957d13 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 30 Oct 2017 10:40:48 -0500 Subject: [PATCH 3920/4971] Update maximum-length-of-repeated-subarray.cpp --- C++/maximum-length-of-repeated-subarray.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/maximum-length-of-repeated-subarray.cpp b/C++/maximum-length-of-repeated-subarray.cpp index e7bdc8356..2264817f8 100644 --- a/C++/maximum-length-of-repeated-subarray.cpp +++ b/C++/maximum-length-of-repeated-subarray.cpp @@ -81,7 +81,6 @@ class Solution2 { } else { result[i - (length - 1)] = hash; hash = (hash - source[i - (length - 1)]) * p_inv % M; - if (hash < 0) hash += M; } } return result; From eda9b2f495a2126cb196b724cccba9c8976b61d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 31 Oct 2017 09:42:33 -0500 Subject: [PATCH 3921/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 2ab3cce3f..1dad62e93 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 683 | [K Empty Slots](https://leetcode.com/problems/k-empty-slots/) | [C++](./C++/k-empty-slots.cpp) [Python](./Python/k-empty-slots.py) | _O(n)_ | _O(n)_ | Hard || 697| [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [C++](./C++/degree-of-an-array.cpp) [Python](./Python/degree-of-an-array.py) | _O(n)_ | _O(n)_ | Easy || 713 | [Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/) | [C++](./C++/subarray-product-less-than-k.cpp) [Python](./Python/subarray-product-less-than-k.py) | _O(n)_ | _O(1)_ | Medium || +717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit and 2-bit Characters/) | [C++](./C++/1-bit and 2-bit Characters.cpp) [Python](./Python/1-bit and 2-bit Characters.py) | _O(n)_ | _O(1)_ | Easy || Greedy ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -153,6 +154,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 415| [Add Strings](https://leetcode.com/problems/add-strings/) | [C++](./C++/add-strings.cpp) [Python](./Python/add-strings.py) | _O(n)_ | _O(1)_ | Easy | | 420| [Strong Password Checker](https://leetcode.com/problems/strong-password-checker/) | [C++](./C++/strong-password-checker.cpp) [Python](./Python/strong-password-checker.py) | _O(n)_ | _O(1)_ | Hard | | 434| [Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/) | [C++](./C++/number-of-segments-in-a-string.cpp) [Python](./Python/number-of-segments-in-a-string.py) | _O(n)_ | _O(1)_ | Easy | | +443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | 556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | @@ -443,6 +445,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 475 | [Heaters](https://leetcode.com/problems/heaters/) | [C++](./C++/heaters.cpp) [Python](./Python/heaters.py) | _O((m + n) * logn)_ | _O(1)_ | Easy | | 658 | [Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/) | [C++](./C++/find-k-closest-elements.cpp) [Python](./Python/find-k-closest-elements.py) | _O(logn + k)_ | _O(1)_ | Medium | | 668 | [Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [C++](./C++/kth-smallest-number-in-multiplication-table.cpp) [Python](./Python/kth-smallest-number-in-multiplication-table.py) | _O(m * log(m * n))_ | _O(1)_ | Hard | | +719 | [Find K-th Smallest Pair Distance](https://leetcode.com/problems/find-k-th-smallest-pair-distance/) | [C++](./C++/find-k-th-smallest-pair-distance.cpp) [Python](./Python/find-k-th-smallest-pair-distance.py) | _O(nlogn + nlogw)_ | _O(1)_ | Hard | | ## Binary Search Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -536,6 +539,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 676| [Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/) | [C++](./C++/implement-magic-dictionary.cpp) [Python](./Python/implement-magic-dictionary.py) | _O(n)_ | _O(d)_ | Medium || Trie, DFS 679| [24 Game](https://leetcode.com/problems/24-game/) | [C++](./C++/24-game.cpp) [Python](./Python/24-game.py) | _O(1)_ | _O(1)_ | Hard || DFS 698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_ | _O(2^n)_ | Medium || DFS, DP, Memoization +718 | [Maximum Length of Repeated Subarray](https://leetcode.com/problems/maximum-length-of-repeated-subarray/) | [C++](./C++/maximum-length-of-repeated-subarray.cpp) [Python](./Python/maximum-length-of-repeated-subarray.py) | _O(m * n)_ | _O(min(m, n))_ | Medium || DP, Hash, Binary Search ## Dynamic Programming | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 6132800b20cf66d563936a852e2fc3cd1819ee7b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 31 Oct 2017 09:43:51 -0500 Subject: [PATCH 3922/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1dad62e93..ff35276d8 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 683 | [K Empty Slots](https://leetcode.com/problems/k-empty-slots/) | [C++](./C++/k-empty-slots.cpp) [Python](./Python/k-empty-slots.py) | _O(n)_ | _O(n)_ | Hard || 697| [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [C++](./C++/degree-of-an-array.cpp) [Python](./Python/degree-of-an-array.py) | _O(n)_ | _O(n)_ | Easy || 713 | [Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/) | [C++](./C++/subarray-product-less-than-k.cpp) [Python](./Python/subarray-product-less-than-k.py) | _O(n)_ | _O(1)_ | Medium || -717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit and 2-bit Characters/) | [C++](./C++/1-bit and 2-bit Characters.cpp) [Python](./Python/1-bit and 2-bit Characters.py) | _O(n)_ | _O(1)_ | Easy || Greedy +717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/) | [C++](./C++/1-bit-and-2-bit-characters.cpp) [Python](./Python/1-bit-and-2-bit-characters.py) | _O(n)_ | _O(1)_ | Easy || Greedy ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 3d9714c54c80c0e2bdb1f5bdc1de5484e1fc27dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 1 Nov 2017 08:56:21 -0500 Subject: [PATCH 3923/4971] Create shortest-distance-in-a-plane.sql --- MySQL/shortest-distance-in-a-plane.sql | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 MySQL/shortest-distance-in-a-plane.sql diff --git a/MySQL/shortest-distance-in-a-plane.sql b/MySQL/shortest-distance-in-a-plane.sql new file mode 100644 index 000000000..374363906 --- /dev/null +++ b/MySQL/shortest-distance-in-a-plane.sql @@ -0,0 +1,10 @@ +# Time: O(n^2) +# Space: O(n^2) + +SELECT + ROUND(SQRT(MIN((POW(p1.x - p2.x, 2) + POW(p1.y - p2.y, 2)))),2) AS shortest +FROM + point_2d p1 + JOIN + point_2d p2 ON (p1.x < p2.x) OR (p1.x = p2.x AND p1.y < p2.y) +; From 1ce8bffb87953493fed62bd15bc878db58f0abef Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 2 Nov 2017 09:50:33 -0500 Subject: [PATCH 3924/4971] Create triangle-judgement.sql --- MySQL/triangle-judgement.sql | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 MySQL/triangle-judgement.sql diff --git a/MySQL/triangle-judgement.sql b/MySQL/triangle-judgement.sql new file mode 100644 index 000000000..996d7dbc7 --- /dev/null +++ b/MySQL/triangle-judgement.sql @@ -0,0 +1,6 @@ +# Time: O(n) +# Space: O(1) + +SELECT *, + IF (x+y>z AND x+z>y AND y+z>x, "Yes","No") AS triangle +FROM triangle; From c1d7e982a7c14efa94e85c510946c0567ced432f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 3 Nov 2017 09:32:23 -0500 Subject: [PATCH 3925/4971] Create tree-node.sql --- MySQL/tree-node.sql | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 MySQL/tree-node.sql diff --git a/MySQL/tree-node.sql b/MySQL/tree-node.sql new file mode 100644 index 000000000..a432b325d --- /dev/null +++ b/MySQL/tree-node.sql @@ -0,0 +1,11 @@ +# Time: O(n^2) +# Space: O(n) + +SELECT + atree.id, + IF(ISNULL(atree.p_id), + 'Root', + IF(atree.id IN (SELECT p_id FROM tree), 'Inner','Leaf')) AS Type +FROM + tree AS atree +ORDER BY atree.id From 328b3c7f0d5efc90d54b08e450dba08bccabeb2b Mon Sep 17 00:00:00 2001 From: JNingWei Date: Sat, 4 Nov 2017 23:31:45 +0800 Subject: [PATCH 3926/4971] Refactor: Simplify the code --- Python/string-to-integer-atoi.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/string-to-integer-atoi.py b/Python/string-to-integer-atoi.py index 87cb1c4ba..56b6c78e8 100644 --- a/Python/string-to-integer-atoi.py +++ b/Python/string-to-integer-atoi.py @@ -50,10 +50,10 @@ def myAtoi(self, str): sign = -1 i += 1 - while i < len(str) and str[i] >= '0' and str[i] <= '9': - if result > (INT_MAX - (ord(str[i]) - ord('0'))) / 10: + while i < len(str) and '0' <= str[i] <= '9': + if result > (INT_MAX - int(str[i])) / 10: return INT_MAX if sign > 0 else INT_MIN - result = result * 10 + ord(str[i]) - ord('0') + result = result * 10 + int(str[i]) i += 1 return sign * result From 7810d642946e11947fbd7a5a46e3f284369cc169 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 4 Nov 2017 10:59:08 -0500 Subject: [PATCH 3927/4971] Create sales-person.sql --- MySQL/sales-person.sql | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 MySQL/sales-person.sql diff --git a/MySQL/sales-person.sql b/MySQL/sales-person.sql new file mode 100644 index 000000000..9a008d568 --- /dev/null +++ b/MySQL/sales-person.sql @@ -0,0 +1,17 @@ +# Time: O(s * o) +# Space: O(s + o) + +SELECT + s.name +FROM + salesperson AS s +WHERE + s.sales_id NOT IN (SELECT + o.sales_id + FROM + orders AS o + LEFT JOIN + company AS c ON o.com_id = c.com_id + WHERE + c.name = 'RED') +; From 519164da86b708717bfc2db431c131e1c613cb41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 07:31:30 -0600 Subject: [PATCH 3928/4971] Create candy-crush.cpp --- C++/candy-crush.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 C++/candy-crush.cpp diff --git a/C++/candy-crush.cpp b/C++/candy-crush.cpp new file mode 100644 index 000000000..0e58e6cd4 --- /dev/null +++ b/C++/candy-crush.cpp @@ -0,0 +1,43 @@ +// Time: O((R * C)^2) +// Space: O(1) + +class Solution { +public: + vector> candyCrush(vector>& board) { + const auto R = board.size(), C = board[0].size(); + bool changed = true; + while (changed) { + changed = false; + for (int r = 0; r < R; ++r) { + for (int c = 0; c + 2 < C; ++c) { + auto v = abs(board[r][c]); + if (v != 0 && v == abs(board[r][c + 1]) && v == abs(board[r][c + 2])) { + board[r][c] = board[r][c + 1] = board[r][c + 2] = -v; + changed = true; + } + } + } + for (int r = 0; r + 2 < R; ++r) { + for (int c = 0; c < C; ++c) { + auto v = abs(board[r][c]); + if (v != 0 && v == abs(board[r + 1][c]) && v == abs(board[r + 2][c])) { + board[r][c] = board[r + 1][c] = board[r + 2][c] = -v; + changed = true; + } + } + } + for (int c = 0; c < C; ++c) { + int i = R - 1; + for (int r = R - 1; r >= 0; --r) { + if (board[r][c] > 0) { + board[i--][c] = board[r][c]; + } + } + while (i >= 0) { + board[i--][c] = 0; + } + } + } + return board; + } +}; From 9ca5d149902c139d5575fcc71523193b3471981f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 07:43:44 -0600 Subject: [PATCH 3929/4971] Update candy-crush.cpp --- C++/candy-crush.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/C++/candy-crush.cpp b/C++/candy-crush.cpp index 0e58e6cd4..702541a4b 100644 --- a/C++/candy-crush.cpp +++ b/C++/candy-crush.cpp @@ -6,8 +6,10 @@ class Solution { vector> candyCrush(vector>& board) { const auto R = board.size(), C = board[0].size(); bool changed = true; + while (changed) { changed = false; + for (int r = 0; r < R; ++r) { for (int c = 0; c + 2 < C; ++c) { auto v = abs(board[r][c]); @@ -17,6 +19,7 @@ class Solution { } } } + for (int r = 0; r + 2 < R; ++r) { for (int c = 0; c < C; ++c) { auto v = abs(board[r][c]); @@ -26,18 +29,20 @@ class Solution { } } } + for (int c = 0; c < C; ++c) { - int i = R - 1; + int empty_r = R - 1; for (int r = R - 1; r >= 0; --r) { if (board[r][c] > 0) { - board[i--][c] = board[r][c]; + board[empty_r--][c] = board[r][c]; } } - while (i >= 0) { - board[i--][c] = 0; + for (int r = empty_r; r >= 0; --r) { + board[r][c] = 0; } } } + return board; } }; From 5e723223b5206e6e92a6140f184d41f1abfdbb3d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 07:47:45 -0600 Subject: [PATCH 3930/4971] Create candy-crush.py --- Python/candy-crush.py | 71 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Python/candy-crush.py diff --git a/Python/candy-crush.py b/Python/candy-crush.py new file mode 100644 index 000000000..782f4af05 --- /dev/null +++ b/Python/candy-crush.py @@ -0,0 +1,71 @@ +# Time: O((R * C)^2) +# Space: O(1) + +# This question is about implementing a basic elimination algorithm for Candy Crush. +# +# Given a 2D integer array board representing the grid of candy, +# different positive integers board[i][j] represent different types of candies. +# A value of board[i][j] = 0 represents that the cell at position (i, j) is empty. +# The given board represents the state of the game following the player's move. +# Now, you need to restore the board to a stable state by crushing candies according to the following rules: +# +# If three or more candies of the same type are adjacent vertically or horizontally, +# "crush" them all at the same time - these positions become empty. +# +# After crushing all candies simultaneously, +# if an empty space on the board has candies on top of itself, +# then these candies will drop until they hit a candy or bottom at the same time. +# (No new candies will drop outside the top boundary.) +# +# After the above steps, there may exist more candies that can be crushed. +# If so, you need to repeat the above steps. +# If there does not exist more candies that can be crushed (ie. the board is stable), +# then return the current board. +# You need to perform the above rules until the board becomes stable, then return the current board. +# +# Example 1: +# Input: +# board = +# [[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]] +# Output: +# [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]] + +# Note: +# The length of board will be in the range [3, 50]. +# The length of board[i] will be in the range [3, 50]. +# Each board[i][j] will initially start as an integer in the range [1, 2000]. + +class Solution(object): + def candyCrush(self, board): + """ + :type board: List[List[int]] + :rtype: List[List[int]] + """ + R, C = len(board), len(board[0]) + changed = True + + while changed: + changed = False + + for r in xrange(R): + for c in xrange(C-2): + if abs(board[r][c]) == abs(board[r][c+1]) == abs(board[r][c+2]) != 0: + board[r][c] = board[r][c+1] = board[r][c+2] = -abs(board[r][c]) + changed = True + + for r in xrange(R-2): + for c in xrange(C): + if abs(board[r][c]) == abs(board[r+1][c]) == abs(board[r+2][c]) != 0: + board[r][c] = board[r+1][c] = board[r+2][c] = -abs(board[r][c]) + changed = True + + for c in xrange(C): + i = R-1 + for r in reversed(xrange(R)): + if board[r][c] > 0: + board[i][c] = board[r][c] + i -= 1 + for r in reversed(xrange(i+1)): + board[r][c] = 0 + + return board From 581d02ae38abedeae0eef48944a5c32b231d487e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 08:39:29 -0600 Subject: [PATCH 3931/4971] Create accounts-merge.py --- Python/accounts-merge.py | 84 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Python/accounts-merge.py diff --git a/Python/accounts-merge.py b/Python/accounts-merge.py new file mode 100644 index 000000000..d998da06f --- /dev/null +++ b/Python/accounts-merge.py @@ -0,0 +1,84 @@ +# Time: O(nlogn), n is the number of total emails, and the max length of email is 320, p.s. {64}@{255} +# Space: O(n) + +# Given a list accounts, each element accounts[i] is a list of strings, +# where the first element accounts[i][0] is a name, +# and the rest of the elements are emails representing emails of the account. +# +# Now, we would like to merge these accounts. +# Two accounts definitely belong to the same person if there is some email that is common to both accounts. +# Note that even if two accounts have the same name, +# they may belong to different people as people could have the same name. +# A person can have any number of accounts initially, but all of their accounts definitely have the same name. +# +# After merging the accounts, return the accounts in the following format: +# the first element of each account is the name, and the rest of the elements are emails in sorted order. +# The accounts themselves can be returned in any order. +# +# Example 1: +# Input: +# accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], +# ["John", "johnnybravo@mail.com"], +# ["John", "johnsmith@mail.com", "john_newyork@mail.com"], +# ["Mary", "mary@mail.com"]] +# Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], +# ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]] +# +# Explanation: +# The first and third John's are the same person as they have the common email "johnsmith@mail.com". +# The second John and Mary are different people as none of their email addresses are used by other accounts. +# We could return these lists in any order, +# for example the answer [['Mary', 'mary@mail.com'], +# ['John', 'johnnybravo@mail.com'], +# ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] +# would still be accepted. +# +# Note: +# +# The length of accounts will be in the range [1, 1000]. +# The length of accounts[i] will be in the range [1, 10]. +# The length of accounts[i][j] will be in the range [1, 30]. + +class UnionFind(object): + def __init__(self): + self.set = [] + + def get_id(self): + self.set.append(len(self.set)) + return len(self.set)-1 + + 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) + + +class Solution(object): + def accountsMerge(self, accounts): + """ + :type accounts: List[List[str]] + :rtype: List[List[str]] + """ + union_find = UnionFind() + email_to_name = {} + email_to_id = {} + for account in accounts: + name = account[0] + for n in xrange(1, len(account)): + email_to_name[account[n]] = name + if account[n] not in email_to_id: + email_to_id[account[n]] = union_find.get_id() + union_find.union_set(email_to_id[account[1]], email_to_id[account[n]]) + + result = collections.defaultdict(list) + for email in email_to_name.keys(): + result[union_find.find_set(email_to_id[email])].append(email) + for emails in result.values(): + emails.sort() + return [[email_to_name[emails[0]]] + emails for emails in result.values()] + From 246f9ab71722ac2c300c510603217d0a5e6aed09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 08:46:25 -0600 Subject: [PATCH 3932/4971] Update accounts-merge.py --- Python/accounts-merge.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Python/accounts-merge.py b/Python/accounts-merge.py index d998da06f..a9cf7dbd1 100644 --- a/Python/accounts-merge.py +++ b/Python/accounts-merge.py @@ -69,11 +69,11 @@ def accountsMerge(self, accounts): email_to_id = {} for account in accounts: name = account[0] - for n in xrange(1, len(account)): - email_to_name[account[n]] = name - if account[n] not in email_to_id: - email_to_id[account[n]] = union_find.get_id() - union_find.union_set(email_to_id[account[1]], email_to_id[account[n]]) + for i in xrange(1, len(account)): + email_to_name[account[i]] = name + if account[i] not in email_to_id: + email_to_id[account[i]] = union_find.get_id() + union_find.union_set(email_to_id[account[1]], email_to_id[account[i]]) result = collections.defaultdict(list) for email in email_to_name.keys(): @@ -81,4 +81,3 @@ def accountsMerge(self, accounts): for emails in result.values(): emails.sort() return [[email_to_name[emails[0]]] + emails for emails in result.values()] - From 4c44ff4af6a41009f41892843decd692b5e808b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 09:02:30 -0600 Subject: [PATCH 3933/4971] Update accounts-merge.py --- Python/accounts-merge.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/accounts-merge.py b/Python/accounts-merge.py index a9cf7dbd1..3f3a57b40 100644 --- a/Python/accounts-merge.py +++ b/Python/accounts-merge.py @@ -70,8 +70,8 @@ def accountsMerge(self, accounts): for account in accounts: name = account[0] for i in xrange(1, len(account)): - email_to_name[account[i]] = name if account[i] not in email_to_id: + email_to_name[account[i]] = name email_to_id[account[i]] = union_find.get_id() union_find.union_set(email_to_id[account[1]], email_to_id[account[i]]) From c809437c2eb59d82464d7b1743a5a8293ce5bde2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 09:04:02 -0600 Subject: [PATCH 3934/4971] Create accounts-merge.cpp --- C++/accounts-merge.cpp | 63 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 C++/accounts-merge.cpp diff --git a/C++/accounts-merge.cpp b/C++/accounts-merge.cpp new file mode 100644 index 000000000..b4d27cc95 --- /dev/null +++ b/C++/accounts-merge.cpp @@ -0,0 +1,63 @@ +// Time: O(nlogn), n is the number of total emails, and the max length of email is 320, p.s. {64}@{255} +// Space: O(n) + +class Solution { +public: + vector> accountsMerge(vector>& accounts) { + UnionFind union_find; + unordered_map email_to_name; + unordered_map email_to_id; + for (const auto& account : accounts) { + const auto& name = account[0]; + for (int i = 1; i < account.size(); ++i) { + if (!email_to_id.count(account[i])) { + email_to_name[account[i]] = name; + email_to_id[account[i]] = union_find.get_id(); + } + union_find.union_set(email_to_id[account[1]], email_to_id[account[i]]); + } + } + + unordered_map> lookup; + for (const auto& kvp : email_to_name) { + const auto& email = kvp.first; + lookup[union_find.find_set(email_to_id[email])].emplace(email); + } + vector> result; + for (const auto& kvp : lookup) { + const auto& emails = kvp.second; + vector tmp{email_to_name[*emails.begin()]}; + for (const auto& email : emails) { + tmp.emplace_back(email); + } + result.emplace_back(move(tmp)); + } + return result; + } + +private: + class UnionFind { + public: + int get_id() { + set_.emplace_back(set_.size()); + return set_.size() - 1; + } + + int find_set(const 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); + } + } + + private: + vector set_; + }; +}; From c79d80a29108b6eee8cfb202d8519986c9cf2831 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 09:15:42 -0600 Subject: [PATCH 3935/4971] Create remove-comments.py --- Python/remove-comments.py | 110 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 Python/remove-comments.py diff --git a/Python/remove-comments.py b/Python/remove-comments.py new file mode 100644 index 000000000..043ca24a4 --- /dev/null +++ b/Python/remove-comments.py @@ -0,0 +1,110 @@ +# Time: O(n), n is the length of the source +# Space: O(k), k is the max length of a line. + +# Given a C++ program, remove comments from it. +# The program source is an array where source[i] is the i-th line of the source code. +# This represents the result of splitting the original source code string by the newline character \n. +# +# In C++, there are two types of comments, line comments, and block comments. +# +# The string // denotes a line comment, which represents that it and +# rest of the characters to the right of it in the same line should be ignored. +# +# The string /* denotes a block comment, +# which represents that all characters until the next (non-overlapping) occurrence of */ +# should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) +# To be clear, the string /*/ does not yet end the block comment, as the ending would be overlapping the beginning. +# +# The first effective comment takes precedence over others: +# if the string // occurs in a block comment, it is ignored. +# Similarly, if the string /* occurs in a line or block comment, it is also ignored. +# +# If a certain line of code is empty after removing comments, +# you must not output that line: each string in the answer list will be non-empty. +# +# There will be no control characters, single quote, or double quote characters. +# For example, source = "string s = "/* Not a comment. */";" will not be a test case. +# (Also, nothing else such as defines or macros will interfere with the comments.) +# +# It is guaranteed that every open block comment will eventually be closed, +# so /* outside of a line or block comment always starts a new comment. +# +# Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details. +# +# After removing the comments from the source code, return the source code in the same format. +# +# Example 1: +# Input: +# source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"] +# +# The line by line code is visualized as below: +# /*Test program */ +# int main() +# { +# // variable declaration +# int a, b, c; +# /* This is a test +# multiline +# comment for +# testing */ +# a = b + c; +# } +# +# Output: ["int main()","{ "," ","int a, b, c;","a = b + c;","}"] +# +# The line by line code is visualized as below: +# int main() +# { +# int a, b, c; +# a = b + c; +# } +# Explanation: +# The string +# /* +# denotes a block comment, including line 1 and lines 6-9. The string +# // +# denotes line 4 as comments. +# +# Example 2: +# Input: +# source = ["a/*comment", "line", "more_comment*/b"] +# Output: ["ab"] +# Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", +# where we have bolded the newline characters. +# After deletion, the implicit newline characters are deleted, +# leaving the string "ab", which when delimited by newline characters becomes ["ab"]. +# +# Note: +# - The length of source is in the range [1, 100]. +# - The length of source[i] is in the range [0, 80]. +# - Every open block comment is eventually closed. +# - There are no single-quote, double-quote, or control characters in the source code. + +class Solution(object): + def removeComments(self, source): + """ + :type source: List[str] + :rtype: List[str] + """ + in_block = False + result = [] + for line in source: + i = 0 + if not in_block: + newline = [] + while i < len(line): + if line[i:i+2] == '/*' and not in_block: + in_block = True + i += 1 + elif line[i:i+2] == '*/' and in_block: + in_block = False + i += 1 + elif not in_block and line[i:i+2] == '//': + break + elif not in_block: + newline.append(line[i]) + i += 1 + if newline and not in_block: + result.append("".join(newline)) + + return result From 993a2dbf1e8f23c721451bbda0c530f3a9c35464 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 09:20:18 -0600 Subject: [PATCH 3936/4971] Update remove-comments.py --- Python/remove-comments.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/remove-comments.py b/Python/remove-comments.py index 043ca24a4..dbb05f88e 100644 --- a/Python/remove-comments.py +++ b/Python/remove-comments.py @@ -93,13 +93,13 @@ def removeComments(self, source): if not in_block: newline = [] while i < len(line): - if line[i:i+2] == '/*' and not in_block: + if not in_block and i+1 < len(line) and line[i:i+2] == '/*': in_block = True i += 1 - elif line[i:i+2] == '*/' and in_block: + elif in_block and i+1 < len(line) and line[i:i+2] == '*/': in_block = False i += 1 - elif not in_block and line[i:i+2] == '//': + elif not in_block and i+1 < len(line) and line[i:i+2] == '//': break elif not in_block: newline.append(line[i]) From 066a65aa0d60a6f83e13798eb74848bbffd199f6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 09:35:00 -0600 Subject: [PATCH 3937/4971] Update remove-comments.py --- Python/remove-comments.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/remove-comments.py b/Python/remove-comments.py index dbb05f88e..32196351e 100644 --- a/Python/remove-comments.py +++ b/Python/remove-comments.py @@ -1,5 +1,5 @@ # Time: O(n), n is the length of the source -# Space: O(k), k is the max length of a line. +# Space: O(k), k is the max length of a line # Given a C++ program, remove comments from it. # The program source is an array where source[i] is the i-th line of the source code. @@ -87,11 +87,11 @@ def removeComments(self, source): :rtype: List[str] """ in_block = False - result = [] + result, newline = [], [] for line in source: - i = 0 if not in_block: newline = [] + i = 0 while i < len(line): if not in_block and i+1 < len(line) and line[i:i+2] == '/*': in_block = True From da874d26fec365609751079704e31e7e84e6fabf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 09:36:30 -0600 Subject: [PATCH 3938/4971] Create remove-comments.cpp --- C++/remove-comments.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/remove-comments.cpp diff --git a/C++/remove-comments.cpp b/C++/remove-comments.cpp new file mode 100644 index 000000000..ab781fa0e --- /dev/null +++ b/C++/remove-comments.cpp @@ -0,0 +1,30 @@ +// Time: O(n), n is the length of the source +// Space: O(k), k is the max length of a line + +class Solution { +public: + vector removeComments(vector& source) { + bool in_block = false; + vector result; + string newline; + for (const auto& line : source) { + for (int i = 0; i < line.length(); ++i) { + if (!in_block && i + 1 < line.length() && line.substr(i, 2) == "/*") { + in_block = true; + ++i; + } else if (in_block && i + 1 < line.length() && line.substr(i, 2) == "*/") { + in_block = false; + ++i; + } else if (!in_block && i + 1 < line.length() && line.substr(i, 2) == "//") { + break; + } else if (!in_block) { + newline.push_back(line[i]); + } + } + if (!in_block && !newline.empty()) { + result.emplace_back(move(newline)); + } + } + return result; + } +}; From 6bf8137674e8863ae405a27f3b9be1b34fa19e5f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 09:37:54 -0600 Subject: [PATCH 3939/4971] Update remove-comments.py --- Python/remove-comments.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Python/remove-comments.py b/Python/remove-comments.py index 32196351e..5b8707e0e 100644 --- a/Python/remove-comments.py +++ b/Python/remove-comments.py @@ -89,8 +89,6 @@ def removeComments(self, source): in_block = False result, newline = [], [] for line in source: - if not in_block: - newline = [] i = 0 while i < len(line): if not in_block and i+1 < len(line) and line[i:i+2] == '/*': @@ -106,5 +104,5 @@ def removeComments(self, source): i += 1 if newline and not in_block: result.append("".join(newline)) - + newline = [] return result From 156e71d7128fb3e4914a11736ee47e30598ce5fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 10:05:39 -0600 Subject: [PATCH 3940/4971] Create longest-word-in-dictionary.py --- Python/longest-word-in-dictionary.py | 53 ++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/longest-word-in-dictionary.py diff --git a/Python/longest-word-in-dictionary.py b/Python/longest-word-in-dictionary.py new file mode 100644 index 000000000..fa2b3c2b2 --- /dev/null +++ b/Python/longest-word-in-dictionary.py @@ -0,0 +1,53 @@ +# Time: O(n), n is the total sum of the lengths of words +# Space: O(t), t is the number of nodes in trie + +# Given a list of strings words representing an English Dictionary, +# find the longest word in words that can be built one character at a time by other words in words. +# If there is more than one possible answer, return the longest word with the smallest lexicographical order. +# +# If there is no answer, return the empty string. +# Example 1: +# Input: +# words = ["w","wo","wor","worl", "world"] +# Output: "world" +# Explanation: +# The word "world" can be built one character at a time by "w", "wo", "wor", and "worl". +# +# Example 2: +# Input: +# words = ["a", "banana", "app", "appl", "ap", "apply", "apple"] +# Output: "apple" +# Explanation: +# Both "apply" and "apple" can be built from other words in the dictionary. +# However, "apple" is lexicographically smaller than "apply". +# +# Note: +# - All the strings in the input will only contain lowercase letters. +# - The length of words will be in the range [1, 1000]. +# - The length of words[i] will be in the range [1, 30]. + +class Solution(object): + def longestWord(self, words): + """ + :type words: List[str] + :rtype: str + """ + _trie = lambda: collections.defaultdict(_trie) + trie = _trie() + for i, s in enumerate(words): + curr = trie + for c in s: + curr = curr[c] + curr["_end"] = i + + # DFS + stack = trie.values() + result = "" + while stack: + curr = stack.pop() + if "_end" in curr: + word = words[curr["_end"]] + if len(word) > len(result) or len(word) == len(result) and word < result: + result = word + stack += [curr[letter] for letter in curr if letter != "_end"] + return result From 08632941b174815a7a2140ee14f1addbf243099d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 10:19:59 -0600 Subject: [PATCH 3941/4971] Update longest-word-in-dictionary.py --- Python/longest-word-in-dictionary.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/longest-word-in-dictionary.py b/Python/longest-word-in-dictionary.py index fa2b3c2b2..8d15f9c82 100644 --- a/Python/longest-word-in-dictionary.py +++ b/Python/longest-word-in-dictionary.py @@ -47,7 +47,7 @@ def longestWord(self, words): curr = stack.pop() if "_end" in curr: word = words[curr["_end"]] - if len(word) > len(result) or len(word) == len(result) and word < result: + if len(word) > len(result) or (len(word) == len(result) and word < result): result = word stack += [curr[letter] for letter in curr if letter != "_end"] return result From 9761a6f962885bc9a31fc0ca9b8854c2271d66d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 10:20:50 -0600 Subject: [PATCH 3942/4971] Create longest-word-in-dictionary.cpp --- C++/longest-word-in-dictionary.cpp | 60 ++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 C++/longest-word-in-dictionary.cpp diff --git a/C++/longest-word-in-dictionary.cpp b/C++/longest-word-in-dictionary.cpp new file mode 100644 index 000000000..51b2f1f0d --- /dev/null +++ b/C++/longest-word-in-dictionary.cpp @@ -0,0 +1,60 @@ +// Time: O(n), n is the total sum of the lengths of words +// Space: O(t), t is the number of nodes in trie + +class Solution { +public: + string longestWord(vector& words) { + TrieNode trie; + for (int i = 0; i < words.size(); ++i) { + trie.Insert(words[i], i); + } + + // DFS + stack stk; + for (const auto& kvp : trie.leaves) { + stk.emplace(kvp.second); + } + + string result; + while (!stk.empty()) { + const auto curr = stk.top(); stk.pop(); + if (curr->isString) { + const auto& word = words[curr->val]; + if (word.size() > result.size() || (word.size() == result.size() && word < result)) { + result = word; + } + for (const auto& kvp : curr->leaves) { + stk.emplace(kvp.second); + } + } + } + return result; + } + +private: + struct TrieNode { + bool isString = false; + int val = 0; + unordered_map leaves; + + void Insert(const string& s, const 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->isString = true; + p->val = i; + } + + ~TrieNode() { + for (auto& kv : leaves) { + if (kv.second) { + delete kv.second; + } + } + } + }; +}; From ade663bb352a114f652f8a62fb1b4222c5de198e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 10:30:25 -0600 Subject: [PATCH 3943/4971] Update longest-word-in-dictionary.cpp --- C++/longest-word-in-dictionary.cpp | 32 ++++++++++++++++++------------ 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/C++/longest-word-in-dictionary.cpp b/C++/longest-word-in-dictionary.cpp index 51b2f1f0d..2d1baf26f 100644 --- a/C++/longest-word-in-dictionary.cpp +++ b/C++/longest-word-in-dictionary.cpp @@ -11,8 +11,10 @@ class Solution { // DFS stack stk; - for (const auto& kvp : trie.leaves) { - stk.emplace(kvp.second); + for (const auto& node : trie.leaves) { + if (node) { + stk.emplace(node); + } } string result; @@ -23,8 +25,10 @@ class Solution { if (word.size() > result.size() || (word.size() == result.size() && word < result)) { result = word; } - for (const auto& kvp : curr->leaves) { - stk.emplace(kvp.second); + for (const auto& node : curr->leaves) { + if (node) { + stk.emplace(node); + } } } } @@ -33,26 +37,28 @@ class Solution { private: struct TrieNode { - bool isString = false; - int val = 0; - unordered_map leaves; + bool isString; + int val; + vector leaves; + + TrieNode() : isString{false}, val{0}, leaves(26) {} void Insert(const string& s, const int i) { auto* p = this; for (const auto& c : s) { - if (p->leaves.find(c) == p->leaves.cend()) { - p->leaves[c] = new TrieNode; + if (!p->leaves[c - 'a']) { + p->leaves[c - 'a'] = new TrieNode; } - p = p->leaves[c]; + p = p->leaves[c - 'a']; } p->isString = true; p->val = i; } ~TrieNode() { - for (auto& kv : leaves) { - if (kv.second) { - delete kv.second; + for (auto& node : leaves) { + if (node) { + delete node; } } } From dc55537d63fe0d6b3ff559ca1cdcc7b708f03339 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 10:39:13 -0600 Subject: [PATCH 3944/4971] Update longest-word-in-dictionary.py --- Python/longest-word-in-dictionary.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Python/longest-word-in-dictionary.py b/Python/longest-word-in-dictionary.py index 8d15f9c82..b6f900c14 100644 --- a/Python/longest-word-in-dictionary.py +++ b/Python/longest-word-in-dictionary.py @@ -34,11 +34,8 @@ def longestWord(self, words): """ _trie = lambda: collections.defaultdict(_trie) trie = _trie() - for i, s in enumerate(words): - curr = trie - for c in s: - curr = curr[c] - curr["_end"] = i + for i, word in enumerate(words): + reduce(dict.__getitem__, word, trie)["_end"] = i # DFS stack = trie.values() From e31ac2afbd1531ae3f531023caa648e4bac45340 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 10:44:45 -0600 Subject: [PATCH 3945/4971] Update replace-words.py --- Python/replace-words.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/Python/replace-words.py b/Python/replace-words.py index f63beadda..8ed8c2513 100644 --- a/Python/replace-words.py +++ b/Python/replace-words.py @@ -23,19 +23,16 @@ # 1 <= sentence words length <= 1000 class Solution(object): - def replaceWords(self, dict, sentence): + def replaceWords(self, dictionary, sentence): """ - :type dict: List[str] + :type dictionary: List[str] :type sentence: str :rtype: str """ _trie = lambda: collections.defaultdict(_trie) trie = _trie() - for s in dict: - curr = trie - for c in s: - curr = curr[c] - curr.setdefault("_end") + for word in dictionary: + reduce(dict.__getitem__, word, trie).setdefault("_end") def replace(word): curr = trie From 775eb7c6c794a7e1749fefcf932cdd766988ed0a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 10:47:12 -0600 Subject: [PATCH 3946/4971] Update implement-magic-dictionary.py --- Python/implement-magic-dictionary.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/Python/implement-magic-dictionary.py b/Python/implement-magic-dictionary.py index 903991255..d7785e595 100644 --- a/Python/implement-magic-dictionary.py +++ b/Python/implement-magic-dictionary.py @@ -32,17 +32,14 @@ def __init__(self): self.trie = _trie() - def buildDict(self, dict): + def buildDict(self, dictionary): """ Build a dictionary through a list of words - :type dict: List[str] + :type dictionary: List[str] :rtype: void """ - for s in dict: - curr = self.trie - for c in s: - curr = curr[c] - curr.setdefault("_end") + for word in dictionary: + reduce(dict.__getitem__, word, self.trie).setdefault("_end") def search(self, word): From 8002e53e670e6886f936c0124e147b0061e3b632 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 5 Nov 2017 11:16:27 -0600 Subject: [PATCH 3947/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ff35276d8..88b513046 100644 --- a/README.md +++ b/README.md @@ -365,7 +365,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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)_ on average | _O(1)_ | Medium | variant of [Sort Colors](https://leetcode.com/problems/sort-colors/) | Tri Partition | 347| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./C++/top-k-frequent-elements.cpp) [Python](./Python/top-k-frequent-elements.py) | _O(n)_ | _O(n)_ | Medium | | Quick Select, Heap, Bucket Sort | -406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium | | | +406| [Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./C++/queue-reconstruction-by-height.cpp) [Python](./Python/queue-reconstruction-by-height.py) | _O(n * sqrt(n))_ | _O(n)_ | Medium | | Tricky | 451| [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/) | [C++](./C++/sort-characters-by-frequency.cpp) [Python](./Python/sort-characters-by-frequency.py) | _O(n)_ | _O(n)_ | Medium | | | 692| [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | [C++](./C++/top-k-frequent-words.cpp) [Python](./Python/top-k-frequent-words.py) | _O(n + klogk)_ on average | _O(n)_ | Medium | | Quick Select, Heap, Bucket Sort | From 68fc90cb3dbd2029602ccc4910c1a7318f7ace68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 6 Nov 2017 08:03:17 -0600 Subject: [PATCH 3948/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 88b513046..f8c4ecec3 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 697| [Degree of an Array](https://leetcode.com/problems/degree-of-an-array/) | [C++](./C++/degree-of-an-array.cpp) [Python](./Python/degree-of-an-array.py) | _O(n)_ | _O(n)_ | Easy || 713 | [Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/) | [C++](./C++/subarray-product-less-than-k.cpp) [Python](./Python/subarray-product-less-than-k.py) | _O(n)_ | _O(1)_ | Medium || 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/) | [C++](./C++/1-bit-and-2-bit-characters.cpp) [Python](./Python/1-bit-and-2-bit-characters.py) | _O(n)_ | _O(1)_ | Easy || Greedy +723 | [Candy Crush](https://leetcode.com/problems/candy-crush/) | [C++](./C++/candy-crush.cpp) [Python](./Python/candy-crush.py) | _O((R * C)^2)_ | _O(1)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -167,6 +168,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 681| [Next Closest Time](https://leetcode.com/problems/next-closest-time/) | [C++](./C++/next-closest-time.cpp) [Python](./Python/next-closest-time.py) | _O(1)_ | _O(1)_ | Medium || 686 | [Repeated String Match](https://leetcode.com/problems/repeated-string-match/) | [C++](./C++/repeated-string-match.cpp) [Python](./Python/repeated-string-match.py) | _O(n + m)_ | _O(1)_ | Easy || `Rabin-Karp Algorithm` | 696| [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/) | [C++](./C++/count-binary-substrings.cpp) [Python](./Python/count-binary-substrings.py) | _O(n)_ | _O(1)_ | Easy|| +720| [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/) | [C++](./C++/longest-word-in-dictionary.cpp) [Python](./Python/longest-word-in-dictionary.py) | _O(n)_ | _O(t)_ | Easy || Trie | +722| [Remove Comments](https://leetcode.com/problems/remove-comments/) | [C++](./C++/remove-comments.cpp) [Python](./Python/remove-comments.py) | _O(n)_ | _O(k)_ | Medium ||| ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -300,6 +303,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | +721| [Accounts Merge](https://leetcode.com/problems/accounts-merge/) | [C++](./C++/accounts-merge.cpp) [Python](./Python/accounts-merge.py) | _O(nlogn)_ | _O(n)_| Medium || Union Find ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 9c75433091cd941593d56e7e1e400cd06e657367 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 08:23:41 -0600 Subject: [PATCH 3949/4971] Create consecutive-available-seats.sql --- MySQL/consecutive-available-seats.sql | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 MySQL/consecutive-available-seats.sql diff --git a/MySQL/consecutive-available-seats.sql b/MySQL/consecutive-available-seats.sql new file mode 100644 index 000000000..79025770a --- /dev/null +++ b/MySQL/consecutive-available-seats.sql @@ -0,0 +1,9 @@ +# Time: O(nlogn) +# Space: O(n) + +SELECT DISTINCT c1.seat_id +FROM cinema c1 JOIN cinema c2 + ON ((c1.seat_id = c2.seat_id - 1) OR (c1.seat_id = c2.seat_id + 1)) + AND c1.free = true AND c2.free = true +ORDER BY c1.seat_id +; From 98e6889319e2372ee4880c870d0b95c1d04652ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 09:36:43 -0600 Subject: [PATCH 3950/4971] Create max-stack.cpp --- C++/max-stack.cpp | 61 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 C++/max-stack.cpp diff --git a/C++/max-stack.cpp b/C++/max-stack.cpp new file mode 100644 index 000000000..3b4fb8a0e --- /dev/null +++ b/C++/max-stack.cpp @@ -0,0 +1,61 @@ + + +class MaxStack { +public: + /** initialize your data structure here. */ + MaxStack() { + + } + + void push(int x) { + const auto idx = idx_to_val_.empty() ? 0 : idx_to_val_.begin()->first + 1; + idx_to_val_[idx] = x; + val_to_idxs_[x].emplace_back(idx); + } + + int pop() { + const auto& it = idx_to_val_.begin(); + const auto val = it->second; + const auto idx = it->first; + remove(idx, val); + return val; + } + + int top() { + return idx_to_val_.begin()->second; + } + + int peekMax() { + return val_to_idxs_.begin()->first; + } + + int popMax() { + const auto& it = val_to_idxs_.begin(); + const auto val = it->first; + const auto idx = val_to_idxs_[val].back(); + remove(idx, val); + return val; + } + +private: + map> idx_to_val_; + map, greater> val_to_idxs_; + + void remove(const int idx, const int val) { + val_to_idxs_[val].pop_back(); + if (val_to_idxs_[val].empty()) { + val_to_idxs_.erase(val); + } + idx_to_val_.erase(idx); + } +}; + +/** + * Your MaxStack object will be instantiated and called as such: + * MaxStack obj = new MaxStack(); + * obj.push(x); + * int param_2 = obj.pop(); + * int param_3 = obj.top(); + * int param_4 = obj.peekMax(); + * int param_5 = obj.popMax(); + */ From 37f8e4725f7ed3612ee852dc7440b4c366c0cf6b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 09:37:37 -0600 Subject: [PATCH 3951/4971] Update max-stack.cpp --- C++/max-stack.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/C++/max-stack.cpp b/C++/max-stack.cpp index 3b4fb8a0e..73ecef2be 100644 --- a/C++/max-stack.cpp +++ b/C++/max-stack.cpp @@ -1,4 +1,5 @@ - +// Time: O(logn), per operation +// Space: O(n), current pushed operations class MaxStack { public: From 5de12a057f7730e6d0f630a096cbced078d016d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 09:38:11 -0600 Subject: [PATCH 3952/4971] Update max-stack.cpp --- C++/max-stack.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/max-stack.cpp b/C++/max-stack.cpp index 73ecef2be..2f454b9d1 100644 --- a/C++/max-stack.cpp +++ b/C++/max-stack.cpp @@ -1,5 +1,5 @@ // Time: O(logn), per operation -// Space: O(n), current pushed operations +// Space: O(n), n is current values in the stack class MaxStack { public: From edaafa4a333c099f3830f3f5b11c26bb0fb2a462 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 09:38:35 -0600 Subject: [PATCH 3953/4971] Update max-stack.cpp --- C++/max-stack.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/max-stack.cpp b/C++/max-stack.cpp index 2f454b9d1..eafc65f9d 100644 --- a/C++/max-stack.cpp +++ b/C++/max-stack.cpp @@ -1,5 +1,5 @@ // Time: O(logn), per operation -// Space: O(n), n is current values in the stack +// Space: O(n), n is the number of values in the current stack class MaxStack { public: From c0134c5e19a96348a7225c68e650e7d2c8069cf2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 10:12:18 -0600 Subject: [PATCH 3954/4971] Update max-stack.cpp --- C++/max-stack.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/C++/max-stack.cpp b/C++/max-stack.cpp index eafc65f9d..e142c4f90 100644 --- a/C++/max-stack.cpp +++ b/C++/max-stack.cpp @@ -1,4 +1,8 @@ -// Time: O(logn), per operation +// Time: push: O(logn) +// pop: O(logn) +// popMax: O(logn) +// top: O(1) +// peekMax: O(1) // Space: O(n), n is the number of values in the current stack class MaxStack { From e1da9e22ae1a35bfd65ba9eca120895729aeecd7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 10:34:57 -0600 Subject: [PATCH 3955/4971] Create max-stack.py --- Python/max-stack.py | 81 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Python/max-stack.py diff --git a/Python/max-stack.py b/Python/max-stack.py new file mode 100644 index 000000000..2b3324cce --- /dev/null +++ b/Python/max-stack.py @@ -0,0 +1,81 @@ +# Time: push: O(1) +# pop: O(n), there is no built-in SortedDict in python. If applied, it could be reduced to O(logn) +# popMax: O(n) +# top: O(1) +# peekMax: O(1) +# Space: O(n), n is the number of values in the current stack + +class MaxStack(object): + + def __init__(self): + """ + initialize your data structure here. + """ + self.__idx = 0 + self.__idx_to_val = collections.defaultdict(int) + self.__val_to_idxs = collections.defaultdict(list) + self.__top = None + self.__max = None + + + def push(self, x): + """ + :type x: int + :rtype: void + """ + self.__idx += 1 + self.__idx_to_val[self.__idx] = x + self.__val_to_idxs[x].append(self.__idx) + self.__top = x + self.__max = max(self.__max, x) + + + def pop(self): + """ + :rtype: int + """ + val = self.__top + self.remove(val) + return val + + + def top(self): + """ + :rtype: int + """ + return self.__top + + + def peekMax(self): + """ + :rtype: int + """ + return self.__max + + + def popMax(self): + """ + :rtype: int + """ + val = self.__max + self.remove(val) + return val + + + def remove(self, val): + idx = self.__val_to_idxs[val][-1] + self.__val_to_idxs[val].pop(); + if not self.__val_to_idxs[val]: + del self.__val_to_idxs[val] + del self.__idx_to_val[idx] + self.__top = self.__idx_to_val[max(self.__idx_to_val.keys())] if self.__idx_to_val else None + self.__max = max(self.__val_to_idxs.keys()) if self.__val_to_idxs else None + + +# Your MaxStack object will be instantiated and called as such: +# obj = MaxStack() +# obj.push(x) +# param_2 = obj.pop() +# param_3 = obj.top() +# param_4 = obj.peekMax() +# param_5 = obj.popMax() From 9d185f2ba31316249a5367831fc40cc1b198920a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 10:37:16 -0600 Subject: [PATCH 3956/4971] Update max-stack.cpp --- C++/max-stack.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/C++/max-stack.cpp b/C++/max-stack.cpp index e142c4f90..f5b29b899 100644 --- a/C++/max-stack.cpp +++ b/C++/max-stack.cpp @@ -21,8 +21,7 @@ class MaxStack { int pop() { const auto& it = idx_to_val_.begin(); const auto val = it->second; - const auto idx = it->first; - remove(idx, val); + remove(val); return val; } @@ -37,8 +36,7 @@ class MaxStack { int popMax() { const auto& it = val_to_idxs_.begin(); const auto val = it->first; - const auto idx = val_to_idxs_[val].back(); - remove(idx, val); + remove(val); return val; } @@ -46,7 +44,8 @@ class MaxStack { map> idx_to_val_; map, greater> val_to_idxs_; - void remove(const int idx, const int val) { + void remove(const int val) { + const auto idx = val_to_idxs_[val].back(); val_to_idxs_[val].pop_back(); if (val_to_idxs_[val].empty()) { val_to_idxs_.erase(val); From 25210a8ff3f9310a9a7eb7af9d30da5d6734a468 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 10:38:04 -0600 Subject: [PATCH 3957/4971] Update max-stack.cpp --- C++/max-stack.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/max-stack.cpp b/C++/max-stack.cpp index f5b29b899..aa6889bee 100644 --- a/C++/max-stack.cpp +++ b/C++/max-stack.cpp @@ -19,8 +19,7 @@ class MaxStack { } int pop() { - const auto& it = idx_to_val_.begin(); - const auto val = it->second; + const auto val = idx_to_val_.begin()->second; remove(val); return val; } @@ -34,8 +33,7 @@ class MaxStack { } int popMax() { - const auto& it = val_to_idxs_.begin(); - const auto val = it->first; + const auto val = val_to_idxs_.begin()->first; remove(val); return val; } From 789f12e7a0f9a18aa374ad6c1c811e8945d7ce85 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 10:39:21 -0600 Subject: [PATCH 3958/4971] Update max-stack.cpp --- C++/max-stack.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/max-stack.cpp b/C++/max-stack.cpp index aa6889bee..e6d868a95 100644 --- a/C++/max-stack.cpp +++ b/C++/max-stack.cpp @@ -13,27 +13,27 @@ class MaxStack { } void push(int x) { - const auto idx = idx_to_val_.empty() ? 0 : idx_to_val_.begin()->first + 1; + const auto idx = idx_to_val_.empty() ? 0 : idx_to_val_.cbegin()->first + 1; idx_to_val_[idx] = x; val_to_idxs_[x].emplace_back(idx); } int pop() { - const auto val = idx_to_val_.begin()->second; + const auto val = idx_to_val_.cbegin()->second; remove(val); return val; } int top() { - return idx_to_val_.begin()->second; + return idx_to_val_.cbegin()->second; } int peekMax() { - return val_to_idxs_.begin()->first; + return val_to_idxs_.cbegin()->first; } int popMax() { - const auto val = val_to_idxs_.begin()->first; + const auto val = val_to_idxs_.cbegin()->first; remove(val); return val; } From 31bdbe5e901356e8ac0ad932b865c4d0521726a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 10:40:33 -0600 Subject: [PATCH 3959/4971] Update max-stack.cpp --- C++/max-stack.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/max-stack.cpp b/C++/max-stack.cpp index e6d868a95..d62fdf41e 100644 --- a/C++/max-stack.cpp +++ b/C++/max-stack.cpp @@ -38,10 +38,7 @@ class MaxStack { return val; } -private: - map> idx_to_val_; - map, greater> val_to_idxs_; - +private: void remove(const int val) { const auto idx = val_to_idxs_[val].back(); val_to_idxs_[val].pop_back(); @@ -50,6 +47,9 @@ class MaxStack { } idx_to_val_.erase(idx); } + + map> idx_to_val_; + map, greater> val_to_idxs_; }; /** From 608cfb8058c6cfae8338df47f33125e89e981736 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 10:43:28 -0600 Subject: [PATCH 3960/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f8c4ecec3..a2328db70 100644 --- a/README.md +++ b/README.md @@ -649,6 +649,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | +716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | ## SQL From b55171e7bd0525d99c6b6de42757ebae837f06dd Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 10:51:12 -0600 Subject: [PATCH 3961/4971] Update max-stack.py --- Python/max-stack.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Python/max-stack.py b/Python/max-stack.py index 2b3324cce..0a20aba7b 100644 --- a/Python/max-stack.py +++ b/Python/max-stack.py @@ -11,7 +11,6 @@ def __init__(self): """ initialize your data structure here. """ - self.__idx = 0 self.__idx_to_val = collections.defaultdict(int) self.__val_to_idxs = collections.defaultdict(list) self.__top = None @@ -23,9 +22,9 @@ def push(self, x): :type x: int :rtype: void """ - self.__idx += 1 - self.__idx_to_val[self.__idx] = x - self.__val_to_idxs[x].append(self.__idx) + idx = (self.__val_to_idxs[self.__top][-1]+1) if self.__val_to_idxs else 0 + self.__idx_to_val[idx] = x + self.__val_to_idxs[x].append(idx) self.__top = x self.__max = max(self.__max, x) From cdfa52e5a061ed0a72eff0ea51651ba2890003b6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 11:03:36 -0600 Subject: [PATCH 3962/4971] Update max-stack.py --- Python/max-stack.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/max-stack.py b/Python/max-stack.py index 0a20aba7b..d92ed7d21 100644 --- a/Python/max-stack.py +++ b/Python/max-stack.py @@ -22,7 +22,7 @@ def push(self, x): :type x: int :rtype: void """ - idx = (self.__val_to_idxs[self.__top][-1]+1) if self.__val_to_idxs else 0 + idx = self.__val_to_idxs[self.__top][-1]+1 if self.__val_to_idxs else 0 self.__idx_to_val[idx] = x self.__val_to_idxs[x].append(idx) self.__top = x @@ -34,7 +34,7 @@ def pop(self): :rtype: int """ val = self.__top - self.remove(val) + self.__remove(val) return val @@ -57,11 +57,11 @@ def popMax(self): :rtype: int """ val = self.__max - self.remove(val) + self.__remove(val) return val - def remove(self, val): + def __remove(self, val): idx = self.__val_to_idxs[val][-1] self.__val_to_idxs[val].pop(); if not self.__val_to_idxs[val]: From 180f23460157adf5a13d8a9c40a5678d33cb542c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 11:15:11 -0600 Subject: [PATCH 3963/4971] Update max-stack.py --- Python/max-stack.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Python/max-stack.py b/Python/max-stack.py index d92ed7d21..a677d3443 100644 --- a/Python/max-stack.py +++ b/Python/max-stack.py @@ -67,8 +67,10 @@ def __remove(self, val): if not self.__val_to_idxs[val]: del self.__val_to_idxs[val] del self.__idx_to_val[idx] - self.__top = self.__idx_to_val[max(self.__idx_to_val.keys())] if self.__idx_to_val else None - self.__max = max(self.__val_to_idxs.keys()) if self.__val_to_idxs else None + if val == self.__top: + self.__top = self.__idx_to_val[max(self.__idx_to_val.keys())] if self.__idx_to_val else None + if val == self.__max: + self.__max = max(self.__val_to_idxs.keys()) if self.__val_to_idxs else None # Your MaxStack object will be instantiated and called as such: From 9b060e0c7d1ed2a056bd7502a159688d6c416051 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 7 Nov 2017 11:21:47 -0600 Subject: [PATCH 3964/4971] Update max-stack.py --- Python/max-stack.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/max-stack.py b/Python/max-stack.py index a677d3443..ee10bd1d8 100644 --- a/Python/max-stack.py +++ b/Python/max-stack.py @@ -42,14 +42,14 @@ def top(self): """ :rtype: int """ - return self.__top + return self.__top def peekMax(self): """ :rtype: int """ - return self.__max + return self.__max def popMax(self): From 8a7560c829cd39147289cd275c1f64c5d9d73090 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 8 Nov 2017 08:49:28 -0600 Subject: [PATCH 3965/4971] Create friend-requests-ii-who-has-the-most-friends.sql --- ...friend-requests-ii-who-has-the-most-friends.sql | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 MySQL/friend-requests-ii-who-has-the-most-friends.sql diff --git a/MySQL/friend-requests-ii-who-has-the-most-friends.sql b/MySQL/friend-requests-ii-who-has-the-most-friends.sql new file mode 100644 index 000000000..baff9f17c --- /dev/null +++ b/MySQL/friend-requests-ii-who-has-the-most-friends.sql @@ -0,0 +1,14 @@ +# Time: O(nlogn) +# Space: O(n) + +SELECT ids as id, COUNT(*) AS num + FROM + ( + SELECT requester_id AS ids FROM request_accepted + UNION ALL + SELECT accepter_id FROM request_accepted + ) AS tmp +GROUP BY ids +ORDER BY num DESC +LIMIT 1 +; From 9b966ac16a6c3936aaf9505d6618e8721d846dac Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 9 Nov 2017 07:41:35 -0600 Subject: [PATCH 3966/4971] Create human-traffic-of-stadium.sql --- MySQL/human-traffic-of-stadium.sql | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 MySQL/human-traffic-of-stadium.sql diff --git a/MySQL/human-traffic-of-stadium.sql b/MySQL/human-traffic-of-stadium.sql new file mode 100644 index 000000000..fcf908393 --- /dev/null +++ b/MySQL/human-traffic-of-stadium.sql @@ -0,0 +1,16 @@ +# Time: O(n^3) +# Space: O(n^3) + +SELECT DISTINCT s1.* +FROM stadium AS s1, stadium AS s2, stadium AS s3 +WHERE s1.people >= 100 AND s2.people >= 100 AND s3.people >= 100 +AND +( + (s2.id = s1.id + 1 AND s3.id = s2.id + 1 AND s3.id = s1.id + 2) -- s1, s2, s3 + OR + (s1.id = s2.id + 1 AND s3.id = s1.id + 1 AND s3.id = s2.id + 2) -- s2, s1, s3 + OR + (s3.id = s2.id + 1 AND s1.id = s3.id + 1 AND s1.id = s2.id + 2) -- s2, s3, s1 +) +ORDER BY s1.id +; From f6595ca67f4a9655d2846ca9aaee533f41dcea2a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 10 Nov 2017 07:24:54 -0600 Subject: [PATCH 3967/4971] Create friend-requests-i-overall-acceptance-rate.sql --- MySQL/friend-requests-i-overall-acceptance-rate.sql | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 MySQL/friend-requests-i-overall-acceptance-rate.sql diff --git a/MySQL/friend-requests-i-overall-acceptance-rate.sql b/MySQL/friend-requests-i-overall-acceptance-rate.sql new file mode 100644 index 000000000..5ca34216d --- /dev/null +++ b/MySQL/friend-requests-i-overall-acceptance-rate.sql @@ -0,0 +1,11 @@ +# Time: O(rlogr + aloga) +# Space: O(r + a) + +SELECT +ROUND( + IFNULL( + (SELECT COUNT(*) FROM (SELECT DISTINCT requester_id, accepter_id FROM request_accepted) AS r) + / + (SELECT COUNT(*) FROM (SELECT DISTINCT sender_id, send_to_id FROM friend_request) AS a), + 0) +, 2) AS accept_rate; From 49ecf4064f2d6f25bf1064031104a1578b571f79 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 11 Nov 2017 08:00:48 -0600 Subject: [PATCH 3968/4971] Create customer-placing-the-largest-number-of-orders.sql --- ...r-placing-the-largest-number-of-orders.sql | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 MySQL/customer-placing-the-largest-number-of-orders.sql diff --git a/MySQL/customer-placing-the-largest-number-of-orders.sql b/MySQL/customer-placing-the-largest-number-of-orders.sql new file mode 100644 index 000000000..164017d90 --- /dev/null +++ b/MySQL/customer-placing-the-largest-number-of-orders.sql @@ -0,0 +1,19 @@ +# Time: O(n) +# Space: O(n) + +SELECT customer_number +FROM orders +GROUP BY customer_number +HAVING COUNT(order_number) = + (SELECT MAX(*) + FROM + (SELECT COUNT(*) AS cnt + FROM + orders + GROUP BY customer_number + ORDER BY NULL + ) AS cnt_tbl + ) +ORDER BY NULL +LIMIT 1 +; From ddb58206a52ef46f5194bf6f5c11ac68b16ab9a8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 09:43:40 -0600 Subject: [PATCH 3969/4971] Create minimum-window-subsequence.py --- Python/minimum-window-subsequence.py | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Python/minimum-window-subsequence.py diff --git a/Python/minimum-window-subsequence.py b/Python/minimum-window-subsequence.py new file mode 100644 index 000000000..e427e66e9 --- /dev/null +++ b/Python/minimum-window-subsequence.py @@ -0,0 +1,29 @@ +# Time: O(S * T) +# Space: O(S) + +class Solution(object): + def minWindow(self, S, T): + """ + :type S: str + :type T: str + :rtype: str + """ + dp = [[None for _ in xrange(len(S))] for _ in xrange(2)] + for i, c in enumerate(S): + if c == T[0]: + dp[0][i] = i + + for j in xrange(1, len(T)): + prev = None + dp[j%2] = [None] * len(S) + for i, c in enumerate(S): + if prev is not None and c == T[j]: + dp[j%2][i] = prev + if dp[(j-1)%2][i] is not None: + prev = dp[(j-1)%2][i] + + start, end = 0, len(S) + for j, i in enumerate(dp[(len(T)-1)%2]): + if i >= 0 and j-i < end-start: + start, end = i, j + return S[start:end+1] if end < len(S) else "" From 259baa86858aefb8919a1caa9f2129e2135a07da Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 09:59:15 -0600 Subject: [PATCH 3970/4971] Update minimum-window-subsequence.py --- Python/minimum-window-subsequence.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Python/minimum-window-subsequence.py b/Python/minimum-window-subsequence.py index e427e66e9..f3b67b90a 100644 --- a/Python/minimum-window-subsequence.py +++ b/Python/minimum-window-subsequence.py @@ -9,18 +9,18 @@ def minWindow(self, S, T): :rtype: str """ dp = [[None for _ in xrange(len(S))] for _ in xrange(2)] - for i, c in enumerate(S): + for j, c in enumerate(S): if c == T[0]: - dp[0][i] = i + dp[0][j] = j - for j in xrange(1, len(T)): + for i in xrange(1, len(T)): prev = None - dp[j%2] = [None] * len(S) - for i, c in enumerate(S): - if prev is not None and c == T[j]: - dp[j%2][i] = prev - if dp[(j-1)%2][i] is not None: - prev = dp[(j-1)%2][i] + dp[i%2] = [None] * len(S) + for j, c in enumerate(S): + if prev is not None and c == T[i]: + dp[i%2][j] = prev + if dp[(i-1)%2][j] is not None: + prev = dp[(i-1)%2][j] start, end = 0, len(S) for j, i in enumerate(dp[(len(T)-1)%2]): From 08184c8d12f34e9d5fb26d00b12e2deb03055837 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 10:01:07 -0600 Subject: [PATCH 3971/4971] Create minimum-window-subsequence.cpp --- C++/minimum-window-subsequence.cpp | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C++/minimum-window-subsequence.cpp diff --git a/C++/minimum-window-subsequence.cpp b/C++/minimum-window-subsequence.cpp new file mode 100644 index 000000000..38ac66ff0 --- /dev/null +++ b/C++/minimum-window-subsequence.cpp @@ -0,0 +1,36 @@ +// Time: O(S * T) +// Space: O(S) + +class Solution { +public: + string minWindow(string S, string T) { + vector> dp(2, vector(S.length(), -1)); + for (int j = 0; j < S.length(); ++j) { + if (S[j] == T[0]) { + dp[0][j] = j; + } + } + + for (int i = 1; i < T.length(); ++i) { + int prev = -1; + dp[i % 2] = vector(S.length(), -1); + for (int j = 0; j < S.length(); ++j) { + if (prev != -1 && S[j] == T[i]) { + dp[i % 2][j] = prev; + } + if (dp[(i - 1) % 2][j] != -1) { + prev = dp[(i - 1) % 2][j]; + } + } + } + + int start = 0, end = S.length(); + for (int j = 0; j < S.length(); ++j) { + int i = dp[(T.length() - 1) % 2][j]; + if (i >= 0 && j - i < end - start) { + tie(start, end) = make_pair(i, j); + } + } + return end < S.length() ? S.substr(start, end - start + 1) : ""; + } +}; From f5b80fedf3d7ae9750dd368b24ea24109cc420f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 10:46:42 -0600 Subject: [PATCH 3972/4971] Create number-of-atoms.cpp --- C++/number-of-atoms.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/number-of-atoms.cpp diff --git a/C++/number-of-atoms.cpp b/C++/number-of-atoms.cpp new file mode 100644 index 000000000..c0fa078cf --- /dev/null +++ b/C++/number-of-atoms.cpp @@ -0,0 +1,40 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + string countOfAtoms(string formula) { + stack> stk; + stk.emplace(); + int submatches[] = { 1, 2, 3, 4, 5 }; + auto e = regex("([A-Z][a-z]*)(\\d*)|(\\()|(\\))(\\d*)"); + for (regex_token_iterator it(formula.begin(), formula.end(), e, submatches), end; + it != end;) { + auto name = (it++)->str(); + auto m1 = (it++)->str(); + auto left_open = (it++)->str(); + auto right_open = (it++)->str(); + auto m2 = (it++)->str(); + if (!name.empty()) { + stk.top()[name] += stoi(!m1.empty() ? m1 : "1"); + } + if (!left_open.empty()) { + stk.emplace(); + } + if (!right_open.empty()) { + const auto top = move(stk.top()); stk.pop(); + for (const auto& kvp: top) { + stk.top()[kvp.first] += kvp.second * stoi(!m2.empty() ? m2 : "1"); + } + } + } + string result; + for (const auto& kvp : stk.top()) { + result += kvp.first; + if (kvp.second > 1) { + result += to_string(kvp.second); + } + } + return result; + } +}; From e39415fbe6a325894abb8d098504150b1c515b57 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 10:51:52 -0600 Subject: [PATCH 3973/4971] Create split-linked-list-in-parts.py --- Python/split-linked-list-in-parts.py | 68 ++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Python/split-linked-list-in-parts.py diff --git a/Python/split-linked-list-in-parts.py b/Python/split-linked-list-in-parts.py new file mode 100644 index 000000000..ca0bb7fab --- /dev/null +++ b/Python/split-linked-list-in-parts.py @@ -0,0 +1,68 @@ +# Time: O(n) +# Space: O(n) + +# Given a chemical formula (given as a string), return the count of each atom. +# +# An atomic element always starts with an uppercase character, +# then zero or more lowercase letters, representing the name. +# +# 1 or more digits representing the count of that element may follow if the count is greater than 1. +# If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible. +# +# Two formulas concatenated together produce another formula. For example, H2O2He3Mg4 is also a formula. +# +# A formula placed in parentheses, and a count (optionally added) is also a formula. +# For example, (H2O2) and (H2O2)3 are formulas. +# +# Given a formula, output the count of all elements as a string in the following form: +# the first name (in sorted order), followed by its count (if that count is more than 1), +# followed by the second name (in sorted order), +# followed by its count (if that count is more than 1), and so on. +# +# Example 1: +# Input: +# formula = "H2O" +# Output: "H2O" +# Explanation: +# The count of elements are {'H': 2, 'O': 1}. +# +# Example 2: +# Input: +# formula = "Mg(OH)2" +# Output: "H2MgO2" +# Explanation: +# The count of elements are {'H': 2, 'Mg': 1, 'O': 2}. +# +# Example 3: +# Input: +# formula = "K4(ON(SO3)2)2" +# Output: "K4N2O14S4" +# Explanation: +# The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}. +# Note: +# +# All atom names consist of lowercase letters, except for the first character which is uppercase. +# The length of formula will be in the range [1, 1000]. +# formula will only consist of letters, digits, and round parentheses, +# and is a valid formula as defined in the problem. + +class Solution(object): + def countOfAtoms(self, formula): + """ + :type formula: str + :rtype: str + """ + parse = re.findall(r"([A-Z][a-z]*)(\d*)|(\()|(\))(\d*)", formula) + stk = [collections.Counter()] + for name, m1, left_open, right_open, m2 in parse: + if name: + stk[-1][name] += int(m1 or 1) + if left_open: + stk.append(collections.Counter()) + if right_open: + top = stk.pop() + for k, v in top.iteritems(): + stk[-1][k] += v * int(m2 or 1) + + return "".join(name + (str(stk[-1][name]) if stk[-1][name] > 1 else '') \ + for name in sorted(stk[-1])) From d970defacf8cbf8545aea4716e0550dcd383ec55 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 10:55:27 -0600 Subject: [PATCH 3974/4971] Update number-of-atoms.cpp --- C++/number-of-atoms.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/number-of-atoms.cpp b/C++/number-of-atoms.cpp index c0fa078cf..64aa73f1f 100644 --- a/C++/number-of-atoms.cpp +++ b/C++/number-of-atoms.cpp @@ -7,14 +7,14 @@ class Solution { stack> stk; stk.emplace(); int submatches[] = { 1, 2, 3, 4, 5 }; - auto e = regex("([A-Z][a-z]*)(\\d*)|(\\()|(\\))(\\d*)"); + const auto e = regex("([A-Z][a-z]*)(\\d*)|(\\()|(\\))(\\d*)"); for (regex_token_iterator it(formula.begin(), formula.end(), e, submatches), end; it != end;) { - auto name = (it++)->str(); - auto m1 = (it++)->str(); - auto left_open = (it++)->str(); - auto right_open = (it++)->str(); - auto m2 = (it++)->str(); + const auto& name = (it++)->str(); + const auto& m1 = (it++)->str(); + const auto& left_open = (it++)->str(); + const auto& right_open = (it++)->str(); + const auto& m2 = (it++)->str(); if (!name.empty()) { stk.top()[name] += stoi(!m1.empty() ? m1 : "1"); } From 97378d5e09236a2f84bf02d729439e18214f9bba Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 11:03:12 -0600 Subject: [PATCH 3975/4971] Create find-pivot-index.cpp --- C++/find-pivot-index.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/find-pivot-index.cpp diff --git a/C++/find-pivot-index.cpp b/C++/find-pivot-index.cpp new file mode 100644 index 000000000..7539acee5 --- /dev/null +++ b/C++/find-pivot-index.cpp @@ -0,0 +1,17 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int pivotIndex(vector& nums) { + const auto total = accumulate(nums.begin(), nums.end(), 0); + auto left_sum = 0; + for (int i = 0; i < nums.size(); ++i) { + if (left_sum == (total - left_sum - nums[i])) { + return i; + } + left_sum += nums[i]; + } + return -1; + } +}; From 37f6c7baaed25bf6dbe9879c3526cb15aa718a5f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 11:05:28 -0600 Subject: [PATCH 3976/4971] Create find-pivot-index.py --- Python/find-pivot-index.py | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/find-pivot-index.py diff --git a/Python/find-pivot-index.py b/Python/find-pivot-index.py new file mode 100644 index 000000000..5ca035a46 --- /dev/null +++ b/Python/find-pivot-index.py @@ -0,0 +1,44 @@ +# Time: O(n) +# Space: O(1) + +# Given an array of integers nums, write a method that returns the "pivot" index of this array. +# +# We define the pivot index as the index where the sum of the numbers to +# the left of the index is equal to the sum of the numbers to the right of the index. +# +# If no such index exists, we should return -1. If there are multiple pivot indexes, +# you should return the left-most pivot index. +# +# Example 1: +# Input: +# nums = [1, 7, 3, 6, 5, 6] +# Output: 3 +# Explanation: +# The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3. +# Also, 3 is the first index where this occurs. +# +# Example 2: +# Input: +# nums = [1, 2, 3] +# Output: -1 +# Explanation: +# There is no index that satisfies the conditions in the problem statement. +# +# Note: +# - The length of nums will be in the range [0, 10000]. +# - Each element nums[i] will be an integer in the range [-1000, 1000]. + +class Solution(object): + def pivotIndex(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + total = sum(nums) + left_sum = 0 + for i, num in enumerate(nums): + if left_sum == (total-left_sum-num): + return i + left_sum += num + return -1 + From 2180eb1e5adc1a268a07d09757d4869b908b2921 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 11:20:33 -0600 Subject: [PATCH 3977/4971] Create split-linked-list-in-parts.cpp --- C++/split-linked-list-in-parts.cpp | 41 ++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 C++/split-linked-list-in-parts.cpp diff --git a/C++/split-linked-list-in-parts.cpp b/C++/split-linked-list-in-parts.cpp new file mode 100644 index 000000000..30d1c1ee5 --- /dev/null +++ b/C++/split-linked-list-in-parts.cpp @@ -0,0 +1,41 @@ +// 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: + vector splitListToParts(ListNode* root, int k) { + auto n = 0; + auto curr = root; + while (curr) { + curr = curr->next; + n += 1; + } + auto width = n / k; + auto remainder = n % k; + + vector result; + curr = root; + for (int i = 0; i < k; ++i) { + auto head = curr; + for (int j = 0; curr && + j < width - 1 + static_cast(i < remainder); ++j) { + curr = curr->next; + } + if (curr) { + auto tail = curr; + curr = curr->next; + tail->next = nullptr; + } + result.emplace_back(head); + } + return result; + } +}; From 6fecd93d3b739846c820501076a0ff4ccaff8c29 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 11:24:39 -0600 Subject: [PATCH 3978/4971] Rename split-linked-list-in-parts.py to number-of-atoms.py --- Python/{split-linked-list-in-parts.py => number-of-atoms.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{split-linked-list-in-parts.py => number-of-atoms.py} (100%) diff --git a/Python/split-linked-list-in-parts.py b/Python/number-of-atoms.py similarity index 100% rename from Python/split-linked-list-in-parts.py rename to Python/number-of-atoms.py From 2bf4fa769755ffb205565855ea67395abf94e7d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 12 Nov 2017 11:25:21 -0600 Subject: [PATCH 3979/4971] Create split-linked-list-in-parts.py --- Python/split-linked-list-in-parts.py | 71 ++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Python/split-linked-list-in-parts.py diff --git a/Python/split-linked-list-in-parts.py b/Python/split-linked-list-in-parts.py new file mode 100644 index 000000000..526aa9776 --- /dev/null +++ b/Python/split-linked-list-in-parts.py @@ -0,0 +1,71 @@ +# Time: O(n) +# Space: O(1) + +# Given a (singly) linked list with head node root, +# write a function to split the linked list into k consecutive linked list "parts". +# +# The length of each part should be as equal as possible: +# no two parts should have a size differing by more than 1. +# This may lead to some parts being null. +# +# The parts should be in order of occurrence in the input list, +# and parts occurring earlier should always have a size greater than or equal parts occurring later. +# +# Return a List of ListNode's representing the linked list parts that are formed. +# +# Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ] +# Example 1: +# Input: +# root = [1, 2, 3], k = 5 +# Output: [[1],[2],[3],[],[]] +# Explanation: +# The input and each element of the output are ListNodes, not arrays. +# For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, +# and root.next.next.next = null. +# The first element output[0] has output[0].val = 1, output[0].next = null. +# The last element output[4] is null, but it's string representation as a ListNode is []. +# +# Example 2: +# Input: +# root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3 +# Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] +# Explanation: +# The input has been split into consecutive parts with size difference at most 1, +# and earlier parts are a larger size than the later parts. +# +# Note: +# - The length of root will be in the range [0, 1000]. +# - Each value of a node in the input will be an integer in the range [0, 999]. +# - k will be an integer in the range [1, 50]. +# +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def splitListToParts(self, root, k): + """ + :type root: ListNode + :type k: int + :rtype: List[ListNode] + """ + n = 0 + curr = root + while curr: + curr = curr.next + n += 1 + width, remainder = divmod(n, k) + + result = [] + curr = root + for i in xrange(k): + head = curr + for j in xrange(width-1+int(i < remainder)): + if curr: + curr = curr.next + if curr: + curr.next, curr = None, curr.next + result.append(head) + return result From cd4610e145dfd39057298778fa2603cc36af29fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Nov 2017 12:37:45 +0800 Subject: [PATCH 3980/4971] Update split-linked-list-in-parts.cpp --- C++/split-linked-list-in-parts.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/split-linked-list-in-parts.cpp b/C++/split-linked-list-in-parts.cpp index 30d1c1ee5..2792a408a 100644 --- a/C++/split-linked-list-in-parts.cpp +++ b/C++/split-linked-list-in-parts.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(n + k) // Space: O(1) /** From 4f68033e6c99362194d4f5ca49eefc2d9673fc5f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Nov 2017 12:38:06 +0800 Subject: [PATCH 3981/4971] Update split-linked-list-in-parts.py --- Python/split-linked-list-in-parts.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/split-linked-list-in-parts.py b/Python/split-linked-list-in-parts.py index 526aa9776..27b6e791f 100644 --- a/Python/split-linked-list-in-parts.py +++ b/Python/split-linked-list-in-parts.py @@ -1,4 +1,4 @@ -# Time: O(n) +# Time: O(n + k) # Space: O(1) # Given a (singly) linked list with head node root, From 42ef250e9e2f4442a442edff83dd5dd75c8dc5a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Nov 2017 12:42:54 +0800 Subject: [PATCH 3982/4971] Update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index a2328db70..29293c0f7 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 713 | [Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/) | [C++](./C++/subarray-product-less-than-k.cpp) [Python](./Python/subarray-product-less-than-k.py) | _O(n)_ | _O(1)_ | Medium || 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/) | [C++](./C++/1-bit-and-2-bit-characters.cpp) [Python](./Python/1-bit-and-2-bit-characters.py) | _O(n)_ | _O(1)_ | Easy || Greedy 723 | [Candy Crush](https://leetcode.com/problems/candy-crush/) | [C++](./C++/candy-crush.cpp) [Python](./Python/candy-crush.py) | _O((R * C)^2)_ | _O(1)_ | Medium || +724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [C++](./C++/find-pivot-index.cpp) [Python](./Python/find-pivot-index.py) | _O(n)_ | _O(1)_ | Easy || + ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -192,6 +194,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)_ | Medium | | 369| [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [C++](./C++/plus-one-linked-list.cpp) [Python](./Python/plus-one-linked-list.py) | _O(n)_ | _O(1)_ | Medium | 📖 | Two Pointers | 445| [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/)| [C++](./C++/add-two-numbers-ii.cpp) [Python](./Python/add-two-numbers-ii.py) | _O(m + n)_ | _O(m + n)_ | Medium ||| +725 | [Split Linked List in Parts](https://leetcode.com/problems/split-linked-list-in-parts/) | [C++](./C++/split-linked-list-in-parts.cpp) [Python](./Python/split-linked-list-in-parts.py) | _O(n + k)_ | _O(1)_ | Medium || ## Stack | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -217,6 +220,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 439| [Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser/) | [C++](./C++/ternary-expression-parser.cpp) [Python](./Python/ternary-expression-parser.py) | _O(n)_ | _O(1)_ | Medium |📖| 456| [132 Pattern](https://leetcode.com/problems/132-pattern/) | [C++](./C++/132-pattern.cpp) [Python](./Python/132-pattern.py) | _O(n)_ | _O(n)_ | Medium || 682| [Baseball Game](https://leetcode.com/problems/baseball-game/) | [C++](./C++/baseball-game.cpp) [Python](./Python/baseball-game.py) | _O(n)_ | _O(n)_ | Easy || +726| [Number of Atoms](https://leetcode.com/problems/number-of-atoms/) | [C++](./C++/number-of-atoms.cpp) [Python](./Python/number-of-atoms.py) | _O(n)_ | _O(n)_ | Hard || ## Queue | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -604,6 +608,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 691 | [Stickers to Spell Word](https://leetcode.com/problems/stickers-to-spell-word/) | [C++](./C++/stickers-to-spell-word.cpp) [Python](./Python/stickers-to-spell-word.py) | _O(T * S^T)_ | _O(T * S^T)_ | Hard || Backtracking, Memoization 712 | [Minimum ASCII Delete Sum for Two Strings](https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/) | [C++](./C++/minimum-ascii-delete-sum-for-two-strings.cpp) [Python](./Python/minimum-ascii-delete-sum-for-two-strings.py) | _O(m * n)_ | _O(n)_ | Medium || 714 | [Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-transaction-fee.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py) | _O(n)_ | _O(1)_ | Medium || +727 | [Minimum Window Subsequence](https://leetcode.com/problems/minimum-window-subsequence/) | [C++](./C++/minimum-window-subsequence.cpp) [Python](./Python/minimum-window-subsequence.py) | _O(s * t)_ | _O(s)_ | Hard |📖| ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From a8dfbca4e4b4881e26ec3428e6dcb57a9bd643b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Nov 2017 12:43:11 +0800 Subject: [PATCH 3983/4971] Update minimum-window-subsequence.cpp --- C++/minimum-window-subsequence.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/minimum-window-subsequence.cpp b/C++/minimum-window-subsequence.cpp index 38ac66ff0..984aae5f4 100644 --- a/C++/minimum-window-subsequence.cpp +++ b/C++/minimum-window-subsequence.cpp @@ -1,5 +1,5 @@ -// Time: O(S * T) -// Space: O(S) +// Time: O(s * t) +// Space: O(s) class Solution { public: From fe5b13c3f2b8c97b889503062fc7e6d13329a960 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 13 Nov 2017 12:43:29 +0800 Subject: [PATCH 3984/4971] Update minimum-window-subsequence.py --- Python/minimum-window-subsequence.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/minimum-window-subsequence.py b/Python/minimum-window-subsequence.py index f3b67b90a..647dcea4c 100644 --- a/Python/minimum-window-subsequence.py +++ b/Python/minimum-window-subsequence.py @@ -1,5 +1,5 @@ -# Time: O(S * T) -# Space: O(S) +# Time: O(s * t) +# Space: O(s) class Solution(object): def minWindow(self, S, T): From d282effadc9e8f75fd9f20be628f6f91ad17a3bf Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 14 Nov 2017 12:20:26 +0800 Subject: [PATCH 3985/4971] Create employee-bonus.sql --- MySQL/employee-bonus.sql | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 MySQL/employee-bonus.sql diff --git a/MySQL/employee-bonus.sql b/MySQL/employee-bonus.sql new file mode 100644 index 000000000..f36c18880 --- /dev/null +++ b/MySQL/employee-bonus.sql @@ -0,0 +1,14 @@ +# Time: O(n) if hash join, O(nlogn) if merge join +# Space: O(n) + +# https://www.quora.com/What-is-time-complexity-of-Join-algorithm-in-Database + +SELECT + Employee.name, Bonus.bonus +FROM + Employee + LEFT JOIN + Bonus ON Employee.empid = Bonus.empid +WHERE + bonus < 1000 OR bonus IS NULL +; From 833fa240776039ae103e74d23109f1eb2159a6c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 14 Nov 2017 12:22:25 +0800 Subject: [PATCH 3986/4971] Update employee-bonus.sql --- MySQL/employee-bonus.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MySQL/employee-bonus.sql b/MySQL/employee-bonus.sql index f36c18880..706ef70d9 100644 --- a/MySQL/employee-bonus.sql +++ b/MySQL/employee-bonus.sql @@ -10,5 +10,5 @@ FROM LEFT JOIN Bonus ON Employee.empid = Bonus.empid WHERE - bonus < 1000 OR bonus IS NULL + Bonus.bonus < 1000 OR Bonus.bonus IS NULL ; From 6fc0add2dd66ff1e784c6160dd7467746b683c58 Mon Sep 17 00:00:00 2001 From: KEQI HUANG Date: Tue, 14 Nov 2017 17:44:34 -0600 Subject: [PATCH 3987/4971] Update merge-sorted-array.py add another solution of merge-sorted-array.py --- Python/merge-sorted-array.py | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/Python/merge-sorted-array.py b/Python/merge-sorted-array.py index 1f07ae31e..af7ff65f1 100644 --- a/Python/merge-sorted-array.py +++ b/Python/merge-sorted-array.py @@ -33,4 +33,30 @@ def merge(self, A, m, B, n): A = [1, 3, 5, 0, 0, 0, 0] B = [2, 4, 6, 7] Solution().merge(A, 3, B, 4) - print A \ No newline at end of file + print A + + +# you may get a input like this, +# nums1 : [0] +# m : 0 +# nums2 : [1] +# n : 1 +# so you need to judge if n is still large than 0 +class Solution2: + def merge(self, nums1, m, nums2, n): + """ + :type nums1: List[int] + :type m: int + :type nums2: List[int] + :type n: int + :rtype: void Do not return anything, modify nums1 in-place instead. + """ + while m > 0 and n > 0: + if nums1[m-1] > nums2[n-1]: + nums1[m+n-1] = nums1[m-1] + m -= 1 + else: + nums1[m+n-1] = nums2[n-1] + n -= 1 + if n > 0: + nums1[:n] = nums2[:n] From cf6ed06b9a78e8caefc4de6f326d51b447d0c006 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Nov 2017 12:53:22 +0800 Subject: [PATCH 3988/4971] Update merge-sorted-array.py --- Python/merge-sorted-array.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Python/merge-sorted-array.py b/Python/merge-sorted-array.py index af7ff65f1..5b6a275fc 100644 --- a/Python/merge-sorted-array.py +++ b/Python/merge-sorted-array.py @@ -35,7 +35,9 @@ def merge(self, A, m, B, n): Solution().merge(A, 3, B, 4) print A - + +# Time: O(n) +# Space: O(n) # you may get a input like this, # nums1 : [0] # m : 0 @@ -59,4 +61,7 @@ def merge(self, nums1, m, nums2, n): nums1[m+n-1] = nums2[n-1] n -= 1 if n > 0: - nums1[:n] = nums2[:n] + nums1[:n] = nums2[:n] # Space: O(n), + # Reference: + # - https://stackoverflow.com/questions/4948293/python-slice-assignment-memory-usage + # - https://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice From 41f40830fc631a7efef452dc91db8f8ec9868ffa Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 15 Nov 2017 13:08:03 +0800 Subject: [PATCH 3989/4971] Create get-highest-answer-rate-question.sql --- MySQL/get-highest-answer-rate-question.sql | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 MySQL/get-highest-answer-rate-question.sql diff --git a/MySQL/get-highest-answer-rate-question.sql b/MySQL/get-highest-answer-rate-question.sql new file mode 100644 index 000000000..e39d30a99 --- /dev/null +++ b/MySQL/get-highest-answer-rate-question.sql @@ -0,0 +1,10 @@ +# Time: O(nlogn) +# Space: O(n) + +SELECT + question_id AS 'survey_log' +FROM + survey_log +GROUP BY question_id +ORDER BY COUNT(answer_id) / COUNT(IF(action = 'show', 1, 0)) DESC +LIMIT 1; From 99fbeed2f97cb52adf1fb87e777bb0083bfc6bbc Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 16 Nov 2017 09:23:57 -0600 Subject: [PATCH 3990/4971] Create investments-in-2016.sql --- MySQL/investments-in-2016.sql | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 MySQL/investments-in-2016.sql diff --git a/MySQL/investments-in-2016.sql b/MySQL/investments-in-2016.sql new file mode 100644 index 000000000..6d9e1ad1e --- /dev/null +++ b/MySQL/investments-in-2016.sql @@ -0,0 +1,29 @@ +# Time: O(n^2) +# Space: O(n) + +SELECT + SUM(insurance.TIV_2016) AS TIV_2016 +FROM + insurance +WHERE + insurance.TIV_2015 IN + ( + SELECT + TIV_2015 + FROM + insurance + GROUP BY TIV_2015 + HAVING COUNT(*) > 1 + ORDER BY NULL + ) + AND CONCAT(LAT, LON) IN + ( + SELECT + CONCAT(LAT, LON) + FROM + insurance + GROUP BY LAT , LON + HAVING COUNT(*) = 1 + ORDER BY NULL + ) +; From c0e7c1212faeb79c4ed26d953bc6e5a3c4d58c94 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Nov 2017 22:19:51 +0800 Subject: [PATCH 3991/4971] Update minimum-index-sum-of-two-lists.cpp --- C++/minimum-index-sum-of-two-lists.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/minimum-index-sum-of-two-lists.cpp b/C++/minimum-index-sum-of-two-lists.cpp index 92d67ece1..b613be6eb 100644 --- a/C++/minimum-index-sum-of-two-lists.cpp +++ b/C++/minimum-index-sum-of-two-lists.cpp @@ -1,4 +1,4 @@ -// Time: O(m * n), m is the size of list1, n is the size of list2 +// Time: O(m + n), m is the size of list1, n is the size of list2 // Space: O(m * l), l is the average string length class Solution { From 892b920c7baf5432875d611704287c1b0434509f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Nov 2017 22:21:06 +0800 Subject: [PATCH 3992/4971] Update minimum-index-sum-of-two-lists.py --- Python/minimum-index-sum-of-two-lists.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/minimum-index-sum-of-two-lists.py b/Python/minimum-index-sum-of-two-lists.py index 5be1ae654..a63dd0a06 100644 --- a/Python/minimum-index-sum-of-two-lists.py +++ b/Python/minimum-index-sum-of-two-lists.py @@ -1,4 +1,4 @@ -# Time: O(m * n), m is the size of list1, n is the size of list2 +# Time: O(m + n), m is the size of list1, n is the size of list2 # Space: O(m * l), l is the max length of string # Suppose Andy and Doris want to choose a restaurant for dinner, From 39eace8a9e412c244960e3c879b368054c001034 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Nov 2017 22:24:51 +0800 Subject: [PATCH 3993/4971] Update minimum-index-sum-of-two-lists.py --- Python/minimum-index-sum-of-two-lists.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/minimum-index-sum-of-two-lists.py b/Python/minimum-index-sum-of-two-lists.py index a63dd0a06..4a953c004 100644 --- a/Python/minimum-index-sum-of-two-lists.py +++ b/Python/minimum-index-sum-of-two-lists.py @@ -1,5 +1,5 @@ -# Time: O(m + n), m is the size of list1, n is the size of list2 -# Space: O(m * l), l is the max length of string +# Time: O((m + n) * l), m is the size of list1, n is the size of list2 +# Space: O(m * l), l is the average length of string # Suppose Andy and Doris want to choose a restaurant for dinner, # and they both have a list of favorite restaurants represented by strings. From 3682555ef017e1c420c16570a84bd0b4acf60921 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Nov 2017 22:26:26 +0800 Subject: [PATCH 3994/4971] Update minimum-index-sum-of-two-lists.cpp --- C++/minimum-index-sum-of-two-lists.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/minimum-index-sum-of-two-lists.cpp b/C++/minimum-index-sum-of-two-lists.cpp index b613be6eb..4657e28fb 100644 --- a/C++/minimum-index-sum-of-two-lists.cpp +++ b/C++/minimum-index-sum-of-two-lists.cpp @@ -1,4 +1,4 @@ -// Time: O(m + n), m is the size of list1, n is the size of list2 +// Time: O((m + n) * l), m is the size of list1, n is the size of list2 // Space: O(m * l), l is the average string length class Solution { From 99bc5a1e75af46a924703e7092289eea834fa404 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 17 Nov 2017 10:48:29 -0600 Subject: [PATCH 3995/4971] Create find-customer-referee.sql --- MySQL/find-customer-referee.sql | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 MySQL/find-customer-referee.sql diff --git a/MySQL/find-customer-referee.sql b/MySQL/find-customer-referee.sql new file mode 100644 index 000000000..4364ed01d --- /dev/null +++ b/MySQL/find-customer-referee.sql @@ -0,0 +1,6 @@ +# Time: O(n) +# Space: O(1) + +SELECT name +FROM customer +WHERE referee_id is NULL OR referee_id != 2; From c9d02222998c43cebfb161bf2091ace44bb43d60 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Nov 2017 09:06:34 -0600 Subject: [PATCH 3996/4971] Create count-student-number-in-departments.sql --- "MySQL/count-student-number-in-departments\b.sql" | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 "MySQL/count-student-number-in-departments\b.sql" diff --git "a/MySQL/count-student-number-in-departments\b.sql" "b/MySQL/count-student-number-in-departments\b.sql" new file mode 100644 index 000000000..335c6430d --- /dev/null +++ "b/MySQL/count-student-number-in-departments\b.sql" @@ -0,0 +1,12 @@ +# Time: O(s+dlogd) +# Space: O(d+s) + +SELECT + dept_name, COUNT(student_id) AS student_number +FROM + department + LEFT JOIN + student ON department.dept_id = student.dept_id +GROUP BY department.dept_name +ORDER BY student_number DESC , department.dept_name +; From cc4135f0e48033895e61345fdeea708a5a323176 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 18 Nov 2017 10:22:47 -0600 Subject: [PATCH 3997/4971] Create find-cumulative-salary-of-an-employee.sql --- .../find-cumulative-salary-of-an-employee.sql | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 MySQL/find-cumulative-salary-of-an-employee.sql diff --git a/MySQL/find-cumulative-salary-of-an-employee.sql b/MySQL/find-cumulative-salary-of-an-employee.sql new file mode 100644 index 000000000..be723db8a --- /dev/null +++ b/MySQL/find-cumulative-salary-of-an-employee.sql @@ -0,0 +1,22 @@ +# Time: O(n^2) +# Space: O(n) + +SELECT EA.Id, + EA.Month, + SUM(EB.salary) AS Salary +FROM (SELECT E1.* + FROM employee E1 + LEFT JOIN (SELECT id, + MAX(month) AS month + FROM employee + GROUP BY id) E2 + ON E1.id = E2.id + WHERE E1.month < E2.month) EA + LEFT JOIN employee EB + ON EA.id = EB.id +WHERE EA.month - 2 <= EB.month + AND EB.month <= EA.month +GROUP BY EA.id, + EA.month +ORDER BY EA.id, + month DESC From 530cfdfe8dff3e359079aadabed6425e74a7da26 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Nov 2017 08:51:04 -0600 Subject: [PATCH 3998/4971] Create self-dividing-numbers.cpp --- C++/self-dividing-numbers.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/self-dividing-numbers.cpp diff --git a/C++/self-dividing-numbers.cpp b/C++/self-dividing-numbers.cpp new file mode 100644 index 000000000..c523befd4 --- /dev/null +++ b/C++/self-dividing-numbers.cpp @@ -0,0 +1,25 @@ +// Time: O(nlogn) +// Space: O(1) + +class Solution { +public: + vector selfDividingNumbers(int left, int right) { + vector result; + for (int i = left; i <= right; ++i) { + if (isDividingNumber(i)) { + result.emplace_back(i); + } + } + return result; + } + +private: + bool isDividingNumber(int num) { + for (int n = num; n > 0; n /= 10) { + if (!(n % 10) || num % (n % 10)) { + return false; + } + } + return true; + } +}; From 89dc202061d640bc66f12dc987a23d9abfc60a22 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Nov 2017 08:59:05 -0600 Subject: [PATCH 3999/4971] Create self-dividing-numbers.py --- Python/self-dividing-numbers.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Python/self-dividing-numbers.py diff --git a/Python/self-dividing-numbers.py b/Python/self-dividing-numbers.py new file mode 100644 index 000000000..343447b88 --- /dev/null +++ b/Python/self-dividing-numbers.py @@ -0,0 +1,23 @@ +# Time: O(nlogn) +# Space: O(1) + +class Solution(object): + def selfDividingNumbers(self, left, right): + """ + :type left: int + :type right: int + :rtype: List[int] + """ + def isDividingNumber(num): + n = num + while n > 0: + if (n%10) == 0 or (num%(n%10)) != 0: + return False + n /= 10 + return True + + result = [] + for num in xrange(left, right+1): + if isDividingNumber(num): + result.append(num) + return result From cfb027aa15b3ad01415c1328e059d993613b9509 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Nov 2017 10:33:50 -0600 Subject: [PATCH 4000/4971] Create count-different-palindromic-subsequences.cpp --- ...unt-different-palindromic-subsequences.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/count-different-palindromic-subsequences.cpp diff --git a/C++/count-different-palindromic-subsequences.cpp b/C++/count-different-palindromic-subsequences.cpp new file mode 100644 index 000000000..d2ab48f07 --- /dev/null +++ b/C++/count-different-palindromic-subsequences.cpp @@ -0,0 +1,40 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + int countPalindromicSubsequences(string S) { + static const int P = 1e9 + 7; + static const string chars = "abcd"; + vector>> dp(3, vector>(S.size(), vector(4))); + for (int len = 1; len <= S.size(); ++len) { + for (int i = 0; i + len <= S.size(); ++i) { + for (const auto& c : chars) { + dp[len % 3][i][c - 'a'] = 0; + if (len == 1) { + dp[len % 3][i][c - 'a'] = S[i] == c; + } else { + if (S[i] != c) { + dp[len % 3][i][c - 'a'] = dp[(len - 1) % 3][i + 1][c - 'a']; + } else if (S[i + len - 1] != c) { + dp[len % 3][i][c - 'a'] = dp[(len - 1) % 3][i][c - 'a']; + } else { + dp[len % 3][i][c - 'a'] = 2; + if (len > 2) { + for (const auto& cc : chars) { + dp[len % 3][i][c - 'a'] += dp[(len - 2) % 3][i + 1][cc - 'a']; + dp[len % 3][i][c - 'a'] %= P; + } + } + } + } + } + } + } + int result = 0; + for (const auto& c : chars) { + result = (result + dp[S.size() % 3][0][c - 'a']) % P; + } + return result; + } +}; From 275f15844433fde67b2e5f6126e313e1e3b5769b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Nov 2017 11:20:24 -0600 Subject: [PATCH 4001/4971] Create count-different-palindromic-subsequences.py --- ...ount-different-palindromic-subsequences.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/count-different-palindromic-subsequences.py diff --git a/Python/count-different-palindromic-subsequences.py b/Python/count-different-palindromic-subsequences.py new file mode 100644 index 000000000..1a8fc7e5d --- /dev/null +++ b/Python/count-different-palindromic-subsequences.py @@ -0,0 +1,43 @@ +# Time: O(n^2) +# Space: O(n) + +class Solution(object): + def countPalindromicSubsequences(self, S): + """ + :type S: str + :rtype: int + """ + def dp(i, j, prv, nxt, lookup): + if lookup[i][j] is not None: + return lookup[i][j] + result = 1 + if i <= j: + for x in xrange(4): + i0 = nxt[i][x] + j0 = prv[j][x] + if i <= i0 <= j: + result += 1 + if None < i0 < j0: + result += dp(i0+1, j0-1, prv, nxt, lookup) + result %= P + lookup[i][j] = result + return result + + N = len(S) + A = [ord(c) - ord('a') for c in S] + prv = [None] * N + nxt = [None] * N + + last = [None] * 4 + for i in xrange(len(S)): + last[ord(S[i])-ord('a')] = i + prv[i] = tuple(last) + + last = [None] * 4 + for i in reversed(xrange(len(S))): + last[ord(S[i])-ord('a')] = i + nxt[i] = tuple(last) + + P = 10**9 + 7 + lookup = [[None] * N for _ in xrange(N)] + return dp(0, N-1, prv, nxt, lookup) - 1 From 1533504e73418431de67115689aa4eb4128fdede Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Nov 2017 11:23:51 -0600 Subject: [PATCH 4002/4971] Update count-different-palindromic-subsequences.py --- Python/count-different-palindromic-subsequences.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/Python/count-different-palindromic-subsequences.py b/Python/count-different-palindromic-subsequences.py index 1a8fc7e5d..42bf0f92c 100644 --- a/Python/count-different-palindromic-subsequences.py +++ b/Python/count-different-palindromic-subsequences.py @@ -23,11 +23,9 @@ def dp(i, j, prv, nxt, lookup): lookup[i][j] = result return result - N = len(S) - A = [ord(c) - ord('a') for c in S] - prv = [None] * N - nxt = [None] * N - + n = len(S) + prv = [None] * n + nxt = [None] * n last = [None] * 4 for i in xrange(len(S)): last[ord(S[i])-ord('a')] = i @@ -39,5 +37,5 @@ def dp(i, j, prv, nxt, lookup): nxt[i] = tuple(last) P = 10**9 + 7 - lookup = [[None] * N for _ in xrange(N)] - return dp(0, N-1, prv, nxt, lookup) - 1 + lookup = [[None] * n for _ in xrange(n)] + return dp(0, n-1, prv, nxt, lookup) - 1 From c4e9daff3218bd144f893ead92c8593dad4870e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Nov 2017 11:24:44 -0600 Subject: [PATCH 4003/4971] Update count-different-palindromic-subsequences.py --- Python/count-different-palindromic-subsequences.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/count-different-palindromic-subsequences.py b/Python/count-different-palindromic-subsequences.py index 42bf0f92c..1c38e5f8c 100644 --- a/Python/count-different-palindromic-subsequences.py +++ b/Python/count-different-palindromic-subsequences.py @@ -23,9 +23,9 @@ def dp(i, j, prv, nxt, lookup): lookup[i][j] = result return result - n = len(S) - prv = [None] * n - nxt = [None] * n + prv = [None] * len(S) + nxt = [None] * len(S) + last = [None] * 4 for i in xrange(len(S)): last[ord(S[i])-ord('a')] = i @@ -37,5 +37,5 @@ def dp(i, j, prv, nxt, lookup): nxt[i] = tuple(last) P = 10**9 + 7 - lookup = [[None] * n for _ in xrange(n)] - return dp(0, n-1, prv, nxt, lookup) - 1 + lookup = [[None] * len(S) for _ in xrange(len(S))] + return dp(0, len(S)-1, prv, nxt, lookup) - 1 From b548983048a0bb04dd8ef000beecb62bcf3d8aca Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Nov 2017 11:37:31 -0600 Subject: [PATCH 4004/4971] Update count-different-palindromic-subsequences.py --- Python/count-different-palindromic-subsequences.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/count-different-palindromic-subsequences.py b/Python/count-different-palindromic-subsequences.py index 1c38e5f8c..3ef1d3b4c 100644 --- a/Python/count-different-palindromic-subsequences.py +++ b/Python/count-different-palindromic-subsequences.py @@ -16,9 +16,9 @@ def dp(i, j, prv, nxt, lookup): i0 = nxt[i][x] j0 = prv[j][x] if i <= i0 <= j: - result += 1 + result = (result + 1) % P if None < i0 < j0: - result += dp(i0+1, j0-1, prv, nxt, lookup) + result = (result + dp(i0+1, j0-1, prv, nxt, lookup)) % P result %= P lookup[i][j] = result return result From a44146c4707596b3089ad3d3127b2cd0c75906dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Nov 2017 11:40:30 -0600 Subject: [PATCH 4005/4971] Update count-different-palindromic-subsequences.cpp --- ...unt-different-palindromic-subsequences.cpp | 51 ++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/C++/count-different-palindromic-subsequences.cpp b/C++/count-different-palindromic-subsequences.cpp index d2ab48f07..7301aaa3f 100644 --- a/C++/count-different-palindromic-subsequences.cpp +++ b/C++/count-different-palindromic-subsequences.cpp @@ -1,6 +1,5 @@ // Time: O(n^2) // Space: O(n) - class Solution { public: int countPalindromicSubsequences(string S) { @@ -38,3 +37,53 @@ class Solution { return result; } }; + +// Time: O(n^2) +// Space: O(n^2) +class Solution2 { +public: + int countPalindromicSubsequences(string S) { + vector> prv(S.length(), vector(4, -1)); + vector> nxt(S.length(), vector(4, -1)); + vector last(4, -1); + for (int i = 0; i < S.length(); ++i) { + last[S[i] - 'a'] = i; + prv[i] = last; + } + last = vector(4, -1); + for (int i = S.length() - 1; i >= 0; --i) { + last[S[i] - 'a'] = i; + nxt[i] = last; + } + vector> lookup(S.length(), vector(S.length(), -1)); + return dp(0, S.length() - 1, prv, nxt, &lookup) - 1; + } + +private: + int dp(const int i, const int j, + const vector>& prv, + const vector>& nxt, + vector> *lookup) { + + if ((*lookup)[i][j] != -1) { + return (*lookup)[i][j]; + } + auto result = 1; + if (i <= j) { + for (int x = 0; x < 4; ++x) { + auto i0 = nxt[i][x]; + auto j0 = prv[j][x]; + if (i <= i0 && i0 <= j) { + result = (result + 1) % P; + } + if (i0 != -1 && j0 != -1 && i0 < j0) { + result = (result + dp(i0 + 1, j0 - 1, prv, nxt, lookup)) % P; + } + } + } + result %= P; + (*lookup)[i][j] = result; + return result; + } + static const int P = 1e9 + 7; +}; From 53c0af3b660366d6ae558dc3f5e5d1298aabca53 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 19 Nov 2017 11:40:59 -0600 Subject: [PATCH 4006/4971] Update count-different-palindromic-subsequences.py --- Python/count-different-palindromic-subsequences.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/count-different-palindromic-subsequences.py b/Python/count-different-palindromic-subsequences.py index 3ef1d3b4c..fd624b0b1 100644 --- a/Python/count-different-palindromic-subsequences.py +++ b/Python/count-different-palindromic-subsequences.py @@ -1,5 +1,5 @@ # Time: O(n^2) -# Space: O(n) +# Space: O(n^2) class Solution(object): def countPalindromicSubsequences(self, S): From 0bd7ee68613e8a1329056aada49e19b1f5c77d6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Nov 2017 09:44:49 -0600 Subject: [PATCH 4007/4971] Update self-dividing-numbers.py --- Python/self-dividing-numbers.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Python/self-dividing-numbers.py b/Python/self-dividing-numbers.py index 343447b88..15f866e3b 100644 --- a/Python/self-dividing-numbers.py +++ b/Python/self-dividing-numbers.py @@ -1,6 +1,24 @@ # Time: O(nlogn) # Space: O(1) +# A self-dividing number is a number that is divisible by every digit it contains. +# +# For example, 128 is a self-dividing number because 128 % 1 == 0, +# 128 % 2 == 0, and 128 % 8 == 0. +# +# Also, a self-dividing number is not allowed to contain the digit zero. +# +# Given a lower and upper number bound, output a list of every possible self dividing number, +# including the bounds if possible. +# +# Example 1: +# Input: +# left = 1, right = 22 +# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] +# +# Note: +# - The boundaries of each input argument are 1 <= left <= right <= 10000. + class Solution(object): def selfDividingNumbers(self, left, right): """ From 7292b2d276db056870993a108466fccc18debcae Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Nov 2017 09:47:52 -0600 Subject: [PATCH 4008/4971] Update count-different-palindromic-subsequences.py --- ...ount-different-palindromic-subsequences.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Python/count-different-palindromic-subsequences.py b/Python/count-different-palindromic-subsequences.py index fd624b0b1..e0b4e7452 100644 --- a/Python/count-different-palindromic-subsequences.py +++ b/Python/count-different-palindromic-subsequences.py @@ -1,6 +1,34 @@ # Time: O(n^2) # Space: O(n^2) +# Given a string S, find the number of different non-empty palindromic subsequences in S, +# and return that number modulo 10^9 + 7. +# +# A subsequence of a string S is obtained by deleting 0 or more characters from S. +# +# A sequence is palindromic if it is equal to the sequence reversed. +# +# Two sequences A_1, A_2, ... and B_1, B_2, ... are different if there is some i for which A_i != B_i. +# +# Example 1: +# Input: +# S = 'bccb' +# Output: 6 +# Explanation: +# The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'. +# Note that 'bcb' is counted only once, even though it occurs twice. +# +# Example 2: +# Input: +# S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba' +# Output: 104860361 +# +# Explanation: +# There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7. +# Note: +# - The length of S will be in the range [1, 1000]. +# - Each character S[i] will be in the set {'a', 'b', 'c', 'd'}. + class Solution(object): def countPalindromicSubsequences(self, S): """ From 1eaefd873a10bb2cd328fbcc58def463e83f8355 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Nov 2017 10:02:59 -0600 Subject: [PATCH 4009/4971] Create my-calendar-i.cpp --- C++/my-calendar-i.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/my-calendar-i.cpp diff --git a/C++/my-calendar-i.cpp b/C++/my-calendar-i.cpp new file mode 100644 index 000000000..28d1b911a --- /dev/null +++ b/C++/my-calendar-i.cpp @@ -0,0 +1,32 @@ +// Time: O(nlogn) +// Space: O(n) + +class MyCalendar { +public: + MyCalendar() { + + } + + bool book(int s, int e) { + auto next = books_.lower_bound(s); + if (next != books_.end() && next->first < e) { + return false; + } + if (next != books_.begin() && s < (--next)->second) { + return false; + } + books_[s] = e; + return true; + } + +private: + map books_; + +}; + +/** + * Your MyCalendar object will be instantiated and called as such: + * MyCalendar obj = new MyCalendar(); + * bool param_1 = obj.book(start,end); + */ + From 7e8ffcef7111fc3cd2f1d58831afb09741d9d8fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Nov 2017 10:20:21 -0600 Subject: [PATCH 4010/4971] Create my-calendar-i.py --- Python/my-calendar-i.py | 53 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/my-calendar-i.py diff --git a/Python/my-calendar-i.py b/Python/my-calendar-i.py new file mode 100644 index 000000000..05249cf67 --- /dev/null +++ b/Python/my-calendar-i.py @@ -0,0 +1,53 @@ +# Time: O(n^2) +# Space: O(n) + +# Implement a MyCalendar class to store your events. +# A new event can be added if adding the event will not cause a double booking. +# +# Your class will have the method, book(int start, int end). +# Formally, this represents a booking on the half open interval [start, end), +# the range of real numbers x such that start <= x < end. +# +# A double booking happens when two events have some non-empty intersection +# (ie., there is some time that is common to both events.) +# +# For each call to the method MyCalendar.book, +# return true if the event can be added to the calendar successfully without causing a double booking. +# Otherwise, return false and do not add the event to the calendar. +# +# Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end) +# Example 1: +# MyCalendar(); +# MyCalendar.book(10, 20); // returns true +# MyCalendar.book(15, 25); // returns false +# MyCalendar.book(20, 30); // returns true +# Explanation: +# The first event can be booked. The second can't because time 15 is already booked by another event. +# The third event can be booked, as the first event takes every time less than 20, but not including 20. +# +# Note: +# - The number of calls to MyCalendar.book per test case will be at most 1000. +# - In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9]. + +class MyCalendar(object): + + def __init__(self): + self.__calendar = [] + + + def book(self, start, end): + """ + :type start: int + :type end: int + :rtype: bool + """ + for i, j in self.__calendar: + if start < j and end > i: + return False + self.__calendar.append((start, end)) + return True + + +# Your MyCalendar object will be instantiated and called as such: +# obj = MyCalendar() +# param_1 = obj.book(start,end) From cf63d2625a2c3ff5a30d93ef762df41efb5882e4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Nov 2017 10:20:25 -0600 Subject: [PATCH 4011/4971] Create my-calendar-ii.py --- Python/my-calendar-ii.py | 64 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Python/my-calendar-ii.py diff --git a/Python/my-calendar-ii.py b/Python/my-calendar-ii.py new file mode 100644 index 000000000..0dc4f14e6 --- /dev/null +++ b/Python/my-calendar-ii.py @@ -0,0 +1,64 @@ +# Time: O(n^2) +# Space: O(n) + +# Implement a MyCalendarTwo class to store your events. +# A new event can be added if adding the event will not cause a triple booking. +# +# Your class will have one method, book(int start, int end). +# Formally, this represents a booking on the half open interval [start, end), +# the range of real numbers x such that start <= x < end. +# +# A triple booking happens when three events have some non-empty intersection +# (ie., there is some time that is common to all 3 events.) +# +# For each call to the method MyCalendar.book, +# return true if the event can be added to the calendar successfully without causing a triple booking. +# Otherwise, return false and do not add the event to the calendar. +# +# Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end) +# Example 1: +# MyCalendar(); +# MyCalendar.book(10, 20); // returns true +# MyCalendar.book(50, 60); // returns true +# MyCalendar.book(10, 40); // returns true +# MyCalendar.book(5, 15); // returns false +# MyCalendar.book(5, 10); // returns true +# MyCalendar.book(25, 55); // returns true +# +# Explanation: +# The first two events can be booked. The third event can be double booked. +# The fourth event (5, 15) can't be booked, because it would result in a triple booking. +# The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked. +# The sixth event (25, 55) can be booked, as the time in [25, 40) will be double booked with the third event; +# the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event. +# +# Note: +# - The number of calls to MyCalendar.book per test case will be at most 1000. +# - In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9]. + +class MyCalendarTwo(object): + + def __init__(self): + self.__overlaps = [] + self.__calendar = [] + + + def book(self, start, end): + """ + :type start: int + :type end: int + :rtype: bool + """ + for i, j in self.__overlaps: + if start < j and end > i: + return False + for i, j in self.__calendar: + if start < j and end > i: + self.__overlaps.append((max(start, i), min(end, j))) + self.__calendar.append((start, end)) + return True + + +# Your MyCalendarTwo object will be instantiated and called as such: +# obj = MyCalendarTwo() +# param_1 = obj.book(start,end) From 61059e24b8a3ff73bee33e8e253f96a66ed2458d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Nov 2017 10:26:43 -0600 Subject: [PATCH 4012/4971] Create my-calendar-ii.cpp --- C++/my-calendar-ii.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/my-calendar-ii.cpp diff --git a/C++/my-calendar-ii.cpp b/C++/my-calendar-ii.cpp new file mode 100644 index 000000000..60e26aa42 --- /dev/null +++ b/C++/my-calendar-ii.cpp @@ -0,0 +1,34 @@ +// Time: O(n^2) +// Space: O(n) + +class MyCalendarTwo { +public: + MyCalendarTwo() { + + } + + bool book(int start, int end) { + for (const auto& p : overlaps_) { + if (start < p.second && end > p.first) { + return false; + } + } + for (const auto& p : calendar_) { + if (start < p.second && end > p.first) { + overlaps_.emplace_back(max(start, p.first), min(end, p.second)); + } + } + calendar_.emplace_back(start, end); + return true; + } + +private: + vector> overlaps_; + vector> calendar_; +}; + +/** + * Your MyCalendarTwo object will be instantiated and called as such: + * MyCalendarTwo obj = new MyCalendarTwo(); + * bool param_1 = obj.book(start,end); + */ From 935e9fc130657ac9bcfab00ed8103ff00a06bb93 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 20 Nov 2017 10:36:59 -0600 Subject: [PATCH 4013/4971] Update my-calendar-i.py --- Python/my-calendar-i.py | 46 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/Python/my-calendar-i.py b/Python/my-calendar-i.py index 05249cf67..8814fc510 100644 --- a/Python/my-calendar-i.py +++ b/Python/my-calendar-i.py @@ -1,4 +1,4 @@ -# Time: O(n^2) +# Time: O(nlogn) on average, O(n^2) on worst case # Space: O(n) # Implement a MyCalendar class to store your events. @@ -28,8 +28,50 @@ # Note: # - The number of calls to MyCalendar.book per test case will be at most 1000. # - In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9]. - + +class Node: + def __init__(self, start, end): + self.__start = start + self.__end = end + self.__left = None + self.__right = None + + + def insert(self, node): + if node.__start >= self.__end: + if not self.__right: + self.__right = node + return True + return self.__right.insert(node) + elif node.__end <= self.__start: + if not self.__left: + self.__left = node + return True + return self.__left.insert(node) + else: + return False + + class MyCalendar(object): + def __init__(self): + self.__root = None + + + def book(self, start, end): + """ + :type start: int + :type end: int + :rtype: bool + """ + if self.__root is None: + self.__root = Node(start, end) + return True + return self.root.insert(Node(start, end)) + + +# Time: O(n^2) +# Space: O(n) +class MyCalendar2(object): def __init__(self): self.__calendar = [] From ed8cf182ecd568cefb9ff95462b10f46c417c826 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Nov 2017 09:20:33 -0600 Subject: [PATCH 4014/4971] Update self-dividing-numbers.cpp --- C++/self-dividing-numbers.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/self-dividing-numbers.cpp b/C++/self-dividing-numbers.cpp index c523befd4..d4a1565c5 100644 --- a/C++/self-dividing-numbers.cpp +++ b/C++/self-dividing-numbers.cpp @@ -1,5 +1,5 @@ -// Time: O(nlogn) -// Space: O(1) +// Time: O(nlogr) = O(n) +// Space: O(logr) = O(1) class Solution { public: From da432b35758bcae12320c460f57c9d2064224cf3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Nov 2017 09:21:05 -0600 Subject: [PATCH 4015/4971] Update self-dividing-numbers.py --- Python/self-dividing-numbers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/self-dividing-numbers.py b/Python/self-dividing-numbers.py index 15f866e3b..84050e5a8 100644 --- a/Python/self-dividing-numbers.py +++ b/Python/self-dividing-numbers.py @@ -1,5 +1,5 @@ -# Time: O(nlogn) -# Space: O(1) +# Time: O(nlogr) = O(n) +# Space: O(logr) = O(1) # A self-dividing number is a number that is divisible by every digit it contains. # From c6f5ccadf8b9a922b7c2d592038a7dbe0464c2dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 21 Nov 2017 09:25:34 -0600 Subject: [PATCH 4016/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 29293c0f7..c639adc45 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 717 | [1-bit and 2-bit Characters](https://leetcode.com/problems/1-bit-and-2-bit-characters/) | [C++](./C++/1-bit-and-2-bit-characters.cpp) [Python](./Python/1-bit-and-2-bit-characters.py) | _O(n)_ | _O(1)_ | Easy || Greedy 723 | [Candy Crush](https://leetcode.com/problems/candy-crush/) | [C++](./C++/candy-crush.cpp) [Python](./Python/candy-crush.py) | _O((R * C)^2)_ | _O(1)_ | Medium || 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [C++](./C++/find-pivot-index.cpp) [Python](./Python/find-pivot-index.py) | _O(n)_ | _O(1)_ | Easy || +729 | [My Calendar I](https://leetcode.com/problems/my-calendar-i/) | [C++](./C++/my-calendar-i.cpp) [Python](./Python/my-calendar-i.py) | _O(nlogn)_ | _O(n)_ | Medium || +731 | [My Calendar II](https://leetcode.com/problems/my-calendar-ii/) | [C++](./C++/my-calendar-ii.cpp) [Python](./Python/my-calendar-ii.py) | _O(n^2)_ | _O(n)_ | Easy || ## String @@ -354,6 +356,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 651 | [4 Keys Keyboard](https://leetcode.com/problems/4-keys-keyboard/) | [C++](./C++/4-keys-keyboard.cpp) [Python](./Python/4-keys-keyboard.py) | _O(1)_ | _O(1)_ | Medium |📖| Math, DP | 660 | [Remove 9](https://leetcode.com/problems/remove-9/) | [C++](./C++/remove-9.cpp) [Python](./Python/remove-9.py) | _O(logn)_ | _O(1)_ | Hard |📖|| 672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/) | [C++](./C++/bulb-switcher-ii.cpp) [Python](./Python/bulb-switcher-ii.py) | _O(1)_ | _O(1)_ | Medium ||| +728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/) | [C++](./C++/self-dividing-numbers.cpp) [Python](./Python/self-dividing-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -609,6 +612,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 712 | [Minimum ASCII Delete Sum for Two Strings](https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/) | [C++](./C++/minimum-ascii-delete-sum-for-two-strings.cpp) [Python](./Python/minimum-ascii-delete-sum-for-two-strings.py) | _O(m * n)_ | _O(n)_ | Medium || 714 | [Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-transaction-fee.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py) | _O(n)_ | _O(1)_ | Medium || 727 | [Minimum Window Subsequence](https://leetcode.com/problems/minimum-window-subsequence/) | [C++](./C++/minimum-window-subsequence.cpp) [Python](./Python/minimum-window-subsequence.py) | _O(s * t)_ | _O(s)_ | Hard |📖| +730 | [Count Different Palindromic Subsequences](https://leetcode.com/problems/count-different-palindromic-subsequences/) | [C++](./C++/count-different-palindromic-subsequences.cpp) [Python](./Python/count-different-palindromic-subsequences.py) | _O(n^2)_ | _O(n)_ | Hard || ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 94e2b8ace14ba61898faf999095d2ce1c0ec9036 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 22 Nov 2017 09:13:17 -0600 Subject: [PATCH 4017/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index c639adc45..6470962d1 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 394| [Decode String](https://leetcode.com/problems/decode-string/)| [C++](./C++/decode-string.cpp) [Python](./Python/decode-string.py) | _O(n)_ | _O(h)_ | Medium ||| 439| [Ternary Expression Parser](https://leetcode.com/problems/ternary-expression-parser/) | [C++](./C++/ternary-expression-parser.cpp) [Python](./Python/ternary-expression-parser.py) | _O(n)_ | _O(1)_ | Medium |📖| 456| [132 Pattern](https://leetcode.com/problems/132-pattern/) | [C++](./C++/132-pattern.cpp) [Python](./Python/132-pattern.py) | _O(n)_ | _O(n)_ | Medium || +636| [Exclusive Time of Functions](https://leetcode.com/problems/exclusive-time-of-functions/) | [C++](./C++/exclusive-time-of-functions.cpp) [Python](./Python/exclusive-time-of-functions.py) | _O(n)_ | _O(n)_ | Medium || 682| [Baseball Game](https://leetcode.com/problems/baseball-game/) | [C++](./C++/baseball-game.cpp) [Python](./Python/baseball-game.py) | _O(n)_ | _O(n)_ | Easy || 726| [Number of Atoms](https://leetcode.com/problems/number-of-atoms/) | [C++](./C++/number-of-atoms.cpp) [Python](./Python/number-of-atoms.py) | _O(n)_ | _O(n)_ | Hard || @@ -256,6 +257,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 | +637 |[Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/)| [C++](./C++/average-of-levels-in-binary-tree.cpp) [Python](./Python/average-of-levels-in-binary-tree.py)| _O(n)_ | _O(h)_ | Easy | | | 652 |[Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/)| [C++](./C++/find-duplicate-subtrees.cpp) [Python](./Python/find-duplicate-subtrees.py)| _O(n)_ | _O(n)_ | Medium | | DFS, Hash | 653 |[Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/)| [C++](./C++/two-sum-iv-input-is-a-bst.cpp) [Python](./Python/two-sum-iv-input-is-a-bst.py)| _O(n)_ | _O(h)_ | Easy | | Two Pointers | 654 |[Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/)| [C++](./C++/maximum-binary-tree.cpp) [Python](./Python/maximum-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | LintCode | Descending Stack | @@ -514,6 +516,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || 440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn)_ | _O(logn)_ | Hard || 464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || +638| [Shopping Offers](https://leetcode.com/problems/shopping-offers/) | [C++](./C++/shopping-offers.cpp) [Python](./Python/shopping-offers.py) | _O(n * 2^n)_ | _O(n)_ | Medium || 690| [Employee Importance](https://leetcode.com/problems/employee-importance/) | [C++](./C++/employee-importance.cpp) [Python](./Python/employee-importance.py) | _O(n)_ | _O(h)_ | Easy || DFS, BFS 694| [Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands/) | [C++](./C++/number-of-distinct-islands.cpp) [Python](./Python/number-of-distinct-islands.py) | _O(m * n)_ | _O(m * n)_ | Medium |📖|| 695| [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [C++](./C++/max-area-of-island.cpp) [Python](./Python/max-area-of-island.py) | _O(m * n)_ | _O(m * n)_ | Easy || @@ -602,6 +605,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +639 | [Decode Ways II](https://leetcode.com/problems/decode-ways-ii/) | [C++](./C++/decode-ways-ii.cpp) [Python](./Python/decode-ways-ii.py) | _O(n)_ | _O(1)_ | Hard ||| 650 | [2 Keys Keyboard](https://leetcode.com/problems/2-keys-keyboard/) | [C++](./C++/2-keys-keyboard.cpp) [Python](./Python/2-keys-keyboard.py) | _O(sqrt(n))_ | _O(1)_ | Medium ||| 656 | [Coin Path](https://leetcode.com/problems/coin-path/) | [C++](./C++/coin-path.cpp) [Python](./Python/coin-path.py) | _O(n * B)_ | _O(n)_ | Hard |📖| 664 | [Strange Printer](https://leetcode.com/problems/strange-printer/) | [C++](./C++/strange-printer.cpp) [Python](./Python/strange-printer.py) | _O(n^3)_ | _O(n^2)_ | Hard || From d53d2dc555ed93da50f5487720408e7700a1885c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Nov 2017 09:31:20 -0600 Subject: [PATCH 4018/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 6470962d1..c0260c2d3 100644 --- a/README.md +++ b/README.md @@ -242,6 +242,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 373 | [Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/) | [C++](./C++/find-k-pairs-with-smallest-sums.cpp) [Python](./Python/find-k-pairs-with-smallest-sums.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium ||| 378 | [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/) | [C++](./C++/kth-smallest-element-in-a-sorted-matrix.cpp) [Python](./Python/kth-smallest-element-in-a-sorted-matrix.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium | LintCode || 407 | [Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/) | [C++](./C++/trapping-rain-water-ii.cpp) [Python](./Python/trapping-rain-water-ii.py) | _O(m * n * (logm + logn))_ | _O(m * n)_ | Hard | LintCode || +632 | [Smallest Range](https://leetcode.com/problems/smallest-range/) | [C++](./C++/smallest-range.cpp) [Python](./Python/smallest-range.py) | _O(nlogk)_ | _O(k)_ | Hard ||| ## Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -354,6 +355,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +633| [Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers/) | [C++](./C++/sum-of-square-numbers.cpp) [Python](./Python/sum-of-square-numbers.py) | _O(sqrt(c) * logc)_ | _O(1)_ | Easy ||| +634| [Find the Derangement of An Array](https://leetcode.com/problems/find-the-derangement-of-an-array/) | [C++](./C++/find-the-derangement-of-an-array.cpp) [Python](./Python/find-the-derangement-of-an-array.py) | _O(n)_ | _O(1)_ | Medium |📖|| 640| [Solve the Equation](https://leetcode.com/problems/solve-the-equation/) | [C++](./C++/solve-the-equation.cpp) [Python](./Python/solve-the-equation.py) | _O(n)_ | _O(n)_ | Medium || | 651 | [4 Keys Keyboard](https://leetcode.com/problems/4-keys-keyboard/) | [C++](./C++/4-keys-keyboard.cpp) [Python](./Python/4-keys-keyboard.py) | _O(1)_ | _O(1)_ | Medium |📖| Math, DP | 660 | [Remove 9](https://leetcode.com/problems/remove-9/) | [C++](./C++/remove-9.cpp) [Python](./Python/remove-9.py) | _O(logn)_ | _O(1)_ | Hard |📖|| @@ -660,6 +663,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_ | Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | +635| [Design Log Storage System](https://leetcode.com/problems/design-log-storage-system/) | [C++](./C++/design-log-storage-system.cpp) [Python](./Python/design-log-storage-system.py) | put: _O(1)_
retrieve: _O(n + dlogd)_ | _O(n)_ | Hard |📖| | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | 716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | From 32c060f5af31ebd8d116f80508e6f9674d8a0e8a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 23 Nov 2017 09:32:02 -0600 Subject: [PATCH 4019/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c0260c2d3..a6b2d1e3a 100644 --- a/README.md +++ b/README.md @@ -663,7 +663,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_ | Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | -635| [Design Log Storage System](https://leetcode.com/problems/design-log-storage-system/) | [C++](./C++/design-log-storage-system.cpp) [Python](./Python/design-log-storage-system.py) | put: _O(1)_
retrieve: _O(n + dlogd)_ | _O(n)_ | Hard |📖| | +635| [Design Log Storage System](https://leetcode.com/problems/design-log-storage-system/) | [C++](./C++/design-log-storage-system.cpp) [Python](./Python/design-log-storage-system.py) | put: _O(1)_
retrieve: _O(n + dlogd)_ | _O(n)_ | Medium |📖| | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | 716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | From c2ca98286c5fc19e8f2e7443da825ba31b0d89cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Nov 2017 09:59:46 -0600 Subject: [PATCH 4020/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index a6b2d1e3a..115c2c3a2 100644 --- a/README.md +++ b/README.md @@ -355,6 +355,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +628| [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [C++](./C++/maximum-product-of-three-numbers.cpp) [Python](./Python/maximum-product-of-three-numbers.py) | _O(n)_ | _O(1)_ | Easy ||| 633| [Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers/) | [C++](./C++/sum-of-square-numbers.cpp) [Python](./Python/sum-of-square-numbers.py) | _O(sqrt(c) * logc)_ | _O(1)_ | Easy ||| 634| [Find the Derangement of An Array](https://leetcode.com/problems/find-the-derangement-of-an-array/) | [C++](./C++/find-the-derangement-of-an-array.cpp) [Python](./Python/find-the-derangement-of-an-array.py) | _O(n)_ | _O(1)_ | Medium |📖|| 640| [Solve the Equation](https://leetcode.com/problems/solve-the-equation/) | [C++](./C++/solve-the-equation.cpp) [Python](./Python/solve-the-equation.py) | _O(n)_ | _O(n)_ | Medium || | @@ -608,6 +609,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +629 | [K Inverse Pairs Array](https://leetcode.com/problems/k-inverse-pairs-array/) | [C++](./C++/k-inverse-pairs-array.cpp) [Python](./Python/k-inverse-pairs-array.py) | _O(n * k)_ | _O(k)_ | Hard ||| 639 | [Decode Ways II](https://leetcode.com/problems/decode-ways-ii/) | [C++](./C++/decode-ways-ii.cpp) [Python](./Python/decode-ways-ii.py) | _O(n)_ | _O(1)_ | Hard ||| 650 | [2 Keys Keyboard](https://leetcode.com/problems/2-keys-keyboard/) | [C++](./C++/2-keys-keyboard.cpp) [Python](./Python/2-keys-keyboard.py) | _O(sqrt(n))_ | _O(1)_ | Medium ||| 656 | [Coin Path](https://leetcode.com/problems/coin-path/) | [C++](./C++/coin-path.cpp) [Python](./Python/coin-path.py) | _O(n * B)_ | _O(n)_ | Hard |📖| @@ -642,6 +644,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | 452 | [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(nlogn)_ | _O(1)_ | Medium | | 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/) | [C++](./C++/assign-cookies.cpp) [Python](./Python/assign-cookies.py) | _O(nlogn)_ | _O(1)_ | Easy | | +630 | [Course Schedule III](https://leetcode.com/problems/course-schedule-iii/) | [C++](./C++/course-schedule-iii.cpp) [Python](./Python/course-schedule-iii.py) | _O(nlogk)_ | _O(k)_ | Hard || 646 | [Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) | [C++](./C++/maximum-length-of-pair-chain.cpp) [Python](./Python/maximum-length-of-pair-chain.py) | _O(nlogn)_ | _O(1)_ | Medium || Scan Line 649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [C++](./C++/dota2-senate.cpp) [Python](./Python/dota2-senate.py) | _O(n)_ | _O(n)_ | Medium ||| 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | @@ -663,6 +666,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_ | Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | +631| [Design Log Storage System](https://leetcode.com/problems/design-log-storage-system/) | [C++](./C++/design-log-storage-system.cpp) [Python](./Python/design-log-storage-system.py) | set: _O((r * c)^2)_
get: _O(1)_
sum: _O((r * c)^2)_ | _O(r * c)_ | Hard |📖| | 635| [Design Log Storage System](https://leetcode.com/problems/design-log-storage-system/) | [C++](./C++/design-log-storage-system.cpp) [Python](./Python/design-log-storage-system.py) | put: _O(1)_
retrieve: _O(n + dlogd)_ | _O(n)_ | Medium |📖| | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | From e514042b9fa3bf55e506c71081b82423dff1218b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Nov 2017 10:01:15 -0600 Subject: [PATCH 4021/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 115c2c3a2..fba86c18e 100644 --- a/README.md +++ b/README.md @@ -644,7 +644,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | 452 | [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(nlogn)_ | _O(1)_ | Medium | | 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/) | [C++](./C++/assign-cookies.cpp) [Python](./Python/assign-cookies.py) | _O(nlogn)_ | _O(1)_ | Easy | | -630 | [Course Schedule III](https://leetcode.com/problems/course-schedule-iii/) | [C++](./C++/course-schedule-iii.cpp) [Python](./Python/course-schedule-iii.py) | _O(nlogk)_ | _O(k)_ | Hard || +630 | [Course Schedule III](https://leetcode.com/problems/course-schedule-iii/) | [C++](./C++/course-schedule-iii.cpp) [Python](./Python/course-schedule-iii.py) | _O(nlogn)_ | _O(k)_ | Hard || 646 | [Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) | [C++](./C++/maximum-length-of-pair-chain.cpp) [Python](./Python/maximum-length-of-pair-chain.py) | _O(nlogn)_ | _O(1)_ | Medium || Scan Line 649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [C++](./C++/dota2-senate.cpp) [Python](./Python/dota2-senate.py) | _O(n)_ | _O(n)_ | Medium ||| 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | From 6f03ea8211e3d8bea87b922bef628809e073ccdc Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 24 Nov 2017 23:02:01 -0600 Subject: [PATCH 4022/4971] Create my-calendar-iii.cpp --- C++/my-calendar-iii.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/my-calendar-iii.cpp diff --git a/C++/my-calendar-iii.cpp b/C++/my-calendar-iii.cpp new file mode 100644 index 000000000..1e2aedcf7 --- /dev/null +++ b/C++/my-calendar-iii.cpp @@ -0,0 +1,30 @@ +// Time: O(n^2) +// Space: O(n) + +class MyCalendarThree { +public: + MyCalendarThree() { + + } + + int book(int start, int end) { + ++books_[start]; + --books_[end]; + int result = 0; + int cnt = 0; + for (auto &book : books_) { + cnt += book.second; + result = max(result, cnt); + } + return result; + } + +private: + map books_; +}; + +/** + * Your MyCalendarThree object will be instantiated and called as such: + * MyCalendarThree obj = new MyCalendarThree(); + * int param_1 = obj.book(start,end); + */ From d94d7c4de21daede2fe253b73af1e27626d84d50 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 25 Nov 2017 00:13:12 -0600 Subject: [PATCH 4023/4971] Update my-calendar-iii.cpp --- C++/my-calendar-iii.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/my-calendar-iii.cpp b/C++/my-calendar-iii.cpp index 1e2aedcf7..895b389dd 100644 --- a/C++/my-calendar-iii.cpp +++ b/C++/my-calendar-iii.cpp @@ -12,7 +12,7 @@ class MyCalendarThree { --books_[end]; int result = 0; int cnt = 0; - for (auto &book : books_) { + for (const auto &book : books_) { cnt += book.second; result = max(result, cnt); } From d7eb204ec9c964555ed917da372a9bba94c4cf5d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 25 Nov 2017 23:27:20 -0600 Subject: [PATCH 4024/4971] Create my-calendar-iii.py --- Python/my-calendar-iii.py | 69 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Python/my-calendar-iii.py diff --git a/Python/my-calendar-iii.py b/Python/my-calendar-iii.py new file mode 100644 index 000000000..985a001a6 --- /dev/null +++ b/Python/my-calendar-iii.py @@ -0,0 +1,69 @@ +# Time: O(n^2) +# Space: O(n) + +# Implement a MyCalendarThree class to store your events. A new event can always be added. +# +# Your class will have one method, book(int start, int end). +# Formally, this represents a booking on the half open interval [start, end), +# the range of real numbers x such that start <= x < end. +# +# A K-booking happens when K events have some non-empty intersection +# (ie., there is some time that is common to all K events.) +# +# For each call to the method MyCalendar.book, +# return an integer K representing the largest integer such that there exists a K-booking in the calendar. +# +# Your class will be called like this: +# MyCalendarThree cal = new MyCalendarThree(); MyCalendarThree.book(start, end) +# Example 1: +# MyCalendarThree(); +# MyCalendarThree.book(10, 20); // returns 1 +# MyCalendarThree.book(50, 60); // returns 1 +# MyCalendarThree.book(10, 40); // returns 2 +# MyCalendarThree.book(5, 15); // returns 3 +# MyCalendarThree.book(5, 10); // returns 3 +# MyCalendarThree.book(25, 55); // returns 3 +# Explanation: +# The first two events can be booked and are disjoint, so the maximum K-booking is a 1-booking. +# The third event [10, 40) intersects the first event, and the maximum K-booking is a 2-booking. +# The remaining events cause the maximum K-booking to be only a 3-booking. +# Note that the last event locally causes a 2-booking, but the answer is still 3 because +# eg. [10, 20), [10, 40), and [5, 15) are still triple booked. +# Note: +# - The number of calls to MyCalendarThree.book per test case will be at most 400. +# - In calls to MyCalendarThree.book(start, end), start and end are integers in the range [0, 10^9]. + +class MyCalendarThree(object): + + def __init__(self): + self.__books = [] + + + def book(self, start, end): + """ + :type start: int + :type end: int + :rtype: int + """ + i = bisect.bisect_left(self.__books, (start, 1)) + if i < len(self.__books) and self.__books[i][0] == start: + self.__books[i] = (self.__books[i][0], self.__books[i][1]+1) + else: + self.__books.insert(i, (start, 1)) + + j = bisect.bisect_left(self.__books, (end, 1)) + if j < len(self.__books) and self.__books[j][0] == end: + self.__books[j] = (self.__books[j][0], self.__books[j][1]-1) + else: + self.__books.insert(j, (end, -1)) + + result, cnt = 0, 0 + for book in self.__books: + cnt += book[1] + result = max(result, cnt) + return result + + +# Your MyCalendarThree object will be instantiated and called as such: +# obj = MyCalendarThree() +# param_1 = obj.book(start,end) From 90dd7bb0d65c4aca5df31b602e9f55435c85a491 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 03:47:45 -0600 Subject: [PATCH 4025/4971] Create flood-fill.py --- Python/flood-fill.py | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Python/flood-fill.py diff --git a/Python/flood-fill.py b/Python/flood-fill.py new file mode 100644 index 000000000..b703277ff --- /dev/null +++ b/Python/flood-fill.py @@ -0,0 +1,57 @@ +# Time: O(r * c) +# Space: O(r * c) + +# An image is represented by a 2-D array of integers, +# each integer representing the pixel value of the image (from 0 to 65535). +# +# Given a coordinate (sr, sc) representing the starting pixel (row and column) +# of the flood fill, and a pixel value newColor, "flood fill" the image. +# +# To perform a "flood fill", consider the starting pixel, +# plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, +# plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), +# and so on. Replace the color of all of the aforementioned pixels with the newColor. +# +# At the end, return the modified image. +# +# Example 1: +# Input: +# image = [[1,1,1],[1,1,0],[1,0,1]] +# sr = 1, sc = 1, newColor = 2 +# Output: [[2,2,2],[2,2,0],[2,0,1]] +# Explanation: +# From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected +# by a path of the same color as the starting pixel are colored with the new color. +# Note the bottom corner is not colored 2, because it is not 4-directionally connected +# to the starting pixel. +# +# Note: +# - The length of image and image[0] will be in the range [1, 50]. +# - The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length. +# - The value of each color in image[i][j] and newColor will be an integer in [0, 65535]. + +class Solution(object): + def floodFill(self, image, sr, sc, newColor): + """ + :type image: List[List[int]] + :type sr: int + :type sc: int + :type newColor: int + :rtype: List[List[int]] + """ + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + + def dfs(image, r, c, color): + if not (0 <= r < len(image) and \ + 0 <= c < len(image[0]) and \ + image[r][c] == color): + return + + image[r][c] = newColor + for d in directions: + dfs(image, r+d[0], c+d[1], color) + + color = image[sr][sc] + if color == newColor: return image + dfs(image, sr, sc, color) + return image From 8ced9f82bd5d47a6130c2cdd8a4e70f5be7fdb17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 03:52:17 -0600 Subject: [PATCH 4026/4971] Update flood-fill.py --- Python/flood-fill.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/flood-fill.py b/Python/flood-fill.py index b703277ff..7f1149a0f 100644 --- a/Python/flood-fill.py +++ b/Python/flood-fill.py @@ -1,5 +1,5 @@ -# Time: O(r * c) -# Space: O(r * c) +# Time: O(m * n) +# Space: O(m * n) # An image is represented by a 2-D array of integers, # each integer representing the pixel value of the image (from 0 to 65535). @@ -41,7 +41,7 @@ def floodFill(self, image, sr, sc, newColor): """ directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] - def dfs(image, r, c, color): + def dfs(image, r, c, newColor, color): if not (0 <= r < len(image) and \ 0 <= c < len(image[0]) and \ image[r][c] == color): @@ -49,9 +49,9 @@ def dfs(image, r, c, color): image[r][c] = newColor for d in directions: - dfs(image, r+d[0], c+d[1], color) + dfs(image, r+d[0], c+d[1], newColor, color) color = image[sr][sc] if color == newColor: return image - dfs(image, sr, sc, color) + dfs(image, sr, sc, newColor, color) return image From 5d3327d6781b25de42f6b7e512da1e06cbfda065 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 03:57:09 -0600 Subject: [PATCH 4027/4971] Create flood-fill.cpp --- C++/flood-fill.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/flood-fill.cpp diff --git a/C++/flood-fill.cpp b/C++/flood-fill.cpp new file mode 100644 index 000000000..0d86958c5 --- /dev/null +++ b/C++/flood-fill.cpp @@ -0,0 +1,27 @@ +// Time: O(m * n) +// Space: O(m * n) + +class Solution { +public: + vector> floodFill(vector>& image, int sr, int sc, int newColor) { + int color = image[sr][sc]; + if (color == newColor) return image; + dfs(&image, sr, sc, newColor, color); + return image; + } + +private: + void dfs(vector> *image, int r, int c, int newColor, int color) { + static const vector> directions{{-1, 0}, { 1, 0}, + { 0, 1}, { 0, -1}}; + if (r < 0 || r >= image->size() || + c < 0 || c >= (*image)[0].size() || + (*image)[r][c] != color) { + return; + } + (*image)[r][c] = newColor; + for (const auto& d : directions) { + dfs(image, r + d.first, c + d.second, newColor, color); + } + } +}; From 044f7b4e94708c1bc9e897e58a40de253c9d5ac3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 04:17:36 -0600 Subject: [PATCH 4028/4971] Create sentence-similarity.cpp --- C++/sentence-similarity.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/sentence-similarity.cpp diff --git a/C++/sentence-similarity.cpp b/C++/sentence-similarity.cpp new file mode 100644 index 000000000..076568ee3 --- /dev/null +++ b/C++/sentence-similarity.cpp @@ -0,0 +1,34 @@ +// Time: O(n + p) +// Space: O(p) + +class Solution { +public: + bool areSentencesSimilar(vector& words1, vector& words2, vector> pairs) { + if (words1.size() != words2.size()) { + return false; + } + unordered_set, PairHash> lookup; + for (const auto& pair : pairs) { + lookup.emplace(pair.first, pair.second); + lookup.emplace(pair.second, pair.first); + } + for (int i = 0; i < words1.size(); ++i) { + if (words1[i] != words2[i] && + !lookup.count(make_pair(words1[i], words2[i]))) { + return false; + } + } + return true; + } + +private: + template + struct PairHash { + size_t operator()(const pair& p) const { + size_t seed = 0; + seed ^= std::hash{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2); + seed ^= std::hash{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2); + return seed; + } + }; +}; From cc4337d226bb73685ad454c3eb9bbf7b7b532141 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 04:21:35 -0600 Subject: [PATCH 4029/4971] Create sentence-similarity.py --- Python/sentence-similarity.py | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/sentence-similarity.py diff --git a/Python/sentence-similarity.py b/Python/sentence-similarity.py new file mode 100644 index 000000000..02ee74720 --- /dev/null +++ b/Python/sentence-similarity.py @@ -0,0 +1,41 @@ +# Time: O(n + p) +# Space: O(p) + +# Given two sentences words1, words2 (each represented as an array of strings), +# and a list of similar word pairs pairs, determine if two sentences are similar. +# +# For example, "great acting skills" and "fine drama talent" are similar, +# if the similar word pairs are pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]. +# +# Note that the similarity relation is not transitive. +# For example, if "great" and "fine" are similar, and "fine" and "good" are similar, +# "great" and "good" are not necessarily similar. +# +# However, similarity is symmetric. +# For example, "great" and "fine" being similar is the same as "fine" and "great" being similar. +# +# Also, a word is always similar with itself. +# For example, the sentences words1 = ["great"], words2 = ["great"], pairs = [] are similar, +# even though there are no specified similar word pairs. +# +# Finally, sentences can only be similar if they have the same number of words. +# So a sentence like words1 = ["great"] can never be similar to words2 = ["doubleplus","good"]. +# +# Note: +# - The length of words1 and words2 will not exceed 1000. +# - The length of pairs will not exceed 2000. +# - The length of each pairs[i] will be 2. +# - The length of each words[i] and pairs[i][j] will be in the range [1, 20]. + +class Solution(object): + def areSentencesSimilar(self, words1, words2, pairs): + """ + :type words1: List[str] + :type words2: List[str] + :type pairs: List[List[str]] + :rtype: bool + """ + if len(words1) != len(words2): return False + lookup = set(map(tuple, pairs)) + return all(w1 == w2 or (w1, w2) in lookup or (w2, w1) in lookup \ + for w1, w2 in itertools.izip(words1, words2)) From 089ca06959de93dc5d26b37690f651abcdd4c27c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 07:44:37 -0600 Subject: [PATCH 4030/4971] Create asteroid-collision.cpp --- C++/asteroid-collision.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/asteroid-collision.cpp diff --git a/C++/asteroid-collision.cpp b/C++/asteroid-collision.cpp new file mode 100644 index 000000000..6a647dff4 --- /dev/null +++ b/C++/asteroid-collision.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector asteroidCollision(vector& asteroids) { + vector result; + for (const auto& asteroid : asteroids) { + bool is_exploded = false; + while (!result.empty() && asteroid < 0 && 0 < result.back()) { + if (result.back() < -asteroid) { + result.pop_back(); + continue; + } else if (result.back() == -asteroid) { + result.pop_back(); + } + is_exploded = true; + break; + } + if (!is_exploded) { + result.emplace_back(asteroid); + } + } + return result; + } +}; From 845afc5e15a44e462b9b3be38e632c7240e90751 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 07:49:00 -0600 Subject: [PATCH 4031/4971] Create asteroid-collision.py --- Python/asteroid-collision.py | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/asteroid-collision.py diff --git a/Python/asteroid-collision.py b/Python/asteroid-collision.py new file mode 100644 index 000000000..223daeaf9 --- /dev/null +++ b/Python/asteroid-collision.py @@ -0,0 +1,61 @@ +# Time: O(n) +# Space: O(n) + +# We are given an array asteroids of integers representing asteroids in a row. +# +# For each asteroid, the absolute value represents its size, +# and the sign represents its direction (positive meaning right, negative meaning left). +# Each asteroid moves at the same speed. +# +# Find out the state of the asteroids after all collisions. +# If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. +# Two asteroids moving in the same direction will never meet. +# +# Example 1: +# Input: +# asteroids = [5, 10, -5] +# Output: [5, 10] +# Explanation: +# The 10 and -5 collide resulting in 10. The 5 and 10 never collide. +# Example 2: +# Input: +# asteroids = [8, -8] +# Output: [] +# Explanation: +# The 8 and -8 collide exploding each other. +# Example 3: +# Input: +# asteroids = [10, 2, -5] +# Output: [10] +# Explanation: +# The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. +# Example 4: +# Input: +# asteroids = [-2, -1, 1, 2] +# Output: [-2, -1, 1, 2] +# Explanation: +# The -2 and -1 are moving left, while the 1 and 2 are moving right. +# Asteroids moving the same direction never meet, so no asteroids will meet each other. +# +# Note: +# - The length of asteroids will be at most 10000. +# - Each asteroid will be a non-zero integer in the range [-1000, 1000]. + +class Solution(object): + def asteroidCollision(self, asteroids): + """ + :type asteroids: List[int] + :rtype: List[int] + """ + result = [] + for asteroid in asteroids: + while result and asteroid < 0 < result[-1]: + if result[-1] < -asteroid: + result.pop() + continue + elif result[-1] == -asteroid: + result.pop() + break + else: + result.append(asteroid) + return result From 533be773568008605d124020ff36c4b550114467 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 09:29:44 -0600 Subject: [PATCH 4032/4971] Create sentence-similarity-ii.py --- Python/sentence-similarity-ii.py | 70 ++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Python/sentence-similarity-ii.py diff --git a/Python/sentence-similarity-ii.py b/Python/sentence-similarity-ii.py new file mode 100644 index 000000000..3e0d8895a --- /dev/null +++ b/Python/sentence-similarity-ii.py @@ -0,0 +1,70 @@ +# Time: O(n + p) +# Space: O(p) + +# Given two sentences words1, words2 (each represented as an array of strings), +# and a list of similar word pairs pairs, determine if two sentences are similar. +# +# For example, words1 = ["great", "acting", "skills"] and +# words2 = ["fine", "drama", "talent"] are similar, +# if the similar word pairs are pairs = +# [["great", "good"], ["fine", "good"], ["acting","drama"], ["skills","talent"]]. +# +# Note that the similarity relation is transitive. +# For example, if "great" and "good" are similar, +# and "fine" and "good" are similar, then "great" and "fine" are similar. +# +# Similarity is also symmetric. +# For example, "great" and "fine" being similar is the same as "fine" and "great" being similar. +# +# Also, a word is always similar with itself. +# For example, the sentences words1 = ["great"], +# words2 = ["great"], pairs = [] are similar, even though there are no specified similar word pairs. +# +# Finally, sentences can only be similar if they have the same number of words. +# So a sentence like words1 = ["great"] can never be similar to words2 = ["doubleplus","good"]. +# +# Note: +# - The length of words1 and words2 will not exceed 1000. +# - The length of pairs will not exceed 2000. +# - The length of each pairs[i] will be 2. +# - The length of each words[i] and pairs[i][j] will be in the range [1, 20]. + +class UnionFind(object): + def __init__(self, n): + self.set = range(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: + return False + self.set[min(x_root, y_root)] = max(x_root, y_root) + return True + + +class Solution(object): + def areSentencesSimilarTwo(self, words1, words2, pairs): + """ + :type words1: List[str] + :type words2: List[str] + :type pairs: List[List[str]] + :rtype: bool + """ + if len(words1) != len(words2): return False + + lookup = {} + union_find = UnionFind(2 * len(pairs)) + for pair in pairs: + for p in pair: + if p not in lookup: + lookup[p] = len(lookup) + union_find.union_set(lookup[pair[0]], lookup[pair[1]]) + + return all(w1 == w2 or + w1 in lookup and w2 in lookup and + union_find.find_set(lookup[w1]) == union_find.find_set(lookup[w2]) + for w1, w2 in itertools.izip(words1, words2)) From c37f169b4326e021b5387dbfb2d23ae7ef37a2c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 09:51:50 -0600 Subject: [PATCH 4033/4971] Create sentence-similarity-ii.cpp --- C++/sentence-similarity-ii.cpp | 58 ++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 C++/sentence-similarity-ii.cpp diff --git a/C++/sentence-similarity-ii.cpp b/C++/sentence-similarity-ii.cpp new file mode 100644 index 000000000..34269a064 --- /dev/null +++ b/C++/sentence-similarity-ii.cpp @@ -0,0 +1,58 @@ +// Time: O(n + p) +// Space: O(p) + +class Solution { +public: + bool areSentencesSimilarTwo(vector& words1, vector& words2, vector> pairs) { + if (words1.size() != words2.size()) { + return false; + } + unordered_map lookup; + UnionFind union_find(2 * pairs.size()); + for (const auto& pair : pairs) { + if (!lookup.count(pair.first)) { + lookup[pair.first] = lookup.size() - 1; + } + if (!lookup.count(pair.second)) { + lookup[pair.second] = lookup.size() - 1; + } + union_find.union_set(lookup[pair.first], lookup[pair.second]); + } + for (int i = 0; i < words1.size(); ++i) { + if (words1[i] != words2[i] && + (!lookup.count(words1[i]) || !lookup.count(words2[i]) || + union_find.find_set(lookup[words1[i]]) != + union_find.find_set(lookup[words2[i]]))) { + return false; + } + } + return true; + } + +private: + class UnionFind { + public: + UnionFind(const int n) : set_(n) { + iota(set_.begin(), set_.end(), 0); + } + + int find_set(const int x) { + if (set_[x] != x) { + set_[x] = find_set(set_[x]); // Path compression. + } + return set_[x]; + } + + bool union_set(const int x, const int y) { + int x_root = find_set(x), y_root = find_set(y); + if (x_root == y_root) { + return false; + } + set_[min(x_root, y_root)] = max(x_root, y_root); + return true; + } + + private: + vector set_; + }; +}; From e9097a4b67bc1b870d72117aaf88d33fe63693fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 11:18:42 -0600 Subject: [PATCH 4034/4971] Create parse-lisp-expression.cpp --- C++/parse-lisp-expression.cpp | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 C++/parse-lisp-expression.cpp diff --git a/C++/parse-lisp-expression.cpp b/C++/parse-lisp-expression.cpp new file mode 100644 index 000000000..3b490f7e6 --- /dev/null +++ b/C++/parse-lisp-expression.cpp @@ -0,0 +1,50 @@ +// Time: O(n^2) +// Space: O(n^2) + +class Solution { +public: + int evaluate(string expression) { + vector tokens{""}; + unordered_map lookup; + vector, unordered_map>> stk; + for (const auto& c : expression) { + if (c == '(') { + if (tokens[0] == "let") { + evaluate(tokens, &lookup); + } + stk.emplace_back(tokens, lookup); + tokens = {""}; + } else if (c == ' ') { + tokens.emplace_back(""); + } else if (c == ')') { + const auto& val = evaluate(tokens, &lookup); + tie(tokens, lookup) = move(stk.back()); + stk.pop_back(); + tokens.back() += val; + } else { + tokens.back().push_back(c); + } + } + return stoi(tokens[0]); + } + +private: + string evaluate(const vector& tokens, unordered_map* lookup) { + static const unordered_set operators{"add", "mult"}; + if (operators.count(tokens[0])) { + const auto& a = stoi(getval(*lookup, tokens[1])); + const auto& b = stoi(getval(*lookup, tokens[2])); + return to_string(tokens[0] == "add" ? a + b : a * b); + } + for (int i = 1; i < tokens.size() - 1; i += 2) { + if (!tokens[i + 1].empty()) { + (*lookup)[tokens[i]] = getval(*lookup, tokens[i + 1]); + } + } + return getval(*lookup, tokens.back()); + } + + string getval(const unordered_map& lookup, const string& x) { + return lookup.count(x) ? lookup.at(x) : x; + } +}; From fe26a87de7275beb7d47851fa6cc5eefe05be3bd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 11:22:52 -0600 Subject: [PATCH 4035/4971] Create parse-lisp-expression.py --- Python/parse-lisp-expression.py | 107 ++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 Python/parse-lisp-expression.py diff --git a/Python/parse-lisp-expression.py b/Python/parse-lisp-expression.py new file mode 100644 index 000000000..6797e8c97 --- /dev/null +++ b/Python/parse-lisp-expression.py @@ -0,0 +1,107 @@ +# You are given a string expression representing a Lisp-like expression to return the integer value of. +# +# The syntax for these expressions is given as follows. +# +# An expression is either an integer, a let-expression, +# an add-expression, a mult-expression, or an assigned variable. +# Expressions always evaluate to a single integer. +# (An integer could be positive or negative.) +# A let-expression takes the form (let v1 e1 v2 e2 ... vn en expr), +# where let is always the string "let", then there are 1 or more pairs of alternating variables and expressions, +# meaning that the first variable v1 is assigned the value of the expression e1, +# the second variable v2 is assigned the value of the expression e2, +# and so on sequentially; and then the value of this let-expression is the value of the expression expr. +# An add-expression takes the form (add e1 e2) where add is always the string "add", +# there are always two expressions e1, e2, +# and this expression evaluates to the addition of the evaluation of e1 and the evaluation of e2. +# A mult-expression takes the form (mult e1 e2) where mult is always the string "mult", +# there are always two expressions e1, e2, +# and this expression evaluates to the multiplication of the evaluation of e1 and the evaluation of e2. +# For the purposes of this question, we will use a smaller subset of variable names. +# A variable starts with a lowercase letter, then zero or more lowercase letters or digits. +# Additionally for your convenience, +# the names "add", "let", or "mult" are protected and will never be used as variable names. +# Finally, there is the concept of scope. +# When an expression of a variable name is evaluated, +# within the context of that evaluation, +# the innermost scope (in terms of parentheses) is checked first for the value of that variable, +# and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. +# Please see the examples for more details on scope. +# +# Evaluation Examples: +# Input: (add 1 2) +# Output: 3 +# +# Input: (mult 3 (add 2 3)) +# Output: 15 +# +# Input: (let x 2 (mult x 5)) +# Output: 10 +# +# Input: (let x 2 (mult x (let x 3 y 4 (add x y)))) +# Output: 14 +# Explanation: In the expression (add x y), when checking for the value of the variable x, +# we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate. +# Since x = 3 is found first, the value of x is 3. +# +# Input: (let x 3 x 2 x) +# Output: 2 +# Explanation: Assignment in let statements is processed sequentially. +# +# Input: (let x 1 y 2 x (add x y) (add x y)) +# Output: 5 +# Explanation: The first (add x y) evaluates as 3, and is assigned to x. +# The second (add x y) evaluates as 3+2 = 5. +# +# Input: (let x 2 (add (let x 3 (let x 4 x)) x)) +# Output: 6 +# Explanation: Even though (let x 4 x) has a deeper scope, it is outside the context +# of the final x in the add-expression. That final x will equal 2. +# +# Input: (let a1 3 b2 (add a1 1) b2) +# Output 4 +# Explanation: Variable names can contain digits after the first character. +# +# Note: +# - The given string expression is well formatted: +# There are no leading or trailing spaces, +# there is only a single space separating different components of the string, +# and no space between adjacent parentheses. +# The expression is guaranteed to be legal and evaluate to an integer. +# - The length of expression is at most 2000. (It is also non-empty, as that would not be a legal expression.) +# - The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer. + +class Solution(object): + def evaluate(self, expression): + """ + :type expression: str + :rtype: int + """ + def getval(lookup, x): + return lookup.get(x, x) + + def evaluate(tokens, lookup): + if tokens[0] in ('add', 'mult'): + a, b = map(int, map(lambda x: getval(lookup, x), tokens[1:])) + return str(a+b if tokens[0] == 'add' else a*b) + for i in xrange(1, len(tokens)-1, 2): + if tokens[i+1]: + lookup[tokens[i]] = getval(lookup, tokens[i+1]) + return getval(lookup, tokens[-1]) + + tokens, lookup, stk = [''], {}, [] + for c in expression: + if c == '(': + if tokens[0] == 'let': + evaluate(tokens, lookup) + stk.append((tokens, dict(lookup))) + tokens = [''] + elif c == ' ': + tokens.append('') + elif c == ')': + val = evaluate(tokens, lookup) + tokens, lookup = stk.pop() + tokens[-1] += val + else: + tokens[-1] += c + return int(tokens[0]) From b026383b4758f8a14b76eab1b53fdc208bad5a32 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 11:23:21 -0600 Subject: [PATCH 4036/4971] Update parse-lisp-expression.py --- Python/parse-lisp-expression.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/parse-lisp-expression.py b/Python/parse-lisp-expression.py index 6797e8c97..e0ecf7b80 100644 --- a/Python/parse-lisp-expression.py +++ b/Python/parse-lisp-expression.py @@ -1,3 +1,6 @@ +# Time: O(n^2) +# Space: O(n^2) + # You are given a string expression representing a Lisp-like expression to return the integer value of. # # The syntax for these expressions is given as follows. From 791d4b156d7c14b3de69fbdfa22714a6b543fb28 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 11:39:02 -0600 Subject: [PATCH 4037/4971] Update parse-lisp-expression.cpp --- C++/parse-lisp-expression.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/parse-lisp-expression.cpp b/C++/parse-lisp-expression.cpp index 3b490f7e6..543bbc56f 100644 --- a/C++/parse-lisp-expression.cpp +++ b/C++/parse-lisp-expression.cpp @@ -12,7 +12,7 @@ class Solution { if (tokens[0] == "let") { evaluate(tokens, &lookup); } - stk.emplace_back(tokens, lookup); + stk.emplace_back(move(tokens), lookup); tokens = {""}; } else if (c == ' ') { tokens.emplace_back(""); From 86e84f4ff7643146ffd5c274ff40add719bd594c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 11:40:09 -0600 Subject: [PATCH 4038/4971] Update parse-lisp-expression.cpp --- C++/parse-lisp-expression.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/parse-lisp-expression.cpp b/C++/parse-lisp-expression.cpp index 543bbc56f..9fdb3b225 100644 --- a/C++/parse-lisp-expression.cpp +++ b/C++/parse-lisp-expression.cpp @@ -15,7 +15,7 @@ class Solution { stk.emplace_back(move(tokens), lookup); tokens = {""}; } else if (c == ' ') { - tokens.emplace_back(""); + tokens.emplace_back(); } else if (c == ')') { const auto& val = evaluate(tokens, &lookup); tie(tokens, lookup) = move(stk.back()); From e1f90dd3f046ee6ef2ccdf12c0e1036a6a1e92e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 26 Nov 2017 13:32:47 -0600 Subject: [PATCH 4039/4971] Update sentence-similarity-ii.cpp --- C++/sentence-similarity-ii.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/sentence-similarity-ii.cpp b/C++/sentence-similarity-ii.cpp index 34269a064..e556e2e69 100644 --- a/C++/sentence-similarity-ii.cpp +++ b/C++/sentence-similarity-ii.cpp @@ -11,10 +11,10 @@ class Solution { UnionFind union_find(2 * pairs.size()); for (const auto& pair : pairs) { if (!lookup.count(pair.first)) { - lookup[pair.first] = lookup.size() - 1; + lookup.emplace(pair.first, lookup.size()); } if (!lookup.count(pair.second)) { - lookup[pair.second] = lookup.size() - 1; + lookup.emplace(pair.second, lookup.size()); } union_find.union_set(lookup[pair.first], lookup[pair.second]); } From ed7477f3e32a54c77f8134e59a575fa383514690 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 27 Nov 2017 08:41:49 -0600 Subject: [PATCH 4040/4971] Update README.md --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index fba86c18e..9818e572c 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 723 | [Candy Crush](https://leetcode.com/problems/candy-crush/) | [C++](./C++/candy-crush.cpp) [Python](./Python/candy-crush.py) | _O((R * C)^2)_ | _O(1)_ | Medium || 724 | [Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) | [C++](./C++/find-pivot-index.cpp) [Python](./Python/find-pivot-index.py) | _O(n)_ | _O(1)_ | Easy || 729 | [My Calendar I](https://leetcode.com/problems/my-calendar-i/) | [C++](./C++/my-calendar-i.cpp) [Python](./Python/my-calendar-i.py) | _O(nlogn)_ | _O(n)_ | Medium || -731 | [My Calendar II](https://leetcode.com/problems/my-calendar-ii/) | [C++](./C++/my-calendar-ii.cpp) [Python](./Python/my-calendar-ii.py) | _O(n^2)_ | _O(n)_ | Easy || +731 | [My Calendar II](https://leetcode.com/problems/my-calendar-ii/) | [C++](./C++/my-calendar-ii.cpp) [Python](./Python/my-calendar-ii.py) | _O(n^2)_ | _O(n)_ | Medium || +732 | [My Calendar III](https://leetcode.com/problems/my-calendar-iii/) | [C++](./C++/my-calendar-iii.cpp) [Python](./Python/my-calendar-iii.py) | _O(n^2)_ | _O(n)_ | Hard || ## String @@ -224,6 +225,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 636| [Exclusive Time of Functions](https://leetcode.com/problems/exclusive-time-of-functions/) | [C++](./C++/exclusive-time-of-functions.cpp) [Python](./Python/exclusive-time-of-functions.py) | _O(n)_ | _O(n)_ | Medium || 682| [Baseball Game](https://leetcode.com/problems/baseball-game/) | [C++](./C++/baseball-game.cpp) [Python](./Python/baseball-game.py) | _O(n)_ | _O(n)_ | Easy || 726| [Number of Atoms](https://leetcode.com/problems/number-of-atoms/) | [C++](./C++/number-of-atoms.cpp) [Python](./Python/number-of-atoms.py) | _O(n)_ | _O(n)_ | Hard || +735| [Asteroid Collision](https://leetcode.com/problems/asteroid-collision/) | [C++](./C++/asteroid-collision.cpp) [Python](./Python/asteroid-collision.py) | _O(n)_ | _O(n)_ | Medium || +736| [Parse Lisp Expression](https://leetcode.com/problems/parse-lisp-expression/) | [C++](./C++/parse-lisp-expression.cpp) [Python](./Python/parse-lisp-expression.py) | _O(n^2)_ | _O(n^2)_ | Hard || ## Queue | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -313,6 +316,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | 721| [Accounts Merge](https://leetcode.com/problems/accounts-merge/) | [C++](./C++/accounts-merge.cpp) [Python](./Python/accounts-merge.py) | _O(nlogn)_ | _O(n)_| Medium || Union Find +734| [Sentence Similarity](https://leetcode.com/problems/sentence-similarity/) | [C++](./C++/sentence-similarity.cpp) [Python](./Python/sentence-similarity.py) | _O(n + p)_ | _O(p)_| Easy || +737| [Sentence Similarity II](https://leetcode.com/problems/sentence-similarity-ii/) | [C++](./C++/sentence-similarity-ii.cpp) [Python](./Python/sentence-similarity-ii.py) | _O(n + p)_ | _O(p)_| Medium || Union Find ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -525,6 +530,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 694| [Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands/) | [C++](./C++/number-of-distinct-islands.cpp) [Python](./Python/number-of-distinct-islands.py) | _O(m * n)_ | _O(m * n)_ | Medium |📖|| 695| [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [C++](./C++/max-area-of-island.cpp) [Python](./Python/max-area-of-island.py) | _O(m * n)_ | _O(m * n)_ | Easy || 711| [Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii/) | [C++](./C++/number-of-distinct-islands-ii.cpp) [Python](./Python/number-of-distinct-islands-ii.py) | _O((m * n) * log(m * n))_ | _O(m * n)_ | Hard |📖| Hash | +733| [Max Area of Island](https://leetcode.com/problems/flood-fill/) | [C++](./C++/flood-fill.cpp) [Python](./Python/flood-fill.py) | _O(m * n)_ | _O(m * n)_ | Easy || ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 0e4009879e65d733bbf0922835a06e85b83ab3d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Nov 2017 08:21:15 -0600 Subject: [PATCH 4041/4971] Update maximum-distance-in-arrays.py --- Python/maximum-distance-in-arrays.py | 22 +--------------------- 1 file changed, 1 insertion(+), 21 deletions(-) diff --git a/Python/maximum-distance-in-arrays.py b/Python/maximum-distance-in-arrays.py index 4a24c82f4..8f300bca8 100644 --- a/Python/maximum-distance-in-arrays.py +++ b/Python/maximum-distance-in-arrays.py @@ -1,26 +1,6 @@ # Time: O(n) # Space: O(1) -# Given m arrays, and each array is sorted in ascending order. -# Now you can pick up two integers from two different arrays (each array picks one) -# and calculate the distance. -# We define the distance between two integers a and b to be their absolute difference |a-b|. -# Your task is to find the maximum distance. -# -# Example 1: -# Input: -# [[1,2,3], -# [4,5], -# [1,2,3]] -# Output: 4 -# Explanation: -# One way to reach the maximum distance 4 is to pick 1 in the first or third array -# and pick 5 in the second array. -# Note: -# Each given array will have at least 1 number. There will be at least two non-empty arrays. -# The total number of the integers in all the m arrays will be in the range of [2, 10000]. -# The integers in the m arrays will be in the range of [-10000, 10000]. - class Solution(object): def maxDistance(self, arrays): """ @@ -34,4 +14,4 @@ def maxDistance(self, arrays): arrays[i][-1] - min_val)) min_val = min(min_val, arrays[i][0]) max_val = max(max_val, arrays[i][-1]) - return result \ No newline at end of file + return result From 856dc987a3be68235e314e89ad8434aa72ae9846 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Nov 2017 08:27:14 -0600 Subject: [PATCH 4042/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 9818e572c..a0c373309 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| +624 | [Maximum Distance in Arrays](https://leetcode.com/problems/maximum-distance-in-arrays/) | [C++](./C++/mmaximum-distance-in-arrays.cpp) [Python](./Python/maximum-distance-in-arrays.py) | _O(n)_ | _O(1)_ | Easy | 📖 | 643 | [Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/) | [C++](./C++/maximum-average-subarray-i.cpp) [Python](./Python/maximum-average-subarray-i.py) | _O(n)_ | _O(1)_ | Easy || Math 644 | [Maximum Average Subarray II](https://leetcode.com/problems/maximum-average-subarray-ii/) | [C++](./C++/maximum-average-subarray-ii.cpp) [Python](./Python/maximum-average-subarray-ii.py) | _O(n)_ | _O(n)_ | Hard | 📖 | Math 661| [Image Smoother](https://leetcode.com/problems/image-smoother/) | [C++](./C++/image-smoother.cpp) [Python](./Python/image-smoother.py) | _O(m * n)_ | _O(1)_ | Easy ||| @@ -261,6 +262,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 | +623 |[Add One Row to Tree](https://leetcode.com/problems/add-one-row-to-tree/)| [C++](./C++/add-one-row-to-tree.cpp) [Python](./Python/add-one-row-to-tree.py)| _O(n)_ | _O(h)_ | Medium | | | 637 |[Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/)| [C++](./C++/average-of-levels-in-binary-tree.cpp) [Python](./Python/average-of-levels-in-binary-tree.py)| _O(n)_ | _O(h)_ | Easy | | | 652 |[Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/)| [C++](./C++/find-duplicate-subtrees.cpp) [Python](./Python/find-duplicate-subtrees.py)| _O(n)_ | _O(n)_ | Medium | | DFS, Hash | 653 |[Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/)| [C++](./C++/two-sum-iv-input-is-a-bst.cpp) [Python](./Python/two-sum-iv-input-is-a-bst.py)| _O(n)_ | _O(h)_ | Easy | | Two Pointers | @@ -360,6 +362,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +625 | [Minimum Factorization](https://leetcode.com/problems/minimum-factorization/) | [C++](./C++/minimum-factorization.cpp) [Python](./Python/minimum-factorization.py) | _O(loga)_ | _O(1)_ | Medium |📖|| 628| [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [C++](./C++/maximum-product-of-three-numbers.cpp) [Python](./Python/maximum-product-of-three-numbers.py) | _O(n)_ | _O(1)_ | Easy ||| 633| [Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers/) | [C++](./C++/sum-of-square-numbers.cpp) [Python](./Python/sum-of-square-numbers.py) | _O(sqrt(c) * logc)_ | _O(1)_ | Easy ||| 634| [Find the Derangement of An Array](https://leetcode.com/problems/find-the-derangement-of-an-array/) | [C++](./C++/find-the-derangement-of-an-array.cpp) [Python](./Python/find-the-derangement-of-an-array.py) | _O(n)_ | _O(1)_ | Medium |📖|| @@ -650,6 +653,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | 452 | [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(nlogn)_ | _O(1)_ | Medium | | 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/) | [C++](./C++/assign-cookies.cpp) [Python](./Python/assign-cookies.py) | _O(nlogn)_ | _O(1)_ | Easy | | +621 | [Task Scheduler](https://leetcode.com/problems/task-scheduler/) | [C++](./C++/task-scheduler.cpp) [Python](./Python/task-scheduler.py) | _O(n)_ | _O(1)_ | Medium | | 630 | [Course Schedule III](https://leetcode.com/problems/course-schedule-iii/) | [C++](./C++/course-schedule-iii.cpp) [Python](./Python/course-schedule-iii.py) | _O(nlogn)_ | _O(k)_ | Hard || 646 | [Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) | [C++](./C++/maximum-length-of-pair-chain.cpp) [Python](./Python/maximum-length-of-pair-chain.py) | _O(nlogn)_ | _O(1)_ | Medium || Scan Line 649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [C++](./C++/dota2-senate.cpp) [Python](./Python/dota2-senate.py) | _O(n)_ | _O(n)_ | Medium ||| From 24a0ea8e143c2d0a74b47ffa0d8527d1f54f73b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 28 Nov 2017 08:28:29 -0600 Subject: [PATCH 4043/4971] Update minimum-factorization.py --- Python/minimum-factorization.py | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/Python/minimum-factorization.py b/Python/minimum-factorization.py index 505ca357f..52d72293a 100644 --- a/Python/minimum-factorization.py +++ b/Python/minimum-factorization.py @@ -1,24 +1,6 @@ # Time: O(loga) # Space: O(1) -# Given a positive integer a, -# find the smallest positive integer b whose multiplication of each digit equals to a. -# -# If there is no answer or the answer is not fit in 32-bit signed integer, then return 0. -# -# Example 1 -# Input: -# -# 48 -# Output: -# 68 -# Example 2 -# Input: -# -# 15 -# Output: -# 35 - class Solution(object): def smallestFactorization(self, a): """ From f1b8e4b8f0e2ca74d4315d55ad17b7c2be1cb253 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 29 Nov 2017 10:01:46 +0800 Subject: [PATCH 4044/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a0c373309..9ae1ec59e 100644 --- a/README.md +++ b/README.md @@ -676,7 +676,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_ | Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | -631| [Design Log Storage System](https://leetcode.com/problems/design-log-storage-system/) | [C++](./C++/design-log-storage-system.cpp) [Python](./Python/design-log-storage-system.py) | set: _O((r * c)^2)_
get: _O(1)_
sum: _O((r * c)^2)_ | _O(r * c)_ | Hard |📖| | +631| [Design Excel Sum Formula](https://leetcode.com/problems/design-excel-sum-formula/) | [C++](./C++/design-excel-sum-formula.cpp) [Python](./Python/design-excel-sum-formula.py) | set: _O((r * c)^2)_
get: _O(1)_
sum: _O((r * c)^2)_ | _O(r * c)_ | Hard |📖| | 635| [Design Log Storage System](https://leetcode.com/problems/design-log-storage-system/) | [C++](./C++/design-log-storage-system.cpp) [Python](./Python/design-log-storage-system.py) | put: _O(1)_
retrieve: _O(n + dlogd)_ | _O(n)_ | Medium |📖| | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | From a192e2b125b7a167e95c9469ff6c9a68c32c997e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 30 Nov 2017 08:48:35 -0600 Subject: [PATCH 4045/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 9ae1ec59e..c7568e263 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | 556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | 557| [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) |[C++](./C++/reverse-words-in-a-string-iii.cpp) [Python](./Python/reverse-words-in-a-string-iii.py) | _O(n)_ | _O(1)_ | Easy | | +616| [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | [C++](./C++/add-bold-tag-in-string.cpp) [Python](./Python/add-bold-tag-in-string.py) | _O(s * d * l)_ | _O(s)_ | Medium | 📖 | 647| [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) | [C++](./C++/palindromic-substrings.cpp) [Python](./Python/palindromic-substrings.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 648| [Replace Words](https://leetcode.com/problems/replace-words/) | [C++](./C++/replace-words.cpp) [Python](./Python/replace-words.py) | _O(n)_ | _O(t)_ | Medium || Trie | 657| [Judge Route Circle](https://leetcode.com/problems/judge-route-circle/) |[C++](./C++/judge-route-circle.cpp) [Python](./Python/judge-route-circle.py) | _O(n)_ | _O(1)_ | Easy | | @@ -262,6 +263,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 | +617 |[Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)| [C++](./C++/merge-two-binary-trees.cpp) [Python](./Python/merge-two-binary-trees.py)| _O(n)_ | _O(h)_ | Easy | | | 623 |[Add One Row to Tree](https://leetcode.com/problems/add-one-row-to-tree/)| [C++](./C++/add-one-row-to-tree.cpp) [Python](./Python/add-one-row-to-tree.py)| _O(n)_ | _O(h)_ | Medium | | | 637 |[Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/)| [C++](./C++/average-of-levels-in-binary-tree.cpp) [Python](./Python/average-of-levels-in-binary-tree.py)| _O(n)_ | _O(h)_ | Easy | | | 652 |[Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/)| [C++](./C++/find-duplicate-subtrees.cpp) [Python](./Python/find-duplicate-subtrees.py)| _O(n)_ | _O(n)_ | Medium | | DFS, Hash | @@ -317,6 +319,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | +609| [Find Duplicate File in System](https://leetcode.com/problems/find-duplicate-file-in-system/) |[C++](./C++/find-duplicate-file-in-system.cpp) [Python](./Python/find-duplicate-file-in-system.py) | _O(n * l)_ | _O(n * l)_ | Medium | | 721| [Accounts Merge](https://leetcode.com/problems/accounts-merge/) | [C++](./C++/accounts-merge.cpp) [Python](./Python/accounts-merge.py) | _O(nlogn)_ | _O(n)_| Medium || Union Find 734| [Sentence Similarity](https://leetcode.com/problems/sentence-similarity/) | [C++](./C++/sentence-similarity.cpp) [Python](./Python/sentence-similarity.py) | _O(n + p)_ | _O(p)_| Easy || 737| [Sentence Similarity II](https://leetcode.com/problems/sentence-similarity-ii/) | [C++](./C++/sentence-similarity-ii.cpp) [Python](./Python/sentence-similarity-ii.py) | _O(n + p)_ | _O(p)_| Medium || Union Find @@ -412,6 +415,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash, Binary Search 360| [Sort Transformed Array](https://leetcode.com/problems/sort-transformed-array/) | [C++](./C++/sort-transformed-array.cpp) [Python](./Python/sort-transformed-array.py) | _O(n)_ | _O(1)_ | Medium |📖| 457| [Circular Array Loop](https://leetcode.com/problems/circular-array-loop/) | [C++](./C++/circular-array-loop.cpp) [Python](./Python/circular-array-loop.py) | _O(n)_ | _O(1)_ | Medium || +611| [Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/) | [C++](./C++/valid-triangle-number.cpp) [Python](./Python/valid-triangle-number.py) | _O(n^2)_ | _O(1)_ | Medium || ## Recursion | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 1e30da1a5f70fa12e30526ab3e9f604618e3838b Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Dec 2017 08:28:41 -0600 Subject: [PATCH 4046/4971] Update README.md --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c7568e263..e0b288cbd 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| -624 | [Maximum Distance in Arrays](https://leetcode.com/problems/maximum-distance-in-arrays/) | [C++](./C++/mmaximum-distance-in-arrays.cpp) [Python](./Python/maximum-distance-in-arrays.py) | _O(n)_ | _O(1)_ | Easy | 📖 | +605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) | [C++](./C++/can-place-flowers.cpp) [Python](./Python/can-place-flowers.py) | _O(n)_ | _O(1)_ | Easy ||| +624 | [Maximum Distance in Arrays](https://leetcode.com/problems/maximum-distance-in-arrays/) | [C++](./C++/maximum-distance-in-arrays.cpp) [Python](./Python/maximum-distance-in-arrays.py) | _O(n)_ | _O(1)_ | Easy | 📖 | 643 | [Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/) | [C++](./C++/maximum-average-subarray-i.cpp) [Python](./Python/maximum-average-subarray-i.py) | _O(n)_ | _O(1)_ | Easy || Math 644 | [Maximum Average Subarray II](https://leetcode.com/problems/maximum-average-subarray-ii/) | [C++](./C++/maximum-average-subarray-ii.cpp) [Python](./Python/maximum-average-subarray-ii.py) | _O(n)_ | _O(n)_ | Hard | 📖 | Math 661| [Image Smoother](https://leetcode.com/problems/image-smoother/) | [C++](./C++/image-smoother.cpp) [Python](./Python/image-smoother.py) | _O(m * n)_ | _O(1)_ | Easy ||| @@ -263,6 +264,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 | +606 |[Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)| [C++](./C++/construct-string-from-binary-tree.cpp) [Python](./Python/construct-string-from-binary-tree.py)| _O(n)_ | _O(h)_ | Easy | | | 617 |[Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)| [C++](./C++/merge-two-binary-trees.cpp) [Python](./Python/merge-two-binary-trees.py)| _O(n)_ | _O(h)_ | Easy | | | 623 |[Add One Row to Tree](https://leetcode.com/problems/add-one-row-to-tree/)| [C++](./C++/add-one-row-to-tree.cpp) [Python](./Python/add-one-row-to-tree.py)| _O(n)_ | _O(h)_ | Medium | | | 637 |[Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/)| [C++](./C++/average-of-levels-in-binary-tree.cpp) [Python](./Python/average-of-levels-in-binary-tree.py)| _O(n)_ | _O(h)_ | Easy | | | @@ -622,6 +624,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +600 | [Non-negative Integers without Consecutive Onesy](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/) | [C++](./C++/non-negative-integers-without-consecutive-ones.cpp) [Python](./Python/non-negative-integers-without-consecutive-ones.py) | _O(1)_ | _O(1)_ | Hard ||| 629 | [K Inverse Pairs Array](https://leetcode.com/problems/k-inverse-pairs-array/) | [C++](./C++/k-inverse-pairs-array.cpp) [Python](./Python/k-inverse-pairs-array.py) | _O(n * k)_ | _O(k)_ | Hard ||| 639 | [Decode Ways II](https://leetcode.com/problems/decode-ways-ii/) | [C++](./C++/decode-ways-ii.cpp) [Python](./Python/decode-ways-ii.py) | _O(n)_ | _O(1)_ | Hard ||| 650 | [2 Keys Keyboard](https://leetcode.com/problems/2-keys-keyboard/) | [C++](./C++/2-keys-keyboard.cpp) [Python](./Python/2-keys-keyboard.py) | _O(sqrt(n))_ | _O(1)_ | Medium ||| @@ -680,6 +683,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_ | Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | +604| [Design Compressed String Iterator/) | [C++](./C++/design-compressed-string-iterator.cpp) [Python](./Python/design-compressed-string-iterator.py) | _O(1)_ | _O(1)_ | Easy |📖| | 631| [Design Excel Sum Formula](https://leetcode.com/problems/design-excel-sum-formula/) | [C++](./C++/design-excel-sum-formula.cpp) [Python](./Python/design-excel-sum-formula.py) | set: _O((r * c)^2)_
get: _O(1)_
sum: _O((r * c)^2)_ | _O(r * c)_ | Hard |📖| | 635| [Design Log Storage System](https://leetcode.com/problems/design-log-storage-system/) | [C++](./C++/design-log-storage-system.cpp) [Python](./Python/design-log-storage-system.py) | put: _O(1)_
retrieve: _O(n + dlogd)_ | _O(n)_ | Medium |📖| | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | From fcddfd2b647f7d4e96214e0e660a430444c8190a Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 1 Dec 2017 08:30:18 -0600 Subject: [PATCH 4047/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e0b288cbd..11a4594d0 100644 --- a/README.md +++ b/README.md @@ -683,7 +683,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_ | Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | -604| [Design Compressed String Iterator/) | [C++](./C++/design-compressed-string-iterator.cpp) [Python](./Python/design-compressed-string-iterator.py) | _O(1)_ | _O(1)_ | Easy |📖| | +604| [Design Compressed String Iterator](https://leetcode.com/problems/design-compressed-string-iterator/) | [C++](./C++/design-compressed-string-iterator.cpp) [Python](./Python/design-compressed-string-iterator.py) | _O(1)_ | _O(1)_ | Easy |📖| | 631| [Design Excel Sum Formula](https://leetcode.com/problems/design-excel-sum-formula/) | [C++](./C++/design-excel-sum-formula.cpp) [Python](./Python/design-excel-sum-formula.py) | set: _O((r * c)^2)_
get: _O(1)_
sum: _O((r * c)^2)_ | _O(r * c)_ | Hard |📖| | 635| [Design Log Storage System](https://leetcode.com/problems/design-log-storage-system/) | [C++](./C++/design-log-storage-system.cpp) [Python](./Python/design-log-storage-system.py) | put: _O(1)_
retrieve: _O(n + dlogd)_ | _O(n)_ | Medium |📖| | 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | From 061df18833d673dafc08d38c227368ce05dd7349 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 2 Dec 2017 09:20:55 -0600 Subject: [PATCH 4048/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 11a4594d0..f44d0fc4d 100644 --- a/README.md +++ b/README.md @@ -321,6 +321,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | +594| [Longest Harmonious Subsequence](https://leetcode.com/problems/longest-harmonious-subsequence/) |[C++](./C++/longest-harmonious-subsequence.cpp) [Python](./Python/longest-harmonious-subsequence.py) | _O(n)_ | _O(n)_ | Easy | | +599| [Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists/) |[C++](./C++/minimum-index-sum-of-two-lists.cpp) [Python](./Python/minimum-index-sum-of-two-lists.py) | _O((m + n) * l)_ | _O(m * l)_ | Easy | | 609| [Find Duplicate File in System](https://leetcode.com/problems/find-duplicate-file-in-system/) |[C++](./C++/find-duplicate-file-in-system.cpp) [Python](./Python/find-duplicate-file-in-system.py) | _O(n * l)_ | _O(n * l)_ | Medium | | 721| [Accounts Merge](https://leetcode.com/problems/accounts-merge/) | [C++](./C++/accounts-merge.cpp) [Python](./Python/accounts-merge.py) | _O(nlogn)_ | _O(n)_| Medium || Union Find 734| [Sentence Similarity](https://leetcode.com/problems/sentence-similarity/) | [C++](./C++/sentence-similarity.cpp) [Python](./Python/sentence-similarity.py) | _O(n + p)_ | _O(p)_| Easy || @@ -367,6 +369,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +593 | [Valid Square](https://leetcode.com/problems/valid-square/) | [C++](./C++/valid-square.cpp) [Python](./Python/valid-square.py) | _O(1)_ | _O(1)_ | Medium ||| +598 | [Range Addition II](https://leetcode.com/problems/range-addition-ii/) | [C++](./C++/range-addition-ii.cpp) [Python](./Python/range-addition-ii.py) | _O(p)_ | _O(1)_ | Easy ||| 625 | [Minimum Factorization](https://leetcode.com/problems/minimum-factorization/) | [C++](./C++/minimum-factorization.cpp) [Python](./Python/minimum-factorization.py) | _O(loga)_ | _O(1)_ | Medium |📖|| 628| [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers/) | [C++](./C++/maximum-product-of-three-numbers.cpp) [Python](./Python/maximum-product-of-three-numbers.py) | _O(n)_ | _O(1)_ | Easy ||| 633| [Sum of Square Numbers](https://leetcode.com/problems/sum-of-square-numbers/) | [C++](./C++/sum-of-square-numbers.cpp) [Python](./Python/sum-of-square-numbers.py) | _O(sqrt(c) * logc)_ | _O(1)_ | Easy ||| From 45e234af39b1106b87ab0c59d66e1dcb6bf4efcb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 09:12:21 -0600 Subject: [PATCH 4049/4971] Create daily-temperatures.cpp --- C++/daily-temperatures.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/daily-temperatures.cpp diff --git a/C++/daily-temperatures.cpp b/C++/daily-temperatures.cpp new file mode 100644 index 000000000..18a0d1bf6 --- /dev/null +++ b/C++/daily-temperatures.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector dailyTemperatures(vector& temperatures) { + vector result(temperatures.size()); + stack stk; + for (int i = 0; i < temperatures.size(); ++i) { + while (!stk.empty() && + temperatures[stk.top()] < temperatures[i]) { + const auto idx = stk.top(); stk.pop(); + result[idx] = i - idx; + } + stk.emplace(i); + } + return result; + } +}; From 3f9e7bc5b9def5e15b6d61533bbbc18b31e679da Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 09:15:01 -0600 Subject: [PATCH 4050/4971] Create daily-temperatures.py --- Python/daily-temperatures.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Python/daily-temperatures.py diff --git a/Python/daily-temperatures.py b/Python/daily-temperatures.py new file mode 100644 index 000000000..1c6d768ca --- /dev/null +++ b/Python/daily-temperatures.py @@ -0,0 +1,18 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def dailyTemperatures(self, temperatures): + """ + :type temperatures: List[int] + :rtype: List[int] + """ + result = [0] * len(temperatures) + stk = [] + for i in xrange(len(temperatures)): + while stk and \ + temperatures[stk[-1]] < temperatures[i]: + idx = stk.pop() + result[idx] = i-idx + stk.append(i) + return result From 3eb4c3fdfd8532542d7b3f757846c4b2c45f0d15 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 09:28:18 -0600 Subject: [PATCH 4051/4971] Create monotone-increasing-digits.cpp --- C++/monotone-increasing-digits.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/monotone-increasing-digits.cpp diff --git a/C++/monotone-increasing-digits.cpp b/C++/monotone-increasing-digits.cpp new file mode 100644 index 000000000..b9cf59927 --- /dev/null +++ b/C++/monotone-increasing-digits.cpp @@ -0,0 +1,20 @@ +// Time: O(logn) = O(1) +// Space: O(logn) = O(1) + +class Solution { +public: + int monotoneIncreasingDigits(int N) { + string s = to_string(N); + int leftmost_inverted_idx = s.length(); + for (int i = s.length() - 1; i > 0; --i) { + if (s[i - 1] > s[i]) { + leftmost_inverted_idx = i; + --s[i - 1]; + } + } + for (int i = leftmost_inverted_idx; i < s.length(); ++i) { + s[i] = '9'; + } + return stoi(s); + } +}; From 7dbc167b006eadd9b9ab033304b8141a78161f23 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 09:34:14 -0600 Subject: [PATCH 4052/4971] Create monotone-increasing-digits.py --- Python/monotone-increasing-digits.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Python/monotone-increasing-digits.py diff --git a/Python/monotone-increasing-digits.py b/Python/monotone-increasing-digits.py new file mode 100644 index 000000000..818c6e1d8 --- /dev/null +++ b/Python/monotone-increasing-digits.py @@ -0,0 +1,18 @@ +# Time: O(logn) = O(1) +# Space: O(logn) = O(1) + +class Solution(object): + def monotoneIncreasingDigits(self, N): + """ + :type N: int + :rtype: int + """ + nums = map(int, list(str(N))) + leftmost_inverted_idx = len(nums) + for i in reversed(xrange(1, len(nums))): + if nums[i-1] > nums[i]: + leftmost_inverted_idx = i + nums[i-1] -= 1 + for i in xrange(leftmost_inverted_idx, len(nums)): + nums[i] = 9 + return int("".join(map(str, nums))) From 31da05c456f43a0414aa45e4a533e2a3c8ff08fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 09:49:40 -0600 Subject: [PATCH 4053/4971] Create delete-and-earn.cpp --- C++/delete-and-earn.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/delete-and-earn.cpp diff --git a/C++/delete-and-earn.cpp b/C++/delete-and-earn.cpp new file mode 100644 index 000000000..322e4441f --- /dev/null +++ b/C++/delete-and-earn.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int deleteAndEarn(vector& nums) { + vector values(10001); + for (const auto& num : nums) { + values[num] += num; + } + int val_i = values[0], val_i_1 = 0, val_i_2 = 0; + for (int i = 1; i < values.size(); ++i) { + val_i_2 = val_i_1; + val_i_1 = val_i; + val_i = max(values[i] + val_i_2, val_i_1); + } + return val_i; + } +}; From 5789108a4951fa2b6fe65824eb835630def0acaf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 09:52:34 -0600 Subject: [PATCH 4054/4971] Update delete-and-earn.cpp --- C++/delete-and-earn.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/delete-and-earn.cpp b/C++/delete-and-earn.cpp index 322e4441f..d4e2b2505 100644 --- a/C++/delete-and-earn.cpp +++ b/C++/delete-and-earn.cpp @@ -4,15 +4,15 @@ class Solution { public: int deleteAndEarn(vector& nums) { - vector values(10001); + vector vals(10001); for (const auto& num : nums) { - values[num] += num; + vals[num] += num; } - int val_i = values[0], val_i_1 = 0, val_i_2 = 0; - for (int i = 1; i < values.size(); ++i) { + int val_i = vals[0], val_i_1 = 0, val_i_2 = 0; + for (int i = 1; i < vals.size(); ++i) { val_i_2 = val_i_1; val_i_1 = val_i; - val_i = max(values[i] + val_i_2, val_i_1); + val_i = max(vals[i] + val_i_2, val_i_1); } return val_i; } From 77b02040aab30b0551ae5471dc4622137aced5be Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 09:53:02 -0600 Subject: [PATCH 4055/4971] Create delete-and-earn.py --- Python/delete-and-earn.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/delete-and-earn.py diff --git a/Python/delete-and-earn.py b/Python/delete-and-earn.py new file mode 100644 index 000000000..1518c569f --- /dev/null +++ b/Python/delete-and-earn.py @@ -0,0 +1,17 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def deleteAndEarn(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + vals = [0] * 10001 + for num in nums: + vals[num] += num + val_i, val_i_1 = vals[0], 0 + for i in xrange(1, len(vals)): + val_i_1, val_i_2 = val_i, val_i_1 + val_i = max(vals[i] + val_i_2, val_i_1) + return val_i From 7c098a477f446ffbcd31077db614ffe0f38e413f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 11:08:10 -0600 Subject: [PATCH 4056/4971] Create cherry-pickup.cpp --- C++/cherry-pickup.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 C++/cherry-pickup.cpp diff --git a/C++/cherry-pickup.cpp b/C++/cherry-pickup.cpp new file mode 100644 index 000000000..a33444ed1 --- /dev/null +++ b/C++/cherry-pickup.cpp @@ -0,0 +1,43 @@ +// Time: O(n^3) +// Space: O(n^2) + +class Solution { +public: + int cherryPickup(vector>& grid) { + // dp holds the max # of cherries two k-length paths can pickup. + // The two k-length paths arrive at (i, k - i) and (j, k - j), + // respectively. + const int n = grid.size(); + vector> dp(n, vector(n, -1)); + dp[0][0] = grid[0][0]; + + const int max_len = 2 * (n - 1); + for (int k = 1; k <= max_len; ++k) { + for (int i = min(k + 1, n) - 1; i >= 0; --i) { + for (int j = min(k + 1, n) - 1; j >= i; --j) { + if (k - i < 0 || k - i >= n || + k - j < 0 || k - j >= n) { + continue; + } + if (grid[i][k - i] == -1 || + grid[j][k - j] == -1) { + dp[i][j] = -1; + continue; + } + int cnt = grid[i][k - i] + ((i == j) ? 0 : grid[j][k - j]); + int max_cnt = -1; + static const vector> directions{{0, 0}, {-1, 0}, {0, -1}, {-1, -1}}; + for (const auto& direction : directions) { + const auto ii = i + direction.first; + const auto jj = j + direction.second; + if (ii >= 0 && jj >= 0 && dp[ii][jj] >= 0) { + max_cnt = max(max_cnt, dp[ii][jj] + cnt); + } + } + dp[i][j] = max_cnt; + } + } + } + return max(dp[n - 1][n - 1], 0); + } +}; From f6c88c8e266d1e3bbb9cb778c89b2cd7ca0a64b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 11:23:00 -0600 Subject: [PATCH 4057/4971] Create cherry-pickup.py --- Python/cherry-pickup.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/cherry-pickup.py diff --git a/Python/cherry-pickup.py b/Python/cherry-pickup.py new file mode 100644 index 000000000..e9e359920 --- /dev/null +++ b/Python/cherry-pickup.py @@ -0,0 +1,35 @@ +# Time: O(n^3) +# Space: O(n^2) + +class Solution(object): + def cherryPickup(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + # dp holds the max # of cherries two k-length paths can pickup. + # The two k-length paths arrive at (i, k - i) and (j, k - j), + # respectively. + n = len(grid); + dp = [[-1 for _ in xrange(n)] for _ in xrange(n)] + dp[0][0] = grid[0][0] + max_len = 2 * (n-1) + directions = [(0, 0), (-1, 0), (0, -1), (-1, -1)] + for k in xrange(1, max_len+1): + for i in reversed(xrange(min(k+1, n))): + for j in reversed(xrange(i, min(k+1, n))): + if not (0 <= k-i < n and 0 <= k-j < n): + continue + if grid[i][k-i] == -1 or grid[j][k-j] == -1: + dp[i][j] = -1 + continue + cnt = grid[i][k-i] + if i != j: + cnt += grid[j][k-j] + max_cnt = -1 + for direction in directions: + ii, jj = i+direction[0], j+direction[1] + if ii >= 0 and jj >= 0 and dp[ii][jj] >= 0: + max_cnt = max(max_cnt, dp[ii][jj]+cnt) + dp[i][j] = max_cnt + return max(dp[n-1][n-1], 0) From 80affc709b9dd676f82f9cc4d9167aa083653807 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 11:25:27 -0600 Subject: [PATCH 4058/4971] Update cherry-pickup.py --- Python/cherry-pickup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/cherry-pickup.py b/Python/cherry-pickup.py index e9e359920..e5924b724 100644 --- a/Python/cherry-pickup.py +++ b/Python/cherry-pickup.py @@ -10,7 +10,7 @@ def cherryPickup(self, grid): # dp holds the max # of cherries two k-length paths can pickup. # The two k-length paths arrive at (i, k - i) and (j, k - j), # respectively. - n = len(grid); + n = len(grid) dp = [[-1 for _ in xrange(n)] for _ in xrange(n)] dp[0][0] = grid[0][0] max_len = 2 * (n-1) From 8c65226b79ad0f7ac3487a117298498cff4b23be Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 11:40:41 -0600 Subject: [PATCH 4059/4971] Update cherry-pickup.py --- Python/cherry-pickup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/cherry-pickup.py b/Python/cherry-pickup.py index e5924b724..31d1c6a4b 100644 --- a/Python/cherry-pickup.py +++ b/Python/cherry-pickup.py @@ -16,7 +16,7 @@ def cherryPickup(self, grid): max_len = 2 * (n-1) directions = [(0, 0), (-1, 0), (0, -1), (-1, -1)] for k in xrange(1, max_len+1): - for i in reversed(xrange(min(k+1, n))): + for i in reversed(xrange(max(0, k-n-1), min(k+1, n))): for j in reversed(xrange(i, min(k+1, n))): if not (0 <= k-i < n and 0 <= k-j < n): continue From a81c8b046190bcbf659a6263e7f7075ceefdaf85 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 11:42:43 -0600 Subject: [PATCH 4060/4971] Update cherry-pickup.cpp --- C++/cherry-pickup.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/cherry-pickup.cpp b/C++/cherry-pickup.cpp index a33444ed1..815270c99 100644 --- a/C++/cherry-pickup.cpp +++ b/C++/cherry-pickup.cpp @@ -13,7 +13,7 @@ class Solution { const int max_len = 2 * (n - 1); for (int k = 1; k <= max_len; ++k) { - for (int i = min(k + 1, n) - 1; i >= 0; --i) { + for (int i = min(k + 1, n) - 1; i >= max(0, k - n - 1); --i) { for (int j = min(k + 1, n) - 1; j >= i; --j) { if (k - i < 0 || k - i >= n || k - j < 0 || k - j >= n) { From fbbd769c0c4ee461f6102581bbfd2ef220ee676b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 12:01:31 -0600 Subject: [PATCH 4061/4971] Update cherry-pickup.cpp --- C++/cherry-pickup.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/cherry-pickup.cpp b/C++/cherry-pickup.cpp index 815270c99..985dbe482 100644 --- a/C++/cherry-pickup.cpp +++ b/C++/cherry-pickup.cpp @@ -13,8 +13,8 @@ class Solution { const int max_len = 2 * (n - 1); for (int k = 1; k <= max_len; ++k) { - for (int i = min(k + 1, n) - 1; i >= max(0, k - n - 1); --i) { - for (int j = min(k + 1, n) - 1; j >= i; --j) { + for (int i = min(k, n - 1); i >= max(0, k - n - 1); --i) { + for (int j = min(k , n - 1); j >= i; --j) { if (k - i < 0 || k - i >= n || k - j < 0 || k - j >= n) { continue; From 3f321f7ffb29af5e661e5e5f7f91191b2f16de9f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 12:03:01 -0600 Subject: [PATCH 4062/4971] Update cherry-pickup.cpp --- C++/cherry-pickup.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/C++/cherry-pickup.cpp b/C++/cherry-pickup.cpp index 985dbe482..7b466df7a 100644 --- a/C++/cherry-pickup.cpp +++ b/C++/cherry-pickup.cpp @@ -15,10 +15,6 @@ class Solution { for (int k = 1; k <= max_len; ++k) { for (int i = min(k, n - 1); i >= max(0, k - n - 1); --i) { for (int j = min(k , n - 1); j >= i; --j) { - if (k - i < 0 || k - i >= n || - k - j < 0 || k - j >= n) { - continue; - } if (grid[i][k - i] == -1 || grid[j][k - j] == -1) { dp[i][j] = -1; From 1131b09b18039ffefcc48c682925e8945de027fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 12:16:13 -0600 Subject: [PATCH 4063/4971] Update cherry-pickup.py --- Python/cherry-pickup.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Python/cherry-pickup.py b/Python/cherry-pickup.py index 31d1c6a4b..e10573071 100644 --- a/Python/cherry-pickup.py +++ b/Python/cherry-pickup.py @@ -16,10 +16,8 @@ def cherryPickup(self, grid): max_len = 2 * (n-1) directions = [(0, 0), (-1, 0), (0, -1), (-1, -1)] for k in xrange(1, max_len+1): - for i in reversed(xrange(max(0, k-n-1), min(k+1, n))): - for j in reversed(xrange(i, min(k+1, n))): - if not (0 <= k-i < n and 0 <= k-j < n): - continue + for i in reversed(xrange(max(0, k-n+1), min(k+1, n))): # 0 <= i < n, 0 <= k-i < n + for j in reversed(xrange(i, min(k+1, n))): # i <= j < n, 0 <= k-j < n if grid[i][k-i] == -1 or grid[j][k-j] == -1: dp[i][j] = -1 continue From 5cad2d9e031b36ee235a55b4abd8c0a4bc834744 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Dec 2017 12:18:20 -0600 Subject: [PATCH 4064/4971] Update cherry-pickup.cpp --- C++/cherry-pickup.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/cherry-pickup.cpp b/C++/cherry-pickup.cpp index 7b466df7a..5c44956c3 100644 --- a/C++/cherry-pickup.cpp +++ b/C++/cherry-pickup.cpp @@ -13,8 +13,8 @@ class Solution { const int max_len = 2 * (n - 1); for (int k = 1; k <= max_len; ++k) { - for (int i = min(k, n - 1); i >= max(0, k - n - 1); --i) { - for (int j = min(k , n - 1); j >= i; --j) { + for (int i = min(k, n - 1); i >= max(0, k - n + 1); --i) { // 0 <= i < n, 0 <= k-i < n + for (int j = min(k , n - 1); j >= i; --j) { // i <= j < n, 0 <= k-j < n if (grid[i][k - i] == -1 || grid[j][k - j] == -1) { dp[i][j] = -1; From 19b2511a15e69c3eb08c6179a9d16726b09946e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Dec 2017 09:23:24 -0600 Subject: [PATCH 4065/4971] Update monotone-increasing-digits.py --- Python/monotone-increasing-digits.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Python/monotone-increasing-digits.py b/Python/monotone-increasing-digits.py index 818c6e1d8..111fb299c 100644 --- a/Python/monotone-increasing-digits.py +++ b/Python/monotone-increasing-digits.py @@ -1,6 +1,26 @@ # Time: O(logn) = O(1) # Space: O(logn) = O(1) +# Given a non-negative integer N, +# find the largest number that is less than or equal to N with monotone increasing digits. +# +# (Recall that an integer has monotone increasing digits if and only +# if each pair of adjacent digits x and y satisfy x <= y.) +# +# Example 1: +# Input: N = 10 +# Output: 9 +# +# Example 2: +# Input: N = 1234 +# Output: 1234 +# +# Example 3: +# Input: N = 332 +# Output: 299 +# +# Note: N is an integer in the range [0, 10^9]. + class Solution(object): def monotoneIncreasingDigits(self, N): """ From 2474ef60d9faf961bfb1487991b7555e72e2505d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Dec 2017 09:24:42 -0600 Subject: [PATCH 4066/4971] Update daily-temperatures.py --- Python/daily-temperatures.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Python/daily-temperatures.py b/Python/daily-temperatures.py index 1c6d768ca..841982d81 100644 --- a/Python/daily-temperatures.py +++ b/Python/daily-temperatures.py @@ -1,6 +1,16 @@ # Time: O(n) # Space: O(n) +# Given a list of daily temperatures, produce a list that, +# for each day in the input, tells you how many days you would have to wait until +# a warmer temperature. If there is no future day for which this is possible, put 0 instead. +# +# For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], +# your output should be [1, 1, 4, 2, 1, 1, 0, 0]. +# +# Note: The length of temperatures will be in the range [1, 30000]. +# Each temperature will be an integer in the range [30, 100]. + class Solution(object): def dailyTemperatures(self, temperatures): """ From 70cc1c97416179929deec9e530ba9a6100a73a5a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Dec 2017 09:26:28 -0600 Subject: [PATCH 4067/4971] Update delete-and-earn.py --- Python/delete-and-earn.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/Python/delete-and-earn.py b/Python/delete-and-earn.py index 1518c569f..4327d0d2b 100644 --- a/Python/delete-and-earn.py +++ b/Python/delete-and-earn.py @@ -1,6 +1,33 @@ # Time: O(n) # Space: O(1) +# Given an array nums of integers, you can perform operations on the array. +# +# In each operation, you pick any nums[i] and delete it to earn nums[i] points. +# After, you must delete every element equal to nums[i] - 1 or nums[i] + 1. +# +# You start with 0 points. +# Return the maximum number of points you can earn by applying such operations. +# +# Example 1: +# Input: nums = [3, 4, 2] +# Output: 6 +# Explanation: +# Delete 4 to earn 4 points, consequently 3 is also deleted. +# Then, delete 2 to earn 2 points. 6 total points are earned. +# +# Example 2: +# Input: nums = [2, 2, 3, 3, 3, 4] +# Output: 9 +# Explanation: +# Delete 3 to earn 3 points, deleting both 2's and the 4. +# Then, delete 3 again to earn 3 points, and 3 again to earn 3 points. +# 9 total points are earned. +# +# Note: +# - The length of nums is at most 20000. +# - Each element nums[i] is an integer in the range [1, 10000]. + class Solution(object): def deleteAndEarn(self, nums): """ From ab67fffae224f6d09babc5e3685570e7734152e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Dec 2017 09:28:16 -0600 Subject: [PATCH 4068/4971] Update cherry-pickup.py --- Python/cherry-pickup.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Python/cherry-pickup.py b/Python/cherry-pickup.py index e10573071..4764f990d 100644 --- a/Python/cherry-pickup.py +++ b/Python/cherry-pickup.py @@ -1,6 +1,36 @@ # Time: O(n^3) # Space: O(n^2) +# In a N x N grid representing a field of cherries, each cell is one of three possible integers. +# +# 0 means the cell is empty, so you can pass through; +# 1 means the cell contains a cherry, that you can pick up and pass through; +# -1 means the cell contains a thorn that blocks your way. +# Your task is to collect maximum number of cherries possible by following the rules below: +# +# Starting at the position (0, 0) and reaching (N-1, N-1) by moving right +# or down through valid path cells (cells with value 0 or 1); +# +# After reaching (N-1, N-1), returning to (0, 0) by moving left or up through valid path cells; +# When passing through a path cell containing a cherry, you pick it up and the cell becomes an empty cell (0); +# If there is no valid path between (0, 0) and (N-1, N-1), then no cherries can be collected. +# Example 1: +# Input: grid = +# [[0, 1, -1], +# [1, 0, -1], +# [1, 1, 1]] +# Output: 5 +# Explanation: +# The player started at (0, 0) and went down, down, right right to reach (2, 2). +# 4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]]. +# Then, the player went left, up, up, left to return home, picking up one more cherry. +# The total number of cherries picked up is 5, and this is the maximum possible. +# +# Note: +# - grid is an N by N 2D array, with 1 <= N <= 50. +# - Each grid[i][j] is an integer in the set {-1, 0, 1}. +# - It is guaranteed that grid[0][0] and grid[N-1][N-1] are not -1. + class Solution(object): def cherryPickup(self, grid): """ From f424338b096d383c332747d6e30a27f1d4452add Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Dec 2017 09:37:39 -0600 Subject: [PATCH 4069/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index f44d0fc4d..d2dbaf3bc 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 726| [Number of Atoms](https://leetcode.com/problems/number-of-atoms/) | [C++](./C++/number-of-atoms.cpp) [Python](./Python/number-of-atoms.py) | _O(n)_ | _O(n)_ | Hard || 735| [Asteroid Collision](https://leetcode.com/problems/asteroid-collision/) | [C++](./C++/asteroid-collision.cpp) [Python](./Python/asteroid-collision.py) | _O(n)_ | _O(n)_ | Medium || 736| [Parse Lisp Expression](https://leetcode.com/problems/parse-lisp-expression/) | [C++](./C++/parse-lisp-expression.cpp) [Python](./Python/parse-lisp-expression.py) | _O(n^2)_ | _O(n^2)_ | Hard || +739| [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) | [C++](./C++/daily-temperatures.cpp) [Python](./Python/daily-temperatures.py) | _O(n)_ | _O(n)_ | Medium || ## Queue | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -642,6 +643,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 714 | [Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/) | [C++](./C++/best-time-to-buy-and-sell-stock-with-transaction-fee.cpp) [Python](./Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py) | _O(n)_ | _O(1)_ | Medium || 727 | [Minimum Window Subsequence](https://leetcode.com/problems/minimum-window-subsequence/) | [C++](./C++/minimum-window-subsequence.cpp) [Python](./Python/minimum-window-subsequence.py) | _O(s * t)_ | _O(s)_ | Hard |📖| 730 | [Count Different Palindromic Subsequences](https://leetcode.com/problems/count-different-palindromic-subsequences/) | [C++](./C++/count-different-palindromic-subsequences.cpp) [Python](./Python/count-different-palindromic-subsequences.py) | _O(n^2)_ | _O(n)_ | Hard || +740 | [Delete and Earn](https://leetcode.com/problems/delete-and-earn/) | [C++](./C++/delete-and-earn.cpp) [Python](./Python/delete-and-earn.py) | _O(n)_ | _O(1)_ | Medium || +741 | [Cherry Pickup](https://leetcode.com/problems/cherry-pickup/) | [C++](./C++/cherry-pickup.cpp) [Python](./Python/cherry-pickup.py) | _O(n^3)_ | _O(n^2)_ | Hard || ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -669,6 +672,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 646 | [Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) | [C++](./C++/maximum-length-of-pair-chain.cpp) [Python](./Python/maximum-length-of-pair-chain.py) | _O(nlogn)_ | _O(1)_ | Medium || Scan Line 649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [C++](./C++/dota2-senate.cpp) [Python](./Python/dota2-senate.py) | _O(n)_ | _O(n)_ | Medium ||| 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | +738 | [Monotone Increasing Digits](https://leetcode.com/problems/monotone-increasing-digits/) | [C++](./C++/monotone-increasing-digits.cpp) [Python](./Python/monotone-increasing-digits.py) | _O(1)_ | _O(1)_ | Medium | | --- ## Design From a3ef2e26abe8879563dc1b45ba82e4bb2b0dc5d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Dec 2017 09:09:27 -0600 Subject: [PATCH 4070/4971] Update erect-the-fence.py --- Python/erect-the-fence.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/erect-the-fence.py b/Python/erect-the-fence.py index dc8e84964..c1ffe423d 100644 --- a/Python/erect-the-fence.py +++ b/Python/erect-the-fence.py @@ -23,7 +23,7 @@ # All input integers will range from 0 to 100. # The garden has at least one tree. # All coordinates are distinct. -#Input points have NO order. No order required for output. +# Input points have NO order. No order required for output. # Definition for a point. # class Point(object): @@ -31,6 +31,7 @@ # self.x = a # self.y = b +# Monotone Chain Algorithm class Solution(object): def outerTrees(self, points): """ From 549da53d25ea7b83ed48c78b45f709a51fedcc50 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Dec 2017 09:20:13 -0600 Subject: [PATCH 4071/4971] Update README.md --- README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d2dbaf3bc..8c72017aa 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates * [Backtracking](https://github.com/kamyu104/LeetCode#backtracking) * [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) * [Greedy](https://github.com/kamyu104/LeetCode#greedy) +* [Geometry](https://github.com/kamyu104/LeetCode#geometry) * [Design](https://github.com/kamyu104/LeetCode#design) @@ -167,6 +168,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | 556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | 557| [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) |[C++](./C++/reverse-words-in-a-string-iii.cpp) [Python](./Python/reverse-words-in-a-string-iii.py) | _O(n)_ | _O(1)_ | Easy | | +591| [Tag Validator](https://leetcode.com/problems/tag-validator/) |[C++](./C++/tag-validator.cpp) [Python](./Python/tag-validator.py) | _O(n)_ | _O(n)_ | Hard | | 616| [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | [C++](./C++/add-bold-tag-in-string.cpp) [Python](./Python/add-bold-tag-in-string.py) | _O(s * d * l)_ | _O(s)_ | Medium | 📖 | 647| [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) | [C++](./C++/palindromic-substrings.cpp) [Python](./Python/palindromic-substrings.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 648| [Replace Words](https://leetcode.com/problems/replace-words/) | [C++](./C++/replace-words.cpp) [Python](./Python/replace-words.py) | _O(n)_ | _O(t)_ | Medium || Trie | @@ -370,6 +372,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +592 | [Fraction Addition and Subtraction](https://leetcode.com/problems/fraction-addition-and-subtraction/) | [C++](./C++/fraction-addition-and-subtraction.cpp) [Python](./Python/fraction-addition-and-subtraction.py) | _O(nlogx)_ | _O(n)_ | Medium ||| 593 | [Valid Square](https://leetcode.com/problems/valid-square/) | [C++](./C++/valid-square.cpp) [Python](./Python/valid-square.py) | _O(1)_ | _O(1)_ | Medium ||| 598 | [Range Addition II](https://leetcode.com/problems/range-addition-ii/) | [C++](./C++/range-addition-ii.cpp) [Python](./Python/range-addition-ii.py) | _O(p)_ | _O(1)_ | Easy ||| 625 | [Minimum Factorization](https://leetcode.com/problems/minimum-factorization/) | [C++](./C++/minimum-factorization.cpp) [Python](./Python/minimum-factorization.py) | _O(loga)_ | _O(1)_ | Medium |📖|| @@ -674,7 +677,11 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | 738 | [Monotone Increasing Digits](https://leetcode.com/problems/monotone-increasing-digits/) | [C++](./C++/monotone-increasing-digits.cpp) [Python](./Python/monotone-increasing-digits.py) | _O(1)_ | _O(1)_ | Medium | | ---- +## Geometry +| # | Title | Solution | Time | Space | Difficulty | Tag | Note| +|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| +587 | [Erect the Fence](https://leetcode.com/problems/erect-the-fence/) | [C++](./C++/erect-the-fence.cpp) [Python](./Python/erect-the-fence.py) | _O(nlogn)_| _O(n)_| Hard || `Monotone Chain` | + ## Design | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| @@ -691,6 +698,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_ | Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | +588| [Design In-Memory File System](https://leetcode.com/problems/design-in-memory-file-system/) | [C++](./C++/design-in-memory-file-system.cpp) [Python](./Python/design-in-memory-file-system.py) | ls: _O(l + klogk)_
mkdir: _O(l)_
addContentToFile: _O(l + c)_
readContentFromFile: _O(l + c)_ | _O(n + s)_ | Hard |📖| | 604| [Design Compressed String Iterator](https://leetcode.com/problems/design-compressed-string-iterator/) | [C++](./C++/design-compressed-string-iterator.cpp) [Python](./Python/design-compressed-string-iterator.py) | _O(1)_ | _O(1)_ | Easy |📖| | 631| [Design Excel Sum Formula](https://leetcode.com/problems/design-excel-sum-formula/) | [C++](./C++/design-excel-sum-formula.cpp) [Python](./Python/design-excel-sum-formula.py) | set: _O((r * c)^2)_
get: _O(1)_
sum: _O((r * c)^2)_ | _O(r * c)_ | Hard |📖| | 635| [Design Log Storage System](https://leetcode.com/problems/design-log-storage-system/) | [C++](./C++/design-log-storage-system.cpp) [Python](./Python/design-log-storage-system.py) | put: _O(1)_
retrieve: _O(n + dlogd)_ | _O(n)_ | Medium |📖| | @@ -698,7 +706,6 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | 716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | - ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| From cbfe1e75c999077c04c344e85fce9ea911d03027 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 5 Dec 2017 09:22:28 -0600 Subject: [PATCH 4072/4971] Update erect-the-fence.cpp --- C++/erect-the-fence.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/C++/erect-the-fence.cpp b/C++/erect-the-fence.cpp index 409b5eee2..e3dd4133a 100644 --- a/C++/erect-the-fence.cpp +++ b/C++/erect-the-fence.cpp @@ -10,6 +10,8 @@ * Point(int a, int b) : x(a), y(b) {} * }; */ + +// Monotone Chain Algorithm class Solution { public: vector outerTrees(vector& points) { From 81a0ee21d8d36dacc64f6513a2de8a8abffe2380 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Dec 2017 09:52:57 -0600 Subject: [PATCH 4073/4971] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8c72017aa..b8cf06130 100644 --- a/README.md +++ b/README.md @@ -632,7 +632,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || -600 | [Non-negative Integers without Consecutive Onesy](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/) | [C++](./C++/non-negative-integers-without-consecutive-ones.cpp) [Python](./Python/non-negative-integers-without-consecutive-ones.py) | _O(1)_ | _O(1)_ | Hard ||| +583 | [Delete Operation for Two Strings](https://leetcode.com/problems/delete-operation-for-two-strings/) | [C++](./C++/delete-operation-for-two-strings.cpp) [Python](./Python/delete-operation-for-two-strings.py) | _O(m * n)_ | _O(n)_ | Medium ||| +600 | [Non-negative Integers without Consecutive Ones](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/) | [C++](./C++/non-negative-integers-without-consecutive-ones.cpp) [Python](./Python/non-negative-integers-without-consecutive-ones.py) | _O(1)_ | _O(1)_ | Hard ||| 629 | [K Inverse Pairs Array](https://leetcode.com/problems/k-inverse-pairs-array/) | [C++](./C++/k-inverse-pairs-array.cpp) [Python](./Python/k-inverse-pairs-array.py) | _O(n * k)_ | _O(k)_ | Hard ||| 639 | [Decode Ways II](https://leetcode.com/problems/decode-ways-ii/) | [C++](./C++/decode-ways-ii.cpp) [Python](./Python/decode-ways-ii.py) | _O(n)_ | _O(1)_ | Hard ||| 650 | [2 Keys Keyboard](https://leetcode.com/problems/2-keys-keyboard/) | [C++](./C++/2-keys-keyboard.cpp) [Python](./Python/2-keys-keyboard.py) | _O(sqrt(n))_ | _O(1)_ | Medium ||| From 569e4467b8383222a16b219cd1ddd8645c6b931c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Dec 2017 09:59:53 -0600 Subject: [PATCH 4074/4971] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index b8cf06130..1ff8f8098 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| +581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray/) | [C++](./C++/shortest-unsorted-continuous-subarray.cpp) [Python](./Python/shortest-unsorted-continuous-subarray.py) | _O(n)_ | _O(1)_ | Easy ||| 605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) | [C++](./C++/can-place-flowers.cpp) [Python](./Python/can-place-flowers.py) | _O(n)_ | _O(1)_ | Easy ||| 624 | [Maximum Distance in Arrays](https://leetcode.com/problems/maximum-distance-in-arrays/) | [C++](./C++/maximum-distance-in-arrays.cpp) [Python](./Python/maximum-distance-in-arrays.py) | _O(n)_ | _O(1)_ | Easy | 📖 | 643 | [Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/) | [C++](./C++/maximum-average-subarray-i.cpp) [Python](./Python/maximum-average-subarray-i.py) | _O(n)_ | _O(1)_ | Easy || Math @@ -542,6 +543,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || 440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn)_ | _O(logn)_ | Hard || 464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || +582| [Kill Process](https://leetcode.com/problems/kill-process/) | [C++](./C++/kill-process.cpp) [Python](./Python/kill-process.py) | _O(n)_ | _O(n)_ | Medium |📖| DFS, BFS | 638| [Shopping Offers](https://leetcode.com/problems/shopping-offers/) | [C++](./C++/shopping-offers.cpp) [Python](./Python/shopping-offers.py) | _O(n * 2^n)_ | _O(n)_ | Medium || 690| [Employee Importance](https://leetcode.com/problems/employee-importance/) | [C++](./C++/employee-importance.cpp) [Python](./Python/employee-importance.py) | _O(n)_ | _O(h)_ | Easy || DFS, BFS 694| [Number of Distinct Islands](https://leetcode.com/problems/number-of-distinct-islands/) | [C++](./C++/number-of-distinct-islands.cpp) [Python](./Python/number-of-distinct-islands.py) | _O(m * n)_ | _O(m * n)_ | Medium |📖|| @@ -632,6 +634,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +576 | [Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths/) | [C++](./C++/out-of-boundary-paths.cpp) [Python](./Python/out-of-boundary-paths.py) | _O(N * m * n)_ | _O(m * n)_ | Medium ||| 583 | [Delete Operation for Two Strings](https://leetcode.com/problems/delete-operation-for-two-strings/) | [C++](./C++/delete-operation-for-two-strings.cpp) [Python](./Python/delete-operation-for-two-strings.py) | _O(m * n)_ | _O(n)_ | Medium ||| 600 | [Non-negative Integers without Consecutive Ones](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/) | [C++](./C++/non-negative-integers-without-consecutive-ones.cpp) [Python](./Python/non-negative-integers-without-consecutive-ones.py) | _O(1)_ | _O(1)_ | Hard ||| 629 | [K Inverse Pairs Array](https://leetcode.com/problems/k-inverse-pairs-array/) | [C++](./C++/k-inverse-pairs-array.cpp) [Python](./Python/k-inverse-pairs-array.py) | _O(n * k)_ | _O(k)_ | Hard ||| From 414e70bc0181207d49877abc025fb62d03b93b85 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 6 Dec 2017 10:00:15 -0600 Subject: [PATCH 4075/4971] Update kill-process.py --- Python/kill-process.py | 34 ---------------------------------- 1 file changed, 34 deletions(-) diff --git a/Python/kill-process.py b/Python/kill-process.py index daedeab3a..88b0e0867 100644 --- a/Python/kill-process.py +++ b/Python/kill-process.py @@ -1,40 +1,6 @@ # Time: O(n) # Space: O(n) -# Given n processes, each process has a unique PID (process id) -# and its PPID (parent process id). -# -# Each process only has one parent process, but may have one or more children processes. -# This is just like a tree structure. Only one process has PPID that is 0, -# which means this process has no parent process. All the PIDs will be distinct positive integers. -# -# We use two list of integers to represent a list of processes, -# where the first list contains PID for each process -# and the second list contains the corresponding PPID. -# -# Now given the two lists, and a PID representing a process you want to kill, -# return a list of PIDs of processes that will be killed in the end. -# You should assume that when a process is killed, -# all its children processes will be killed. -# No order is required for the final answer. -# -# Example 1: -# Input: -# pid = [1, 3, 10, 5] -# ppid = [3, 0, 5, 3] -# kill = 5 -# Output: [5,10] -# Explanation: -# 3 -# / \ -# 1 5 -# / -# 10 -# Kill 5 will also kill 10. -# Note: -# The given kill id is guaranteed to be one of the given PIDs. -# n >= 1. - # DFS solution. class Solution(object): def killProcess(self, pid, ppid, kill): From 4a92d5327efcd098c9c453e8c64da7629ed18e50 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 7 Dec 2017 09:02:28 -0600 Subject: [PATCH 4076/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 1ff8f8098..8bb406125 100644 --- a/README.md +++ b/README.md @@ -268,6 +268,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 | +572 |[Subtree of Another Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)| [C++](./C++/subtree-of-another-tree.cpp) [Python](./Python/subtree-of-another-tree.py)| _O(m * n)_ | _O(h)_ | Easy | | | 606 |[Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)| [C++](./C++/construct-string-from-binary-tree.cpp) [Python](./Python/construct-string-from-binary-tree.py)| _O(n)_ | _O(h)_ | Easy | | | 617 |[Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)| [C++](./C++/merge-two-binary-trees.cpp) [Python](./Python/merge-two-binary-trees.py)| _O(n)_ | _O(h)_ | Easy | | | 623 |[Add One Row to Tree](https://leetcode.com/problems/add-one-row-to-tree/)| [C++](./C++/add-one-row-to-tree.cpp) [Python](./Python/add-one-row-to-tree.py)| _O(n)_ | _O(h)_ | Medium | | | @@ -325,6 +326,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | +575| [Distribute Candies](https://leetcode.com/problems/distribute-candies/) |[C++](./C++/distribute-candies.cpp) [Python](./Python/distribute-candies.py) | _O(n)_ | _O(n)_ | Easy | | 594| [Longest Harmonious Subsequence](https://leetcode.com/problems/longest-harmonious-subsequence/) |[C++](./C++/longest-harmonious-subsequence.cpp) [Python](./Python/longest-harmonious-subsequence.py) | _O(n)_ | _O(n)_ | Easy | | 599| [Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists/) |[C++](./C++/minimum-index-sum-of-two-lists.cpp) [Python](./Python/minimum-index-sum-of-two-lists.py) | _O((m + n) * l)_ | _O(m * l)_ | Easy | | 609| [Find Duplicate File in System](https://leetcode.com/problems/find-duplicate-file-in-system/) |[C++](./C++/find-duplicate-file-in-system.cpp) [Python](./Python/find-duplicate-file-in-system.py) | _O(n * l)_ | _O(n * l)_ | Medium | | @@ -373,6 +375,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +573 | [Squirrel Simulation](https://leetcode.com/problems/squirrel-simulation/) | [C++](./C++/squirrel-simulation.cpp) [Python](./Python/squirrel-simulation.py) | _O(n)_ | _O(1)_ | Medium |📖|| 592 | [Fraction Addition and Subtraction](https://leetcode.com/problems/fraction-addition-and-subtraction/) | [C++](./C++/fraction-addition-and-subtraction.cpp) [Python](./Python/fraction-addition-and-subtraction.py) | _O(nlogx)_ | _O(n)_ | Medium ||| 593 | [Valid Square](https://leetcode.com/problems/valid-square/) | [C++](./C++/valid-square.cpp) [Python](./Python/valid-square.py) | _O(1)_ | _O(1)_ | Medium ||| 598 | [Range Addition II](https://leetcode.com/problems/range-addition-ii/) | [C++](./C++/range-addition-ii.cpp) [Python](./Python/range-addition-ii.py) | _O(p)_ | _O(1)_ | Easy ||| @@ -634,6 +637,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +568 | [Maximum Vacation Days](https://leetcode.com/problems/maximum-vacation-days/) | [C++](./C++/maximum-vacation-days.cpp) [Python](./Python/maximum-vacation-days.py) | _O(n^2 * k)_ | _O(k)_ | Hard |📖|| 576 | [Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths/) | [C++](./C++/out-of-boundary-paths.cpp) [Python](./Python/out-of-boundary-paths.py) | _O(N * m * n)_ | _O(m * n)_ | Medium ||| 583 | [Delete Operation for Two Strings](https://leetcode.com/problems/delete-operation-for-two-strings/) | [C++](./C++/delete-operation-for-two-strings.cpp) [Python](./Python/delete-operation-for-two-strings.py) | _O(m * n)_ | _O(n)_ | Medium ||| 600 | [Non-negative Integers without Consecutive Ones](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/) | [C++](./C++/non-negative-integers-without-consecutive-ones.cpp) [Python](./Python/non-negative-integers-without-consecutive-ones.py) | _O(1)_ | _O(1)_ | Hard ||| From a6b2d49d7b5cadd61fc9102a9143f391eabe00ab Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Dec 2017 09:52:54 -0600 Subject: [PATCH 4077/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 8bb406125..7eb71f304 100644 --- a/README.md +++ b/README.md @@ -429,6 +429,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 350| [Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [C++](./C++/intersection-of-two-arrays-ii.cpp) [Python](./Python/intersection-of-two-arrays-ii.py) | _O(m + n)_ | _O(1)_ | Easy | EPI | Hash, Binary Search 360| [Sort Transformed Array](https://leetcode.com/problems/sort-transformed-array/) | [C++](./C++/sort-transformed-array.cpp) [Python](./Python/sort-transformed-array.py) | _O(n)_ | _O(1)_ | Medium |📖| 457| [Circular Array Loop](https://leetcode.com/problems/circular-array-loop/) | [C++](./C++/circular-array-loop.cpp) [Python](./Python/circular-array-loop.py) | _O(n)_ | _O(1)_ | Medium || +567| [Permutation in String](https://leetcode.com/problems/permutation-in-string/) | [C++](./C++/permutation-in-string.cpp) [Python](./Python/permutation-in-string.py) | _O(n)_ | _O(1)_ | Medium || 611| [Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/) | [C++](./C++/valid-triangle-number.cpp) [Python](./Python/valid-triangle-number.py) | _O(n^2)_ | _O(1)_ | Medium || ## Recursion From bec1aed175569c532b07b252d3b57e4f7b12a06f Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 8 Dec 2017 10:25:07 -0600 Subject: [PATCH 4078/4971] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 7eb71f304..7f800e2b9 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| +565 | [Array Nesting](https://leetcode.com/problems/array-nesting/) | [C++](./C++/array-nesting.cpp) [Python](./Python/array-nesting.py) | _O(n)_ | _O(1)_ | Medium ||| +566 | [Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix/) | [C++](./C++/reshape-the-matrix.cpp) [Python](./Python/reshape-the-matrix.py) | _O(m * n)_ | _O(m * n)_ | Easy ||| 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray/) | [C++](./C++/shortest-unsorted-continuous-subarray.cpp) [Python](./Python/shortest-unsorted-continuous-subarray.py) | _O(n)_ | _O(1)_ | Easy ||| 605 | [Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) | [C++](./C++/can-place-flowers.cpp) [Python](./Python/can-place-flowers.py) | _O(n)_ | _O(1)_ | Easy ||| 624 | [Maximum Distance in Arrays](https://leetcode.com/problems/maximum-distance-in-arrays/) | [C++](./C++/maximum-distance-in-arrays.cpp) [Python](./Python/maximum-distance-in-arrays.py) | _O(n)_ | _O(1)_ | Easy | 📖 | @@ -169,6 +171,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | 556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | 557| [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) |[C++](./C++/reverse-words-in-a-string-iii.cpp) [Python](./Python/reverse-words-in-a-string-iii.py) | _O(n)_ | _O(1)_ | Easy | | +564| [Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/) |[C++](./C++/find-the-closest-palindrome.cpp) [Python](./Python/find-the-closest-palindrome.py) | _O(l)_ | _O(l)_ | Hard | | 591| [Tag Validator](https://leetcode.com/problems/tag-validator/) |[C++](./C++/tag-validator.cpp) [Python](./Python/tag-validator.py) | _O(n)_ | _O(n)_ | Hard | | 616| [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | [C++](./C++/add-bold-tag-in-string.cpp) [Python](./Python/add-bold-tag-in-string.py) | _O(s * d * l)_ | _O(s)_ | Medium | 📖 | 647| [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) | [C++](./C++/palindromic-substrings.cpp) [Python](./Python/palindromic-substrings.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` From 3f60262ddb2e21a63b6e29777d0d11021ed4d0a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Dec 2017 07:55:19 -0600 Subject: [PATCH 4079/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 7f800e2b9..cb2bcc54b 100644 --- a/README.md +++ b/README.md @@ -271,6 +271,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 | +563 |[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/)| [C++](./C++/binary-tree-tilt.cpp) [Python](./Python/binary-tree-tilt.py)| _O(n)_ | _O(n)_ | Easy | | | 572 |[Subtree of Another Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)| [C++](./C++/subtree-of-another-tree.cpp) [Python](./Python/subtree-of-another-tree.py)| _O(m * n)_ | _O(h)_ | Easy | | | 606 |[Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)| [C++](./C++/construct-string-from-binary-tree.cpp) [Python](./Python/construct-string-from-binary-tree.py)| _O(n)_ | _O(h)_ | Easy | | | 617 |[Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)| [C++](./C++/merge-two-binary-trees.cpp) [Python](./Python/merge-two-binary-trees.py)| _O(n)_ | _O(h)_ | Easy | | | @@ -329,6 +330,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | +560| [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) |[C++](./C++/subarray-sum-equals-k.cpp) [Python](./Python/subarray-sum-equals-k.py) | _O(n)_ | _O(n)_ | Medium | | +561| [Array Partition I](https://leetcode.com/problems/array-partition-i/) |[C++](./C++/array-partition-i.cpp) [Python](./Python/array-partition-i.py) | _O(r)_ | _O(r)_ | Easy | | 575| [Distribute Candies](https://leetcode.com/problems/distribute-candies/) |[C++](./C++/distribute-candies.cpp) [Python](./Python/distribute-candies.py) | _O(n)_ | _O(n)_ | Easy | | 594| [Longest Harmonious Subsequence](https://leetcode.com/problems/longest-harmonious-subsequence/) |[C++](./C++/longest-harmonious-subsequence.cpp) [Python](./Python/longest-harmonious-subsequence.py) | _O(n)_ | _O(n)_ | Easy | | 599| [Minimum Index Sum of Two Lists](https://leetcode.com/problems/minimum-index-sum-of-two-lists/) |[C++](./C++/minimum-index-sum-of-two-lists.cpp) [Python](./Python/minimum-index-sum-of-two-lists.py) | _O((m + n) * l)_ | _O(m * l)_ | Easy | | @@ -641,6 +644,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +562 | [Longest Line of Consecutive One in Matrix](https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/) | [C++](./C++/longest-line-of-consecutive-one-in-matrix.cpp) [Python](./Python/longest-line-of-consecutive-one-in-matrix.py) | _O(m * n)_ | _O(n)_ | Medium |📖|| 568 | [Maximum Vacation Days](https://leetcode.com/problems/maximum-vacation-days/) | [C++](./C++/maximum-vacation-days.cpp) [Python](./Python/maximum-vacation-days.py) | _O(n^2 * k)_ | _O(k)_ | Hard |📖|| 576 | [Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths/) | [C++](./C++/out-of-boundary-paths.cpp) [Python](./Python/out-of-boundary-paths.py) | _O(N * m * n)_ | _O(m * n)_ | Medium ||| 583 | [Delete Operation for Two Strings](https://leetcode.com/problems/delete-operation-for-two-strings/) | [C++](./C++/delete-operation-for-two-strings.cpp) [Python](./Python/delete-operation-for-two-strings.py) | _O(m * n)_ | _O(n)_ | Medium ||| From ace78fa86256f0bbac902bd6944c355c746116c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Dec 2017 07:55:50 -0600 Subject: [PATCH 4080/4971] Update array-partition-i.cpp --- C++/array-partition-i.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/array-partition-i.cpp b/C++/array-partition-i.cpp index d2072e8fb..2bd831e8f 100644 --- a/C++/array-partition-i.cpp +++ b/C++/array-partition-i.cpp @@ -1,5 +1,5 @@ -// Time: O(R), R is the range size of the integers -// Space: O(R) +// Time: O(r), r is the range size of the integers +// Space: O(r) class Solution { public: From a59b6539f16dada785fff01857424196e2898486 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 9 Dec 2017 07:56:26 -0600 Subject: [PATCH 4081/4971] Update array-partition-i.py --- Python/array-partition-i.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/array-partition-i.py b/Python/array-partition-i.py index 66bcd87eb..65e190c22 100644 --- a/Python/array-partition-i.py +++ b/Python/array-partition-i.py @@ -1,5 +1,5 @@ -# Time: O(R), R is the range size of the integers -# Space: O(R) +# Time: O(r), r is the range size of the integers +# Space: O(r) # Given an array of 2n integers, your task is to group these integers into n pairs of integer, # say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. From 16be8db3a34acde4a967f0192319fbbedee26b02 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 09:01:19 -0600 Subject: [PATCH 4082/4971] Create find-smallest-letter-greater-than-target.py --- Python/find-smallest-letter-greater-than-target.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Python/find-smallest-letter-greater-than-target.py diff --git a/Python/find-smallest-letter-greater-than-target.py b/Python/find-smallest-letter-greater-than-target.py new file mode 100644 index 000000000..0843c592c --- /dev/null +++ b/Python/find-smallest-letter-greater-than-target.py @@ -0,0 +1,12 @@ +# Time: O(logn) +# Space: O(1) + +class Solution(object): + def nextGreatestLetter(self, letters, target): + """ + :type letters: List[str] + :type target: str + :rtype: str + """ + i = bisect.bisect_right(letters, target) + return letters[0] if i == len(letters) else letters[i] From e0bde42ea4bcf5b45d5c817b6502da9e6086fd6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 09:05:19 -0600 Subject: [PATCH 4083/4971] Create find-smallest-letter-greater-than-target.cpp --- C++/find-smallest-letter-greater-than-target.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 C++/find-smallest-letter-greater-than-target.cpp diff --git a/C++/find-smallest-letter-greater-than-target.cpp b/C++/find-smallest-letter-greater-than-target.cpp new file mode 100644 index 000000000..2b1434be2 --- /dev/null +++ b/C++/find-smallest-letter-greater-than-target.cpp @@ -0,0 +1,10 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + char nextGreatestLetter(vector& letters, char target) { + const auto cit = upper_bound(letters.cbegin(), letters.cend(), target); + return cit != letters.cend() ? *cit : letters.front(); + } +}; From ef96c4e1a27289f5cdad5de78ee2a2dfc1b91bd0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 09:36:39 -0600 Subject: [PATCH 4084/4971] Create network-delay-time.py --- Python/network-delay-time.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/network-delay-time.py diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py new file mode 100644 index 000000000..c1cf6e4d3 --- /dev/null +++ b/Python/network-delay-time.py @@ -0,0 +1,27 @@ +# Time: O((|E| + |V|) * log|V|) +# Space: O(|E| + |V|) + +# Dijkstra's algorithm +class Solution(object): + def networkDelayTime(self, times, N, K): + """ + :type times: List[List[int]] + :type N: int + :type K: int + :rtype: int + """ + min_heap = [] + adj = [[] for _ in xrange(N)] + for u, v, w in times: + adj[u-1].append((v-1, w)) + + lookup, result = set(), 0 + heapq.heappush(min_heap, (0, K-1)) + while min_heap and len(lookup) != N: + result, u = heapq.heappop(min_heap) + lookup.add(u) + for v, w in adj[u]: + if v in lookup: continue + heapq.heappush(min_heap, (result+w, v)) + return result if len(lookup) == N else -1 + From ae43cc483c2eb142fd9cf3a0b4db284136fd3385 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 09:53:26 -0600 Subject: [PATCH 4085/4971] Create network-delay-time.cpp --- C++/network-delay-time.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/network-delay-time.cpp diff --git a/C++/network-delay-time.cpp b/C++/network-delay-time.cpp new file mode 100644 index 000000000..c2035bef0 --- /dev/null +++ b/C++/network-delay-time.cpp @@ -0,0 +1,32 @@ +// Time: O((|E| + |V|) * log|V|) +// Space: O(|E| + |V|) + +class Solution { +public: + int networkDelayTime(vector>& times, int N, int K) { + using P = pair; + priority_queue, greater

> min_heap; + vector> adj(N); + for (const auto& time : times) { + int u, v, w; + tie(u, v, w) = make_tuple(time[0] - 1, time[1] - 1, time[2]); + adj[u].emplace_back(v, w); + } + + int result = 0; + unordered_set lookup; + min_heap.emplace(0, K - 1); + while (!min_heap.empty() && lookup.size() != N) { + int u; + tie(result, u) = min_heap.top(); min_heap.pop(); + lookup.emplace(u); + for (const auto& kvp : adj[u]) { + int v, w; + tie(v, w) = kvp; + if (lookup.count(v)) continue; + min_heap.emplace(result + w, v); + } + } + return lookup.size() == N ? result : -1; + } +}; From 275bc3f6e29650024bd42fcae93e9e6ce39cf0c6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 09:53:59 -0600 Subject: [PATCH 4086/4971] Update network-delay-time.cpp --- C++/network-delay-time.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/network-delay-time.cpp b/C++/network-delay-time.cpp index c2035bef0..6068b82c3 100644 --- a/C++/network-delay-time.cpp +++ b/C++/network-delay-time.cpp @@ -1,6 +1,7 @@ // Time: O((|E| + |V|) * log|V|) // Space: O(|E| + |V|) +// Dijkstra's algorithm class Solution { public: int networkDelayTime(vector>& times, int N, int K) { From 5013a7dfc3297a5f8d6f6d7107f0839f5b12d150 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 09:58:42 -0600 Subject: [PATCH 4087/4971] Update network-delay-time.py --- Python/network-delay-time.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index c1cf6e4d3..f4a0d8664 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -10,13 +10,13 @@ def networkDelayTime(self, times, N, K): :type K: int :rtype: int """ - min_heap = [] adj = [[] for _ in xrange(N)] for u, v, w in times: adj[u-1].append((v-1, w)) - - lookup, result = set(), 0 - heapq.heappush(min_heap, (0, K-1)) + + result = 0 + lookup = set() + min_heap = [(0, K-1)] while min_heap and len(lookup) != N: result, u = heapq.heappop(min_heap) lookup.add(u) From e79283da6dbf09fa55bbf3a51e96a1e179c74ef1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 10:01:04 -0600 Subject: [PATCH 4088/4971] Update network-delay-time.cpp --- C++/network-delay-time.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/network-delay-time.cpp b/C++/network-delay-time.cpp index 6068b82c3..7b226d905 100644 --- a/C++/network-delay-time.cpp +++ b/C++/network-delay-time.cpp @@ -6,7 +6,6 @@ class Solution { public: int networkDelayTime(vector>& times, int N, int K) { using P = pair; - priority_queue, greater

> min_heap; vector> adj(N); for (const auto& time : times) { int u, v, w; @@ -16,6 +15,7 @@ class Solution { int result = 0; unordered_set lookup; + priority_queue, greater

> min_heap; min_heap.emplace(0, K - 1); while (!min_heap.empty() && lookup.size() != N) { int u; From 4b1c729233fc8c1694e46bbf6765efc68835ab41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 10:18:54 -0600 Subject: [PATCH 4089/4971] Create closest-leaf-in-a-binary-tree.py --- Python/closest-leaf-in-a-binary-tree.py | 46 +++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/closest-leaf-in-a-binary-tree.py diff --git a/Python/closest-leaf-in-a-binary-tree.py b/Python/closest-leaf-in-a-binary-tree.py new file mode 100644 index 000000000..e1b594fb8 --- /dev/null +++ b/Python/closest-leaf-in-a-binary-tree.py @@ -0,0 +1,46 @@ +# 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 + +class Solution(object): + def findClosestLeaf(self, root, k): + """ + :type root: TreeNode + :type k: int + :rtype: int + """ + def traverse(node, neighbors, leaves): + if not node: + return + if not node.left and not node.right: + leaves.add(node.val) + return + if node.left: + neighbors[node.val].append(node.left.val) + neighbors[node.left.val].append(node.val) + traverse(node.left, neighbors, leaves) + if node.right: + neighbors[node.val].append(node.right.val) + neighbors[node.right.val].append(node.val) + traverse(node.right, neighbors, leaves) + + neighbors, leaves = collections.defaultdict(list), set() + traverse(root, neighbors, leaves) + q, lookup = [k], set([k]) + while q: + next_q = [] + for u in q: + if u in leaves: + return u + for v in neighbors[u]: + if v in lookup: + continue + lookup.add(v) + next_q.append(v) + q = next_q From 6fb0a6930dca415e772f84e07c6f572d5616bd17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 11:03:41 -0600 Subject: [PATCH 4090/4971] Update closest-leaf-in-a-binary-tree.py --- Python/closest-leaf-in-a-binary-tree.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/closest-leaf-in-a-binary-tree.py b/Python/closest-leaf-in-a-binary-tree.py index e1b594fb8..3f6d6b1e9 100644 --- a/Python/closest-leaf-in-a-binary-tree.py +++ b/Python/closest-leaf-in-a-binary-tree.py @@ -44,3 +44,4 @@ def traverse(node, neighbors, leaves): lookup.add(v) next_q.append(v) q = next_q + return 0 From 755f8a1e7f205082d6f1b05f34e7510069bcf51a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 11:04:18 -0600 Subject: [PATCH 4091/4971] Create closest-leaf-in-a-binary-tree.cpp --- C++/closest-leaf-in-a-binary-tree.cpp | 63 +++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 C++/closest-leaf-in-a-binary-tree.cpp diff --git a/C++/closest-leaf-in-a-binary-tree.cpp b/C++/closest-leaf-in-a-binary-tree.cpp new file mode 100644 index 000000000..8fecbb19c --- /dev/null +++ b/C++/closest-leaf-in-a-binary-tree.cpp @@ -0,0 +1,63 @@ +// 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: + int findClosestLeaf(TreeNode* root, int k) { + unordered_map> neighbors; + unordered_set leaves; + traverse(root, &neighbors, &leaves); + vector q{k}; + unordered_set lookup{k}; + while (!q.empty()) { + vector next_q; + for (const auto& u : q) { + if (leaves.count(u)) { + return u; + } + for (const auto& v : neighbors[u]) { + if (lookup.count(v)) { + continue; + } + lookup.emplace(v); + next_q.emplace_back(v); + } + } + swap(q, next_q); + } + return 0; + } + +private: + void traverse(TreeNode *node, + unordered_map> *neighbors, + unordered_set *leaves) { + + if (!node) { + return; + } + if (!node->left && !node->right) { + leaves->emplace(node->val); + return; + } + if (node->left) { + (*neighbors)[node->val].emplace_back(node->left->val); + (*neighbors)[node->left->val].emplace_back(node->val); + traverse(node->left, neighbors, leaves); + } + if (node->right) { + (*neighbors)[node->val].emplace_back(node->right->val); + (*neighbors)[node->right->val].emplace_back(node->val); + traverse(node->right, neighbors, leaves); + } + } +}; From 593b9577b19a24a5d281f1660682882cfc8702da Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 11:55:43 -0600 Subject: [PATCH 4092/4971] Create prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 80 ++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 C++/prefix-and-suffix-search.cpp diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp new file mode 100644 index 000000000..1e992c540 --- /dev/null +++ b/C++/prefix-and-suffix-search.cpp @@ -0,0 +1,80 @@ +// Time: O(m + n), m is the number of prefix match, n is the number of suffix match +// Space: O(t * w), t is the number of nodes in trie, w is the number of words + +struct TrieNode { + vector words; // index of words + vector leaves; + + TrieNode() : leaves(26) {} + + void insert(const string& s, const int i) { + auto* p = this; + p->words.emplace_back(i); + for (const auto& c : s) { + if (!p->leaves[c - 'a']) { + p->leaves[c - 'a'] = new TrieNode; + } + p = p->leaves[c - 'a']; + p->words.emplace_back(i); + } + } + + const vector& find(const string& s) const { + auto* p = this; + for (const auto& c : s) { + if (!p->leaves[c - 'a']) { + static const vector empty; + return empty; + } + p = p->leaves[c - 'a']; + } + return p->words; + } + + ~TrieNode() { + for (auto& node : leaves) { + if (node) { + delete node; + } + } + } +}; + +class WordFilter { +public: + WordFilter(vector words) { + for (int i = words.size() - 1; i >= 0; --i) { + auto word = words[i]; + prefix_trie_.insert(word, i); + reverse(word.begin(), word.end()); + suffix_trie_.insert(word, i); + } + } + + int f(string prefix, string suffix) { + const auto& prefix_match = prefix_trie_.find(prefix); + reverse(suffix.begin(), suffix.end()); + const auto& suffix_match = suffix_trie_.find(suffix); + int i = 0, j = 0; + while (i != prefix_match.size() && j != suffix_match.size()) { + if (prefix_match[i] == suffix_match[j]) { + return prefix_match[i]; + } else if (prefix_match[i] > suffix_match[j]) { + ++i; + } else { + ++j; + } + } + return -1; + } + +private: + TrieNode prefix_trie_, suffix_trie_; +}; + +/** + * Your WordFilter object will be instantiated and called as such: + * WordFilter obj = new WordFilter(words); + * int param_1 = obj.f(prefix,suffix); + */ + From e005d5fce11ac8f3204b906589842f293505c7a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 12:21:01 -0600 Subject: [PATCH 4093/4971] Create prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 59 ++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/prefix-and-suffix-search.py diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py new file mode 100644 index 000000000..a0f1fcc00 --- /dev/null +++ b/Python/prefix-and-suffix-search.py @@ -0,0 +1,59 @@ +# Time: O(m + n), m is the number of prefix match, n is the number of suffix match +# Space: O(t * w), t is the number of nodes in trie, w is the number of words + +class WordFilter(object): + + def __init__(self, words): + """ + :type words: List[str] + """ + def insert(trie, word, i): + def add_word(cur, i): + if "_words" not in cur: + cur["_words"] = [] + cur["_words"].append(i) + + cur = trie + add_word(cur, i) + for c in word: + cur = cur[c] + add_word(cur, i) + + _trie = lambda: collections.defaultdict(_trie) + self.__prefix_trie = _trie() + self.__suffix_trie = _trie() + for i in reversed(xrange(len(words))): + insert(self.__prefix_trie, words[i], i) + insert(self.__suffix_trie, words[i][::-1], i) + + def f(self, prefix, suffix): + """ + :type prefix: str + :type suffix: str + :rtype: int + """ + def find(trie, word): + cur = trie + for c in word: + if c not in cur: + return [] + cur = cur[c] + return cur["_words"] + + prefix_match = find(self.__prefix_trie, prefix) + suffix_match = find(self.__suffix_trie, suffix[::-1]) + i, j = 0, 0 + while i != len(prefix_match) and j != len(suffix_match): + if prefix_match[i] == suffix_match[j]: + return prefix_match[i] + elif prefix_match[i] > suffix_match[j]: + i += 1 + else: + j += 1 + return -1 + + + +# Your WordFilter object will be instantiated and called as such: +# obj = WordFilter(words) +# param_1 = obj.f(prefix,suffix) From 79eb06b08099c45ad165507ed0473965eff3ddae Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 12:26:08 -0600 Subject: [PATCH 4094/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index a0f1fcc00..1f896a6b2 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -1,5 +1,5 @@ # Time: O(m + n), m is the number of prefix match, n is the number of suffix match -# Space: O(t * w), t is the number of nodes in trie, w is the number of words +# Space: O(t^2), t is the number of nodes in trie class WordFilter(object): From 150d5949c6476a2678b1c16a2b55db2c365b0277 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 12:27:27 -0600 Subject: [PATCH 4095/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index 1f896a6b2..2de53675e 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -1,5 +1,5 @@ # Time: O(m + n), m is the number of prefix match, n is the number of suffix match -# Space: O(t^2), t is the number of nodes in trie +# Space: O(t * w), t is the number of nodes in trie, w is the number of words class WordFilter(object): @@ -52,8 +52,6 @@ def find(trie, word): j += 1 return -1 - - # Your WordFilter object will be instantiated and called as such: # obj = WordFilter(words) # param_1 = obj.f(prefix,suffix) From 00c3d830d10a4d5a43083110d7f97c5e29b83a1b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 12:33:36 -0600 Subject: [PATCH 4096/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 63 +++++++++++++++++------------- 1 file changed, 35 insertions(+), 28 deletions(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index 2de53675e..a211af555 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -1,47 +1,54 @@ # Time: O(m + n), m is the number of prefix match, n is the number of suffix match # Space: O(t * w), t is the number of nodes in trie, w is the number of words +class Trie(object): + + def __init__(self): + _trie = lambda: collections.defaultdict(_trie) + self.__trie = _trie() + + def insert(self, word, i): + def add_word(cur, i): + if "_words" not in cur: + cur["_words"] = [] + cur["_words"].append(i) + + cur = self.__trie + add_word(cur, i) + for c in word: + cur = cur[c] + add_word(cur, i) + + def find(self, word): + cur = self.__trie + for c in word: + if c not in cur: + return [] + cur = cur[c] + return cur["_words"] + + class WordFilter(object): def __init__(self, words): """ :type words: List[str] - """ - def insert(trie, word, i): - def add_word(cur, i): - if "_words" not in cur: - cur["_words"] = [] - cur["_words"].append(i) - - cur = trie - add_word(cur, i) - for c in word: - cur = cur[c] - add_word(cur, i) - + """ _trie = lambda: collections.defaultdict(_trie) - self.__prefix_trie = _trie() - self.__suffix_trie = _trie() + self.__prefix_trie = Trie() + self.__suffix_trie = Trie() for i in reversed(xrange(len(words))): - insert(self.__prefix_trie, words[i], i) - insert(self.__suffix_trie, words[i][::-1], i) + self.__prefix_trie.insert(words[i], i) + self.__suffix_trie.insert(words[i][::-1], i) def f(self, prefix, suffix): """ :type prefix: str :type suffix: str :rtype: int - """ - def find(trie, word): - cur = trie - for c in word: - if c not in cur: - return [] - cur = cur[c] - return cur["_words"] - - prefix_match = find(self.__prefix_trie, prefix) - suffix_match = find(self.__suffix_trie, suffix[::-1]) + """ + prefix_match = self.__prefix_trie.find(prefix) + suffix_match = self.__suffix_trie.find(suffix[::-1]) i, j = 0, 0 while i != len(prefix_match) and j != len(suffix_match): if prefix_match[i] == suffix_match[j]: From ec160da3489cb324d1c636998f68251b27b65c6a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Dec 2017 12:34:03 -0600 Subject: [PATCH 4097/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index a211af555..c37efc86a 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -34,7 +34,6 @@ def __init__(self, words): """ :type words: List[str] """ - _trie = lambda: collections.defaultdict(_trie) self.__prefix_trie = Trie() self.__suffix_trie = Trie() for i in reversed(xrange(len(words))): From 7add2079f332679a25a6c3de89119a8a60e3641c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:47:05 -0600 Subject: [PATCH 4098/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index cb2bcc54b..1916985f2 100644 --- a/README.md +++ b/README.md @@ -496,6 +496,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 658 | [Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/) | [C++](./C++/find-k-closest-elements.cpp) [Python](./Python/find-k-closest-elements.py) | _O(logn + k)_ | _O(1)_ | Medium | | 668 | [Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [C++](./C++/kth-smallest-number-in-multiplication-table.cpp) [Python](./Python/kth-smallest-number-in-multiplication-table.py) | _O(m * log(m * n))_ | _O(1)_ | Hard | | 719 | [Find K-th Smallest Pair Distance](https://leetcode.com/problems/find-k-th-smallest-pair-distance/) | [C++](./C++/find-k-th-smallest-pair-distance.cpp) [Python](./Python/find-k-th-smallest-pair-distance.py) | _O(nlogn + nlogw)_ | _O(1)_ | Hard | | +744 | [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/) | [C++](./C++/find-smallest-letter-greater-than-target.cpp) [Python](./Python/find-smallest-letter-greater-than-target.py) | _O(logn)_ | _O(1)_ | Easy | | ## Binary Search Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -530,6 +531,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 444| [Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction/)| [C++](./C++/sequence-reconstruction.cpp) [Python](./Python/sequence-reconstruction.py) | _O(n * s)_ | _O(n)_ | Medium |📖| Topological Sort | 666| [Path Sum IV](https://leetcode.com/problems/path-sum-iv/)| [C++](./C++/path-sum-iv.cpp) [Python](./Python/path-sum-iv.py) | _O(n)_ | _O(w)_ | Medium |📖| Topological Sort | 675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | +742|[Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree/)| [C++](./C++/closest-leaf-in-a-binary-tree.cpp) [Python](./Python/closest-leaf-in-a-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | | | +743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O((|E| + |V|) * log|V|)_ | _O(|E| + |V|)_ | Medium | | `Dijkstra's algorithm` | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -721,6 +724,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | 716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | +745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(m + n)_ | _O(w * t)_ | Hard |📖| Trie | ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 7d5166811ac59885c8d08533bd9f454b2846ad89 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:50:01 -0600 Subject: [PATCH 4099/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index c37efc86a..c4de50bf0 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -1,5 +1,6 @@ -# Time: O(m + n), m is the number of prefix match, n is the number of suffix match -# Space: O(t * w), t is the number of nodes in trie, w is the number of words +# Time: ctor: O(w * l), l is the word length on average +# search: O(m + n), m is the number of prefix match, n is the number of suffix match +# Space: O(w * l), w is the number of words class Trie(object): From 8383cd3119eb342ab9e08fc1c7625bccc53afe4f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:50:37 -0600 Subject: [PATCH 4100/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index 1e992c540..6158c6282 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -1,5 +1,6 @@ -// Time: O(m + n), m is the number of prefix match, n is the number of suffix match -// Space: O(t * w), t is the number of nodes in trie, w is the number of words +// Time: ctor: O(w * l), w is the number of words, l is the word length on average +// search: O(m + n), m is the number of prefix match, n is the number of suffix match +// Space: O(w * l) struct TrieNode { vector words; // index of words From cc04592ea5ea15944f668928d5b8e6f7d8e257a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:51:00 -0600 Subject: [PATCH 4101/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index c4de50bf0..c0f8e26c6 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -1,6 +1,6 @@ -# Time: ctor: O(w * l), l is the word length on average +# Time: ctor: O(w * l), w is the number of words, l is the word length on average # search: O(m + n), m is the number of prefix match, n is the number of suffix match -# Space: O(w * l), w is the number of words +# Space: O(w * l) class Trie(object): From 314e4478bfe2768596373437c236665c6f15293e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:51:31 -0600 Subject: [PATCH 4102/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1916985f2..87f2ec999 100644 --- a/README.md +++ b/README.md @@ -724,7 +724,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | 716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | -745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(m + n)_ | _O(w * t)_ | Hard |📖| Trie | +745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(m + n)_ | _O(w * l)_ | Hard |📖| Trie | ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 9efd56a996ef561ba1b1a64cf2b004bad2999578 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:52:52 -0600 Subject: [PATCH 4103/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index 6158c6282..4d3c39f52 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -1,5 +1,5 @@ // Time: ctor: O(w * l), w is the number of words, l is the word length on average -// search: O(m + n), m is the number of prefix match, n is the number of suffix match +// search: O(l + m + n), m is the number of prefix match, n is the number of suffix match // Space: O(w * l) struct TrieNode { From 90f858d15de75ea96ff447ba5d86f38dce2bfbbf Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:53:08 -0600 Subject: [PATCH 4104/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index c0f8e26c6..0d8060db1 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -1,5 +1,5 @@ # Time: ctor: O(w * l), w is the number of words, l is the word length on average -# search: O(m + n), m is the number of prefix match, n is the number of suffix match +# search: O(l + m + n), m is the number of prefix match, n is the number of suffix match # Space: O(w * l) class Trie(object): From 97ea016c4736ff9fac3ff6cec6e3ec7afe96359c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:53:36 -0600 Subject: [PATCH 4105/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 87f2ec999..611811a80 100644 --- a/README.md +++ b/README.md @@ -724,7 +724,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | 716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | -745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(m + n)_ | _O(w * l)_ | Hard |📖| Trie | +745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(l + m + n)_ | _O(w * l)_ | Hard |📖| Trie | ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 59be49a53fc9ef640bde570e14bc008dc27b2ca5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:56:17 -0600 Subject: [PATCH 4106/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index 0d8060db1..7c8300509 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -1,5 +1,6 @@ # Time: ctor: O(w * l), w is the number of words, l is the word length on average -# search: O(l + m + n), m is the number of prefix match, n is the number of suffix match +# search: O(p + s + m + n), p is the length of the prefix, s is the length of the suffix, +# m is the number of the prefix match, n is the number of the suffix match # Space: O(w * l) class Trie(object): From f2097afd2ae1ad348f39547efca6e257eef314c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:56:51 -0600 Subject: [PATCH 4107/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index 4d3c39f52..65711f905 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -1,5 +1,6 @@ -// Time: ctor: O(w * l), w is the number of words, l is the word length on average -// search: O(l + m + n), m is the number of prefix match, n is the number of suffix match +// Time: ctor: O(w * l), w is the number of words, l is the word length on average +// search: O(p + s + m + n), p is the length of the prefix, s is the length of the suffix, +// m is the number of the prefix match, n is the number of the suffix match // Space: O(w * l) struct TrieNode { From 3f4d257d2f874797935d151abfb736c23c0713b4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:57:25 -0600 Subject: [PATCH 4108/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index 65711f905..d289868ae 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -1,6 +1,6 @@ -// Time: ctor: O(w * l), w is the number of words, l is the word length on average -// search: O(p + s + m + n), p is the length of the prefix, s is the length of the suffix, -// m is the number of the prefix match, n is the number of the suffix match +// Time: ctor: O(w * l), w is the number of words, l is the word length on average +// search: O(p + s + m + n), p is the length of the prefix, s is the length of the suffix, +// m is the number of the prefix match, n is the number of the suffix match // Space: O(w * l) struct TrieNode { From 02ea722ef7a6bd56d5a363c867582aad1e423532 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:57:55 -0600 Subject: [PATCH 4109/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 611811a80..eaf11ed31 100644 --- a/README.md +++ b/README.md @@ -724,7 +724,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | 716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | -745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(l + m + n)_ | _O(w * l)_ | Hard |📖| Trie | +745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(p + s + m + n)_ | _O(w * l)_ | Hard |📖| Trie | ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From f2e79b074be7db61d1d78344112b6015565b8f4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:59:32 -0600 Subject: [PATCH 4110/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index 7c8300509..680299ff9 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -1,6 +1,6 @@ # Time: ctor: O(w * l), w is the number of words, l is the word length on average -# search: O(p + s + m + n), p is the length of the prefix, s is the length of the suffix, -# m is the number of the prefix match, n is the number of the suffix match +# search: O(p + s + max(m, n)), p is the length of the prefix, s is the length of the suffix, +# m is the number of the prefix match, n is the number of the suffix match # Space: O(w * l) class Trie(object): From 5775a5d9653b01e51374f2b53322b6d65a716d21 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 08:59:55 -0600 Subject: [PATCH 4111/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index d289868ae..6a8a23a8d 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -1,6 +1,6 @@ // Time: ctor: O(w * l), w is the number of words, l is the word length on average -// search: O(p + s + m + n), p is the length of the prefix, s is the length of the suffix, -// m is the number of the prefix match, n is the number of the suffix match +// search: O(p + s + max(m, n)), p is the length of the prefix, s is the length of the suffix, +// m is the number of the prefix match, n is the number of the suffix match // Space: O(w * l) struct TrieNode { From 1f749d29cdecbdc3491709f2bca55b4d9dc5176f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 11 Dec 2017 09:00:23 -0600 Subject: [PATCH 4112/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eaf11ed31..4ac121219 100644 --- a/README.md +++ b/README.md @@ -724,7 +724,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | 716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | -745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(p + s + m + n)_ | _O(w * l)_ | Hard |📖| Trie | +745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(p + s + max(m, n))_ | _O(w * l)_ | Hard |📖| Trie | ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 3612cfbe0d4d96a6e849af665709f6269ad6721f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 09:56:50 -0600 Subject: [PATCH 4113/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4ac121219..fd47709c0 100644 --- a/README.md +++ b/README.md @@ -724,7 +724,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | 716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | -745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(p + s + max(m, n))_ | _O(w * l)_ | Hard |📖| Trie | +745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(p + s + max(m, n))_ | _O(w * l)_ | Hard || Trie | ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From db26ea6033186081ae530394bb45fffd93217957 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 10:11:53 -0600 Subject: [PATCH 4114/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 85 ++++++++++++++---------------- 1 file changed, 39 insertions(+), 46 deletions(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index 680299ff9..a46450329 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -1,34 +1,25 @@ # Time: ctor: O(w * l), w is the number of words, l is the word length on average -# search: O(p + s + max(m, n)), p is the length of the prefix, s is the length of the suffix, -# m is the number of the prefix match, n is the number of the suffix match +# search: O(p + s), p is the length of the prefix, s is the length of the suffix, # Space: O(w * l) -class Trie(object): - - def __init__(self): - _trie = lambda: collections.defaultdict(_trie) - self.__trie = _trie() - - def insert(self, word, i): - def add_word(cur, i): - if "_words" not in cur: - cur["_words"] = [] - cur["_words"].append(i) - - cur = self.__trie - add_word(cur, i) - for c in word: - cur = cur[c] - add_word(cur, i) - - def find(self, word): - cur = self.__trie - for c in word: - if c not in cur: - return [] - cur = cur[c] - return cur["_words"] - +# Given many words, words[i] has weight i. +# +# Design a class WordFilter that supports one function, +# WordFilter.f(String prefix, String suffix). +# It will return the word with given prefix and suffix with maximum weight. +# If no word exists, return -1. +# +# Examples: +# Input: +# WordFilter(["apple"]) +# WordFilter.f("a", "e") // returns 0 +# WordFilter.f("b", "") // returns -1 +# Note: +# words has length in range [1, 15000]. +# For each test case, up to words.length queries WordFilter.f may be made. +# words[i] has length in range [1, 10]. +# prefix, suffix have lengths in range [0, 10]. +# words[i] and prefix, suffix queries consist of lowercase letters only. class WordFilter(object): @@ -36,30 +27,32 @@ def __init__(self, words): """ :type words: List[str] """ - self.__prefix_trie = Trie() - self.__suffix_trie = Trie() - for i in reversed(xrange(len(words))): - self.__prefix_trie.insert(words[i], i) - self.__suffix_trie.insert(words[i][::-1], i) + _trie = lambda: collections.defaultdict(_trie) + self.__trie = _trie() + for weight, word in enumerate(words): + word += '#' + for i in xrange(len(word)): + cur = self.__trie + cur["_weight"] = weight + for j in xrange(i, 2 * len(word) - 1): + cur = cur[word[j % len(word)]] + cur["_weight"] = weight + def f(self, prefix, suffix): """ :type prefix: str :type suffix: str :rtype: int - """ - prefix_match = self.__prefix_trie.find(prefix) - suffix_match = self.__suffix_trie.find(suffix[::-1]) - i, j = 0, 0 - while i != len(prefix_match) and j != len(suffix_match): - if prefix_match[i] == suffix_match[j]: - return prefix_match[i] - elif prefix_match[i] > suffix_match[j]: - i += 1 - else: - j += 1 - return -1 - + """ + cur = self.__trie + for letter in suffix + '#' + prefix: + if letter not in cur: + return -1 + cur = cur[letter] + return cur["_weight"] + + # Your WordFilter object will be instantiated and called as such: # obj = WordFilter(words) # param_1 = obj.f(prefix,suffix) From 5ba888f6148d946241428dafb578e56b28ee07e4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 10:17:18 -0600 Subject: [PATCH 4115/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fd47709c0..3b7fa8204 100644 --- a/README.md +++ b/README.md @@ -724,7 +724,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 642| [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/) | [C++](./C++/design-search-autocomplete-system.cpp) [Python](./Python/design-search-autocomplete-system.py) | _O(p^2)_ | _O(p * t + s)_ | Hard |📖| | 715| [Range Module](https://leetcode.com/problems/range-module/) | [C++](./C++/range-module.cpp) [Python](./Python/range-module.py) | add: _O(n)_
remove: _O(n)_
query: _O(logn)_ | _O(n)_ | Hard || | 716| [Max Stack](https://leetcode.com/problems/max-stack/) | [C++](./C++/max-stack.cpp) [Python](./Python/max-stack.py) | push: _O(logn)_
pop: _O(logn)_
popMax: _O(logn)_
top: _O(1)_
peekMax: _O(1)_ | _O(n)_ | Easy || | -745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l)_
search : _O(p + s + max(m, n))_ | _O(w * l)_ | Hard || Trie | +745| [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/) | [C++](./C++/prefix-and-suffix-search.cpp) [Python](./Python/prefix-and-suffix-search.py) | ctor: _O(w * l^2)_
search : _O(p + s)_ | _O(t)_ | Hard || Trie | ## SQL | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From d9ddebaf383235f6e6cc11153a97611ce81bbd55 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 10:17:52 -0600 Subject: [PATCH 4116/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index a46450329..c274b0ebf 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -1,6 +1,6 @@ -# Time: ctor: O(w * l), w is the number of words, l is the word length on average -# search: O(p + s), p is the length of the prefix, s is the length of the suffix, -# Space: O(w * l) +# Time: ctor: O(w * l^2), w is the number of words, l is the word length on average +# search: O(p + s) , p is the length of the prefix, s is the length of the suffix, +# Space: O(t), t is the number of trie nodes # Given many words, words[i] has weight i. # From 5eb07f99ac4d29f890efcab8cdb120545bc470f1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 10:19:11 -0600 Subject: [PATCH 4117/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index c274b0ebf..f7ca9b9a2 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -35,8 +35,8 @@ def __init__(self, words): for i in xrange(len(word)): cur = self.__trie cur["_weight"] = weight - for j in xrange(i, 2 * len(word) - 1): - cur = cur[word[j % len(word)]] + for j in xrange(i, 2*len(word)-1): + cur = cur[word[j%len(word)]] cur["_weight"] = weight def f(self, prefix, suffix): From 82d402237a6a9fc10eddb864c238a3bea39c32ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 10:51:06 -0600 Subject: [PATCH 4118/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index 6a8a23a8d..08ef44de7 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -1,7 +1,7 @@ -// Time: ctor: O(w * l), w is the number of words, l is the word length on average -// search: O(p + s + max(m, n)), p is the length of the prefix, s is the length of the suffix, -// m is the number of the prefix match, n is the number of the suffix match -// Space: O(w * l) +// Time: ctor: O(w * l^2), w is the number of words, l is the word length on average +// search: O(p + s) , p is the length of the prefix, s is the length of the suffix, +// Space: O(t), t is the number of trie nodes + struct TrieNode { vector words; // index of words From 8651d490b06fcab8b523244361757f3790a45472 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 10:51:35 -0600 Subject: [PATCH 4119/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 49 +++++++++++--------------------- 1 file changed, 17 insertions(+), 32 deletions(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index 08ef44de7..892bb7fce 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -2,35 +2,33 @@ // search: O(p + s) , p is the length of the prefix, s is the length of the suffix, // Space: O(t), t is the number of trie nodes - struct TrieNode { - vector words; // index of words + int weight; vector leaves; - TrieNode() : leaves(26) {} + TrieNode() : weight(0), leaves(27) {} - void insert(const string& s, const int i) { + void insert(const string& s, const int weight) { auto* p = this; - p->words.emplace_back(i); + p->weight = weight; for (const auto& c : s) { if (!p->leaves[c - 'a']) { p->leaves[c - 'a'] = new TrieNode; } p = p->leaves[c - 'a']; - p->words.emplace_back(i); + p->weight = weight; } } - const vector& find(const string& s) const { + int find(const string& s) const { auto* p = this; for (const auto& c : s) { if (!p->leaves[c - 'a']) { - static const vector empty; - return empty; + return -1; } p = p->leaves[c - 'a']; } - return p->words; + return p->weight; } ~TrieNode() { @@ -45,33 +43,21 @@ struct TrieNode { class WordFilter { public: WordFilter(vector words) { - for (int i = words.size() - 1; i >= 0; --i) { - auto word = words[i]; - prefix_trie_.insert(word, i); - reverse(word.begin(), word.end()); - suffix_trie_.insert(word, i); + for (int i = 0; i < words.size(); ++i) { + auto word = words[i] + SEPARATOR + words[i]; + for (int j = 0; j < word.length(); ++j) { + trie_.insert(word.substr(j), i); + } } } int f(string prefix, string suffix) { - const auto& prefix_match = prefix_trie_.find(prefix); - reverse(suffix.begin(), suffix.end()); - const auto& suffix_match = suffix_trie_.find(suffix); - int i = 0, j = 0; - while (i != prefix_match.size() && j != suffix_match.size()) { - if (prefix_match[i] == suffix_match[j]) { - return prefix_match[i]; - } else if (prefix_match[i] > suffix_match[j]) { - ++i; - } else { - ++j; - } - } - return -1; + return trie_.find(suffix + SEPARATOR + prefix); } - + private: - TrieNode prefix_trie_, suffix_trie_; + const string SEPARATOR = "{"; // ascii code of 'z' + 1 + TrieNode trie_; }; /** @@ -79,4 +65,3 @@ class WordFilter { * WordFilter obj = new WordFilter(words); * int param_1 = obj.f(prefix,suffix); */ - From 9b9227d1e5f6113f4ec26de80f31f45551953035 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 10:59:52 -0600 Subject: [PATCH 4120/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index 892bb7fce..b5d3cdae3 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -1,3 +1,4 @@ + // Time: ctor: O(w * l^2), w is the number of words, l is the word length on average // search: O(p + s) , p is the length of the prefix, s is the length of the suffix, // Space: O(t), t is the number of trie nodes @@ -44,9 +45,9 @@ class WordFilter { public: WordFilter(vector words) { for (int i = 0; i < words.size(); ++i) { - auto word = words[i] + SEPARATOR + words[i]; - for (int j = 0; j < word.length(); ++j) { - trie_.insert(word.substr(j), i); + for (int j = 0; j <= words[i].length(); ++j) { + const auto& word = words[i].substr(j) + SEPARATOR + words[i]; + trie_.insert(word, i); } } } From 1d38f77140fc32c7f4cd2febcfb4f7f8dd2d5b01 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:00:50 -0600 Subject: [PATCH 4121/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index b5d3cdae3..5f3d70738 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -46,8 +46,7 @@ class WordFilter { WordFilter(vector words) { for (int i = 0; i < words.size(); ++i) { for (int j = 0; j <= words[i].length(); ++j) { - const auto& word = words[i].substr(j) + SEPARATOR + words[i]; - trie_.insert(word, i); + trie_.insert(words[i].substr(j) + SEPARATOR + words[i], i); } } } From 2f614d2266d6ae352a15c0ead837fd0a5fce1cce Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:01:55 -0600 Subject: [PATCH 4122/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index 5f3d70738..f5c9b4eb4 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -1,4 +1,3 @@ - // Time: ctor: O(w * l^2), w is the number of words, l is the word length on average // search: O(p + s) , p is the length of the prefix, s is the length of the suffix, // Space: O(t), t is the number of trie nodes From abc3f54d0fc2e94ef1fde187101903ab11dcca7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:17:19 -0600 Subject: [PATCH 4123/4971] Update prefix-and-suffix-search.cpp --- C++/prefix-and-suffix-search.cpp | 145 +++++++++++++++++++++++-------- 1 file changed, 109 insertions(+), 36 deletions(-) diff --git a/C++/prefix-and-suffix-search.cpp b/C++/prefix-and-suffix-search.cpp index f5c9b4eb4..644b4378d 100644 --- a/C++/prefix-and-suffix-search.cpp +++ b/C++/prefix-and-suffix-search.cpp @@ -2,61 +2,134 @@ // search: O(p + s) , p is the length of the prefix, s is the length of the suffix, // Space: O(t), t is the number of trie nodes -struct TrieNode { - int weight; - vector leaves; - - TrieNode() : weight(0), leaves(27) {} - - void insert(const string& s, const int weight) { - auto* p = this; - p->weight = weight; - for (const auto& c : s) { - if (!p->leaves[c - 'a']) { - p->leaves[c - 'a'] = new TrieNode; +class WordFilter { +public: + WordFilter(vector words) { + for (int i = 0; i < words.size(); ++i) { + for (int j = 0; j <= words[i].length(); ++j) { + trie_.insert(words[i].substr(j) + SEPARATOR + words[i], i); } - p = p->leaves[c - 'a']; - p->weight = weight; } } - int find(const string& s) const { - auto* p = this; - for (const auto& c : s) { - if (!p->leaves[c - 'a']) { - return -1; + int f(string prefix, string suffix) { + return trie_.find(suffix + SEPARATOR + prefix); + } + +private: + struct TrieNode { + int weight; + vector leaves; + + TrieNode() : weight(0), leaves(27) {} + + void insert(const string& s, const int weight) { + auto* p = this; + p->weight = weight; + for (const auto& c : s) { + if (!p->leaves[c - 'a']) { + p->leaves[c - 'a'] = new TrieNode; + } + p = p->leaves[c - 'a']; + p->weight = weight; } - p = p->leaves[c - 'a']; } - return p->weight; - } - ~TrieNode() { - for (auto& node : leaves) { - if (node) { - delete node; + int find(const string& s) const { + auto* p = this; + for (const auto& c : s) { + if (!p->leaves[c - 'a']) { + return -1; + } + p = p->leaves[c - 'a']; } + return p->weight; } - } + + ~TrieNode() { + for (auto& node : leaves) { + if (node) { + delete node; + } + } + } + }; + const string SEPARATOR = "{"; // ascii code of 'z' + 1 + TrieNode trie_; }; -class WordFilter { +// Time: ctor: O(w * l), w is the number of words, l is the word length on average +// search: O(p + s + max(m, n)), p is the length of the prefix, s is the length of the suffix, +// m is the number of the prefix match, n is the number of the suffix match +// Space: O(w * l) +class WordFilter2 { public: WordFilter(vector words) { - for (int i = 0; i < words.size(); ++i) { - for (int j = 0; j <= words[i].length(); ++j) { - trie_.insert(words[i].substr(j) + SEPARATOR + words[i], i); - } + for (int i = words.size() - 1; i >= 0; --i) { + auto word = words[i]; + prefix_trie_.insert(word, i); + reverse(word.begin(), word.end()); + suffix_trie_.insert(word, i); } } int f(string prefix, string suffix) { - return trie_.find(suffix + SEPARATOR + prefix); + const auto& prefix_match = prefix_trie_.find(prefix); + reverse(suffix.begin(), suffix.end()); + const auto& suffix_match = suffix_trie_.find(suffix); + int i = 0, j = 0; + while (i != prefix_match.size() && j != suffix_match.size()) { + if (prefix_match[i] == suffix_match[j]) { + return prefix_match[i]; + } else if (prefix_match[i] > suffix_match[j]) { + ++i; + } else { + ++j; + } + } + return -1; } - + private: - const string SEPARATOR = "{"; // ascii code of 'z' + 1 - TrieNode trie_; + struct TrieNode { + vector words; // index of words + vector leaves; + + TrieNode() : leaves(26) {} + + void insert(const string& s, const int i) { + auto* p = this; + p->words.emplace_back(i); + for (const auto& c : s) { + if (!p->leaves[c - 'a']) { + p->leaves[c - 'a'] = new TrieNode; + } + p = p->leaves[c - 'a']; + p->words.emplace_back(i); + } + } + + const vector& find(const string& s) const { + auto* p = this; + for (const auto& c : s) { + if (!p->leaves[c - 'a']) { + static const vector empty; + return empty; + } + p = p->leaves[c - 'a']; + } + return p->words; + } + + ~TrieNode() { + for (auto& node : leaves) { + if (node) { + delete node; + } + } + } + }; + TrieNode prefix_trie_, suffix_trie_; }; /** From c80eb64224415d4ad0363c8eb7e1e7d726cd2716 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:19:20 -0600 Subject: [PATCH 4124/4971] Update prefix-and-suffix-search.py --- Python/prefix-and-suffix-search.py | 62 ++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index f7ca9b9a2..caecf336c 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -53,6 +53,68 @@ def f(self, prefix, suffix): return cur["_weight"] +# Time: ctor: O(w * l), w is the number of words, l is the word length on average +# search: O(p + s + max(m, n)), p is the length of the prefix, s is the length of the suffix, +# m is the number of the prefix match, n is the number of the suffix match +# Space: O(w * l) +class Trie(object): + + def __init__(self): + _trie = lambda: collections.defaultdict(_trie) + self.__trie = _trie() + + def insert(self, word, i): + def add_word(cur, i): + if "_words" not in cur: + cur["_words"] = [] + cur["_words"].append(i) + + cur = self.__trie + add_word(cur, i) + for c in word: + cur = cur[c] + add_word(cur, i) + + def find(self, word): + cur = self.__trie + for c in word: + if c not in cur: + return [] + cur = cur[c] + return cur["_words"] + + +class WordFilter2(object): + + def __init__(self, words): + """ + :type words: List[str] + """ + self.__prefix_trie = Trie() + self.__suffix_trie = Trie() + for i in reversed(xrange(len(words))): + self.__prefix_trie.insert(words[i], i) + self.__suffix_trie.insert(words[i][::-1], i) + + def f(self, prefix, suffix): + """ + :type prefix: str + :type suffix: str + :rtype: int + """ + prefix_match = self.__prefix_trie.find(prefix) + suffix_match = self.__suffix_trie.find(suffix[::-1]) + i, j = 0, 0 + while i != len(prefix_match) and j != len(suffix_match): + if prefix_match[i] == suffix_match[j]: + return prefix_match[i] + elif prefix_match[i] > suffix_match[j]: + i += 1 + else: + j += 1 + return -1 + + # Your WordFilter object will be instantiated and called as such: # obj = WordFilter(words) # param_1 = obj.f(prefix,suffix) From c78987d52cf8c5ab479f04165e62e41439a849de Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:22:01 -0600 Subject: [PATCH 4125/4971] Update find-smallest-letter-greater-than-target.py --- ...ind-smallest-letter-greater-than-target.py | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/Python/find-smallest-letter-greater-than-target.py b/Python/find-smallest-letter-greater-than-target.py index 0843c592c..0f8fc0c37 100644 --- a/Python/find-smallest-letter-greater-than-target.py +++ b/Python/find-smallest-letter-greater-than-target.py @@ -1,6 +1,46 @@ # Time: O(logn) # Space: O(1) +# Given a list of sorted characters letters containing only lowercase letters, +# and given a target letter target, find the smallest element in the list that is larger than the given target. +# +# Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'. +# +# Examples: +# Input: +# letters = ["c", "f", "j"] +# target = "a" +# Output: "c" +# +# Input: +# letters = ["c", "f", "j"] +# target = "c" +# Output: "f" +# +# Input: +# letters = ["c", "f", "j"] +# target = "d" +# Output: "f" +# +# Input: +# letters = ["c", "f", "j"] +# target = "g" +# Output: "j" +# +# Input: +# letters = ["c", "f", "j"] +# target = "j" +# Output: "c" +# +# Input: +# letters = ["c", "f", "j"] +# target = "k" +# Output: "c" +# Note: +# - letters has a length in range [2, 10000]. +# - letters consists of lowercase letters, and contains at least 2 unique letters. +# - target is a lowercase letter. + class Solution(object): def nextGreatestLetter(self, letters, target): """ From 342cceed578910742a7cf57d47717251abca44b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:23:33 -0600 Subject: [PATCH 4126/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3b7fa8204..8a3b2087d 100644 --- a/README.md +++ b/README.md @@ -532,7 +532,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 666| [Path Sum IV](https://leetcode.com/problems/path-sum-iv/)| [C++](./C++/path-sum-iv.cpp) [Python](./Python/path-sum-iv.py) | _O(n)_ | _O(w)_ | Medium |📖| Topological Sort | 675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | 742|[Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree/)| [C++](./C++/closest-leaf-in-a-binary-tree.cpp) [Python](./Python/closest-leaf-in-a-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | | | -743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O((|E| + |V|) * log|V|)_ | _O(|E| + |V|)_ | Medium | | `Dijkstra's algorithm` | +743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O((\|E\| + \|V\|) * log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From b6fbc947a740238ba8460a030189dd4d46ec3db0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:23:55 -0600 Subject: [PATCH 4127/4971] Update network-delay-time.py --- Python/network-delay-time.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index f4a0d8664..4bef926cc 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -1,6 +1,21 @@ # Time: O((|E| + |V|) * log|V|) # Space: O(|E| + |V|) +# There are N network nodes, labelled 1 to N. +# +# Given times, a list of travel times as directed edges times[i] = (u, v, w), +# where u is the source node, v is the target node, +# and w is the time it takes for a signal to travel from source to target. +# +# Now, we send a signal from a certain node K. +# How long will it take for all nodes to receive the signal? If it is impossible, return -1. +# +# Note: +# - N will be in the range [1, 100]. +# - K will be in the range [1, N]. +# - The length of times will be in the range [1, 6000]. +# - All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100. + # Dijkstra's algorithm class Solution(object): def networkDelayTime(self, times, N, K): From c5f0833f07b8dbc392cdf13e7b9bbb9ce6288171 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:25:48 -0600 Subject: [PATCH 4128/4971] Update closest-leaf-in-a-binary-tree.py --- Python/closest-leaf-in-a-binary-tree.py | 50 +++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/Python/closest-leaf-in-a-binary-tree.py b/Python/closest-leaf-in-a-binary-tree.py index 3f6d6b1e9..839133c9f 100644 --- a/Python/closest-leaf-in-a-binary-tree.py +++ b/Python/closest-leaf-in-a-binary-tree.py @@ -1,6 +1,56 @@ # Time: O(n) # Space: O(n) +# Given a binary tree where every node has a unique value, and a target key k, +# find the value of the closest leaf node to target k in the tree. +# +# Here, closest to a leaf means the least number of edges travelled on the binary tree to reach +# any leaf of the tree. Also, a node is called a leaf if it has no children. +# +# In the following examples, the input tree is represented in flattened form row by row. +# The actual root tree given will be a TreeNode object. +# +# Example 1: +# +# Input: +# root = [1, 3, 2], k = 1 +# Diagram of binary tree: +# 1 +# / \ +# 3 2 +# +# Output: 2 (or 3) +# +# Explanation: Either 2 or 3 is the closest leaf node to the target of 1. +# Example 2: +# +# Input: +# root = [1], k = 1 +# Output: 1 +# +# Explanation: The closest leaf node is the root node itself. +# Example 3: +# +# Input: +# root = [1,2,3,4,null,null,null,5,null,6], k = 2 +# Diagram of binary tree: +# 1 +# / \ +# 2 3 +# / +# 4 +# / +# 5 +# / +# 6 +# +# Output: 3 +# Explanation: The leaf node with value 3 (and not the leaf node with value 6) is closest to the node with value 2. +# Note: +# - root represents a binary tree with at least 1 node and at most 1000 nodes. +# - Every node has a unique node.val in range [1, 1000]. +# - There exists some node in the given binary tree for which node.val == k. + # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): From 1cd30475a3e479cec2a61b6a99f908a60f7ab6a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:29:35 -0600 Subject: [PATCH 4129/4971] Update network-delay-time.py --- Python/network-delay-time.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index 4bef926cc..b8f2a237f 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -1,4 +1,4 @@ -# Time: O((|E| + |V|) * log|V|) +# Time: O(|E| + |V|log|V|) # Space: O(|E| + |V|) # There are N network nodes, labelled 1 to N. From a902ccb30b12213039fb4fbe200e554b27d8dcec Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:29:55 -0600 Subject: [PATCH 4130/4971] Update network-delay-time.cpp --- C++/network-delay-time.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/network-delay-time.cpp b/C++/network-delay-time.cpp index 7b226d905..444e033dd 100644 --- a/C++/network-delay-time.cpp +++ b/C++/network-delay-time.cpp @@ -1,4 +1,4 @@ -// Time: O((|E| + |V|) * log|V|) +// Time: O(|E| + |V|log|V|) // Space: O(|E| + |V|) // Dijkstra's algorithm From 4a1a3fc91b5d70def72c075922c89eb208822928 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 12 Dec 2017 11:30:39 -0600 Subject: [PATCH 4131/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8a3b2087d..a47c018da 100644 --- a/README.md +++ b/README.md @@ -532,7 +532,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 666| [Path Sum IV](https://leetcode.com/problems/path-sum-iv/)| [C++](./C++/path-sum-iv.cpp) [Python](./Python/path-sum-iv.py) | _O(n)_ | _O(w)_ | Medium |📖| Topological Sort | 675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | 742|[Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree/)| [C++](./C++/closest-leaf-in-a-binary-tree.cpp) [Python](./Python/closest-leaf-in-a-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | | | -743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O((\|E\| + \|V\|) * log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | +743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O(\|E\| + \|V\|log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 0a53fd0c3b00824615537ec589b615519a9344f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Dec 2017 17:29:51 +0800 Subject: [PATCH 4132/4971] Update water-and-jug-problem.py --- Python/water-and-jug-problem.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/Python/water-and-jug-problem.py b/Python/water-and-jug-problem.py index 20030b4ad..b0d1dc743 100644 --- a/Python/water-and-jug-problem.py +++ b/Python/water-and-jug-problem.py @@ -22,12 +22,8 @@ # Input: x = 2, y = 6, z = 5 # Output: False - -def gcd(a, b): - while b: - a, b = b, a%b - return a - +# Bézout's identity (also called Bézout's lemma) +from fractions import gcd class Solution(object): def canMeasureWater(self, x, y, z): """ @@ -36,4 +32,7 @@ def canMeasureWater(self, x, y, z): :type z: int :rtype: bool """ - return z == 0 or ((x + y >= z) and (z % gcd(x, y) == 0)) + # The problem is to solve: + # - check z <= max(x, y) + # - check if there is any (a, b) integers s.t. ax + by = z + return z <= max(x, y) and z % gcd(x, y) == 0 From 0084791a232620078ced01e4c5beb3672f5632a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Dec 2017 17:30:33 +0800 Subject: [PATCH 4133/4971] Update water-and-jug-problem.cpp --- C++/water-and-jug-problem.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/water-and-jug-problem.cpp b/C++/water-and-jug-problem.cpp index 21c402d2a..29402f4be 100644 --- a/C++/water-and-jug-problem.cpp +++ b/C++/water-and-jug-problem.cpp @@ -1,6 +1,7 @@ // Time: O(logn), n is the max of (x, y) // Space: O(1) +// Bézout's identity (also called Bézout's lemma) class Solution { public: bool canMeasureWater(int x, int y, int z) { From 761dba8dc450e3f8accdd9820d9d64e414d4625d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Dec 2017 17:31:52 +0800 Subject: [PATCH 4134/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a47c018da..deb6edcdb 100644 --- a/README.md +++ b/README.md @@ -367,7 +367,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | [C++](./C++/self-crossing.cpp) [Python](./Python/self-crossing.py) | _O(n)_ | _O(1)_ | Hard ||| 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./C++/counting-bits.cpp) [Python](./Python/counting-bits.py) | _O(n)_ | _O(n)_ | Medium ||| 343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(1)_ | Medium || Tricky, DP | -365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || Euclidean Algorithm | +365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || `Euclidean Algorithm`, `Bézout's identity` | 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| From d94fd0e7d2377cfa4f0c69ac955fa64bb742e273 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Dec 2017 07:22:10 -0600 Subject: [PATCH 4135/4971] Update water-and-jug-problem.py --- Python/water-and-jug-problem.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Python/water-and-jug-problem.py b/Python/water-and-jug-problem.py index b0d1dc743..ca94c3c41 100644 --- a/Python/water-and-jug-problem.py +++ b/Python/water-and-jug-problem.py @@ -23,7 +23,6 @@ # Output: False # Bézout's identity (also called Bézout's lemma) -from fractions import gcd class Solution(object): def canMeasureWater(self, x, y, z): """ @@ -32,7 +31,12 @@ def canMeasureWater(self, x, y, z): :type z: int :rtype: bool """ + def gcd(a, b): + while b: + a, b = b, a%b + return a + # The problem is to solve: - # - check z <= max(x, y) + # - check x + y >= z # - check if there is any (a, b) integers s.t. ax + by = z - return z <= max(x, y) and z % gcd(x, y) == 0 + return z == 0 or ((x + y >= z) and (z % gcd(x, y) == 0)) From c48b194ac268d97e6ddd01f91e423d5d76b7aaa8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 13 Dec 2017 07:23:41 -0600 Subject: [PATCH 4136/4971] Update water-and-jug-problem.py --- Python/water-and-jug-problem.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/water-and-jug-problem.py b/Python/water-and-jug-problem.py index ca94c3c41..b6dcfe954 100644 --- a/Python/water-and-jug-problem.py +++ b/Python/water-and-jug-problem.py @@ -37,6 +37,6 @@ def gcd(a, b): return a # The problem is to solve: - # - check x + y >= z + # - check z <= x + y # - check if there is any (a, b) integers s.t. ax + by = z - return z == 0 or ((x + y >= z) and (z % gcd(x, y) == 0)) + return z == 0 or ((z <= x + y) and (z % gcd(x, y) == 0)) From e0b4a79ee0fb04fa4cdb5d21e9f58c65d25355fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 14 Dec 2017 08:55:25 -0600 Subject: [PATCH 4137/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index deb6edcdb..70c43429a 100644 --- a/README.md +++ b/README.md @@ -367,7 +367,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 335 | [Self Crossing](https://leetcode.com/problems/self-crossing/) | [C++](./C++/self-crossing.cpp) [Python](./Python/self-crossing.py) | _O(n)_ | _O(1)_ | Hard ||| 338 | [Counting Bits](https://leetcode.com/problems/counting-bits/) | [C++](./C++/counting-bits.cpp) [Python](./Python/counting-bits.py) | _O(n)_ | _O(n)_ | Medium ||| 343 | [Integer Break](https://leetcode.com/problems/integer-break/) | [C++](./C++/integer-break.cpp) [Python](./Python/integer-break.py) | _O(logn)_ | _O(1)_ | Medium || Tricky, DP | -365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || `Euclidean Algorithm`, `Bézout's identity` | +365 | [Water and Jug Problem](https://leetcode.com/problems/water-and-jug-problem/) | [C++](./C++/water-and-jug-problem.cpp) [Python](./Python/water-and-jug-problem.py) | _O(logn)_ | _O(1)_ | Medium || `Bézout's identity` | 372 | [Super Pow](https://leetcode.com/problems/super-pow/) | [C++](./C++/super-pow.cpp) [Python](./Python/super-pow.py) | _O(n)_ | _O(1)_ | Medium ||| 382 | [Linked List Random Node](https://leetcode.com/problems/linked-list-random-node/) | [C++](./C++/linked-list-random-node.cpp) [Python](./Python/linked-list-random-node.py) | _O(n)_ | _O(1)_ | Medium || `Reservoir Sampling` | 386 | [Lexicographical Numbers](https://leetcode.com/problems/lexicographical-numbers/) | [C++](./C++/lexicographical-numbers.cpp) [Python](./Python/lexicographical-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| From 4fd836e75cd00f96783dcfbebdfd948ba3515f57 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 15 Dec 2017 09:50:19 -0600 Subject: [PATCH 4138/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 70c43429a..ee46ffbbb 100644 --- a/README.md +++ b/README.md @@ -381,6 +381,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +553 | [Optimal Division](https://leetcode.com/problems/optimal-division/) | [C++](./C++/optimal-division.cpp) [Python](./Python/optimal-division.py) | _O(n)_ | _O(1)_ | Medium ||| 573 | [Squirrel Simulation](https://leetcode.com/problems/squirrel-simulation/) | [C++](./C++/squirrel-simulation.cpp) [Python](./Python/squirrel-simulation.py) | _O(n)_ | _O(1)_ | Medium |📖|| 592 | [Fraction Addition and Subtraction](https://leetcode.com/problems/fraction-addition-and-subtraction/) | [C++](./C++/fraction-addition-and-subtraction.cpp) [Python](./Python/fraction-addition-and-subtraction.py) | _O(nlogx)_ | _O(n)_ | Medium ||| 593 | [Valid Square](https://leetcode.com/problems/valid-square/) | [C++](./C++/valid-square.cpp) [Python](./Python/valid-square.py) | _O(1)_ | _O(1)_ | Medium ||| From be68c61ab9e50185244a11382a40108e3cc3fafe Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Dec 2017 09:55:50 -0600 Subject: [PATCH 4139/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ee46ffbbb..8553cbbba 100644 --- a/README.md +++ b/README.md @@ -648,6 +648,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +552 | [Student Attendance Record II](https://leetcode.com/problems/student-attendance-record-ii/) | [C++](./C++/student-attendance-record-ii.cpp) [Python](./Python/student-attendance-record-ii.py) | _O(n)_ | _O(m)_ | Hard ||| 562 | [Longest Line of Consecutive One in Matrix](https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/) | [C++](./C++/longest-line-of-consecutive-one-in-matrix.cpp) [Python](./Python/longest-line-of-consecutive-one-in-matrix.py) | _O(m * n)_ | _O(n)_ | Medium |📖|| 568 | [Maximum Vacation Days](https://leetcode.com/problems/maximum-vacation-days/) | [C++](./C++/maximum-vacation-days.cpp) [Python](./Python/maximum-vacation-days.py) | _O(n^2 * k)_ | _O(k)_ | Hard |📖|| 576 | [Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths/) | [C++](./C++/out-of-boundary-paths.cpp) [Python](./Python/out-of-boundary-paths.py) | _O(N * m * n)_ | _O(m * n)_ | Medium ||| From 6cc4b4c48207d46011dfecfedbe0ac744302fb88 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 16 Dec 2017 09:56:32 -0600 Subject: [PATCH 4140/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8553cbbba..9e1a608f3 100644 --- a/README.md +++ b/README.md @@ -648,7 +648,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || -552 | [Student Attendance Record II](https://leetcode.com/problems/student-attendance-record-ii/) | [C++](./C++/student-attendance-record-ii.cpp) [Python](./Python/student-attendance-record-ii.py) | _O(n)_ | _O(m)_ | Hard ||| +552 | [Student Attendance Record II](https://leetcode.com/problems/student-attendance-record-ii/) | [C++](./C++/student-attendance-record-ii.cpp) [Python](./Python/student-attendance-record-ii.py) | _O(n)_ | _O(1)_ | Hard ||| 562 | [Longest Line of Consecutive One in Matrix](https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/) | [C++](./C++/longest-line-of-consecutive-one-in-matrix.cpp) [Python](./Python/longest-line-of-consecutive-one-in-matrix.py) | _O(m * n)_ | _O(n)_ | Medium |📖|| 568 | [Maximum Vacation Days](https://leetcode.com/problems/maximum-vacation-days/) | [C++](./C++/maximum-vacation-days.cpp) [Python](./Python/maximum-vacation-days.py) | _O(n^2 * k)_ | _O(k)_ | Hard |📖|| 576 | [Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths/) | [C++](./C++/out-of-boundary-paths.cpp) [Python](./Python/out-of-boundary-paths.py) | _O(N * m * n)_ | _O(m * n)_ | Medium ||| From 592fb5bfe1870c1638819c2aa706c04b98aaed57 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 07:33:33 -0600 Subject: [PATCH 4141/4971] Create min-cost-climbing-stairs.cpp --- C++/min-cost-climbing-stairs.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/min-cost-climbing-stairs.cpp diff --git a/C++/min-cost-climbing-stairs.cpp b/C++/min-cost-climbing-stairs.cpp new file mode 100644 index 000000000..531aba227 --- /dev/null +++ b/C++/min-cost-climbing-stairs.cpp @@ -0,0 +1,15 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + vector dp(3); + for (int i = cost.size() - 1; i >= 0; --i) { + dp[i % 3] = cost[i] + + min(dp[(i + 1) % 3], + dp[(i + 2) % 3]); + } + return min(dp[0], dp[1]); + } +}; From 0ad632b095af0b4034d67ee58dab8d1b2348a4a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 07:35:36 -0600 Subject: [PATCH 4142/4971] Create min-cost-climbing-stairs.py --- Python/min-cost-climbing-stairs.py | 31 ++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/min-cost-climbing-stairs.py diff --git a/Python/min-cost-climbing-stairs.py b/Python/min-cost-climbing-stairs.py new file mode 100644 index 000000000..89c0c3380 --- /dev/null +++ b/Python/min-cost-climbing-stairs.py @@ -0,0 +1,31 @@ +# Time: O(n) +# Space: O(1) + +# On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). +# +# Once you pay the cost, you can either climb one or two steps. +# You need to find minimum cost to reach the top of the floor, +# and you can either start from the step with index 0, or the step with index 1. +# +# Example 1: +# Input: cost = [10, 15, 20] +# Output: 15 +# Explanation: Cheapest is start on cost[1], pay that cost and go to the top. +# Example 2: +# Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] +# Output: 6 +# Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. +# Note: +# - cost will have a length in the range [2, 1000]. +# - Every cost[i] will be an integer in the range [0, 999]. + +class Solution(object): + def minCostClimbingStairs(self, cost): + """ + :type cost: List[int] + :rtype: int + """ + dp = [0] * 3 + for i in reversed(xrange(len(cost))): + dp[i%3] = cost[i] + min(dp[(i+1)%3], dp[(i+2)%3]) + return min(dp[0], dp[1]) From 94baa6664a2db471a72deb2424f348e225533d9e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 07:52:54 -0600 Subject: [PATCH 4143/4971] Create shortest-completing-word.py --- Python/shortest-completing-word.py | 53 ++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/shortest-completing-word.py diff --git a/Python/shortest-completing-word.py b/Python/shortest-completing-word.py new file mode 100644 index 000000000..49c50fe11 --- /dev/null +++ b/Python/shortest-completing-word.py @@ -0,0 +1,53 @@ +# Time: O(n) +# Space: O(1) + +# Find the minimum length word from a given dictionary words, +# which has all the letters from the string licensePlate. +# Such a word is said to complete the given string licensePlate +# +# Here, for letters we ignore case. +# For example, "P" on the licensePlate still matches "p" on the word. +# +# It is guaranteed an answer exists. +# If there are multiple answers, return the one that occurs first in the array. +# +# The license plate might have the same letter occurring multiple times. +# For example, given a licensePlate of "PP", +# the word "pair" does not complete the licensePlate, but the word "supper" does. +# +# Example 1: +# Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"] +# Output: "steps" +# Explanation: The smallest length word that contains the letters "S", "P", "S", and "T". +# Note that the answer is not "step", because the letter "s" must occur in the word twice. +# Also note that we ignored case for the purposes of comparing whether a letter exists in the word. +# Example 2: +# Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"] +# Output: "pest" +# Explanation: There are 3 smallest length words that contains the letters "s". +# We return the one that occurred first. +# Note: +# - licensePlate will be a string with length in range [1, 7]. +# - licensePlate will contain digits, spaces, or letters (uppercase or lowercase). +# - words will have a length in the range [10, 1000]. +# - Every words[i] will consist of lowercase letters, and have length in range [1, 15]. + +class Solution(object): + def shortestCompletingWord(self, licensePlate, words): + """ + :type licensePlate: str + :type words: List[str] + :rtype: str + """ + def contains(counter1, w2): + c2 = collections.Counter(w2.lower()) + c2.subtract(counter1) + return all(map(lambda x: x >= 0, c2.values())) + + result = None + counter = collections.Counter(c.lower() for c in licensePlate if c.isalpha()) + for word in words: + if (result is None or (len(word) < len(result))) and \ + contains(counter, word): + result = word + return result From d43f2725cd82a2e04b58ffcbe2b6ba830a30224d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 08:03:07 -0600 Subject: [PATCH 4144/4971] Create shortest-completing-word.cpp --- C++/shortest-completing-word.cpp | 38 ++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 C++/shortest-completing-word.cpp diff --git a/C++/shortest-completing-word.cpp b/C++/shortest-completing-word.cpp new file mode 100644 index 000000000..0ece33588 --- /dev/null +++ b/C++/shortest-completing-word.cpp @@ -0,0 +1,38 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string shortestCompletingWord(string licensePlate, vector& words) { + string result; + const auto& counter = counts(licensePlate); + for (const auto& word : words) { + if ((result.empty() || word.length() < result.length()) && + contains(counter, word)) { + result = word; + } + } + return result; + } + +private: + bool contains(const vector& counter1, const string& w2) const { + const auto& counter2 = counts(w2); + for (int i = 0; i < counter2.size(); ++i) { + if (counter1[i] > counter2[i]) { + return false; + } + } + return true; + } + + vector counts(const string& s) const { + vector count(26); + for (const auto& c : s) { + if (isalpha(c)) { + ++count[tolower(c) - 'a']; + } + } + return count; + } +}; From 7210c74ff0b9f0f6754ae667f85fbbf2582b45b9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 09:02:12 -0600 Subject: [PATCH 4145/4971] Create number-of-corner-rectangles.cpp --- C++/number-of-corner-rectangles.cpp | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/number-of-corner-rectangles.cpp diff --git a/C++/number-of-corner-rectangles.cpp b/C++/number-of-corner-rectangles.cpp new file mode 100644 index 000000000..7d2b7a2a5 --- /dev/null +++ b/C++/number-of-corner-rectangles.cpp @@ -0,0 +1,32 @@ +// Time: O(m^2 * n), m is the number of rows with 1s, n is the number of cols with 1s +// Space: O(m * n) + +class Solution { +public: + int countCornerRectangles(vector>& grid) { + vector> rows; + for (int i = 0; i < grid.size(); ++i) { + vector row; + for (int j = 0; j < grid[i].size(); ++j) { + if (grid[i][j]) { + row.emplace_back(j); + } + } + if (!row.empty()) { + rows.emplace_back(move(row)); + } + } + int result = 0; + for (int i = 0; i < rows.size(); ++i) { + unordered_set lookup(rows[i].begin(), rows[i].end()); + for (int j = 0; j < i; ++j) { + int count = 0; + for (const auto& c : rows[j]) { + count += lookup.count(c); + } + result += count * (count - 1) / 2; + } + } + return result; + } +}; From 2a7d229c3e60626708d95fc0ac982d521a7d83ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 09:07:27 -0600 Subject: [PATCH 4146/4971] Create number-of-corner-rectangles.py --- Python/number-of-corner-rectangles.py | 50 +++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/number-of-corner-rectangles.py diff --git a/Python/number-of-corner-rectangles.py b/Python/number-of-corner-rectangles.py new file mode 100644 index 000000000..6dbe75bee --- /dev/null +++ b/Python/number-of-corner-rectangles.py @@ -0,0 +1,50 @@ +# Time: O(n * m^2), n is the number of rows with 1s, m is the number of cols with 1s +# Space: O(n * m) + +# Given a grid where each entry is only 0 or 1, find the number of corner rectangles. +# +# A corner rectangle is 4 distinct 1s on the grid that form an axis-aligned rectangle. +# Note that only the corners need to have the value 1. Also, all four 1s used must be distinct. +# +# Example 1: +# Input: grid = +# [[1, 0, 0, 1, 0], +# [0, 0, 1, 0, 1], +# [0, 0, 0, 1, 0], +# [1, 0, 1, 0, 1]] +# Output: 1 +# Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. +# +# Example 2: +# Input: grid = +# [[1, 1, 1], +# [1, 1, 1], +# [1, 1, 1]] +# Output: 9 +# Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle. +# +# Example 3: +# Input: grid = +# [[1, 1, 1, 1]] +# Output: 0 +# Explanation: Rectangles must have four distinct corners. +# Note: +# - The number of rows and columns of grid will each be in the range [1, 200]. +# - Each grid[i][j] will be either 0 or 1. +# - The number of 1s in the grid will be at most 6000. + +class Solution(object): + def countCornerRectangles(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + rows = [[c for c, val in enumerate(row) if val] + for row in grid] + result = 0 + for i in xrange(len(rows)): + lookup = set(rows[i]) + for j in xrange(i): + count = sum(1 for c in rows[j] if c in lookup) + result += count*(count-1)/2 + return result From 632a637f76833cb51205e0af59f61e7349e55cc4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 12:12:24 -0600 Subject: [PATCH 4147/4971] Create contain-virus.cpp --- C++/contain-virus.cpp | 101 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 C++/contain-virus.cpp diff --git a/C++/contain-virus.cpp b/C++/contain-virus.cpp new file mode 100644 index 000000000..e364c2fd3 --- /dev/null +++ b/C++/contain-virus.cpp @@ -0,0 +1,101 @@ +// Time: O((R * C)^(4/3)) +// Space: O(R * C) + +class Solution { +public: + int containVirus(vector>& grid) { + int result = 0; + while (true) { + P_SET lookup; + vector regions, frontiers; + vector perimeters; + for (int r = 0; r < grid.size(); ++r) { + for (int c = 0; c < grid[r].size(); ++c) { + const auto& p = make_pair(r, c); + if (grid[r][c] == 1 && lookup.count(p) == 0) { + regions.emplace_back(); + frontiers.emplace_back(); + perimeters.emplace_back(); + dfs(grid, p, &lookup, ®ions, &frontiers, &perimeters); + } + } + } + if (regions.empty()) { + break; + } + + int triage_idx = 0; + for (int i = 0; i < frontiers.size(); ++i) { + if (frontiers[i].size() > frontiers[triage_idx].size()) { + triage_idx = i; + } + } + for (int i = 0; i < regions.size(); ++i) { + if (i == triage_idx) { + result += perimeters[i]; + for (const auto& p : regions[i]) { + grid[p.first][p.second] = -1; + } + } else { + for (const auto& p : regions[i]) { + for (const auto& d : directions) { + int nr = p.first + d.first; + int nc = p.second + d.second; + if (nr < 0 || nr >= grid.size() || + nc < 0 || nc >= grid[nr].size()) { + continue; + } + if (grid[nr][nc] == 0) { + grid[nr][nc] = 1; + } + } + } + } + } + } + + return result; + } + +private: + template + struct PairHash { + size_t operator()(const pair& p) const { + size_t seed = 0; + seed ^= std::hash{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2); + seed ^= std::hash{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2); + return seed; + } + }; + using P = pair; + using P_SET = unordered_set>; + + void dfs(const vector>& grid, + const P& p, + P_SET *lookup, + vector *regions, + vector *frontiers, + vector *perimeters) { + + if (lookup->count(p)) { + return; + } + lookup->emplace(p); + regions->back().emplace(p); + for (const auto& d : directions) { + int nr = p.first + d.first; + int nc = p.second + d.second; + if (nr < 0 || nr >= grid.size() || + nc < 0 || nc >= grid[nr].size()) { + continue; + } + if (grid[nr][nc] == 1) { + dfs(grid, make_pair(nr, nc), lookup, regions, frontiers, perimeters); + } else if (grid[nr][nc] == 0) { + frontiers->back().emplace(nr, nc); + ++perimeters->back(); + } + } + } + const vector

directions = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; +}; From 45312b84cf2c31d2e1cb4757025894be914cc985 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 12:12:28 -0600 Subject: [PATCH 4148/4971] Create contain-virus.py --- Python/contain-virus.py | 116 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 Python/contain-virus.py diff --git a/Python/contain-virus.py b/Python/contain-virus.py new file mode 100644 index 000000000..fa67c2681 --- /dev/null +++ b/Python/contain-virus.py @@ -0,0 +1,116 @@ +# Time: O((R * C)^(4/3)) +# Space: O(R * C) + +# A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. +# +# The world is modeled as a 2-D array of cells, +# where 0 represents uninfected cells, +# and 1 represents cells contaminated with the virus. +# A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, +# on the shared boundary. +# +# Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. +# Resources are limited. +# Each day, you can install walls around only one region -- +# the affected area (continuous block of infected cells) that +# threatens the most uninfected cells the following night. +# There will never be a tie. +# +# Can you save the day? If so, what is the number of walls required? +# If not, and the world becomes fully infected, return the number of walls used. +# +# Example 1: +# Input: grid = +# [[0,1,0,0,0,0,0,1], +# [0,1,0,0,0,0,0,1], +# [0,0,0,0,0,0,0,1], +# [0,0,0,0,0,0,0,0]] +# Output: 10 +# Explanation: +# There are 2 contaminated regions. +# On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is: +# +# [[0,1,0,0,0,0,1,1], +# [0,1,0,0,0,0,1,1], +# [0,0,0,0,0,0,1,1], +# [0,0,0,0,0,0,0,1]] +# +# On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained. +# +# Example 2: +# Input: grid = +# [[1,1,1], +# [1,0,1], +# [1,1,1]] +# Output: 4 +# Explanation: Even though there is only one cell saved, there are 4 walls built. +# Notice that walls are only built on the shared boundary of two different cells. +# +# Example 3: +# Input: grid = +# [[1,1,1,0,0,0,0,0,0], +# [1,0,1,0,1,1,1,1,1], +# [1,1,1,0,0,0,0,0,0]] +# Output: 13 +# +# Explanation: The region on the left only builds two new walls. +# Note: +# - The number of rows and columns of grid will each be in the range [1, 50]. +# - Each grid[i][j] will be either 0 or 1. +# - Throughout the described process, there is always a contiguous viral region +# that will infect strictly more uncontaminated squares in the next round. + +class Solution(object): + def containVirus(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + directions = [(0, 1), (0, -1), (-1, 0), (1, 0)] + + def dfs(grid, r, c, lookup, regions, frontiers, perimeters): + if (r, c) in lookup: + return + lookup.add((r, c)) + regions[-1].add((r, c)) + for d in directions: + nr, nc = r+d[0], c+d[1] + if not (0 <= nr < len(grid) and \ + 0 <= nc < len(grid[r])): + continue + if grid[nr][nc] == 1: + dfs(grid, nr, nc, lookup, regions, frontiers, perimeters) + elif grid[nr][nc] == 0: + frontiers[-1].add((nr, nc)) + perimeters[-1] += 1 + + result = 0 + while True: + lookup, regions, frontiers, perimeters = set(), [], [], [] + for r, row in enumerate(grid): + for c, val in enumerate(row): + if val == 1 and (r, c) not in lookup: + regions.append(set()) + frontiers.append(set()) + perimeters.append(0) + dfs(grid, r, c, lookup, regions, frontiers, perimeters) + + if not regions: break + + triage_idx = frontiers.index(max(frontiers, key = len)) + for i, region in enumerate(regions): + if i == triage_idx: + result += perimeters[i] + for r, c in region: + grid[r][c] = -1 + else: + for r, c in region: + for d in directions: + nr, nc = r+d[0], c+d[1] + if not (0 <= nr < len(grid) and \ + 0 <= nc < len(grid[r])): + continue + if grid[nr][nc] == 0: + grid[nr][nc] = 1 + + return result From c4942f754d8e353ddb458cec701461183c14b8cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 12:16:50 -0600 Subject: [PATCH 4149/4971] Update contain-virus.cpp --- C++/contain-virus.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/C++/contain-virus.cpp b/C++/contain-virus.cpp index e364c2fd3..f78fdbb67 100644 --- a/C++/contain-virus.cpp +++ b/C++/contain-virus.cpp @@ -36,18 +36,18 @@ class Solution { for (const auto& p : regions[i]) { grid[p.first][p.second] = -1; } - } else { - for (const auto& p : regions[i]) { - for (const auto& d : directions) { - int nr = p.first + d.first; - int nc = p.second + d.second; - if (nr < 0 || nr >= grid.size() || - nc < 0 || nc >= grid[nr].size()) { - continue; - } - if (grid[nr][nc] == 0) { - grid[nr][nc] = 1; - } + continue; + } + for (const auto& p : regions[i]) { + for (const auto& d : directions) { + int nr = p.first + d.first; + int nc = p.second + d.second; + if (nr < 0 || nr >= grid.size() || + nc < 0 || nc >= grid[nr].size()) { + continue; + } + if (grid[nr][nc] == 0) { + grid[nr][nc] = 1; } } } From 330113f1d5f18f3af5c24c35fb81dbfe763d3469 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 12:17:58 -0600 Subject: [PATCH 4150/4971] Update contain-virus.py --- Python/contain-virus.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Python/contain-virus.py b/Python/contain-virus.py index fa67c2681..49736f65e 100644 --- a/Python/contain-virus.py +++ b/Python/contain-virus.py @@ -103,14 +103,14 @@ def dfs(grid, r, c, lookup, regions, frontiers, perimeters): result += perimeters[i] for r, c in region: grid[r][c] = -1 - else: - for r, c in region: - for d in directions: - nr, nc = r+d[0], c+d[1] - if not (0 <= nr < len(grid) and \ - 0 <= nc < len(grid[r])): - continue - if grid[nr][nc] == 0: - grid[nr][nc] = 1 + continue + for r, c in region: + for d in directions: + nr, nc = r+d[0], c+d[1] + if not (0 <= nr < len(grid) and \ + 0 <= nc < len(grid[r])): + continue + if grid[nr][nc] == 0: + grid[nr][nc] = 1 return result From 85b2cdcdac8fbf9c18af3513fcb74c4e9a7a18d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 12:21:41 -0600 Subject: [PATCH 4151/4971] Update contain-virus.py --- Python/contain-virus.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/contain-virus.py b/Python/contain-virus.py index 49736f65e..964edd845 100644 --- a/Python/contain-virus.py +++ b/Python/contain-virus.py @@ -1,4 +1,4 @@ -# Time: O((R * C)^(4/3)) +# Time: O((R * C)^(4/3)), days = O((R * C)^(1/3)) # Space: O(R * C) # A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. From e12e8a85512f000f4bb82040a8f95204fea8a3eb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 17 Dec 2017 12:22:18 -0600 Subject: [PATCH 4152/4971] Update contain-virus.cpp --- C++/contain-virus.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/contain-virus.cpp b/C++/contain-virus.cpp index f78fdbb67..d3c31f496 100644 --- a/C++/contain-virus.cpp +++ b/C++/contain-virus.cpp @@ -1,4 +1,4 @@ -// Time: O((R * C)^(4/3)) +// Time: O((R * C)^(4/3)), days = O((R * C)^(1/3)) // Space: O(R * C) class Solution { From 94aeb955ebd3b4012bc6e6495c80f61918b71c98 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Dec 2017 09:20:02 -0600 Subject: [PATCH 4153/4971] Update contain-virus.cpp --- C++/contain-virus.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/contain-virus.cpp b/C++/contain-virus.cpp index d3c31f496..57d2bc5e5 100644 --- a/C++/contain-virus.cpp +++ b/C++/contain-virus.cpp @@ -1,5 +1,5 @@ -// Time: O((R * C)^(4/3)), days = O((R * C)^(1/3)) -// Space: O(R * C) +// Time: O((m * n)^(4/3)), days = O((m * n)^(1/3)) +// Space: O(m * n) class Solution { public: From 746c7c9c73be6ad24c188a689eb6b2c8cd6f5f8c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Dec 2017 09:20:30 -0600 Subject: [PATCH 4154/4971] Update contain-virus.py --- Python/contain-virus.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/contain-virus.py b/Python/contain-virus.py index 964edd845..abf74ca92 100644 --- a/Python/contain-virus.py +++ b/Python/contain-virus.py @@ -1,5 +1,5 @@ -# Time: O((R * C)^(4/3)), days = O((R * C)^(1/3)) -# Space: O(R * C) +# Time: O((m * n)^(4/3)), days = O((m * n)^(1/3)) +# Space: O(m * n) # A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls. # From 3447d516f8a3fcd47ad8f0ae65129478e2b87e2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Dec 2017 09:24:25 -0600 Subject: [PATCH 4155/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 9e1a608f3..ccd3909ff 100644 --- a/README.md +++ b/README.md @@ -339,6 +339,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 721| [Accounts Merge](https://leetcode.com/problems/accounts-merge/) | [C++](./C++/accounts-merge.cpp) [Python](./Python/accounts-merge.py) | _O(nlogn)_ | _O(n)_| Medium || Union Find 734| [Sentence Similarity](https://leetcode.com/problems/sentence-similarity/) | [C++](./C++/sentence-similarity.cpp) [Python](./Python/sentence-similarity.py) | _O(n + p)_ | _O(p)_| Easy || 737| [Sentence Similarity II](https://leetcode.com/problems/sentence-similarity-ii/) | [C++](./C++/sentence-similarity-ii.cpp) [Python](./Python/sentence-similarity-ii.py) | _O(n + p)_ | _O(p)_| Medium || Union Find +748 | [Shortest Completing Word](https://leetcode.com/problems/shortest-completing-word/) | [C++](./C++/shortest-completing-word.cpp) [Python](./Python/shortest-completing-word.py) | _O(n)_ | _O(1)_ | Easy || ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -564,6 +565,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 695| [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | [C++](./C++/max-area-of-island.cpp) [Python](./Python/max-area-of-island.py) | _O(m * n)_ | _O(m * n)_ | Easy || 711| [Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii/) | [C++](./C++/number-of-distinct-islands-ii.cpp) [Python](./Python/number-of-distinct-islands-ii.py) | _O((m * n) * log(m * n))_ | _O(m * n)_ | Hard |📖| Hash | 733| [Max Area of Island](https://leetcode.com/problems/flood-fill/) | [C++](./C++/flood-fill.cpp) [Python](./Python/flood-fill.py) | _O(m * n)_ | _O(m * n)_ | Easy || +749| [Contain Virus](https://leetcode.com/problems/contain-virus/) | [C++](./C++/contain-virus.cpp) [Python](./Python/contain-virus.py) | _O((m * n)^(4/3))_ | _O(m * n)_ | Hard || Simulation| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -669,6 +671,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 730 | [Count Different Palindromic Subsequences](https://leetcode.com/problems/count-different-palindromic-subsequences/) | [C++](./C++/count-different-palindromic-subsequences.cpp) [Python](./Python/count-different-palindromic-subsequences.py) | _O(n^2)_ | _O(n)_ | Hard || 740 | [Delete and Earn](https://leetcode.com/problems/delete-and-earn/) | [C++](./C++/delete-and-earn.cpp) [Python](./Python/delete-and-earn.py) | _O(n)_ | _O(1)_ | Medium || 741 | [Cherry Pickup](https://leetcode.com/problems/cherry-pickup/) | [C++](./C++/cherry-pickup.cpp) [Python](./Python/cherry-pickup.py) | _O(n^3)_ | _O(n^2)_ | Hard || +746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) | [C++](./C++/min-cost-climbing-stairs.cpp) [Python](./Python/min-cost-climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || +750 | [Number Of Corner Rectangles](https://leetcode.com/problems/number-of-corner-rectangles/) | [C++](./C++/number-of-corner-rectangles.cpp) [Python](./Python/number-of-corner-rectangles.py) | _O(n * m^2)_ | _O(n * m)_ | Medium || ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From ccce8e79733836676fead5d354809bb818592eec Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 19 Dec 2017 09:42:17 -0600 Subject: [PATCH 4156/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ccd3909ff..ee839f966 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | +551 | [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i/) | [C++](./C++/student-attendance-record-i.cpp) [Python](./Python/student-attendance-record-i.py) | _O(n)_ | _O(1)_ | Easy ||| 556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | 557| [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) |[C++](./C++/reverse-words-in-a-string-iii.cpp) [Python](./Python/reverse-words-in-a-string-iii.py) | _O(n)_ | _O(1)_ | Easy | | 564| [Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/) |[C++](./C++/find-the-closest-palindrome.cpp) [Python](./Python/find-the-closest-palindrome.py) | _O(l)_ | _O(l)_ | Hard | | From 339770f751c5ecd1980d84becfe019db79b283ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 20 Dec 2017 09:08:39 -0600 Subject: [PATCH 4157/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ee839f966..ac4e18740 100644 --- a/README.md +++ b/README.md @@ -272,6 +272,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 | +548 | [Split Array with Equal Sum](https://leetcode.com/problems/split-array-with-equal-sum/) | [C++](./C++/split-array-with-equal-sum.cpp) [Python](./Python/split-array-with-equal-sum.py) | _O(n^2)_ | _O(n)_ | Medium |📖| 563 |[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/)| [C++](./C++/binary-tree-tilt.cpp) [Python](./Python/binary-tree-tilt.py)| _O(n)_ | _O(n)_ | Easy | | | 572 |[Subtree of Another Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)| [C++](./C++/subtree-of-another-tree.cpp) [Python](./Python/subtree-of-another-tree.py)| _O(m * n)_ | _O(h)_ | Easy | | | 606 |[Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)| [C++](./C++/construct-string-from-binary-tree.cpp) [Python](./Python/construct-string-from-binary-tree.py)| _O(n)_ | _O(h)_ | Easy | | | From eb6350c806453ff447f8457c5916987206eae854 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Dec 2017 08:21:12 -0600 Subject: [PATCH 4158/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ac4e18740..7c4199197 100644 --- a/README.md +++ b/README.md @@ -560,6 +560,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || 440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn)_ | _O(logn)_ | Hard || 464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || +547| [Friend Circles](https://leetcode.com/problems/friend-circles/) | [C++](./C++/friend-circles.cpp) [Python](./Python/friend-circles.py) | _O(n^2)_ | _O(n)_ | Medium || Union Find | 582| [Kill Process](https://leetcode.com/problems/kill-process/) | [C++](./C++/kill-process.cpp) [Python](./Python/kill-process.py) | _O(n)_ | _O(n)_ | Medium |📖| DFS, BFS | 638| [Shopping Offers](https://leetcode.com/problems/shopping-offers/) | [C++](./C++/shopping-offers.cpp) [Python](./Python/shopping-offers.py) | _O(n * 2^n)_ | _O(n)_ | Medium || 690| [Employee Importance](https://leetcode.com/problems/employee-importance/) | [C++](./C++/employee-importance.cpp) [Python](./Python/employee-importance.py) | _O(n)_ | _O(h)_ | Easy || DFS, BFS From 9102baeba3528a132d8db5c333734ece575c7aaf Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Dec 2017 09:39:06 -0600 Subject: [PATCH 4159/4971] Update median-of-two-sorted-arrays.cpp --- C++/median-of-two-sorted-arrays.cpp | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/C++/median-of-two-sorted-arrays.cpp b/C++/median-of-two-sorted-arrays.cpp index fd47192ae..bc58c8913 100644 --- a/C++/median-of-two-sorted-arrays.cpp +++ b/C++/median-of-two-sorted-arrays.cpp @@ -69,22 +69,15 @@ class Solution_Generic { } } // left xxxxxxxooooooo right, find first xo or oo - while (left + 1 < right) { + while (left <= right) { const auto mid = left + (right - left) / 2; if (match(arrays, mid, k)) { - right = mid; + right = mid - 1; } else { - left = mid; + left = mid + 1; } } - // case: xoo - // ^^ - if (match(arrays, left, k)) { - return left; - } - // case: xo - // ^^ - return right; + return left; } bool match(const vector *>& arrays, int num, int target) { From ad95f0dfa35e382331dfd132fb5cb6fb92fe77a6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Dec 2017 09:41:17 -0600 Subject: [PATCH 4160/4971] 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 bc58c8913..cbe6c46e1 100644 --- a/C++/median-of-two-sorted-arrays.cpp +++ b/C++/median-of-two-sorted-arrays.cpp @@ -71,7 +71,7 @@ class Solution_Generic { // left xxxxxxxooooooo right, find first xo or oo while (left <= right) { const auto mid = left + (right - left) / 2; - if (match(arrays, mid, k)) { + if (!match(arrays, mid, k)) { right = mid - 1; } else { left = mid + 1; @@ -88,6 +88,6 @@ class Solution_Generic { array->cend()); } } - return res < target; + return res >= target; } }; From fb05de165989669d1e1912e1db0264b5bc8291d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Dec 2017 09:54:24 -0600 Subject: [PATCH 4161/4971] 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 cbe6c46e1..bc58c8913 100644 --- a/C++/median-of-two-sorted-arrays.cpp +++ b/C++/median-of-two-sorted-arrays.cpp @@ -71,7 +71,7 @@ class Solution_Generic { // left xxxxxxxooooooo right, find first xo or oo while (left <= right) { const auto mid = left + (right - left) / 2; - if (!match(arrays, mid, k)) { + if (match(arrays, mid, k)) { right = mid - 1; } else { left = mid + 1; @@ -88,6 +88,6 @@ class Solution_Generic { array->cend()); } } - return res >= target; + return res < target; } }; From 0a0d181702b50b069d084850216dc85e7ff935fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Dec 2017 10:05:19 -0600 Subject: [PATCH 4162/4971] 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 ea12f74f3..f09b317d5 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -55,7 +55,7 @@ def binarySearch3(self, compare, nums, target): right = mid else: left = mid - return right + return left if compare(nums[left], target) else right if __name__ == "__main__": From 904c8572f56044fa515de17e84079be8e6b5cd8e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Dec 2017 10:15:54 -0600 Subject: [PATCH 4163/4971] 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 f09b317d5..74bf58ac7 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -55,7 +55,7 @@ def binarySearch3(self, compare, nums, target): right = mid else: left = mid - return left if compare(nums[left], target) else right + return left if left != -1 and compare(nums[left], target) else right if __name__ == "__main__": From dc28ac4be8cc8870ffb54d880f39ac677a804bfe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Dec 2017 10:47:07 -0600 Subject: [PATCH 4164/4971] Update median-of-two-sorted-arrays.cpp --- C++/median-of-two-sorted-arrays.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/median-of-two-sorted-arrays.cpp b/C++/median-of-two-sorted-arrays.cpp index bc58c8913..b0cb5d931 100644 --- a/C++/median-of-two-sorted-arrays.cpp +++ b/C++/median-of-two-sorted-arrays.cpp @@ -25,7 +25,7 @@ class Solution { 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. + // where min left s.t. A[left - 1] >= B[k - 1 - left]. Thus left is the k-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]) { From e6ca74dac84eb32e931263e19cdd590ac57c997d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Dec 2017 10:47:59 -0600 Subject: [PATCH 4165/4971] Update median-of-two-sorted-arrays.cpp --- C++/median-of-two-sorted-arrays.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/median-of-two-sorted-arrays.cpp b/C++/median-of-two-sorted-arrays.cpp index b0cb5d931..1c73550aa 100644 --- a/C++/median-of-two-sorted-arrays.cpp +++ b/C++/median-of-two-sorted-arrays.cpp @@ -25,7 +25,7 @@ class Solution { int left = 0; int right = m; // Find a partition of A and B - // where min left s.t. A[left - 1] >= B[k - 1 - left]. Thus left is the k-th element. + // where min left s.t. A[left - 1] >= B[k - 1 - left]. Thus A[left - 1] is the kth 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]) { From 3cc2f934a9a5f975201178476564766872e92f79 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 21 Dec 2017 10:54:55 -0600 Subject: [PATCH 4166/4971] Update median-of-two-sorted-arrays.cpp --- C++/median-of-two-sorted-arrays.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/median-of-two-sorted-arrays.cpp b/C++/median-of-two-sorted-arrays.cpp index 1c73550aa..d119db59e 100644 --- a/C++/median-of-two-sorted-arrays.cpp +++ b/C++/median-of-two-sorted-arrays.cpp @@ -25,7 +25,7 @@ class Solution { int left = 0; int right = m; // Find a partition of A and B - // where min left s.t. A[left - 1] >= B[k - 1 - left]. Thus A[left - 1] is the kth element. + // where min left s.t. A[left] >= B[k - 1 - left]. Thus A[left] is the (k+1)-th or above 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]) { From 2f9433e2b3deed09f9d5a0d07fef27d2e85fbdcd Mon Sep 17 00:00:00 2001 From: Aven Xiangwen Liu Date: Thu, 21 Dec 2017 13:00:49 -0600 Subject: [PATCH 4167/4971] Update two-sum.py --- Python/two-sum.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/two-sum.py b/Python/two-sum.py index d7f27f0f1..9a1ed7008 100644 --- a/Python/two-sum.py +++ b/Python/two-sum.py @@ -25,7 +25,6 @@ def twoSum(self, nums, target): if target - num in lookup: return [lookup[target - num], i] lookup[num] = i - return [] def twoSum2(self, nums, target): """ From 4c3d01268c7028a8bfb22a9bbb41b6ad248064ad Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 23 Dec 2017 09:29:12 -0600 Subject: [PATCH 4168/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7c4199197..895a5c0bb 100644 --- a/README.md +++ b/README.md @@ -653,6 +653,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +546 | [Remove Boxes](https://leetcode.com/problems/remove-boxes/) | [C++](./C++/remove-boxes.cpp) [Python](./Python/remove-boxes.py) | _O(n^3)_ ~ _O(n^4)_ | _O(n^3)_ | Hard ||| 552 | [Student Attendance Record II](https://leetcode.com/problems/student-attendance-record-ii/) | [C++](./C++/student-attendance-record-ii.cpp) [Python](./Python/student-attendance-record-ii.py) | _O(n)_ | _O(1)_ | Hard ||| 562 | [Longest Line of Consecutive One in Matrix](https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/) | [C++](./C++/longest-line-of-consecutive-one-in-matrix.cpp) [Python](./Python/longest-line-of-consecutive-one-in-matrix.py) | _O(m * n)_ | _O(n)_ | Medium |📖|| 568 | [Maximum Vacation Days](https://leetcode.com/problems/maximum-vacation-days/) | [C++](./C++/maximum-vacation-days.cpp) [Python](./Python/maximum-vacation-days.py) | _O(n^2 * k)_ | _O(k)_ | Hard |📖|| From ee77bd07382d3800db8090e534f51fff7bc197af Mon Sep 17 00:00:00 2001 From: gecong Date: Sat, 23 Dec 2017 11:49:35 -0500 Subject: [PATCH 4169/4971] update difference on versions minor change --- Python/add-two-numbers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/add-two-numbers.py b/Python/add-two-numbers.py index ee93acf4c..11061b81a 100644 --- a/Python/add-two-numbers.py +++ b/Python/add-two-numbers.py @@ -32,7 +32,7 @@ def addTwoNumbers(self, l1, l2): if l2: val += l2.val l2 = l2.next - carry, val = val / 10, val % 10 + carry, val = val / 10, val % 10 # val = val//10 if python 3 current.next = ListNode(val) current = current.next From 0cbcdebbe282c8b84a75b230224f4877f2371218 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 05:50:30 -0600 Subject: [PATCH 4170/4971] Create largest-number-greater-than-twice-of-others.cpp --- ...argest-number-greater-than-twice-of-others.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/largest-number-greater-than-twice-of-others.cpp diff --git a/C++/largest-number-greater-than-twice-of-others.cpp b/C++/largest-number-greater-than-twice-of-others.cpp new file mode 100644 index 000000000..0916f320c --- /dev/null +++ b/C++/largest-number-greater-than-twice-of-others.cpp @@ -0,0 +1,15 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int dominantIndex(vector& nums) { + const auto result = distance(nums.begin(), max_element(nums.begin(),nums.end())); + for (int i = 0; i < nums.size(); ++i) { + if (i != result && 2 * nums[i] > nums[result]) { + return -1; + } + } + return result; + } +}; From 6e84feb49a054702e996c200b09e65882f6168bd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 05:52:51 -0600 Subject: [PATCH 4171/4971] Create largest-number-greater-than-twice-of-others.py --- ...est-number-greater-than-twice-of-others.py | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Python/largest-number-greater-than-twice-of-others.py diff --git a/Python/largest-number-greater-than-twice-of-others.py b/Python/largest-number-greater-than-twice-of-others.py new file mode 100644 index 000000000..e47058e62 --- /dev/null +++ b/Python/largest-number-greater-than-twice-of-others.py @@ -0,0 +1,33 @@ +# Time: O(n) +# Space: O(1) + +# In a given integer array nums, there is always exactly one largest element. +# Find whether the largest element in the array is +# at least twice as much as every other number in the array. +# If it is, return the index of the largest element, otherwise return -1. +# +# Example 1: +# Input: nums = [3, 6, 1, 0] +# Output: 1 +# Explanation: 6 is the largest integer, and for every other number in the array x, +# 6 is more than twice as big as x. The index of value 6 is 1, so we return 1. +# +# Example 2: +# Input: nums = [1, 2, 3, 4] +# Output: -1 +# Explanation: 4 isn't at least as big as twice the value of 3, so we return -1. +# +# Note: +# - nums will have a length in the range [1, 50]. +# - Every nums[i] will be an integer in the range [0, 99]. + +class Solution(object): + def dominantIndex(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + m = max(nums) + if all(m >= 2*x for x in nums if x != m): + return nums.index(m) + return -1 From bd11e8bee9c5a5b8aebb525a804d46a3c217a85d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 07:39:00 -0600 Subject: [PATCH 4172/4971] Create cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/cracking-the-safe.cpp diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp new file mode 100644 index 000000000..91ac57832 --- /dev/null +++ b/C++/cracking-the-safe.cpp @@ -0,0 +1,26 @@ +// Time: O(n *k^n) +// Space: O(n *k^n) + +class Solution { +public: + string crackSafe(int n, int k) { + unordered_set lookup; + string result; + string node(n - 1, '0'); + dfs(k, node, &lookup, &result); + result += string(n - 1, '0'); + return result; + } + +private: + void dfs(int k, const string& node, unordered_set *lookup, string *result) { + for (int i = 0; i < k; ++i) { + const auto& neighbor = node + to_string(i); + if (!lookup->count(neighbor)) { + lookup->emplace(neighbor); + dfs(k, neighbor.substr(1), lookup, result); + result->push_back('0' + i); + } + } + } +}; From 3e97731449027e5ac0d3a047e1b872956feac528 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 08:04:54 -0600 Subject: [PATCH 4173/4971] Create cracking-the-safe.py --- Python/cracking-the-safe.py | 68 +++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Python/cracking-the-safe.py diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py new file mode 100644 index 000000000..34fdb200b --- /dev/null +++ b/Python/cracking-the-safe.py @@ -0,0 +1,68 @@ +# Time: O(k^n) +# Space: O(k^n) + +# There is a box protected by a password. +# The password is n digits, where each letter can be one of the first k digits 0, 1, ..., k-1. +# +# You can keep inputting the password, +# the password will automatically be matched against the last n digits entered. +# +# For example, assuming the password is "345", +# I can open it when I type "012345", but I enter a total of 6 digits. +# +# Please return any string of minimum length that is guaranteed to open the box after the entire string is inputted. +# +# Example 1: +# Input: n = 1, k = 2 +# Output: "01" +# Note: "10" will be accepted too. +# +# Example 2: +# Input: n = 2, k = 2 +# Output: "00110" +# Note: "01100", "10011", "11001" will be accepted too. +# +# Note: +# - n will be in the range [1, 4]. +# - k will be in the range [1, 10]. +# - k^n will be at most 4096. + +# https://en.wikipedia.org/wiki/De_Bruijn_sequence +class Solution(object): + def crackSafe(self, n, k): + """ + :type n: int + :type k: int + :rtype: str + """ + M = k**(n-1) + P = [q*k+i for i in xrange(k) for q in xrange(M)] + result = [] + for i in xrange(k**n): + j = i + while P[j] >= 0: + result.append(str(j//M)) + P[j], j = -1, P[j] + return "".join(result) + "0"*(n-1) + + +# Time: O(n *k^n) +# Space: O(n *k^n) +class Solution2(object): + def crackSafe(self, n, k): + """ + :type n: int + :type k: int + :rtype: str + """ + def dfs(k, node, lookup, result): + for i in xrange(k): + neigbor = node + str(i) + if neigbor not in lookup: + lookup.add(neigbor) + dfs(k, neigbor[1:], lookup, result) + result.append(str(i)) + lookup = set() + result = [] + dfs(k, "0"*(n-1), lookup, result) + return "".join(result) + "0"*(n-1) From e2a070650a3dfc3c03f86bb7ddb4b6de64c1ae68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 08:28:35 -0600 Subject: [PATCH 4174/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index 91ac57832..967d98224 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -1,7 +1,36 @@ -// Time: O(n *k^n) -// Space: O(n *k^n) +// Time: O(k^n) +// Space: O(k^n) +// https://en.wikipedia.org/wiki/De_Bruijn_sequence class Solution { +public: + string crackSafe(int n, int k) { + const int M = pow(k, n - 1); + vector P; + for (int i = 0; i < k; ++i) { + for (int q = 0; q < M; ++q) { + P.emplace_back(q * k + i); + } + } + const int N = pow(k, n); + string result; + for (int i = 0; i < N; ++i) { + int j = i; + while (P[j] >= 0) { + result.push_back('0' + j / M); + auto Pj = P[j]; + P[j] = -1; + j = Pj; + } + } + result += string(n - 1, '0'); + return result; + } +}; + +// Time: O(n *k^n) +// Space: O(n *k^n) +class Solution2 { public: string crackSafe(int n, int k) { unordered_set lookup; From fcb3fff1205ee78482e6814585aae67c9d9d7149 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 09:15:33 -0600 Subject: [PATCH 4175/4971] Create open-the-lock.cpp --- C++/open-the-lock.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/open-the-lock.cpp diff --git a/C++/open-the-lock.cpp b/C++/open-the-lock.cpp new file mode 100644 index 000000000..85cda74fe --- /dev/null +++ b/C++/open-the-lock.cpp @@ -0,0 +1,40 @@ +// Time: O(k * n^k + d), n is the number of alphabets, +// k is the length of target, +// d is the size of deadends +// Space: O(k * n^k + d) + +class Solution { +public: + int openLock(vector& deadends, string target) { + unordered_set dead(deadends.begin(), deadends.end()); + vector q{"0000"}; + unordered_set lookup{"0000"}; + int depth = 0; + while (!q.empty()) { + vector next_q; + for (const auto& node : q) { + if (node == target) { + return depth; + } + if (dead.count(node)) { + continue; + } + for (int i = 0; i < 4; ++i) { + auto n = node[i] - '0'; + for (const auto& d : {-1, 1}) { + auto nn = (n + d + 10) % 10; + auto neighbor = node; + neighbor[i] = '0' + nn; + if (!lookup.count(neighbor)) { + lookup.emplace(neighbor); + next_q.emplace_back(neighbor); + } + } + } + } + swap(q, next_q); + ++depth; + } + return -1; + } +}; From b1683188d616d3762a915704d39db367c769254b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 09:15:37 -0600 Subject: [PATCH 4176/4971] Create open-the-lock.py --- Python/open-the-lock.py | 77 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Python/open-the-lock.py diff --git a/Python/open-the-lock.py b/Python/open-the-lock.py new file mode 100644 index 000000000..99c9c25b5 --- /dev/null +++ b/Python/open-the-lock.py @@ -0,0 +1,77 @@ +# Time: O(k * n^k + d), n is the number of alphabets, +# k is the length of target, +# d is the size of deadends +# Space: O(k * n^k + d) + +# You have a lock in front of you with 4 circular wheels. +# Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. +# The wheels can rotate freely and wrap around: +# for example we can turn '9' to be '0', or '0' to be '9'. +# Each move consists of turning one wheel one slot. +# +# The lock initially starts at '0000', a string representing the state of the 4 wheels. +# +# You are given a list of deadends dead ends, +# meaning if the lock displays any of these codes, +# the wheels of the lock will stop turning and you will be unable to open it. +# +# Given a target representing the value of the wheels that will unlock the lock, +# return the minimum total number of turns required to open the lock, or -1 if it is impossible. +# +# Example 1: +# Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" +# Output: 6 +# Explanation: +# A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". +# Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, +# because the wheels of the lock become stuck after the display becomes the dead end "0102". +# +# Example 2: +# Input: deadends = ["8888"], target = "0009" +# Output: 1 +# Explanation: +# We can turn the last wheel in reverse to move from "0000" -> "0009". +# +# Example 3: +# Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" +# Output: -1 +# Explanation: +# We can't reach the target without getting stuck. +# +# Example 4: +# Input: deadends = ["0000"], target = "8888" +# Output: -1 +# +# Note: +# - The length of deadends will be in the range [1, 500]. +# - target will not be in the list deadends. +# - Every string in deadends and the string target will be a string of 4 digits +# from the 10,000 possibilities '0000' to '9999'. + +class Solution(object): + def openLock(self, deadends, target): + """ + :type deadends: List[str] + :type target: str + :rtype: int + """ + dead = set(deadends) + q = ["0000"] + lookup = {"0000"} + depth = 0 + while q: + next_q = [] + for node in q: + if node == target: return depth + if node in dead: continue + for i in xrange(4): + n = int(node[i]) + for d in (-1, 1): + nn = (n+d) % 10 + neighbor = node[:i] + str(nn) + node[i+1:] + if neighbor not in lookup: + lookup.add(neighbor) + next_q.append(neighbor) + q, next_q = next_q, [] + depth += 1 + return -1 From 8b24e45bd42b2bfe7ff069698c17ac0a5fa82856 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 10:01:46 -0600 Subject: [PATCH 4177/4971] Create ip-to-cidr.cpp --- C++/ip-to-cidr.cpp | 60 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 C++/ip-to-cidr.cpp diff --git a/C++/ip-to-cidr.cpp b/C++/ip-to-cidr.cpp new file mode 100644 index 000000000..baa111fbc --- /dev/null +++ b/C++/ip-to-cidr.cpp @@ -0,0 +1,60 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector ipToCIDR(string ip, int range) { + auto start = ipToInt(ip); + vector result; + while (range > 0) { + auto mask = max(33 - bitLength(start & ~(start - 1)), + 33 - bitLength(range)); + result.emplace_back(intToIP(start) + "/" + to_string(mask)); + start += 1 << (32 - mask); + range -= 1 << (32 - mask); + } + return result; + } + +private: + uint32_t ipToInt(const string& ip) { + uint32_t result = 0; + for (const auto& n : split(ip, '.')) { + result = 256 * result + stoi(n); + } + return result; + } + + string intToIP(uint32_t n) { + string ip; + for (const auto& i : {24, 16, 8, 0}) { + ip += to_string((n >> i) % 256); + ip += "."; + } + ip.pop_back(); + return ip; + } + + vector split(const string& s, const char delim) { + vector tokens; + stringstream ss(s); + string token; + while (getline(ss, token, delim)) { + tokens.emplace_back(token); + } + return tokens; + } + + uint32_t bitLength(uint32_t n) { + uint32_t left = 1, right = 32; + while (left <= right) { + auto mid = left + (right - left) / 2; + if ((1 << mid) > n) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } +}; From 6457f51c5a000b6781f4ae2201f67cee1c82ffe7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 10:05:22 -0600 Subject: [PATCH 4178/4971] Create ip-to-cidr.py --- Python/ip-to-cidr.py | 74 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Python/ip-to-cidr.py diff --git a/Python/ip-to-cidr.py b/Python/ip-to-cidr.py new file mode 100644 index 000000000..3c4bb3b6f --- /dev/null +++ b/Python/ip-to-cidr.py @@ -0,0 +1,74 @@ +# Time: O(n) +# Space: O(1) + +# Given a start IP address ip and a number of ips we need to cover n, +# return a representation of the range as a list (of smallest possible length) of CIDR blocks. +# +# A CIDR block is a string consisting of an IP, followed by a slash, +# and then the prefix length. For example: "123.45.67.89/20". +# That prefix length "20" represents the number of common prefix bits in the specified range. +# +# Example 1: +# Input: ip = "255.0.0.7", n = 10 +# Output: ["255.0.0.7/32","255.0.0.8/29","255.0.0.16/32"] +# Explanation: +# The initial ip address, when converted to binary, looks like this (spaces added for clarity): +# 255.0.0.7 -> 11111111 00000000 00000000 00000111 +# The address "255.0.0.7/32" specifies all addresses with a common prefix of 32 bits to the given address, +# ie. just this one address. +# +# The address "255.0.0.8/29" specifies all addresses with a common prefix of 29 bits to the given address: +# 255.0.0.8 -> 11111111 00000000 00000000 00001000 +# Addresses with common prefix of 29 bits are: +# 11111111 00000000 00000000 00001000 +# 11111111 00000000 00000000 00001001 +# 11111111 00000000 00000000 00001010 +# 11111111 00000000 00000000 00001011 +# 11111111 00000000 00000000 00001100 +# 11111111 00000000 00000000 00001101 +# 11111111 00000000 00000000 00001110 +# 11111111 00000000 00000000 00001111 +# +# The address "255.0.0.16/32" specifies all addresses with a common prefix of 32 bits to the given address, +# ie. just 11111111 00000000 00000000 00010000. +# +# In total, the answer specifies the range of 10 ips starting with the address 255.0.0.7 . +# +# There were other representations, such as: +# ["255.0.0.7/32","255.0.0.8/30", "255.0.0.12/30", "255.0.0.16/32"], +# but our answer was the shortest possible. +# +# Also note that a representation beginning with say, "255.0.0.7/30" would be incorrect, +# because it includes addresses like 255.0.0.4 = 11111111 00000000 00000000 00000100 +# that are outside the specified range. +# Note: +# - ip will be a valid IPv4 address. +# - Every implied address ip + x (for x < n) will be a valid IPv4 address. +# - n will be an integer in the range [1, 1000]. + +class Solution(object): + def ipToCIDR(self, ip, n): + """ + :type ip: str + :type n: int + :rtype: List[str] + """ + def ipToInt(ip): + result = 0 + for i in ip.split('.'): + result = 256 * result + int(i) + return result + + def intToIP(n): + return ".".join(str((n >> i) % 256) \ + for i in (24, 16, 8, 0)) + + start = ipToInt(ip) + result = [] + while n: + mask = max(33-(start & ~(start-1)).bit_length(), \ + 33-n.bit_length()) + result.append(intToIP(start) + '/' + str(mask)) + start += 1 << (32-mask) + n -= 1 << (32-mask) + return result From c217f2073689b3a19d8c45d004806ef89c636b18 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 11:45:12 -0600 Subject: [PATCH 4179/4971] Update cracking-the-safe.py --- Python/cracking-the-safe.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index 34fdb200b..46f0a09a0 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -57,10 +57,10 @@ def crackSafe(self, n, k): """ def dfs(k, node, lookup, result): for i in xrange(k): - neigbor = node + str(i) - if neigbor not in lookup: - lookup.add(neigbor) - dfs(k, neigbor[1:], lookup, result) + neighbor = node + str(i) + if neighbor not in lookup: + lookup.add(neighbor) + dfs(k, neighbor[1:], lookup, result) result.append(str(i)) lookup = set() result = [] From 0a0a52075d248bd8c77b2f58cd7df963df6baa75 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 11:45:40 -0600 Subject: [PATCH 4180/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index 967d98224..dad099ce7 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -31,6 +31,31 @@ class Solution { // Time: O(n *k^n) // Space: O(n *k^n) class Solution2 { +public: + string crackSafe(int n, int k) { + string result(n, '0'); + unordered_set lookup; + lookup.emplace(result); + int total = pow(k, n); + while (lookup.size() < total) { + auto node = result.substr(result.length() - n + 1); + for (int i = k - 1; i >= 0; --i) { + auto neighbor = node; + neighbor.push_back('0' + i); + if (!lookup.count(neighbor)) { + lookup.emplace(neighbor); + result.push_back('0' + i); + break; + } + } + } + return result; + } +}; + +// Time: O(n *k^n) +// Space: O(n *k^n) +class Solution3 { public: string crackSafe(int n, int k) { unordered_set lookup; From f713b4e0ba83dac008c83bd80df49d6ec8944441 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 11:46:16 -0600 Subject: [PATCH 4181/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index dad099ce7..a7add9161 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -28,8 +28,8 @@ class Solution { } }; -// Time: O(n *k^n) -// Space: O(n *k^n) +// Time: O(n * k^n) +// Space: O(n * k^n) class Solution2 { public: string crackSafe(int n, int k) { @@ -53,8 +53,8 @@ class Solution2 { } }; -// Time: O(n *k^n) -// Space: O(n *k^n) +// Time: O(n * k^n) +// Space: O(n * k^n) class Solution3 { public: string crackSafe(int n, int k) { From 59a8cffb02e24b2c41d6067bd09db0b210a4488b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 11:48:09 -0600 Subject: [PATCH 4182/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index a7add9161..ce0219e21 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -33,13 +33,13 @@ class Solution { class Solution2 { public: string crackSafe(int n, int k) { - string result(n, '0'); + string result(n, '0' + k - 1); unordered_set lookup; lookup.emplace(result); int total = pow(k, n); while (lookup.size() < total) { auto node = result.substr(result.length() - n + 1); - for (int i = k - 1; i >= 0; --i) { + for (int i = 0; i < k; ++i) { auto neighbor = node; neighbor.push_back('0' + i); if (!lookup.count(neighbor)) { From 28cce5c24171a36201e791dd1818ecb51babe622 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 11:58:24 -0600 Subject: [PATCH 4183/4971] Update cracking-the-safe.py --- Python/cracking-the-safe.py | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index 46f0a09a0..3c49602a6 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -46,9 +46,32 @@ def crackSafe(self, n, k): return "".join(result) + "0"*(n-1) -# Time: O(n *k^n) -# Space: O(n *k^n) +# Time: O(n * k^n) +# Space: O(n * k^n) class Solution2(object): + def crackSafe(self, n, k): + """ + :type n: int + :type k: int + :rtype: str + """ + result = [str(k-1)]*n + lookup = {"".join(result)} + total = k**n + while len(lookup) < total: + node = result[len(result)-n+1:] + for i in xrange(k): + neighbor = "".join(node) + str(i) + if neighbor not in lookup: + lookup.add(neighbor) + result.append(str(i)) + break + return "".join(result) + + +# Time: O(n * k^n) +# Space: O(n * k^n) +class Solution3(object): def crackSafe(self, n, k): """ :type n: int From 7175c03c1463d4ca2dee107af6b727dad9eff171 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 12:03:15 -0600 Subject: [PATCH 4184/4971] Update cracking-the-safe.py --- Python/cracking-the-safe.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index 3c49602a6..ca6168ab0 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -83,9 +83,10 @@ def dfs(k, node, lookup, result): neighbor = node + str(i) if neighbor not in lookup: lookup.add(neighbor) - dfs(k, neighbor[1:], lookup, result) result.append(str(i)) + dfs(k, neighbor[1:], lookup, result) + lookup = set() result = [] - dfs(k, "0"*(n-1), lookup, result) - return "".join(result) + "0"*(n-1) + dfs(k, str(k-1)*(n-1), lookup, result) + return str(k-1)*(n-1) + "".join(result) From 18ca30315059474fed44353ce109056c6fa4e7d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 12:05:32 -0600 Subject: [PATCH 4185/4971] Update cracking-the-safe.py --- Python/cracking-the-safe.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index ca6168ab0..9be10d073 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -87,6 +87,6 @@ def dfs(k, node, lookup, result): dfs(k, neighbor[1:], lookup, result) lookup = set() - result = [] + result = [str(k-1)]*(n-1) dfs(k, str(k-1)*(n-1), lookup, result) - return str(k-1)*(n-1) + "".join(result) + return "".join(result) From b9c4a2e2b8f7f65a2726ca873de0667e83d494e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 12:08:09 -0600 Subject: [PATCH 4186/4971] Update cracking-the-safe.py --- Python/cracking-the-safe.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index 9be10d073..ba798a26d 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -88,5 +88,5 @@ def dfs(k, node, lookup, result): lookup = set() result = [str(k-1)]*(n-1) - dfs(k, str(k-1)*(n-1), lookup, result) + dfs(k, "".join(result), lookup, result) return "".join(result) From bb91441c8e658883d0c7f4be504b181fe089f96d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 12:09:07 -0600 Subject: [PATCH 4187/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index ce0219e21..61d159023 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -59,10 +59,9 @@ class Solution3 { public: string crackSafe(int n, int k) { unordered_set lookup; - string result; - string node(n - 1, '0'); + string result(n - 1, '0' + k - 1); + auto node = result; dfs(k, node, &lookup, &result); - result += string(n - 1, '0'); return result; } @@ -72,8 +71,8 @@ class Solution3 { const auto& neighbor = node + to_string(i); if (!lookup->count(neighbor)) { lookup->emplace(neighbor); - dfs(k, neighbor.substr(1), lookup, result); result->push_back('0' + i); + dfs(k, neighbor.substr(1), lookup, result); } } } From e56eea07ead6d17fa02d8984348a00bae138bcc9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 12:13:21 -0600 Subject: [PATCH 4188/4971] Update cracking-the-safe.py --- Python/cracking-the-safe.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index ba798a26d..307ef140a 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -37,13 +37,13 @@ def crackSafe(self, n, k): """ M = k**(n-1) P = [q*k+i for i in xrange(k) for q in xrange(M)] - result = [] + result = [str(k-1)]*(n-1) for i in xrange(k**n): j = i while P[j] >= 0: result.append(str(j//M)) P[j], j = -1, P[j] - return "".join(result) + "0"*(n-1) + return "".join(result) # Time: O(n * k^n) @@ -86,7 +86,7 @@ def dfs(k, node, lookup, result): result.append(str(i)) dfs(k, neighbor[1:], lookup, result) - lookup = set() result = [str(k-1)]*(n-1) + lookup = set() dfs(k, "".join(result), lookup, result) return "".join(result) From 1be6c07ac277a1ba29d06eab566877585ad73ca2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 12:14:42 -0600 Subject: [PATCH 4189/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index 61d159023..712a87c87 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -13,7 +13,7 @@ class Solution { } } const int N = pow(k, n); - string result; + string result(n - 1, '0' + k - 1); for (int i = 0; i < N; ++i) { int j = i; while (P[j] >= 0) { @@ -23,7 +23,6 @@ class Solution { j = Pj; } } - result += string(n - 1, '0'); return result; } }; From 2763f3e5399b6e7d959135cf4c61f6759372384e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Dec 2017 12:25:54 -0600 Subject: [PATCH 4190/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index 712a87c87..53de1c224 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -12,9 +12,9 @@ class Solution { P.emplace_back(q * k + i); } } - const int N = pow(k, n); + const int total = pow(k, n); string result(n - 1, '0' + k - 1); - for (int i = 0; i < N; ++i) { + for (int i = 0; i < total; ++i) { int j = i; while (P[j] >= 0) { result.push_back('0' + j / M); @@ -35,7 +35,7 @@ class Solution2 { string result(n, '0' + k - 1); unordered_set lookup; lookup.emplace(result); - int total = pow(k, n); + const int total = pow(k, n); while (lookup.size() < total) { auto node = result.substr(result.length() - n + 1); for (int i = 0; i < k; ++i) { From 588e8747c0cb3223425f53ec73db0b67bd1d09d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 00:34:55 -0600 Subject: [PATCH 4191/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index 53de1c224..4c025dc71 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -72,6 +72,7 @@ class Solution3 { lookup->emplace(neighbor); result->push_back('0' + i); dfs(k, neighbor.substr(1), lookup, result); + break; } } } From 5d74867f2044eba94fccdb75608dd99648da53af Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 00:35:18 -0600 Subject: [PATCH 4192/4971] Update cracking-the-safe.py --- Python/cracking-the-safe.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index 307ef140a..07d9f86a3 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -85,6 +85,7 @@ def dfs(k, node, lookup, result): lookup.add(neighbor) result.append(str(i)) dfs(k, neighbor[1:], lookup, result) + break result = [str(k-1)]*(n-1) lookup = set() From bc30b8e564457d5013f8e437fe3e7158870b74be Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 03:59:58 -0600 Subject: [PATCH 4193/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index 4c025dc71..6a44b2346 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -40,10 +40,10 @@ class Solution2 { auto node = result.substr(result.length() - n + 1); for (int i = 0; i < k; ++i) { auto neighbor = node; - neighbor.push_back('0' + i); + neighbor.push_back('0' + i); if (!lookup.count(neighbor)) { lookup.emplace(neighbor); - result.push_back('0' + i); + result.push_back('0' + i); break; } } From e6f1675e72e768d2e656cbcac37e24a686bdfcb0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 04:01:43 -0600 Subject: [PATCH 4194/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index 6a44b2346..b56788ff5 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -39,8 +39,7 @@ class Solution2 { while (lookup.size() < total) { auto node = result.substr(result.length() - n + 1); for (int i = 0; i < k; ++i) { - auto neighbor = node; - neighbor.push_back('0' + i); + const auto& neighbor = node + to_string(i); if (!lookup.count(neighbor)) { lookup.emplace(neighbor); result.push_back('0' + i); From 0766e60141b3bd91cf4f43643f1b45a850e3b960 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 04:03:53 -0600 Subject: [PATCH 4195/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index b56788ff5..c96e1d63b 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -37,7 +37,7 @@ class Solution2 { lookup.emplace(result); const int total = pow(k, n); while (lookup.size() < total) { - auto node = result.substr(result.length() - n + 1); + const auto& node = result.substr(result.length() - n + 1); for (int i = 0; i < k; ++i) { const auto& neighbor = node + to_string(i); if (!lookup.count(neighbor)) { From b0bfca6b6f8b10be82b8d84bcc5b25049a000e5f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 04:15:17 -0600 Subject: [PATCH 4196/4971] Update cracking-the-safe.py --- Python/cracking-the-safe.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index 07d9f86a3..400f8a038 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -36,7 +36,7 @@ def crackSafe(self, n, k): :rtype: str """ M = k**(n-1) - P = [q*k+i for i in xrange(k) for q in xrange(M)] + P = [q*k+i for i in xrange(k) for q in xrange(M)] # rotate: i*k^(n-1) + q => q*k + i result = [str(k-1)]*(n-1) for i in xrange(k**n): j = i From ba2201342b5bf3847404ee682759907db99d316f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 04:16:10 -0600 Subject: [PATCH 4197/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index c96e1d63b..e016ac34f 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -9,7 +9,7 @@ class Solution { vector P; for (int i = 0; i < k; ++i) { for (int q = 0; q < M; ++q) { - P.emplace_back(q * k + i); + P.emplace_back(q * k + i); // rotate: i*k^(n-1) + q => q*k + i } } const int total = pow(k, n); From ddbd604fdecd3adf86e87a27a667d6a98013b949 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 07:59:29 -0600 Subject: [PATCH 4198/4971] Update cracking-the-safe.py --- Python/cracking-the-safe.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index 400f8a038..79c8a2115 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -40,6 +40,7 @@ def crackSafe(self, n, k): result = [str(k-1)]*(n-1) for i in xrange(k**n): j = i + # concatenation in lexicographic order of Lyndon words while P[j] >= 0: result.append(str(j//M)) P[j], j = -1, P[j] From d219c441be09076ef90b4a685364763685177bbf Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 08:01:10 -0600 Subject: [PATCH 4199/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index e016ac34f..4152ec4da 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -16,6 +16,7 @@ class Solution { string result(n - 1, '0' + k - 1); for (int i = 0; i < total; ++i) { int j = i; + // concatenation in lexicographic order of Lyndon words while (P[j] >= 0) { result.push_back('0' + j / M); auto Pj = P[j]; From 9b32636f8e0b4357a16e34b47302aa1750fd515a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 08:13:47 -0600 Subject: [PATCH 4200/4971] Update cracking-the-safe.cpp --- C++/cracking-the-safe.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/cracking-the-safe.cpp b/C++/cracking-the-safe.cpp index 4152ec4da..93dbe4fcb 100644 --- a/C++/cracking-the-safe.cpp +++ b/C++/cracking-the-safe.cpp @@ -2,6 +2,7 @@ // Space: O(k^n) // https://en.wikipedia.org/wiki/De_Bruijn_sequence +// https://en.wikipedia.org/wiki/Lyndon_word class Solution { public: string crackSafe(int n, int k) { From a132822be4cfaa2cdc7601dd212ebe840b194c02 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 08:14:21 -0600 Subject: [PATCH 4201/4971] Update cracking-the-safe.py --- Python/cracking-the-safe.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index 79c8a2115..916fc26fc 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -28,6 +28,7 @@ # - k^n will be at most 4096. # https://en.wikipedia.org/wiki/De_Bruijn_sequence +# https://en.wikipedia.org/wiki/Lyndon_word class Solution(object): def crackSafe(self, n, k): """ From 294309569ff0314a92887423a33e08302b3f4842 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 08:24:15 -0600 Subject: [PATCH 4202/4971] Update README.md --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 895a5c0bb..abf3e4974 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 729 | [My Calendar I](https://leetcode.com/problems/my-calendar-i/) | [C++](./C++/my-calendar-i.cpp) [Python](./Python/my-calendar-i.py) | _O(nlogn)_ | _O(n)_ | Medium || 731 | [My Calendar II](https://leetcode.com/problems/my-calendar-ii/) | [C++](./C++/my-calendar-ii.cpp) [Python](./Python/my-calendar-ii.py) | _O(n^2)_ | _O(n)_ | Medium || 732 | [My Calendar III](https://leetcode.com/problems/my-calendar-iii/) | [C++](./C++/my-calendar-iii.cpp) [Python](./Python/my-calendar-iii.py) | _O(n^2)_ | _O(n)_ | Hard || - +747 | [Largest Number Greater Than Twice of Others](https://leetcode.com/problems/largest-number-greater-than-twice-of-others/) | [C++](./C++/largest-number-greater-than-twice-of-others.cpp) [Python](./Python/largest-number-greater-than-twice-of-others.py) | _O(n)_ | _O(1)_ | Easy || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -185,6 +185,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 696| [Count Binary Substrings](https://leetcode.com/problems/count-binary-substrings/) | [C++](./C++/count-binary-substrings.cpp) [Python](./Python/count-binary-substrings.py) | _O(n)_ | _O(1)_ | Easy|| 720| [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/) | [C++](./C++/longest-word-in-dictionary.cpp) [Python](./Python/longest-word-in-dictionary.py) | _O(n)_ | _O(t)_ | Easy || Trie | 722| [Remove Comments](https://leetcode.com/problems/remove-comments/) | [C++](./C++/remove-comments.cpp) [Python](./Python/remove-comments.py) | _O(n)_ | _O(k)_ | Medium ||| +751| [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) | [C++](./C++/ip-to-cidr.cpp) [Python](./Python/ip-to-cidr.py) | _O(n)_ | _O(1)_ | Medium ||| ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -537,6 +538,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | 742|[Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree/)| [C++](./C++/closest-leaf-in-a-binary-tree.cpp) [Python](./Python/closest-leaf-in-a-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | | | 743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O(\|E\| + \|V\|log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | +752|[Open the Lock](https://leetcode.com/problems/open-the-lock/)| [C++](./C++/open-the-lock.cpp) [Python](./Python/open-the-lock.py)| _O(k * n^k + d)_ | _O(k * n^k + d)_ | Medium | | | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -569,6 +571,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 711| [Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii/) | [C++](./C++/number-of-distinct-islands-ii.cpp) [Python](./Python/number-of-distinct-islands-ii.py) | _O((m * n) * log(m * n))_ | _O(m * n)_ | Hard |📖| Hash | 733| [Max Area of Island](https://leetcode.com/problems/flood-fill/) | [C++](./C++/flood-fill.cpp) [Python](./Python/flood-fill.py) | _O(m * n)_ | _O(m * n)_ | Easy || 749| [Contain Virus](https://leetcode.com/problems/contain-virus/) | [C++](./C++/contain-virus.cpp) [Python](./Python/contain-virus.py) | _O((m * n)^(4/3))_ | _O(m * n)_ | Hard || Simulation| +753| [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [C++](./C++/cracking-the-safe.cpp) [Python](./Python/cracking-the-safe.py) | _O(k^n)_ | _O(k^n)_ | Hard || `de Bruijn sequences`, `Lydon Words` | ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 55adbdce7bc7214ea7459dfd879540242901ffae Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 08:24:44 -0600 Subject: [PATCH 4203/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index abf3e4974..38f4eb79b 100644 --- a/README.md +++ b/README.md @@ -571,7 +571,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 711| [Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii/) | [C++](./C++/number-of-distinct-islands-ii.cpp) [Python](./Python/number-of-distinct-islands-ii.py) | _O((m * n) * log(m * n))_ | _O(m * n)_ | Hard |📖| Hash | 733| [Max Area of Island](https://leetcode.com/problems/flood-fill/) | [C++](./C++/flood-fill.cpp) [Python](./Python/flood-fill.py) | _O(m * n)_ | _O(m * n)_ | Easy || 749| [Contain Virus](https://leetcode.com/problems/contain-virus/) | [C++](./C++/contain-virus.cpp) [Python](./Python/contain-virus.py) | _O((m * n)^(4/3))_ | _O(m * n)_ | Hard || Simulation| -753| [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [C++](./C++/cracking-the-safe.cpp) [Python](./Python/cracking-the-safe.py) | _O(k^n)_ | _O(k^n)_ | Hard || `de Bruijn sequences`, `Lydon Words` | +753| [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [C++](./C++/cracking-the-safe.cpp) [Python](./Python/cracking-the-safe.py) | _O(k^n)_ | _O(k^n)_ | Hard || `de Bruijn sequences`, `Lyndon Words` | ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 557ae5699da89b3a3f0d14e7767c83749b5a414c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 25 Dec 2017 08:25:06 -0600 Subject: [PATCH 4204/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 38f4eb79b..e1c273458 100644 --- a/README.md +++ b/README.md @@ -571,7 +571,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 711| [Number of Distinct Islands II](https://leetcode.com/problems/number-of-distinct-islands-ii/) | [C++](./C++/number-of-distinct-islands-ii.cpp) [Python](./Python/number-of-distinct-islands-ii.py) | _O((m * n) * log(m * n))_ | _O(m * n)_ | Hard |📖| Hash | 733| [Max Area of Island](https://leetcode.com/problems/flood-fill/) | [C++](./C++/flood-fill.cpp) [Python](./Python/flood-fill.py) | _O(m * n)_ | _O(m * n)_ | Easy || 749| [Contain Virus](https://leetcode.com/problems/contain-virus/) | [C++](./C++/contain-virus.cpp) [Python](./Python/contain-virus.py) | _O((m * n)^(4/3))_ | _O(m * n)_ | Hard || Simulation| -753| [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [C++](./C++/cracking-the-safe.cpp) [Python](./Python/cracking-the-safe.py) | _O(k^n)_ | _O(k^n)_ | Hard || `de Bruijn sequences`, `Lyndon Words` | +753| [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [C++](./C++/cracking-the-safe.cpp) [Python](./Python/cracking-the-safe.py) | _O(k^n)_ | _O(k^n)_ | Hard || `de Bruijn sequences`, `Lyndon word` | ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 8a81f0162df6a82ba582707721763ab25e8894d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 26 Dec 2017 09:36:00 -0600 Subject: [PATCH 4205/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index e1c273458..5e6c5f9eb 100644 --- a/README.md +++ b/README.md @@ -273,6 +273,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 | +545 | [Boundary of Binary Tree](https://leetcode.com/problems/boundary-of-binary-tree/) | [C++](./C++/boundary-of-binary-tree.cpp) [Python](./Python/boundary-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium |📖| 548 | [Split Array with Equal Sum](https://leetcode.com/problems/split-array-with-equal-sum/) | [C++](./C++/split-array-with-equal-sum.cpp) [Python](./Python/split-array-with-equal-sum.py) | _O(n^2)_ | _O(n)_ | Medium |📖| 563 |[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/)| [C++](./C++/binary-tree-tilt.cpp) [Python](./Python/binary-tree-tilt.py)| _O(n)_ | _O(n)_ | Easy | | | 572 |[Subtree of Another Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)| [C++](./C++/subtree-of-another-tree.cpp) [Python](./Python/subtree-of-another-tree.py)| _O(m * n)_ | _O(h)_ | Easy | | | From fef3de550767bf5c33ee218be7acc08ac42e84bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 27 Dec 2017 23:25:38 +0800 Subject: [PATCH 4206/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5e6c5f9eb..9ed8d6a80 100644 --- a/README.md +++ b/README.md @@ -470,6 +470,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 395| [Longest Substring with At Least K Repeating Characters](https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/) | [C++](./C++/longest-substring-with-at-least-k-repeating-characters.cpp) [Python](./Python/longest-substring-with-at-least-k-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 404| [Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./C++/sum-of-left-leaves.cpp) [Python](./Python/sum-of-left-leaves.py) | _O(n)_ | _O(h)_ | Easy || 437| [Path Sum III](https://leetcode.com/problems/path-sum-iii/) | [C++](./C++/path-sum-iii.cpp) [Python](./Python/path-sum-iii.py) | _O(n)_ | _O(h)_ | Easy || +544| [Output Contest Matches](https://leetcode.com/problems/output-contest-matches/) | [C++](./C++/output-contest-matches.cpp) [Python](./Python/output-contest-matches.py) | _O(n)_ | _O(n)_ | Medium || 549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| 669| [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C++](./C++/trim-a-binary-search-tree.cpp) [Python](./Python/trim-a-binary-search-tree.py) | _O(n)_ | _O(h)_ | Easy || 671| [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [C++](./C++/second-minimum-node-in-a-binary-tree.cpp) [Python](./Python/second-minimum-node-in-a-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || From 8ca341d933475fe9c028f7e2089df0d9c3e87182 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 28 Dec 2017 23:40:26 +0800 Subject: [PATCH 4207/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 9ed8d6a80..ad4926c8c 100644 --- a/README.md +++ b/README.md @@ -273,6 +273,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 | +543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [C++](./C++/diameter-of-binary-tree.cpp) [Python](./Python/diameter-of-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || 545 | [Boundary of Binary Tree](https://leetcode.com/problems/boundary-of-binary-tree/) | [C++](./C++/boundary-of-binary-tree.cpp) [Python](./Python/boundary-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium |📖| 548 | [Split Array with Equal Sum](https://leetcode.com/problems/split-array-with-equal-sum/) | [C++](./C++/split-array-with-equal-sum.cpp) [Python](./Python/split-array-with-equal-sum.py) | _O(n^2)_ | _O(n)_ | Medium |📖| 563 |[Binary Tree Tilt](https://leetcode.com/problems/binary-tree-tilt/)| [C++](./C++/binary-tree-tilt.cpp) [Python](./Python/binary-tree-tilt.py)| _O(n)_ | _O(n)_ | Easy | | | From 474afba1ec3b107ee51569c6a9794ebe194ceb1c Mon Sep 17 00:00:00 2001 From: SangHee Kim Date: Thu, 28 Dec 2017 11:51:07 -0500 Subject: [PATCH 4208/4971] Update implement-queue-using-stacks.py It requires an integer result value from pop now. Maybe the question has been changed. ``` def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ ``` --- Python/implement-queue-using-stacks.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/implement-queue-using-stacks.py b/Python/implement-queue-using-stacks.py index 1cfeb014d..02b3e4860 100644 --- a/Python/implement-queue-using-stacks.py +++ b/Python/implement-queue-using-stacks.py @@ -28,10 +28,10 @@ def __init__(self): def push(self, x): self.A.append(x) - # @return nothing + # @return an integer def pop(self): self.peek() - self.B.pop() + return self.B.pop() # @return an integer def peek(self): From f019a149909f939d47aeb117330b2e30c03b70e6 Mon Sep 17 00:00:00 2001 From: SangHee Kim Date: Thu, 28 Dec 2017 11:45:28 -0500 Subject: [PATCH 4209/4971] Update README.md fixed: 453 got wrong links. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ad4926c8c..0b678c0b2 100644 --- a/README.md +++ b/README.md @@ -384,7 +384,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 413 | [Arithmetic Slices](https://leetcode.com/problems/arithmetic-slices/) | [C++](./C++/arithmetic-slices.cpp) [Python](./Python/arithmetic-slices.py) | _O(n)_ | _O(1)_ | Medium ||| 423 | [Reconstruct Original Digits from English](https://leetcode.com/problems/reconstruct-original-digits-from-english/) | [C++](./C++/reconstruct-original-digits-from-english.cpp) [Python](./Python/reconstruct-original-digits-from-english.py) | _O(n)_ | _O(1)_ | Medium | [GCJ2016 - Round 1B](https://code.google.com/codejam/contest/11254486/dashboard#s=p0)|| 441 | [Arranging Coins](https://leetcode.com/problems/arranging-coins/) | [C++](./C++/arranging-coins.cpp) [Python](./Python/arranging-coins.py) | _O(nlogn)_ | _O(1)_ | Easy || Binary Search| -453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(n)_ | _O(1)_ | Easy ||| +453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/) | [C++](./C++/minimum-moves-to-equal-array-elements.cpp) [Python](./Python/minimum-moves-to-equal-array-elements.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| 553 | [Optimal Division](https://leetcode.com/problems/optimal-division/) | [C++](./C++/optimal-division.cpp) [Python](./Python/optimal-division.py) | _O(n)_ | _O(1)_ | Medium ||| From 93852863f12b74c7c523414fa964ccc0e01d60fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Dec 2017 19:11:21 +0800 Subject: [PATCH 4210/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0b678c0b2..c7673e8f4 100644 --- a/README.md +++ b/README.md @@ -537,6 +537,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 | 📖 | 433| [Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation/)| [C++](./C++/minimum-genetic-mutation.cpp) [Python](./Python/minimum-genetic-mutation.py) | _O(n * b)_ | _O(b)_ | Medium || 444| [Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction/)| [C++](./C++/sequence-reconstruction.cpp) [Python](./Python/sequence-reconstruction.py) | _O(n * s)_ | _O(n)_ | Medium |📖| Topological Sort | +542| [01 Matrix](https://leetcode.com/problems/01-matrix/)| [C++](./C++/01-matrix.cpp) [Python](./Python/01-matrix.py) | _O(m * n)_ | _O(m + n)_ | Medium || 666| [Path Sum IV](https://leetcode.com/problems/path-sum-iv/)| [C++](./C++/path-sum-iv.cpp) [Python](./Python/path-sum-iv.py) | _O(n)_ | _O(w)_ | Medium |📖| Topological Sort | 675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | 742|[Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree/)| [C++](./C++/closest-leaf-in-a-binary-tree.cpp) [Python](./Python/closest-leaf-in-a-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | | | From eae552875c65c41d35ac5a4e8ea62af52e69e09f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Dec 2017 19:12:17 +0800 Subject: [PATCH 4211/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c7673e8f4..ad6faf643 100644 --- a/README.md +++ b/README.md @@ -537,7 +537,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 | 📖 | 433| [Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation/)| [C++](./C++/minimum-genetic-mutation.cpp) [Python](./Python/minimum-genetic-mutation.py) | _O(n * b)_ | _O(b)_ | Medium || 444| [Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction/)| [C++](./C++/sequence-reconstruction.cpp) [Python](./Python/sequence-reconstruction.py) | _O(n * s)_ | _O(n)_ | Medium |📖| Topological Sort | -542| [01 Matrix](https://leetcode.com/problems/01-matrix/)| [C++](./C++/01-matrix.cpp) [Python](./Python/01-matrix.py) | _O(m * n)_ | _O(m + n)_ | Medium || +542| [01 Matrix](https://leetcode.com/problems/01-matrix/)| [C++](./C++/01-matrix.cpp) [Python](./Python/01-matrix.py) | _O(m * n)_ | _O(m * n)_ | Medium || 666| [Path Sum IV](https://leetcode.com/problems/path-sum-iv/)| [C++](./C++/path-sum-iv.cpp) [Python](./Python/path-sum-iv.py) | _O(n)_ | _O(w)_ | Medium |📖| Topological Sort | 675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | 742|[Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree/)| [C++](./C++/closest-leaf-in-a-binary-tree.cpp) [Python](./Python/closest-leaf-in-a-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | | | From c417b9f69b33e4e7965649bb816fe49b6fe7519b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Dec 2017 19:25:15 +0800 Subject: [PATCH 4212/4971] Update 01-matrix.cpp --- C++/01-matrix.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/C++/01-matrix.cpp b/C++/01-matrix.cpp index bb7c65b70..75a07b2b5 100644 --- a/C++/01-matrix.cpp +++ b/C++/01-matrix.cpp @@ -35,3 +35,43 @@ class Solution { return matrix; } }; + +// Time: O(m * n) +// Space: O(m * n) +// dp solution +class Solution2 { +public: + vector> updateMatrix(vector>& matrix) { + vector > dp(matrix.size(), + vector(matrix[0].size(), + numeric_limits::max() - 10000)); + + for (int i = 0; i < matrix.size(); ++i) { + for (int j = 0; j < matrix[i].size(); ++j) { + if (matrix[i][j] == 0) + dp[i][j] = 0; + else { + if (i > 0) { + dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1); + } + if (j > 0) { + dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1); + } + } + } + } + + for (int i = matrix.size() - 1; i >= 0; --i) { + for (int j = matrix[i].size() - 1; j >= 0; --j) { + if (i < matrix.size() - 1) { + dp[i][j] = min(dp[i][j], dp[i + 1][j] + 1); + } + if (j < matrix[i].size() - 1) { + dp[i][j] = min(dp[i][j], dp[i][j + 1] + 1); + } + } + } + + return dp; + } +}; From b469b7e80ec97672e97296318ca4f92c89eab23a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Dec 2017 19:27:40 +0800 Subject: [PATCH 4213/4971] Update 01-matrix.cpp --- C++/01-matrix.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/01-matrix.cpp b/C++/01-matrix.cpp index 75a07b2b5..e2cff5480 100644 --- a/C++/01-matrix.cpp +++ b/C++/01-matrix.cpp @@ -48,9 +48,9 @@ class Solution2 { for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[i].size(); ++j) { - if (matrix[i][j] == 0) + if (matrix[i][j] == 0) { dp[i][j] = 0; - else { + } else { if (i > 0) { dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1); } From 8b6fbbf1f2aee9f4bbd9ef51c3e3611e7a8e461e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Dec 2017 19:36:02 +0800 Subject: [PATCH 4214/4971] Update 01-matrix.py --- Python/01-matrix.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Python/01-matrix.py b/Python/01-matrix.py index 16934096d..c0411ca13 100644 --- a/Python/01-matrix.py +++ b/Python/01-matrix.py @@ -59,3 +59,31 @@ def updateMatrix(self, matrix): matrix[i][j] = matrix[cell[0]][cell[1]]+1 return matrix + + +# Time: O(m * n) +# Space: O(m * n) +# dp solution +class Solution2(object): + def updateMatrix(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[List[int]] + """ + dp = [[float("inf")]*len(matrix[0]) for _ in xrange(len(matrix))] + for i in xrange(len(matrix)): + for j in xrange(len(matrix[i])): + if matrix[i][j] == 0: + dp[i][j] = 0 + else: + if i > 0: + dp[i][j] = min(dp[i][j], dp[i-1][j]+1) + if j > 0: + dp[i][j] = min(dp[i][j], dp[i][j-1]+1) + for i in reversed(xrange(len(matrix))): + for j in reversed(xrange(len(matrix[i]))): + if i < len(matrix)-1: + dp[i][j] = min(dp[i][j], dp[i+1][j]+1) + if j < len(matrix[i])-1: + dp[i][j] = min(dp[i][j], dp[i][j+1]+1) + return dp From 2939fab8e5024bdb82a301e77de61a44eef946c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Dec 2017 19:36:46 +0800 Subject: [PATCH 4215/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ad6faf643..50e8526bb 100644 --- a/README.md +++ b/README.md @@ -537,7 +537,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 | 📖 | 433| [Minimum Genetic Mutation](https://leetcode.com/problems/minimum-genetic-mutation/)| [C++](./C++/minimum-genetic-mutation.cpp) [Python](./Python/minimum-genetic-mutation.py) | _O(n * b)_ | _O(b)_ | Medium || 444| [Sequence Reconstruction](https://leetcode.com/problems/sequence-reconstruction/)| [C++](./C++/sequence-reconstruction.cpp) [Python](./Python/sequence-reconstruction.py) | _O(n * s)_ | _O(n)_ | Medium |📖| Topological Sort | -542| [01 Matrix](https://leetcode.com/problems/01-matrix/)| [C++](./C++/01-matrix.cpp) [Python](./Python/01-matrix.py) | _O(m * n)_ | _O(m * n)_ | Medium || +542| [01 Matrix](https://leetcode.com/problems/01-matrix/)| [C++](./C++/01-matrix.cpp) [Python](./Python/01-matrix.py) | _O(m * n)_ | _O(m * n)_ | Medium || DP 666| [Path Sum IV](https://leetcode.com/problems/path-sum-iv/)| [C++](./C++/path-sum-iv.cpp) [Python](./Python/path-sum-iv.py) | _O(n)_ | _O(w)_ | Medium |📖| Topological Sort | 675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | 742|[Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree/)| [C++](./C++/closest-leaf-in-a-binary-tree.cpp) [Python](./Python/closest-leaf-in-a-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | | | From 4f422e5034c9e5b1171158d65a2ff504d10b74b5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Dec 2017 19:40:55 +0800 Subject: [PATCH 4216/4971] Update 01-matrix.py --- Python/01-matrix.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Python/01-matrix.py b/Python/01-matrix.py index c0411ca13..a4ff877ba 100644 --- a/Python/01-matrix.py +++ b/Python/01-matrix.py @@ -82,8 +82,11 @@ def updateMatrix(self, matrix): dp[i][j] = min(dp[i][j], dp[i][j-1]+1) for i in reversed(xrange(len(matrix))): for j in reversed(xrange(len(matrix[i]))): - if i < len(matrix)-1: - dp[i][j] = min(dp[i][j], dp[i+1][j]+1) - if j < len(matrix[i])-1: - dp[i][j] = min(dp[i][j], dp[i][j+1]+1) + if matrix[i][j] == 0: + dp[i][j] = 0 + else: + if i < len(matrix)-1: + dp[i][j] = min(dp[i][j], dp[i+1][j]+1) + if j < len(matrix[i])-1: + dp[i][j] = min(dp[i][j], dp[i][j+1]+1) return dp From 31f7a0f86f442f48727c563e7e1fb86c02ab6c3c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 30 Dec 2017 19:41:26 +0800 Subject: [PATCH 4217/4971] Update 01-matrix.cpp --- C++/01-matrix.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/C++/01-matrix.cpp b/C++/01-matrix.cpp index e2cff5480..11b49a9b3 100644 --- a/C++/01-matrix.cpp +++ b/C++/01-matrix.cpp @@ -63,11 +63,15 @@ class Solution2 { for (int i = matrix.size() - 1; i >= 0; --i) { for (int j = matrix[i].size() - 1; j >= 0; --j) { - if (i < matrix.size() - 1) { - dp[i][j] = min(dp[i][j], dp[i + 1][j] + 1); - } - if (j < matrix[i].size() - 1) { - dp[i][j] = min(dp[i][j], dp[i][j + 1] + 1); + if (matrix[i][j] == 0) { + dp[i][j] = 0; + } else { + if (i < matrix.size() - 1) { + dp[i][j] = min(dp[i][j], dp[i + 1][j] + 1); + } + if (j < matrix[i].size() - 1) { + dp[i][j] = min(dp[i][j], dp[i][j + 1] + 1); + } } } } From 10e3b43d983f66844c8eb4c19f073752df6ed6b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Dec 2017 16:30:46 +0800 Subject: [PATCH 4218/4971] Create reach-a-number.cpp --- C++/reach-a-number.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/reach-a-number.cpp diff --git a/C++/reach-a-number.cpp b/C++/reach-a-number.cpp new file mode 100644 index 000000000..eb9ea166f --- /dev/null +++ b/C++/reach-a-number.cpp @@ -0,0 +1,15 @@ +// Time: O(sqrt(n)) +// Space: O(1) + +class Solution { +public: + int reachNumber(int target) { + target = abs(target); + int k = 0; + while (target > 0) { + ++k; + target -= k; + } + return (target % 2 == 0) ? k : k + 1 + k % 2; + } +}; From 6cf760d49b4e6f1b4af3cbf3b3d744166e21d48d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Dec 2017 16:32:40 +0800 Subject: [PATCH 4219/4971] Create reach-a-number.py --- Python/reach-a-number.py | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/reach-a-number.py diff --git a/Python/reach-a-number.py b/Python/reach-a-number.py new file mode 100644 index 000000000..64241496f --- /dev/null +++ b/Python/reach-a-number.py @@ -0,0 +1,41 @@ +# Time: O(sqrt(n)) +# Space: O(1) + +# You are standing at position 0 on an infinite number line. There is a goal at position target. +# +# On each move, you can either go left or right. +# During the n-th move (starting from 1), you take n steps. +# +# Return the minimum number of steps required to reach the destination. +# +# Example 1: +# Input: target = 3 +# Output: 2 +# Explanation: +# On the first move we step from 0 to 1. +# On the second step we step from 1 to 3. +# +# Example 2: +# Input: target = 2 +# Output: 3 +# Explanation: +# On the first move we step from 0 to 1. +# On the second move we step from 1 to -1. +# On the third move we step from -1 to 2. +# +# Note: +# - target will be a non-zero integer in the range [-10^9, 10^9]. + +class Solution(object): + def reachNumber(self, target): + """ + :type target: int + :rtype: int + """ + target = abs(target) + k = 0 + while target > 0: + k += 1 + target -= k + return k if target%2 == 0 else k+1+k%2 + From 349496389e1a0920218a47d0432d48c21fc835dd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Dec 2017 16:39:15 +0800 Subject: [PATCH 4220/4971] Update reach-a-number.py --- Python/reach-a-number.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Python/reach-a-number.py b/Python/reach-a-number.py index 64241496f..f23a8bb49 100644 --- a/Python/reach-a-number.py +++ b/Python/reach-a-number.py @@ -1,4 +1,4 @@ -# Time: O(sqrt(n)) +# Time: O(logn) # Space: O(1) # You are standing at position 0 on an infinite number line. There is a goal at position target. @@ -27,6 +27,20 @@ # - target will be a non-zero integer in the range [-10^9, 10^9]. class Solution(object): + def reachNumber(self, target): + """ + :type target: int + :rtype: int + """ + target = abs(target); + k = int(math.ceil((-1+math.sqrt(1+8*target))/2)) + target -= k*(k+1)/2; + return k if target%2 == 0 else k+1+k%2 + + +# Time: O(sqrt(n)) +# Space: O(1) +class Solution2(object): def reachNumber(self, target): """ :type target: int From 8a1875a7c2ad6cbcaf8e5545fa533b81a7f65398 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Dec 2017 16:39:48 +0800 Subject: [PATCH 4221/4971] Update reach-a-number.py --- Python/reach-a-number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/reach-a-number.py b/Python/reach-a-number.py index f23a8bb49..138054d34 100644 --- a/Python/reach-a-number.py +++ b/Python/reach-a-number.py @@ -32,9 +32,9 @@ def reachNumber(self, target): :type target: int :rtype: int """ - target = abs(target); + target = abs(target) k = int(math.ceil((-1+math.sqrt(1+8*target))/2)) - target -= k*(k+1)/2; + target -= k*(k+1)/2 return k if target%2 == 0 else k+1+k%2 From b3ce4c10db2caf841962eefd5c861dcb8f42e1d2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Dec 2017 16:46:13 +0800 Subject: [PATCH 4222/4971] Update reach-a-number.cpp --- C++/reach-a-number.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/C++/reach-a-number.cpp b/C++/reach-a-number.cpp index eb9ea166f..62fc14ba2 100644 --- a/C++/reach-a-number.cpp +++ b/C++/reach-a-number.cpp @@ -1,7 +1,20 @@ -// Time: O(sqrt(n)) +// Time: O(logn) // Space: O(1) class Solution { +public: + int reachNumber(int target) { + target = abs(target); + auto k = static_cast(ceil((-1 + sqrt(1 + 8.0 * target)) / 2)); + target -= k * (k + 1) / 2; + return (target % 2 == 0) ? k : k + 1 + k % 2; + } +}; + + +// Time: O(sqrt(n)) +// Space: O(1) +class Solution2 { public: int reachNumber(int target) { target = abs(target); From d45bdf62d54c0a5efc77be639f4259807a286d6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Dec 2017 17:58:09 +0800 Subject: [PATCH 4223/4971] Create pour-water.py --- Python/pour-water.py | 140 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 Python/pour-water.py diff --git a/Python/pour-water.py b/Python/pour-water.py new file mode 100644 index 000000000..fcaa7ad4c --- /dev/null +++ b/Python/pour-water.py @@ -0,0 +1,140 @@ +# Time: O(v * n) +# Space: O(1) + +# We are given an elevation map, heights[i] representing the height of the terrain at that index. +# The width at each index is 1. After V units of water fall at index K, how much water is at each index? +# +# Water first drops at index K and rests on top of the highest terrain or water at that index. +# Then, it flows according to the following rules: +# +# If the droplet would eventually fall by moving left, then move left. +# Otherwise, if the droplet would eventually fall by moving right, then move right. +# Otherwise, rise at it's current position. +# Here, "eventually fall" means that the droplet will eventually be at a lower level +# if it moves in that direction. +# Also, "level" means the height of the terrain plus any water in that column. +# We can assume there's infinitely high terrain on the two sides out of bounds of the array. +# Also, there could not be partial water being spread out evenly on more than 1 grid block - +# each unit of water has to be in exactly one block. +# +# Example 1: +# Input: heights = [2,1,1,2,1,2,2], V = 4, K = 3 +# Output: [2,2,2,3,2,2,2] +# Explanation: +# # # +# # # +# ## # ### +# ######### +# 0123456 <- index +# +# The first drop of water lands at index K = 3: +# +# # # +# # w # +# ## # ### +# ######### +# 0123456 +# +# When moving left or right, the water can only move to the same level or a lower level. +# (By level, we mean the total height of the terrain plus any water in that column.) +# Since moving left will eventually make it fall, it moves left. +# (A droplet "made to fall" means go to a lower height than it was at previously.) +# +# # # +# # # +# ## w# ### +# ######### +# 0123456 +# +# Since moving left will not make it fall, it stays in place. The next droplet falls: +# +# # # +# # w # +# ## w# ### +# ######### +# 0123456 +# +# Since the new droplet moving left will eventually make it fall, it moves left. +# Notice that the droplet still preferred to move left, +# even though it could move right (and moving right makes it fall quicker.) +# +# # # +# # w # +# ## w# ### +# ######### +# 0123456 +# +# # # +# # # +# ##ww# ### +# ######### +# 0123456 +# +# After those steps, the third droplet falls. +# Since moving left would not eventually make it fall, it tries to move right. +# Since moving right would eventually make it fall, it moves right. +# +# # # +# # w # +# ##ww# ### +# ######### +# 0123456 +# +# # # +# # # +# ##ww#w### +# ######### +# 0123456 +# +# Finally, the fourth droplet falls. +# Since moving left would not eventually make it fall, it tries to move right. +# Since moving right would not eventually make it fall, it stays in place: +# +# # # +# # w # +# ##ww#w### +# ######### +# 0123456 +# +# The final answer is [2,2,2,3,2,2,2]: +# +# # +# ####### +# ####### +# 0123456 +# +# Example 2: +# Input: heights = [1,2,3,4], V = 2, K = 2 +# Output: [2,3,3,4] +# Explanation: +# The last droplet settles at index 1, +# since moving further left would not cause it to eventually fall to a lower height. +# +# Example 3: +# Input: heights = [3,1,3], V = 5, K = 1 +# Output: [4,4,4] +# +# Note: +# - heights will have length in [1, 100] and contain integers in [0, 99]. +# - V will be in range [0, 2000]. +# - K will be in range [0, heights.length - 1]. + +class Solution(object): + def pourWater(self, heights, V, K): + """ + :type heights: List[int] + :type V: int + :type K: int + :rtype: List[int] + """ + for _ in xrange(V): + for d in (-1, 1): + i = best = K + while 0 <= i+d < len(heights) and \ + heights[i+d] <= heights[i]: + if heights[i+d] < heights[i]: best = i+d + i += d + if best != K: + break + heights[best] += 1 + return heights From 57863beef3f15e039bf07fde63561bb0aa2b5387 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Dec 2017 18:03:24 +0800 Subject: [PATCH 4224/4971] Update pour-water.py --- Python/pour-water.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/pour-water.py b/Python/pour-water.py index fcaa7ad4c..7d331cac1 100644 --- a/Python/pour-water.py +++ b/Python/pour-water.py @@ -128,8 +128,9 @@ def pourWater(self, heights, V, K): :rtype: List[int] """ for _ in xrange(V): + best = K for d in (-1, 1): - i = best = K + i = K while 0 <= i+d < len(heights) and \ heights[i+d] <= heights[i]: if heights[i+d] < heights[i]: best = i+d From 46916f8e20a4912b015e94175515daa64b72517e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Dec 2017 18:04:20 +0800 Subject: [PATCH 4225/4971] Create pour-water.cpp --- C++/pour-water.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/pour-water.cpp diff --git a/C++/pour-water.cpp b/C++/pour-water.cpp new file mode 100644 index 000000000..3d24b2d9c --- /dev/null +++ b/C++/pour-water.cpp @@ -0,0 +1,26 @@ +// Time: O(v * n) +// Space: O(1) + +class Solution { +public: + vector pourWater(vector& heights, int V, int K) { + for (; V > 0; --V) { + int best = K; + for (const auto& d : {-1, 1}) { + int i = K; + while (0 <= i + d && i + d < heights.size() && + heights[i + d] <= heights[i]) { + if (heights[i + d] < heights[i]) { + best = i + d; + } + i += d; + } + if (best != K) { + break; + } + } + ++heights[best]; + } + return heights; + } +}; From bd03552698ccc890c210ba025ec467f4e6738515 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Dec 2017 18:35:35 +0800 Subject: [PATCH 4226/4971] Create set-intersection-size-at-least-two.cpp --- C++/set-intersection-size-at-least-two.cpp | 28 ++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/set-intersection-size-at-least-two.cpp diff --git a/C++/set-intersection-size-at-least-two.cpp b/C++/set-intersection-size-at-least-two.cpp new file mode 100644 index 000000000..834948726 --- /dev/null +++ b/C++/set-intersection-size-at-least-two.cpp @@ -0,0 +1,28 @@ +// Time: O(nlogn) +// Space: O(n) + +// greedy solution +class Solution { +public: + int intersectionSizeTwo(vector>& intervals) { + sort(intervals.begin(), intervals.end(), + [](const vector& a, const vector& b) { + return (a[0] != b[0]) ? (a[0] < b[0]) : (b[1] < a[1]); + }); + vector cnts(intervals.size(), 2); + int result = 0; + while (!intervals.empty()) { + auto start = intervals.back()[0]; intervals.pop_back(); + auto cnt = cnts.back(); cnts.pop_back(); + for (int s = start; s < start + cnt; ++s) { + for (int i = 0; i < intervals.size(); ++i) { + if (cnts[i] && s <= intervals[i][1]) { + --cnts[i]; + } + } + } + result += cnt; + } + return result; + } +}; From 39473b1aa0d8c54b0fb43b5e97545596ed087d59 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 31 Dec 2017 18:38:21 +0800 Subject: [PATCH 4227/4971] Create set-intersection-size-at-least-two.py --- Python/set-intersection-size-at-least-two.py | 46 ++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/set-intersection-size-at-least-two.py diff --git a/Python/set-intersection-size-at-least-two.py b/Python/set-intersection-size-at-least-two.py new file mode 100644 index 000000000..571b8ddd5 --- /dev/null +++ b/Python/set-intersection-size-at-least-two.py @@ -0,0 +1,46 @@ +# Time: O(nlogn) +# Space: O(n) + +# An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from a to b, +# including a and b. +# +# Find the minimum size of a set S such that for every integer interval A in intervals, +# the intersection of S with A has size at least 2. +# +# Example 1: +# Input: intervals = [[1, 3], [1, 4], [2, 5], [3, 5]] +# Output: 3 +# Explanation: +# Consider the set S = {2, 3, 4}. For each interval, there are at least 2 elements from S in the interval. +# Also, there isn't a smaller size set that fulfills the above condition. +# Thus, we output the size of this set, which is 3. +# +# Example 2: +# Input: intervals = [[1, 2], [2, 3], [2, 4], [4, 5]] +# Output: 5 +# Explanation: +# An example of a minimum sized set is {1, 2, 3, 4, 5}. +# +# Note: +# intervals will have length in range [1, 3000]. +# intervals[i] will have length 2, representing some integer interval. +# intervals[i][j] will be an integer in [0, 10^8]. + +# greedy solution +class Solution(object): + def intersectionSizeTwo(self, intervals): + """ + :type intervals: List[List[int]] + :rtype: int + """ + intervals.sort(key = lambda(s, e): (s, -e)) + cnts = [2] * len(intervals) + result = 0 + while intervals: + (start, _), cnt = intervals.pop(), cnts.pop() + for s in xrange(start, start+cnt): + for i in xrange(len(intervals)): + if cnts[i] and s <= intervals[i][1]: + cnts[i] -= 1 + result += cnt + return result From 2a3669d367dd5cdb14e762959cadf8294c0a170f Mon Sep 17 00:00:00 2001 From: SangHee Kim Date: Sun, 31 Dec 2017 11:08:28 -0500 Subject: [PATCH 4228/4971] Update binary-tree-vertical-order-traversal.py Error due to unused triple-quoted string literal --- 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 8dd332ee4..69e483787 100644 --- a/Python/binary-tree-vertical-order-traversal.py +++ b/Python/binary-tree-vertical-order-traversal.py @@ -15,7 +15,6 @@ def verticalOrder(self, root): :type root: TreeNode :rtype: List[List[int]] """ - """ cols = collections.defaultdict(list) queue = [(root, 0)] for node, i in queue: From e5c56d939fa407822d1f8e9bdac8c0d6e867957c Mon Sep 17 00:00:00 2001 From: SangHee Kim Date: Sun, 31 Dec 2017 12:27:15 -0500 Subject: [PATCH 4229/4971] Update course-schedule.py missing import --- Python/course-schedule.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/course-schedule.py b/Python/course-schedule.py index 158d6a9d0..ecb7fbf72 100644 --- a/Python/course-schedule.py +++ b/Python/course-schedule.py @@ -30,6 +30,9 @@ # of Topological Sort. # Topological sort could also be done via BFS. # + +import collections + class Solution(object): def canFinish(self, numCourses, prerequisites): """ From 9141b397274a61031f91d57c3b2ffed3830afd07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 12:59:42 +0800 Subject: [PATCH 4230/4971] Create pyramid-transition-matrix.cpp --- C++/pyramid-transition-matrix.cpp | 41 +++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 C++/pyramid-transition-matrix.cpp diff --git a/C++/pyramid-transition-matrix.cpp b/C++/pyramid-transition-matrix.cpp new file mode 100644 index 000000000..6661d58f3 --- /dev/null +++ b/C++/pyramid-transition-matrix.cpp @@ -0,0 +1,41 @@ +// Time: O(a^(b*(b-1)/2)), a is the size of allowed, +// b is the length of bottom +// Space: O(a + b^2) + +class Solution { +public: + bool pyramidTransition(string bottom, vector& allowed) { + vector>> edges(7, vector>(7)); + for (const auto& s: allowed) { + edges[s[0] - 'A'][s[1] - 'A'].emplace_back(s[2] - 'A'); + } + return pyramidTransitionHelper(bottom, edges); + } + +private: + bool pyramidTransitionHelper(const string& bottom, const vector>>& edges) { + if (bottom.size() == 1) { + return true; + } + for (int i = 0; i < bottom.size() - 1; ++i) { + if (edges[bottom[i] - 'A'][bottom[i + 1] - 'A'].empty()) { + return false; + } + } + string new_bottom(bottom.size() - 1, 'A'); + return dfs(bottom, edges, &new_bottom, 0); + } + + bool dfs(const string& bottom, const vector>>& edges, string *new_bottom, int idx) { + if (idx == bottom.size() - 1) { + return pyramidTransitionHelper(*new_bottom, edges); + } + for (const auto& i : edges[bottom[idx] - 'A'][bottom[idx + 1] - 'A']) { + (*new_bottom)[idx] = i + 'A'; + if (dfs(bottom, edges, new_bottom, idx + 1)) { + return true; + } + } + return false; + } +}; From febc2dee92b5af2b75b771d99fdce0890b947f6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 13:05:23 +0800 Subject: [PATCH 4231/4971] Update pyramid-transition-matrix.cpp --- C++/pyramid-transition-matrix.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/pyramid-transition-matrix.cpp b/C++/pyramid-transition-matrix.cpp index 6661d58f3..9efc96eb9 100644 --- a/C++/pyramid-transition-matrix.cpp +++ b/C++/pyramid-transition-matrix.cpp @@ -1,4 +1,4 @@ -// Time: O(a^(b*(b-1)/2)), a is the size of allowed, +// Time: O(a^(b*(b+1)/2)-1), a is the size of allowed, // b is the length of bottom // Space: O(a + b^2) From 250a65084e69951cf4a94abb7ced20c020db5fa0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 13:05:47 +0800 Subject: [PATCH 4232/4971] Update pyramid-transition-matrix.cpp --- C++/pyramid-transition-matrix.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/pyramid-transition-matrix.cpp b/C++/pyramid-transition-matrix.cpp index 9efc96eb9..e92ae5a81 100644 --- a/C++/pyramid-transition-matrix.cpp +++ b/C++/pyramid-transition-matrix.cpp @@ -1,5 +1,5 @@ // Time: O(a^(b*(b+1)/2)-1), a is the size of allowed, -// b is the length of bottom +// b is the length of bottom // Space: O(a + b^2) class Solution { From d26245a39eb2cb69248e66a4966b69084c5670df Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 13:19:00 +0800 Subject: [PATCH 4233/4971] Create pyramid-transition-matrix.py --- Python/pyramid-transition-matrix.py | 70 +++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Python/pyramid-transition-matrix.py diff --git a/Python/pyramid-transition-matrix.py b/Python/pyramid-transition-matrix.py new file mode 100644 index 000000000..a78333dbf --- /dev/null +++ b/Python/pyramid-transition-matrix.py @@ -0,0 +1,70 @@ +# Time: O(a^(b*(b-1)/2)), a is the size of allowed, +# b is the length of bottom +# Space: O(a + b^2) + +# We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`. +# +# For every block of color `C` we place not in the bottom row, +# we are placing it on top of a left block of color `A` and right block of color `B`. +# We are allowed to place the block there only if `(A, B, C)` is an allowed triple. +# +# We start with a bottom row of bottom, represented as a single string. +# We also start with a list of allowed triples allowed. +# Each allowed triple is represented as a string of length 3. +# +# Return true if we can build the pyramid all the way to the top, otherwise false. +# +# Example 1: +# Input: bottom = "XYZ", allowed = ["XYD", "YZE", "DEA", "FFF"] +# Output: true +# Explanation: +# We can stack the pyramid like this: +# A +# / \ +# D E +# / \ / \ +# X Y Z +# +# This works because ('X', 'Y', 'D'), ('Y', 'Z', 'E'), and ('D', 'E', 'A') are allowed triples. +# Example 1: +# Input: bottom = "XXYX", allowed = ["XXX", "XXY", "XYX", "XYY", "YXZ"] +# Output: false +# Explanation: +# We can't stack the pyramid to the top. +# Note that there could be allowed triples (A, B, C) and (A, B, D) with C != D. +# +# Note: +# bottom will be a string with length in range [2, 100]. +# allowed will have length in range [0, 350]. +# Letters in all strings will be chosen from the set {'A', 'B', 'C', 'D', 'E', 'F', 'G'}. + +# dfs solution +class Solution(object): + def pyramidTransition(self, bottom, allowed): + """ + :type bottom: str + :type allowed: List[str] + :rtype: bool + """ + def pyramidTransitionHelper(bottom, edges): + def dfs(bottom, edges, new_bottom, idx): + if idx == len(bottom)-1: + return pyramidTransitionHelper(new_bottom, edges) + for i in edges[ord(bottom[idx])-ord('A')][ord(bottom[idx+1])-ord('A')]: + new_bottom[idx] = chr(i+ord('A')); + if dfs(bottom, edges, new_bottom, idx+1): + return True + return False + + if len(bottom) == 1: + return True + for i in xrange(len(bottom)-1): + if not edges[ord(bottom[i])-ord('A')][ord(bottom[i+1])-ord('A')]: + return False + new_bottom = ['A'] * (len(bottom)-1) + return dfs(bottom, edges, new_bottom, 0) + + edges = [[[] for _ in xrange(7)] for _ in xrange(7)] + for s in allowed: + edges[ord(s[0])-ord('A')][ord(s[1])-ord('A')].append(ord(s[2])-ord('A')) + return pyramidTransitionHelper(bottom, edges) From b2dda1e8a9a8bb92d624b56e1ac18d8906d346a7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 13:19:23 +0800 Subject: [PATCH 4234/4971] Update pyramid-transition-matrix.cpp --- C++/pyramid-transition-matrix.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/pyramid-transition-matrix.cpp b/C++/pyramid-transition-matrix.cpp index e92ae5a81..587e2104e 100644 --- a/C++/pyramid-transition-matrix.cpp +++ b/C++/pyramid-transition-matrix.cpp @@ -2,6 +2,7 @@ // b is the length of bottom // Space: O(a + b^2) +// dfs solution class Solution { public: bool pyramidTransition(string bottom, vector& allowed) { From 5ba5bff77245f9d2a6423f2845f5f331986cc576 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 13:41:52 +0800 Subject: [PATCH 4235/4971] Update pyramid-transition-matrix.cpp --- C++/pyramid-transition-matrix.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/pyramid-transition-matrix.cpp b/C++/pyramid-transition-matrix.cpp index 587e2104e..4f755f83b 100644 --- a/C++/pyramid-transition-matrix.cpp +++ b/C++/pyramid-transition-matrix.cpp @@ -1,5 +1,5 @@ -// Time: O(a^(b*(b+1)/2)-1), a is the size of allowed, -// b is the length of bottom +// Time: O(b^2 * a^(b*(b+1)/2-1)), a is the size of allowed, +// b is the length of bottom // Space: O(a + b^2) // dfs solution From b63470a8057a4c6f02b5e863ac6e0091ae0c27d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 13:42:29 +0800 Subject: [PATCH 4236/4971] Update pyramid-transition-matrix.py --- Python/pyramid-transition-matrix.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/pyramid-transition-matrix.py b/Python/pyramid-transition-matrix.py index a78333dbf..cb6aafefb 100644 --- a/Python/pyramid-transition-matrix.py +++ b/Python/pyramid-transition-matrix.py @@ -1,5 +1,5 @@ -# Time: O(a^(b*(b-1)/2)), a is the size of allowed, -# b is the length of bottom +# Time: O(b^2 * a^(b*(b+1)/2-1)), a is the size of allowed, +# b is the length of bottom # Space: O(a + b^2) # We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`. From 66aaaf7fef826efe0df6db63a4c036d4d95c8fc2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 13:43:52 +0800 Subject: [PATCH 4237/4971] Update pyramid-transition-matrix.py --- Python/pyramid-transition-matrix.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/pyramid-transition-matrix.py b/Python/pyramid-transition-matrix.py index cb6aafefb..46a8013ea 100644 --- a/Python/pyramid-transition-matrix.py +++ b/Python/pyramid-transition-matrix.py @@ -1,5 +1,5 @@ -# Time: O(b^2 * a^(b*(b+1)/2-1)), a is the size of allowed, -# b is the length of bottom +# Time: O(a^(b*(b+1)/2-1)), a is the size of allowed, +# b is the length of bottom # Space: O(a + b^2) # We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`. From b7c5febbbda3591b36466cff71253f3c13538aff Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 13:46:13 +0800 Subject: [PATCH 4238/4971] Update pyramid-transition-matrix.cpp --- C++/pyramid-transition-matrix.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/pyramid-transition-matrix.cpp b/C++/pyramid-transition-matrix.cpp index 4f755f83b..60f740889 100644 --- a/C++/pyramid-transition-matrix.cpp +++ b/C++/pyramid-transition-matrix.cpp @@ -1,5 +1,5 @@ -// Time: O(b^2 * a^(b*(b+1)/2-1)), a is the size of allowed, -// b is the length of bottom +// Time: O(a^(b*(b+1)/2-1)), a is the size of allowed, +// b is the length of bottom // Space: O(a + b^2) // dfs solution From a3c175ff6663eecb097f0754d9894053b98cd458 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 14:12:02 +0800 Subject: [PATCH 4239/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 50e8526bb..81546d87a 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 731 | [My Calendar II](https://leetcode.com/problems/my-calendar-ii/) | [C++](./C++/my-calendar-ii.cpp) [Python](./Python/my-calendar-ii.py) | _O(n^2)_ | _O(n)_ | Medium || 732 | [My Calendar III](https://leetcode.com/problems/my-calendar-iii/) | [C++](./C++/my-calendar-iii.cpp) [Python](./Python/my-calendar-iii.py) | _O(n^2)_ | _O(n)_ | Hard || 747 | [Largest Number Greater Than Twice of Others](https://leetcode.com/problems/largest-number-greater-than-twice-of-others/) | [C++](./C++/largest-number-greater-than-twice-of-others.cpp) [Python](./Python/largest-number-greater-than-twice-of-others.py) | _O(n)_ | _O(1)_ | Easy || +756 | [Pour Water](https://leetcode.com/problems/pour-water/) | [C++](./C++/pour-water.cpp) [Python](./Python/pour-water.py) | _O(v * n)_ | _O(1)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -401,6 +402,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 660 | [Remove 9](https://leetcode.com/problems/remove-9/) | [C++](./C++/remove-9.cpp) [Python](./Python/remove-9.py) | _O(logn)_ | _O(1)_ | Hard |📖|| 672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/) | [C++](./C++/bulb-switcher-ii.cpp) [Python](./Python/bulb-switcher-ii.py) | _O(1)_ | _O(1)_ | Medium ||| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/) | [C++](./C++/self-dividing-numbers.cpp) [Python](./Python/self-dividing-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| +755 | [Reach a Number](https://leetcode.com/problems/reach-a-number/) | [C++](./C++/reach-a-number.cpp) [Python](./Python/reach-a-number.py) | _O(logn)_ | _O(1)_ | Medium ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -576,6 +578,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 733| [Max Area of Island](https://leetcode.com/problems/flood-fill/) | [C++](./C++/flood-fill.cpp) [Python](./Python/flood-fill.py) | _O(m * n)_ | _O(m * n)_ | Easy || 749| [Contain Virus](https://leetcode.com/problems/contain-virus/) | [C++](./C++/contain-virus.cpp) [Python](./Python/contain-virus.py) | _O((m * n)^(4/3))_ | _O(m * n)_ | Hard || Simulation| 753| [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [C++](./C++/cracking-the-safe.cpp) [Python](./Python/cracking-the-safe.py) | _O(k^n)_ | _O(k^n)_ | Hard || `de Bruijn sequences`, `Lyndon word` | +757| [Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix/) | [C++](./C++/pyramid-transition-matrix.cpp) [Python](./Python/pyramid-transition-matrix.py) | _O(a^(b*(b-1)/2))_ | _O(a + b^2)_ | Medium ||| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -712,6 +715,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [C++](./C++/dota2-senate.cpp) [Python](./Python/dota2-senate.py) | _O(n)_ | _O(n)_ | Medium ||| 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | 738 | [Monotone Increasing Digits](https://leetcode.com/problems/monotone-increasing-digits/) | [C++](./C++/monotone-increasing-digits.cpp) [Python](./Python/monotone-increasing-digits.py) | _O(1)_ | _O(1)_ | Medium | | +759 | [Set Intersection Size At Least Two](https://leetcode.com/problems/set-intersection-size-at-least-two/) | [C++](./C++/set-intersection-size-at-least-two.cpp) [Python](./Python/set-intersection-size-at-least-two.py) | _O(nlogn)_ | _O(n)_ | Hard | | ## Geometry | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From fd09483fe06453ac02abfbd81131a339b37a443f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 14:13:16 +0800 Subject: [PATCH 4240/4971] Update pyramid-transition-matrix.py --- Python/pyramid-transition-matrix.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/pyramid-transition-matrix.py b/Python/pyramid-transition-matrix.py index 46a8013ea..3a5b01c8a 100644 --- a/Python/pyramid-transition-matrix.py +++ b/Python/pyramid-transition-matrix.py @@ -61,7 +61,7 @@ def dfs(bottom, edges, new_bottom, idx): for i in xrange(len(bottom)-1): if not edges[ord(bottom[i])-ord('A')][ord(bottom[i+1])-ord('A')]: return False - new_bottom = ['A'] * (len(bottom)-1) + new_bottom = ['A']*(len(bottom)-1) return dfs(bottom, edges, new_bottom, 0) edges = [[[] for _ in xrange(7)] for _ in xrange(7)] From 2af3d814e2797a16d5cd7fc2d03c8d6bc0435d82 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 21:42:21 +0800 Subject: [PATCH 4241/4971] Update pyramid-transition-matrix.cpp --- C++/pyramid-transition-matrix.cpp | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/C++/pyramid-transition-matrix.cpp b/C++/pyramid-transition-matrix.cpp index 60f740889..75d7825df 100644 --- a/C++/pyramid-transition-matrix.cpp +++ b/C++/pyramid-transition-matrix.cpp @@ -1,20 +1,22 @@ -// Time: O(a^(b*(b+1)/2-1)), a is the size of allowed, -// b is the length of bottom -// Space: O(a + b^2) +// Time: O((a^(b+1)-a)/(a-1)) = O(a^b) , a is the size of allowed, +// b is the length of bottom +// Space: O((a^(b+1)-a)/(a-1)) = O(a^b) // dfs solution class Solution { public: bool pyramidTransition(string bottom, vector& allowed) { vector>> edges(7, vector>(7)); + unordered_set lookup; for (const auto& s: allowed) { edges[s[0] - 'A'][s[1] - 'A'].emplace_back(s[2] - 'A'); } - return pyramidTransitionHelper(bottom, edges); + return pyramidTransitionHelper(bottom, edges, &lookup); } private: - bool pyramidTransitionHelper(const string& bottom, const vector>>& edges) { + bool pyramidTransitionHelper(const string& bottom, const vector>>& edges, + unordered_set *lookup) { if (bottom.size() == 1) { return true; } @@ -23,17 +25,22 @@ class Solution { return false; } } + if (lookup->count(bottom)) { + return false; + } + lookup->emplace(bottom); string new_bottom(bottom.size() - 1, 'A'); - return dfs(bottom, edges, &new_bottom, 0); + return dfs(bottom, edges, &new_bottom, 0, lookup); } - bool dfs(const string& bottom, const vector>>& edges, string *new_bottom, int idx) { + bool dfs(const string& bottom, const vector>>& edges, string *new_bottom, int idx, + unordered_set *lookup) { if (idx == bottom.size() - 1) { - return pyramidTransitionHelper(*new_bottom, edges); + return pyramidTransitionHelper(*new_bottom, edges, lookup); } for (const auto& i : edges[bottom[idx] - 'A'][bottom[idx + 1] - 'A']) { (*new_bottom)[idx] = i + 'A'; - if (dfs(bottom, edges, new_bottom, idx + 1)) { + if (dfs(bottom, edges, new_bottom, idx + 1, lookup)) { return true; } } From 17c6d2cf5a5a06408979eb53cab2d3f09b531198 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 21:42:24 +0800 Subject: [PATCH 4242/4971] Update pyramid-transition-matrix.py --- Python/pyramid-transition-matrix.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/Python/pyramid-transition-matrix.py b/Python/pyramid-transition-matrix.py index 3a5b01c8a..de895e8c7 100644 --- a/Python/pyramid-transition-matrix.py +++ b/Python/pyramid-transition-matrix.py @@ -1,6 +1,6 @@ -# Time: O(a^(b*(b+1)/2-1)), a is the size of allowed, -# b is the length of bottom -# Space: O(a + b^2) +# Time: O((a^(b+1)-a)/(a-1)) = O(a^b) , a is the size of allowed, +# b is the length of bottom +# Space: O((a^(b+1)-a)/(a-1)) = O(a^b) # We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`. # @@ -46,25 +46,29 @@ def pyramidTransition(self, bottom, allowed): :type allowed: List[str] :rtype: bool """ - def pyramidTransitionHelper(bottom, edges): - def dfs(bottom, edges, new_bottom, idx): + def pyramidTransitionHelper(bottom, edges, lookup): + def dfs(bottom, edges, new_bottom, idx, lookup): if idx == len(bottom)-1: - return pyramidTransitionHelper(new_bottom, edges) + return pyramidTransitionHelper(new_bottom, edges, lookup) for i in edges[ord(bottom[idx])-ord('A')][ord(bottom[idx+1])-ord('A')]: new_bottom[idx] = chr(i+ord('A')); - if dfs(bottom, edges, new_bottom, idx+1): + if dfs(bottom, edges, new_bottom, idx+1, lookup): return True return False if len(bottom) == 1: return True + if "".join(bottom) in lookup: + return False + lookup.add("".join(bottom)) for i in xrange(len(bottom)-1): if not edges[ord(bottom[i])-ord('A')][ord(bottom[i+1])-ord('A')]: return False new_bottom = ['A']*(len(bottom)-1) - return dfs(bottom, edges, new_bottom, 0) + return dfs(bottom, edges, new_bottom, 0, lookup) edges = [[[] for _ in xrange(7)] for _ in xrange(7)] for s in allowed: edges[ord(s[0])-ord('A')][ord(s[1])-ord('A')].append(ord(s[2])-ord('A')) - return pyramidTransitionHelper(bottom, edges) + return pyramidTransitionHelper(bottom, edges, set()) + From 22376b3920fced7221aa772f283b4fef8faa9398 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 21:43:22 +0800 Subject: [PATCH 4243/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 81546d87a..0641941f0 100644 --- a/README.md +++ b/README.md @@ -578,7 +578,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 733| [Max Area of Island](https://leetcode.com/problems/flood-fill/) | [C++](./C++/flood-fill.cpp) [Python](./Python/flood-fill.py) | _O(m * n)_ | _O(m * n)_ | Easy || 749| [Contain Virus](https://leetcode.com/problems/contain-virus/) | [C++](./C++/contain-virus.cpp) [Python](./Python/contain-virus.py) | _O((m * n)^(4/3))_ | _O(m * n)_ | Hard || Simulation| 753| [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [C++](./C++/cracking-the-safe.cpp) [Python](./Python/cracking-the-safe.py) | _O(k^n)_ | _O(k^n)_ | Hard || `de Bruijn sequences`, `Lyndon word` | -757| [Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix/) | [C++](./C++/pyramid-transition-matrix.cpp) [Python](./Python/pyramid-transition-matrix.py) | _O(a^(b*(b-1)/2))_ | _O(a + b^2)_ | Medium ||| +757| [Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix/) | [C++](./C++/pyramid-transition-matrix.cpp) [Python](./Python/pyramid-transition-matrix.py) | _O(a^b)_ | _O(a^b)_ | Medium ||| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 072c19ab63f6e9fd6fe5d6069836fe7657b92e2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 1 Jan 2018 21:46:08 +0800 Subject: [PATCH 4244/4971] Update pyramid-transition-matrix.py --- Python/pyramid-transition-matrix.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/Python/pyramid-transition-matrix.py b/Python/pyramid-transition-matrix.py index de895e8c7..413a4df90 100644 --- a/Python/pyramid-transition-matrix.py +++ b/Python/pyramid-transition-matrix.py @@ -49,7 +49,7 @@ def pyramidTransition(self, bottom, allowed): def pyramidTransitionHelper(bottom, edges, lookup): def dfs(bottom, edges, new_bottom, idx, lookup): if idx == len(bottom)-1: - return pyramidTransitionHelper(new_bottom, edges, lookup) + return pyramidTransitionHelper("".join(new_bottom), edges, lookup) for i in edges[ord(bottom[idx])-ord('A')][ord(bottom[idx+1])-ord('A')]: new_bottom[idx] = chr(i+ord('A')); if dfs(bottom, edges, new_bottom, idx+1, lookup): @@ -58,9 +58,9 @@ def dfs(bottom, edges, new_bottom, idx, lookup): if len(bottom) == 1: return True - if "".join(bottom) in lookup: + if bottom in lookup: return False - lookup.add("".join(bottom)) + lookup.add(bottom) for i in xrange(len(bottom)-1): if not edges[ord(bottom[i])-ord('A')][ord(bottom[i+1])-ord('A')]: return False @@ -71,4 +71,3 @@ def dfs(bottom, edges, new_bottom, idx, lookup): for s in allowed: edges[ord(s[0])-ord('A')][ord(s[1])-ord('A')].append(ord(s[2])-ord('A')) return pyramidTransitionHelper(bottom, edges, set()) - From 8688b9852be8da38621811e294f9fcf2251eeada Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 2 Jan 2018 22:30:57 +0800 Subject: [PATCH 4245/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0641941f0..7f9726edb 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | +541| [Reverse String II](https://leetcode.com/problems/reverse-string-ii/) | [C++](./C++/reverse-string-ii.cpp) [Python](./Python/reverse-string-ii.py) | _O(n)_ | _O(1)_ | Easy | | 551 | [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i/) | [C++](./C++/student-attendance-record-i.cpp) [Python](./Python/student-attendance-record-i.py) | _O(n)_ | _O(1)_ | Easy ||| 556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | 557| [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) |[C++](./C++/reverse-words-in-a-string-iii.cpp) [Python](./Python/reverse-words-in-a-string-iii.py) | _O(n)_ | _O(1)_ | Easy | | From b15d4537d8a012a5dbce7976cd722da414663cd4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 3 Jan 2018 23:35:22 +0800 Subject: [PATCH 4246/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7f9726edb..44762dbe3 100644 --- a/README.md +++ b/README.md @@ -504,6 +504,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 410| [Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/)| [C++](./C++/split-array-largest-sum.cpp) [Python](./Python/split-array-largest-sum.py) | _O(nlogs)_ | _O(1)_ | Hard | | 436 | [Find Right Interval](https://leetcode.com/problems/find-right-interval/) | [C++](./C++/find-right-interval.cpp) [Python](./Python/find-right-interval.py) | _O(nlogn)_ | _O(n)_ | Medium | | 475 | [Heaters](https://leetcode.com/problems/heaters/) | [C++](./C++/heaters.cpp) [Python](./Python/heaters.py) | _O((m + n) * logn)_ | _O(1)_ | Easy | | +540|[Single Element in a Sorted Array](https://leetcode.com/problems/dsingle-element-in-a-sorted-array/)| [C++](./C++/single-element-in-a-sorted-array.cpp) [Python](./Python/single-element-in-a-sorted-array.py)| _O(logn)_ | _O(1)_ | Medium | | 658 | [Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/) | [C++](./C++/find-k-closest-elements.cpp) [Python](./Python/find-k-closest-elements.py) | _O(logn + k)_ | _O(1)_ | Medium | | 668 | [Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [C++](./C++/kth-smallest-number-in-multiplication-table.cpp) [Python](./Python/kth-smallest-number-in-multiplication-table.py) | _O(m * log(m * n))_ | _O(1)_ | Hard | | 719 | [Find K-th Smallest Pair Distance](https://leetcode.com/problems/find-k-th-smallest-pair-distance/) | [C++](./C++/find-k-th-smallest-pair-distance.cpp) [Python](./Python/find-k-th-smallest-pair-distance.py) | _O(nlogn + nlogw)_ | _O(1)_ | Hard | | From 8f0b1970ede90342f58266182eea45e82017de7a Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 4 Jan 2018 23:11:21 +0800 Subject: [PATCH 4247/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 44762dbe3..4dc99dde4 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | +539| [Minimum Time Difference](https://leetcode.com/problems/minimum-time-difference/) | [C++](./C++/minimum-time-difference.cpp) [Python](./Python/minimum-time-difference.py) | _O(nlogn)_ | _O(n)_ | Medium | | 541| [Reverse String II](https://leetcode.com/problems/reverse-string-ii/) | [C++](./C++/reverse-string-ii.cpp) [Python](./Python/reverse-string-ii.py) | _O(n)_ | _O(1)_ | Easy | | 551 | [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i/) | [C++](./C++/student-attendance-record-i.cpp) [Python](./Python/student-attendance-record-i.py) | _O(n)_ | _O(1)_ | Easy ||| 556| [Next Greater Element III](https://leetcode.com/problems/next-greater-element-iii/) |[C++](./C++/next-greater-element-iii.cpp) [Python](./Python/next-greater-element-iii.py) | _O(1)_ | _O(1)_ | Medium | | From 9921b83bc032d4e27e51974d7b76d634d2238fb9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 5 Jan 2018 21:53:11 +0800 Subject: [PATCH 4248/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 4dc99dde4..c958bf9aa 100644 --- a/README.md +++ b/README.md @@ -276,6 +276,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 | +538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [C++](./C++/convert-bst-to-greater-tree.cpp) [Python](./Python/convert-bst-to-greater-tree.py) | _O(n)_ | _O(h)_ | Easy || 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [C++](./C++/diameter-of-binary-tree.cpp) [Python](./Python/diameter-of-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || 545 | [Boundary of Binary Tree](https://leetcode.com/problems/boundary-of-binary-tree/) | [C++](./C++/boundary-of-binary-tree.cpp) [Python](./Python/boundary-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium |📖| 548 | [Split Array with Equal Sum](https://leetcode.com/problems/split-array-with-equal-sum/) | [C++](./C++/split-array-with-equal-sum.cpp) [Python](./Python/split-array-with-equal-sum.py) | _O(n^2)_ | _O(n)_ | Medium |📖| From bc521b7fbde01c3433c0e8a44838949cf4f6cd62 Mon Sep 17 00:00:00 2001 From: SangHee Kim Date: Fri, 5 Jan 2018 11:45:07 -0500 Subject: [PATCH 4249/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 50e8526bb..e70453ffc 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 729 | [My Calendar I](https://leetcode.com/problems/my-calendar-i/) | [C++](./C++/my-calendar-i.cpp) [Python](./Python/my-calendar-i.py) | _O(nlogn)_ | _O(n)_ | Medium || 731 | [My Calendar II](https://leetcode.com/problems/my-calendar-ii/) | [C++](./C++/my-calendar-ii.cpp) [Python](./Python/my-calendar-ii.py) | _O(n^2)_ | _O(n)_ | Medium || 732 | [My Calendar III](https://leetcode.com/problems/my-calendar-iii/) | [C++](./C++/my-calendar-iii.cpp) [Python](./Python/my-calendar-iii.py) | _O(n^2)_ | _O(n)_ | Hard || -747 | [Largest Number Greater Than Twice of Others](https://leetcode.com/problems/largest-number-greater-than-twice-of-others/) | [C++](./C++/largest-number-greater-than-twice-of-others.cpp) [Python](./Python/largest-number-greater-than-twice-of-others.py) | _O(n)_ | _O(1)_ | Easy || +747 | [Largest Number Greater Than Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others/) | [C++](./C++/largest-number-greater-than-twice-of-others.cpp) [Python](./Python/largest-number-greater-than-twice-of-others.py) | _O(n)_ | _O(1)_ | Easy || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From d51b7363f19b128b9596167bc36245e22cb61246 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 Jan 2018 11:16:13 +0800 Subject: [PATCH 4250/4971] Rename largest-number-greater-than-twice-of-others.cpp to largest-number-at-least-twice-of-others.cpp --- ...-of-others.cpp => largest-number-at-least-twice-of-others.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{largest-number-greater-than-twice-of-others.cpp => largest-number-at-least-twice-of-others.cpp} (100%) diff --git a/C++/largest-number-greater-than-twice-of-others.cpp b/C++/largest-number-at-least-twice-of-others.cpp similarity index 100% rename from C++/largest-number-greater-than-twice-of-others.cpp rename to C++/largest-number-at-least-twice-of-others.cpp From e3cd6983cc27bf6b34083383e9733b8684c3a136 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 6 Jan 2018 11:16:33 +0800 Subject: [PATCH 4251/4971] Rename largest-number-greater-than-twice-of-others.py to largest-number-at-least-twice-of-others.py --- ...ce-of-others.py => largest-number-at-least-twice-of-others.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{largest-number-greater-than-twice-of-others.py => largest-number-at-least-twice-of-others.py} (100%) diff --git a/Python/largest-number-greater-than-twice-of-others.py b/Python/largest-number-at-least-twice-of-others.py similarity index 100% rename from Python/largest-number-greater-than-twice-of-others.py rename to Python/largest-number-at-least-twice-of-others.py From eb55ae726780fb9e830df9eec2f892ac896ed67e Mon Sep 17 00:00:00 2001 From: Sanghee Kim Date: Sat, 6 Jan 2018 18:35:52 -0500 Subject: [PATCH 4252/4971] leetcode changed anagrams to group-anagrams --- C++/{anagrams.cpp => group-anagrams.cpp} | 0 Python/{anagrams.py => group-anagrams.py} | 0 README.md | 2 +- 3 files changed, 1 insertion(+), 1 deletion(-) rename C++/{anagrams.cpp => group-anagrams.cpp} (100%) rename Python/{anagrams.py => group-anagrams.py} (100%) diff --git a/C++/anagrams.cpp b/C++/group-anagrams.cpp similarity index 100% rename from C++/anagrams.cpp rename to C++/group-anagrams.cpp diff --git a/Python/anagrams.py b/Python/group-anagrams.py similarity index 100% rename from Python/anagrams.py rename to Python/group-anagrams.py diff --git a/README.md b/README.md index c157c8366..32a0e98f9 100644 --- a/README.md +++ b/README.md @@ -305,7 +305,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || 30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [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/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || -49| [Group Anagrams](https://leetcode.com/problems/anagrams/) | [C++](./C++/anagrams.cpp) [Python](./Python/anagrams.py) | _O(n * glogg)_ | _O(n)_ | Medium || +49| [Group Anagrams](https://leetcode.com/problems/group-anagrams/) | [C++](./C++/group-anagrams.cpp) [Python](./Python/group-anagrams.py) | _O(n * glogg)_ | _O(n)_ | Medium || 76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [C++](./C++/minimum-window-substring.cpp) [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/) | [C++](./C++/max-points-on-a-line.cpp) [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/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| From 750771c531aa6d52bbe637e6da066742314f642a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 08:00:40 +0800 Subject: [PATCH 4253/4971] Update integer-to-english-words.cpp --- C++/integer-to-english-words.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/integer-to-english-words.cpp b/C++/integer-to-english-words.cpp index fef662047..f311b5242 100644 --- a/C++/integer-to-english-words.cpp +++ b/C++/integer-to-english-words.cpp @@ -1,4 +1,4 @@ -// Time: O(logn), n is the value of the integer +// Time: O(logn) = O(1), n is the value of the integer, which is less than 2^31 - 1 // Space: O(1) class Solution { From b5f40d55d748ec022e05a3e0b0657f7bb0eda601 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 08:01:04 +0800 Subject: [PATCH 4254/4971] 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 8525612f5..3c5ab64db 100644 --- a/Python/integer-to-english-words.py +++ b/Python/integer-to-english-words.py @@ -1,4 +1,4 @@ -# Time: O(logn), n is the value of the integer +# Time: O(logn) = O(1), n is the value of the integer, which is less than 2^31 - 1 # Space: O(1) # # Convert a non-negative integer to its english words representation. From ebc5fcce0f9529e26b7ac8bdd157ac9d4e0f019f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 08:01:29 +0800 Subject: [PATCH 4255/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 32a0e98f9..2f3357cee 100644 --- a/README.md +++ b/README.md @@ -159,7 +159,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` 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 | 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)_ | Hard | | +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(1)_ | _O(1)_ | Hard | | 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 | | 383| [Ransom Note](https://leetcode.com/problems/ransom-note/) | [C++](./C++/ransom-note.cpp) [Python](./Python/ransom-note.py) | _O(n)_ | _O(1)_ | Easy | EPI | 405| [Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./C++/convert-a-number-to-hexadecimal.cpp) [Python](./Python/convert-a-number-to-hexadecimal.py) | _O(n)_ | _O(1)_ | Easy | | From ecdb8e833927064a33e0590b3cb9ec34400e0d0c Mon Sep 17 00:00:00 2001 From: SangHee Kim Date: Sat, 6 Jan 2018 19:27:05 -0500 Subject: [PATCH 4256/4971] Update strobogrammatic-number.py It doesn't need `i += 1`. Based on git blame, it seems it was accidentally added. --- Python/strobogrammatic-number.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/strobogrammatic-number.py b/Python/strobogrammatic-number.py index 37a542b93..289c531d7 100644 --- a/Python/strobogrammatic-number.py +++ b/Python/strobogrammatic-number.py @@ -12,5 +12,4 @@ def isStrobogrammatic(self, num): 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 8f1e058ac2d146644f700c36f37b1250351b3349 Mon Sep 17 00:00:00 2001 From: JXZGitHub <35183837+JXZGitHub@users.noreply.github.com> Date: Sat, 6 Jan 2018 23:02:52 -0500 Subject: [PATCH 4257/4971] Update lru-cache.py I can't explain why, but with 'del node', the following code will go into an infinite loop: l = LinkedList() one=ListNode('a',1) two=ListNode('b',2) three=ListNode('c',3) four=ListNode('d',4) l.insert(one) l.insert(two) l.insert(three) l.insert(four) print (l) l.remove(three) print (l) l.insert(three) print (l) l.remove(one) print (l) l.remove(three) print (l) --- Python/lru-cache.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/lru-cache.py b/Python/lru-cache.py index bc618fd31..0a3431229 100644 --- a/Python/lru-cache.py +++ b/Python/lru-cache.py @@ -55,7 +55,8 @@ def delete(self, node): node.next.prev = node.prev else: self.tail = node.prev - del node + node.next = None + node.prev = None class LRUCache(object): From 108c71f88a8336a039cc17405df0bcd53100840a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 15:53:49 +0800 Subject: [PATCH 4258/4971] Update lru-cache.py --- Python/lru-cache.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/lru-cache.py b/Python/lru-cache.py index 0a3431229..14cc5333d 100644 --- a/Python/lru-cache.py +++ b/Python/lru-cache.py @@ -39,6 +39,7 @@ def __init__(self): self.tail = None def insert(self, node): + node.next, node.prev = None, None # avoid dirty node if self.head is None: self.head = node else: @@ -55,8 +56,7 @@ def delete(self, node): node.next.prev = node.prev else: self.tail = node.prev - node.next = None - node.prev = None + node.next, node.prev = None, None # make node clean class LRUCache(object): From 0ffa0ba5e7cd4a77339ed19133b56685c4a9f207 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 16:01:43 +0800 Subject: [PATCH 4259/4971] Update lfu-cache.py --- Python/lfu-cache.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/lfu-cache.py b/Python/lfu-cache.py index 087f61380..97a153540 100644 --- a/Python/lfu-cache.py +++ b/Python/lfu-cache.py @@ -46,6 +46,7 @@ def __init__(self): self.tail = None def append(self, node): + node.next, node.prev = None, None # avoid dirty node if self.head is None: self.head = node else: @@ -62,7 +63,7 @@ def delete(self, node): node.next.prev = node.prev else: self.tail = node.prev - del node + node.next, node.prev = None, None # make node clean class LFUCache(object): From 8f506c20ccad47ee6f2454a419145b1b2b48adba Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 16:45:10 +0800 Subject: [PATCH 4260/4971] Create bold-words-in-string.py --- Python/bold-words-in-string.py | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/bold-words-in-string.py diff --git a/Python/bold-words-in-string.py b/Python/bold-words-in-string.py new file mode 100644 index 000000000..f5cca8349 --- /dev/null +++ b/Python/bold-words-in-string.py @@ -0,0 +1,36 @@ +# Time: O(n * l), n is the length of S, l is the average length of words +# Space: O(t), t is the size of trie + +class Solution(object): + def boldWords(self, words, S): + """ + :type words: List[str] + :type S: str + :rtype: str + """ + _trie = lambda: collections.defaultdict(_trie) + trie = _trie() + for i, word in enumerate(words): + reduce(dict.__getitem__, word, trie)["_end"] = i + + lookup = [False] * len(S) + for i in xrange(len(S)): + curr = trie + k = -1 + for j in xrange(i, len(S)): + if S[j] not in curr: + break + curr = curr[S[j]] + if "_end" in curr: + k = j + for j in xrange(i, k+1): + lookup[j] = True + + result = [] + for i in xrange(len(S)): + if lookup[i] and (i == 0 or not lookup[i-1]): + result.append("") + result.append(S[i]) + if lookup[i] and (i == len(S)-1 or not lookup[i+1]): + result.append(""); + return "".join(result) From 9f5fbeed399bea95dc5a4235023d89988064f007 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 16:49:48 +0800 Subject: [PATCH 4261/4971] Update bold-words-in-string.py --- Python/bold-words-in-string.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/bold-words-in-string.py b/Python/bold-words-in-string.py index f5cca8349..98a309c9b 100644 --- a/Python/bold-words-in-string.py +++ b/Python/bold-words-in-string.py @@ -11,7 +11,7 @@ def boldWords(self, words, S): _trie = lambda: collections.defaultdict(_trie) trie = _trie() for i, word in enumerate(words): - reduce(dict.__getitem__, word, trie)["_end"] = i + reduce(dict.__getitem__, word, trie).setdefault("_end") lookup = [False] * len(S) for i in xrange(len(S)): From 3b388e610bbe879cfd9b237ab5e314c554499244 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 17:08:08 +0800 Subject: [PATCH 4262/4971] Update bold-words-in-string.py --- Python/bold-words-in-string.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/bold-words-in-string.py b/Python/bold-words-in-string.py index 98a309c9b..e47032839 100644 --- a/Python/bold-words-in-string.py +++ b/Python/bold-words-in-string.py @@ -1,5 +1,5 @@ # Time: O(n * l), n is the length of S, l is the average length of words -# Space: O(t), t is the size of trie +# Space: O(t) , t is the size of trie class Solution(object): def boldWords(self, words, S): From 2ed5747dd30221e321e59fb83d68720ad8a16ceb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 17:09:25 +0800 Subject: [PATCH 4263/4971] Create bold-words-in-string.cpp --- C++/bold-words-in-string.cpp | 69 ++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 C++/bold-words-in-string.cpp diff --git a/C++/bold-words-in-string.cpp b/C++/bold-words-in-string.cpp new file mode 100644 index 000000000..9c4dd66b6 --- /dev/null +++ b/C++/bold-words-in-string.cpp @@ -0,0 +1,69 @@ +// Time: O(n * l), n is the length of S, l is the average length of words +// Space: O(t) , t is the size of trie + +class Solution { +public: + string boldWords(vector& words, string S) { + TrieNode trie; + for (const auto& word : words) { + trie.Insert(word); + } + + vector lookup(S.length()); + for (int i = 0; i < S.length(); ++i) { + auto curr = ≜ + int k = -1; + for (int j = i; j < S.length(); ++j) { + if (!curr->leaves[S[j] - 'a']) { + break; + } + curr = curr->leaves[S[j] - 'a']; + if (curr->isString) { + k = j; + } + } + for (int j = i; j <= k; ++j) { + lookup[j] = true; + } + } + + string result; + for (int i = 0; i < S.length(); ++i) { + if (lookup[i] && (i == 0 || !lookup[i - 1])) { + result += ""; + } + result.push_back(S[i]); + if (lookup[i] && (i == (S.length() - 1) || !lookup[i + 1])) { + result += ""; + } + } + return result; + } + +private: + struct TrieNode { + bool isString; + vector leaves; + + TrieNode() : isString{false}, leaves(26) {} + + void Insert(const string& s) { + auto* p = this; + for (const auto& c : s) { + if (!p->leaves[c - 'a']) { + p->leaves[c - 'a'] = new TrieNode; + } + p = p->leaves[c - 'a']; + } + p->isString = true; + } + + ~TrieNode() { + for (auto& node : leaves) { + if (node) { + delete node; + } + } + } + }; +}; From 70de623d64ea437172855b649b01bd6af3a50514 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 17:15:54 +0800 Subject: [PATCH 4264/4971] Create find-anagram-mappings.cpp --- C++/find-anagram-mappings.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/find-anagram-mappings.cpp diff --git a/C++/find-anagram-mappings.cpp b/C++/find-anagram-mappings.cpp new file mode 100644 index 000000000..a9e2e9483 --- /dev/null +++ b/C++/find-anagram-mappings.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector anagramMappings(vector& A, vector& B) { + unordered_map> lookup; + for (int i = 0; i < B.size(); ++i) { + lookup[B[i]].emplace(i); + } + vector result; + for (const auto& el : A) { + result.emplace_back(lookup[el].back()); + lookup[el].pop(); + } + return result; + } +}; From 2a183109c3cf5b0b3be088e90bb8e36367590561 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 17:17:41 +0800 Subject: [PATCH 4265/4971] Update find-anagram-mappings.cpp --- C++/find-anagram-mappings.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/find-anagram-mappings.cpp b/C++/find-anagram-mappings.cpp index a9e2e9483..1fa2f037b 100644 --- a/C++/find-anagram-mappings.cpp +++ b/C++/find-anagram-mappings.cpp @@ -9,9 +9,9 @@ class Solution { lookup[B[i]].emplace(i); } vector result; - for (const auto& el : A) { - result.emplace_back(lookup[el].back()); - lookup[el].pop(); + for (const auto& n : A) { + result.emplace_back(lookup[n].back()); + lookup[n].pop(); } return result; } From 7d29d96385ec9a3274f5e6409e04635e89f8c8c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 17:19:20 +0800 Subject: [PATCH 4266/4971] Create find-anagram-mappings.py --- Python/find-anagram-mappings.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Python/find-anagram-mappings.py diff --git a/Python/find-anagram-mappings.py b/Python/find-anagram-mappings.py new file mode 100644 index 000000000..6b54fa4fe --- /dev/null +++ b/Python/find-anagram-mappings.py @@ -0,0 +1,17 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def anagramMappings(self, A, B): + """ + :type A: List[int] + :type B: List[int] + :rtype: List[int] + """ + lookup = collections.defaultdict(collections.deque) + for i, n in enumerate(B): + lookup[n].append(i) + result = [] + for n in A: + result.append(lookup[n].popleft()) + return result From fbc3e69f8cb65e1c4204720803644a772fbd6748 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 18:04:05 +0800 Subject: [PATCH 4267/4971] Create employee-free-time.cpp --- C++/employee-free-time.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/employee-free-time.cpp diff --git a/C++/employee-free-time.cpp b/C++/employee-free-time.cpp new file mode 100644 index 000000000..85cc530db --- /dev/null +++ b/C++/employee-free-time.cpp @@ -0,0 +1,37 @@ +// Time: O(m * logn), m is the number of schedule, n is the number of employees, m >= n +// 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: + vector employeeFreeTime(vector>& schedule) { + vector result; + using P = pair>; + priority_queue, greater

> min_heap; + for (int i = 0; i < schedule.size(); ++i) { + min_heap.emplace(schedule[i][0].start, make_pair(i, 0)); + } + int last_end = -1; + while (!min_heap.empty()) { + int t; + pair p; + tie(t, p) = min_heap.top(); min_heap.pop(); + if (0 <= last_end && last_end < t) { + result.emplace_back(last_end, t); + } + last_end = max(last_end, schedule[p.first][p.second].end); + if (p.second + 1 < schedule[p.first].size()) { + min_heap.emplace(schedule[p.first][p.second + 1].start, make_pair(p.first, p.second + 1)); + } + } + return result; + } +}; From e215b468ec5ec28c837e1270e399369ded3ffc7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 18:04:54 +0800 Subject: [PATCH 4268/4971] Create employee-free-time.py --- Python/employee-free-time.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/employee-free-time.py diff --git a/Python/employee-free-time.py b/Python/employee-free-time.py new file mode 100644 index 000000000..067a35951 --- /dev/null +++ b/Python/employee-free-time.py @@ -0,0 +1,27 @@ +# Time: O(m * logn), m is the number of schedule, n is the number of employees, m >= n +# Space: O(n) + +# Definition for an interval. +# class Interval(object): +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class Solution(object): + def employeeFreeTime(self, schedule): + """ + :type schedule: List[List[Interval]] + :rtype: List[Interval] + """ + result = [] + min_heap = [(emp[0].start, eid, 0) for eid, emp in enumerate(schedule)] + heapq.heapify(min_heap) + last_end = -1 + while min_heap: + t, eid, i = heapq.heappop(min_heap) + if 0 <= last_end < t: + result.append(Interval(last_end, t)) + last_end = max(last_end, schedule[eid][i].end) + if i+1 < len(schedule[eid]): + heapq.heappush(min_heap, (schedule[eid][i+1].start, eid, i+1)) + return result From ecfb8c8e1458a5d0a1ca85076e9ecc325e6c08fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 18:56:48 +0800 Subject: [PATCH 4269/4971] Create special-binary-string.cpp --- C++/special-binary-string.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/special-binary-string.cpp diff --git a/C++/special-binary-string.cpp b/C++/special-binary-string.cpp new file mode 100644 index 000000000..428d9f362 --- /dev/null +++ b/C++/special-binary-string.cpp @@ -0,0 +1,24 @@ +// Time: f(n) = kf(n/k) + n/k * klogk <= O(logn * nlogk) <= O(n^2) +// n is the length of S, k is the max number of special strings in each depth +// Space: O(n) + +class Solution { +public: + string makeLargestSpecial(string S) { + vector result; + int anchor = 0, count = 0; + for (int i = 0; i < S.length(); ++i) { + (S[i] == '1') ? ++count : --count; + if (count == 0) { + string tmp; + tmp += "1"; + tmp += makeLargestSpecial(S.substr(anchor + 1, i - anchor - 1)); + tmp += "0"; + result.emplace_back(move(tmp)); + anchor = i + 1; + } + } + sort(result.begin(), result.end(), greater()); + return accumulate(result.begin(), result.end(), string()); + } +}; From c313a21274f4e77d0c4baad13c5c0f5781ac13ef Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 18:56:55 +0800 Subject: [PATCH 4270/4971] Create special-binary-string.py --- Python/special-binary-string.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Python/special-binary-string.py diff --git a/Python/special-binary-string.py b/Python/special-binary-string.py new file mode 100644 index 000000000..d295bd92a --- /dev/null +++ b/Python/special-binary-string.py @@ -0,0 +1,19 @@ +# Time: f(n) = kf(n/k) + n/k * klogk <= O(logn * nlogk) <= O(n^2) +# n is the length of S, k is the max number of special strings in each depth +# Space: O(n) + +class Solution(object): + def makeLargestSpecial(self, S): + """ + :type S: str + :rtype: str + """ + result = [] + j = count = 0 + for i, v in enumerate(S): + count += 1 if v == '1' else -1 + if count == 0: + result.append("1{}0".format(self.makeLargestSpecial(S[j+1:i]))) + j = i+1 + result.sort(reverse = True) + return "".join(result) From a5492c342b5606bfdd4cee5635474253ce0716ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 18:57:21 +0800 Subject: [PATCH 4271/4971] Update special-binary-string.cpp --- C++/special-binary-string.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/special-binary-string.cpp b/C++/special-binary-string.cpp index 428d9f362..53dba36bd 100644 --- a/C++/special-binary-string.cpp +++ b/C++/special-binary-string.cpp @@ -1,4 +1,4 @@ -// Time: f(n) = kf(n/k) + n/k * klogk <= O(logn * nlogk) <= O(n^2) +// Time: f(n) = k * f(n/k) + n/k * klogk <= O(logn * nlogk) <= O(n^2) // n is the length of S, k is the max number of special strings in each depth // Space: O(n) From a10ee58380231cf9cf1522772d2faa9ae9fc057f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 18:57:59 +0800 Subject: [PATCH 4272/4971] Update special-binary-string.py --- Python/special-binary-string.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/special-binary-string.py b/Python/special-binary-string.py index d295bd92a..124bd7ad0 100644 --- a/Python/special-binary-string.py +++ b/Python/special-binary-string.py @@ -1,4 +1,4 @@ -# Time: f(n) = kf(n/k) + n/k * klogk <= O(logn * nlogk) <= O(n^2) +# Time: f(n) = k * f(n/k) + n/k * klogk <= O(logn * nlogk) <= O(n^2) # n is the length of S, k is the max number of special strings in each depth # Space: O(n) From 315c6a924a5a5be19809ea21e58141eee60cf2b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 19:03:05 +0800 Subject: [PATCH 4273/4971] Update special-binary-string.cpp --- C++/special-binary-string.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/C++/special-binary-string.cpp b/C++/special-binary-string.cpp index 53dba36bd..7405effe4 100644 --- a/C++/special-binary-string.cpp +++ b/C++/special-binary-string.cpp @@ -10,11 +10,9 @@ class Solution { for (int i = 0; i < S.length(); ++i) { (S[i] == '1') ? ++count : --count; if (count == 0) { - string tmp; - tmp += "1"; - tmp += makeLargestSpecial(S.substr(anchor + 1, i - anchor - 1)); - tmp += "0"; - result.emplace_back(move(tmp)); + result.emplace_back("1"); + result.back() += makeLargestSpecial(S.substr(anchor + 1, i - anchor - 1)); + result.back() += "0"; anchor = i + 1; } } From 423187054d0c0201b35f7894fb3257e2cb7f26b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 19:04:02 +0800 Subject: [PATCH 4274/4971] Update special-binary-string.py --- Python/special-binary-string.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/special-binary-string.py b/Python/special-binary-string.py index 124bd7ad0..2b577a0a4 100644 --- a/Python/special-binary-string.py +++ b/Python/special-binary-string.py @@ -9,11 +9,11 @@ def makeLargestSpecial(self, S): :rtype: str """ result = [] - j = count = 0 + anchor = count = 0 for i, v in enumerate(S): count += 1 if v == '1' else -1 if count == 0: - result.append("1{}0".format(self.makeLargestSpecial(S[j+1:i]))) - j = i+1 + result.append("1{}0".format(self.makeLargestSpecial(S[anchor+1:i]))) + anchor = i+1 result.sort(reverse = True) return "".join(result) From bbb28b85164576d42d861370fc5a242a12afc0ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 19:22:24 +0800 Subject: [PATCH 4275/4971] Update add-bold-tag-in-string.cpp --- C++/add-bold-tag-in-string.cpp | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/C++/add-bold-tag-in-string.cpp b/C++/add-bold-tag-in-string.cpp index 9e695c2c6..4cc69d754 100644 --- a/C++/add-bold-tag-in-string.cpp +++ b/C++/add-bold-tag-in-string.cpp @@ -4,25 +4,23 @@ class Solution { public: string addBoldTag(string s, vector& dict) { - vector bold(s.length()); + vector lookup(s.length()); for (const auto& d: dict) { auto pos = -1; while ((pos = s.find(d, pos + 1)) != string::npos) { - fill(bold.begin() + pos, bold.begin() + pos + d.length(), true); + fill(lookup.begin() + pos, lookup.begin() + pos + d.length(), true); } } string result; - bool prev = false; for (int i = 0; i < s.length(); ++i) { - if (prev != bold[i]) { - result += prev ? "" : ""; - prev = bold[i]; + if (lookup[i] && (i == 0 || !lookup[i - 1])) { + result += ""; } result.push_back(s[i]); - } - if (prev) { - result += ""; + if (lookup[i] && (i == (s.length() - 1) || !lookup[i + 1])) { + result += ""; + } } return result; } -}; \ No newline at end of file +}; From b735d58a9934d0954fd82cf486bee165429d9413 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 19:23:47 +0800 Subject: [PATCH 4276/4971] Update add-bold-tag-in-string.py --- Python/add-bold-tag-in-string.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/Python/add-bold-tag-in-string.py b/Python/add-bold-tag-in-string.py index 12b709857..0c5fafd1a 100644 --- a/Python/add-bold-tag-in-string.py +++ b/Python/add-bold-tag-in-string.py @@ -8,19 +8,18 @@ def addBoldTag(self, s, dict): :type dict: List[str] :rtype: str """ - bold = [0] * len(s) + lookup = [0] * len(s) for d in dict: pos = s.find(d) while pos != -1: - bold[pos:pos+len(d)] = [1] * len(d) + lookup[pos:pos+len(d)] = [1] * len(d) pos = s.find(d, pos + 1) - result, prev = [], 0 + result = [] for i in xrange(len(s)): - if prev != bold[i]: - result += "" if prev else "" - prev = bold[i] - result += s[i] - if prev: - result += "" + if lookup[i] and (i == 0 or not lookup[i-1]): + result.append("") + result.append(s[i]) + if lookup[i] and (i == len(s)-1 or not lookup[i+1]): + result.append(""); return "".join(result) From 681d82209597b9c02fd55d23016ac575464030ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 19:27:15 +0800 Subject: [PATCH 4277/4971] Update bold-words-in-string.py --- Python/bold-words-in-string.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Python/bold-words-in-string.py b/Python/bold-words-in-string.py index e47032839..455e3717f 100644 --- a/Python/bold-words-in-string.py +++ b/Python/bold-words-in-string.py @@ -34,3 +34,29 @@ def boldWords(self, words, S): if lookup[i] and (i == len(S)-1 or not lookup[i+1]): result.append(""); return "".join(result) + + +# Time: O(n * d * l), l is the average length of words +# Space: O(n) +class Solution2(object): + def boldWords(self, words, S): + """ + :type words: List[str] + :type S: str + :rtype: str + """ + lookup = [0] * len(S) + for d in words: + pos = S.find(d) + while pos != -1: + lookup[pos:pos+len(d)] = [1] * len(d) + pos = S.find(d, pos+1) + + result = [] + for i in xrange(len(S)): + if lookup[i] and (i == 0 or not lookup[i-1]): + result.append("") + result.append(S[i]) + if lookup[i] and (i == len(S)-1 or not lookup[i+1]): + result.append(""); + return "".join(result) From 159fc5b9075ab3f28172b70ee8fc91ac470909fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 19:29:03 +0800 Subject: [PATCH 4278/4971] Update bold-words-in-string.cpp --- C++/bold-words-in-string.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/C++/bold-words-in-string.cpp b/C++/bold-words-in-string.cpp index 9c4dd66b6..8eee16c47 100644 --- a/C++/bold-words-in-string.cpp +++ b/C++/bold-words-in-string.cpp @@ -67,3 +67,30 @@ class Solution { } }; }; + + +// Time: O(n * d * l), l is the average length of words +// Space: O(n) +class Solution2 { +public: + string boldWords(vector& words, string S) { + vector lookup(S.length()); + for (const auto& d: words) { + auto pos = -1; + while ((pos = S.find(d, pos + 1)) != string::npos) { + fill(lookup.begin() + pos, lookup.begin() + pos + d.length(), true); + } + } + string result; + for (int i = 0; i < S.length(); ++i) { + if (lookup[i] && (i == 0 || !lookup[i - 1])) { + result += ""; + } + result.push_back(S[i]); + if (lookup[i] && (i == (S.length() - 1) || !lookup[i + 1])) { + result += ""; + } + } + return result; + } +}; From e6b25610b84df63334e632e708271a6ff5a127ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 7 Jan 2018 23:34:20 +0800 Subject: [PATCH 4279/4971] Update bold-words-in-string.cpp --- C++/bold-words-in-string.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/bold-words-in-string.cpp b/C++/bold-words-in-string.cpp index 8eee16c47..71cbedbe9 100644 --- a/C++/bold-words-in-string.cpp +++ b/C++/bold-words-in-string.cpp @@ -12,7 +12,7 @@ class Solution { vector lookup(S.length()); for (int i = 0; i < S.length(); ++i) { auto curr = ≜ - int k = -1; + int k = i - 1; for (int j = i; j < S.length(); ++j) { if (!curr->leaves[S[j] - 'a']) { break; @@ -22,9 +22,7 @@ class Solution { k = j; } } - for (int j = i; j <= k; ++j) { - lookup[j] = true; - } + fill(lookup.begin() + i, lookup.begin() + k + 1, true); } string result; From 8f11c6f0e90a187d99329d9e4d129c10d7a39579 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jan 2018 13:16:54 +0800 Subject: [PATCH 4280/4971] Update README.md --- README.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2f3357cee..e44d7feac 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 731 | [My Calendar II](https://leetcode.com/problems/my-calendar-ii/) | [C++](./C++/my-calendar-ii.cpp) [Python](./Python/my-calendar-ii.py) | _O(n^2)_ | _O(n)_ | Medium || 732 | [My Calendar III](https://leetcode.com/problems/my-calendar-iii/) | [C++](./C++/my-calendar-iii.cpp) [Python](./Python/my-calendar-iii.py) | _O(n^2)_ | _O(n)_ | Hard || 747 | [Largest Number At Least Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others/) | [C++](./C++/largest-number-at-least-twice-of-others.cpp) [Python](./Python/largest-number-at-least-twice-of-others.py) | _O(n)_ | _O(1)_ | Easy || -756 | [Pour Water](https://leetcode.com/problems/pour-water/) | [C++](./C++/pour-water.cpp) [Python](./Python/pour-water.py) | _O(v * n)_ | _O(1)_ | Medium || +755 | [Pour Water](https://leetcode.com/problems/pour-water/) | [C++](./C++/pour-water.cpp) [Python](./Python/pour-water.py) | _O(v * n)_ | _O(1)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -189,6 +189,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 720| [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/) | [C++](./C++/longest-word-in-dictionary.cpp) [Python](./Python/longest-word-in-dictionary.py) | _O(n)_ | _O(t)_ | Easy || Trie | 722| [Remove Comments](https://leetcode.com/problems/remove-comments/) | [C++](./C++/remove-comments.cpp) [Python](./Python/remove-comments.py) | _O(n)_ | _O(k)_ | Medium ||| 751| [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) | [C++](./C++/ip-to-cidr.cpp) [Python](./Python/ip-to-cidr.py) | _O(n)_ | _O(1)_ | Medium ||| +758| [Bold Words in String](https://leetcode.com/problems/bold-words-in-string/) | [C++](./C++/bold-words-in-string.cpp) [Python](./Python/bold-words-in-string.py) | _O(n * l)_ | _O(t)_ | Easy | variant of [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -349,6 +350,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 734| [Sentence Similarity](https://leetcode.com/problems/sentence-similarity/) | [C++](./C++/sentence-similarity.cpp) [Python](./Python/sentence-similarity.py) | _O(n + p)_ | _O(p)_| Easy || 737| [Sentence Similarity II](https://leetcode.com/problems/sentence-similarity-ii/) | [C++](./C++/sentence-similarity-ii.cpp) [Python](./Python/sentence-similarity-ii.py) | _O(n + p)_ | _O(p)_| Medium || Union Find 748 | [Shortest Completing Word](https://leetcode.com/problems/shortest-completing-word/) | [C++](./C++/shortest-completing-word.cpp) [Python](./Python/shortest-completing-word.py) | _O(n)_ | _O(1)_ | Easy || +760 | [Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings/) | [C++](./C++/find-anagram-mappings.cpp) [Python](./Python/find-anagram-mappings.py) | _O(n)_ | _O(n)_ | Easy || ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -405,7 +407,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 660 | [Remove 9](https://leetcode.com/problems/remove-9/) | [C++](./C++/remove-9.cpp) [Python](./Python/remove-9.py) | _O(logn)_ | _O(1)_ | Hard |📖|| 672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/) | [C++](./C++/bulb-switcher-ii.cpp) [Python](./Python/bulb-switcher-ii.py) | _O(1)_ | _O(1)_ | Medium ||| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/) | [C++](./C++/self-dividing-numbers.cpp) [Python](./Python/self-dividing-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| -755 | [Reach a Number](https://leetcode.com/problems/reach-a-number/) | [C++](./C++/reach-a-number.cpp) [Python](./Python/reach-a-number.py) | _O(logn)_ | _O(1)_ | Medium ||| +754 | [Reach a Number](https://leetcode.com/problems/reach-a-number/) | [C++](./C++/reach-a-number.cpp) [Python](./Python/reach-a-number.py) | _O(logn)_ | _O(1)_ | Medium ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -480,6 +482,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 549 | [Binary Tree Longest Consecutive Sequence II](https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/) | [C++](./C++/binary-tree-longest-consecutive-sequence-ii.cpp) [Python](./Python/binary-tree-longest-consecutive-sequence-ii.py) | _O(n)_ | _O(h)_ | Medium |📖| 669| [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C++](./C++/trim-a-binary-search-tree.cpp) [Python](./Python/trim-a-binary-search-tree.py) | _O(n)_ | _O(h)_ | Easy || 671| [Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [C++](./C++/second-minimum-node-in-a-binary-tree.cpp) [Python](./Python/second-minimum-node-in-a-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || +761| [Special Binary String](https://leetcode.com/problems/special-binary-string/) | [C++](./C++/special-binary-string.cpp) [Python](./Python/special-binary-string.py) | _O(n^2)_ | _O(n)_ | Hard || ## Binary Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -582,7 +585,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 733| [Max Area of Island](https://leetcode.com/problems/flood-fill/) | [C++](./C++/flood-fill.cpp) [Python](./Python/flood-fill.py) | _O(m * n)_ | _O(m * n)_ | Easy || 749| [Contain Virus](https://leetcode.com/problems/contain-virus/) | [C++](./C++/contain-virus.cpp) [Python](./Python/contain-virus.py) | _O((m * n)^(4/3))_ | _O(m * n)_ | Hard || Simulation| 753| [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [C++](./C++/cracking-the-safe.cpp) [Python](./Python/cracking-the-safe.py) | _O(k^n)_ | _O(k^n)_ | Hard || `de Bruijn sequences`, `Lyndon word` | -757| [Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix/) | [C++](./C++/pyramid-transition-matrix.cpp) [Python](./Python/pyramid-transition-matrix.py) | _O(a^b)_ | _O(a^b)_ | Medium ||| +756| [Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix/) | [C++](./C++/pyramid-transition-matrix.cpp) [Python](./Python/pyramid-transition-matrix.py) | _O(a^b)_ | _O(a^b)_ | Medium ||| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -719,7 +722,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [C++](./C++/dota2-senate.cpp) [Python](./Python/dota2-senate.py) | _O(n)_ | _O(n)_ | Medium ||| 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | 738 | [Monotone Increasing Digits](https://leetcode.com/problems/monotone-increasing-digits/) | [C++](./C++/monotone-increasing-digits.cpp) [Python](./Python/monotone-increasing-digits.py) | _O(1)_ | _O(1)_ | Medium | | -759 | [Set Intersection Size At Least Two](https://leetcode.com/problems/set-intersection-size-at-least-two/) | [C++](./C++/set-intersection-size-at-least-two.cpp) [Python](./Python/set-intersection-size-at-least-two.py) | _O(nlogn)_ | _O(n)_ | Hard | | +757 | [Set Intersection Size At Least Two](https://leetcode.com/problems/set-intersection-size-at-least-two/) | [C++](./C++/set-intersection-size-at-least-two.cpp) [Python](./Python/set-intersection-size-at-least-two.py) | _O(nlogn)_ | _O(n)_ | Hard | | +759 | [Employee Free Time](https://leetcode.com/problems/employee-free-time/) | [C++](./C++/employee-free-time.cpp) [Python](./Python/employee-free-time.py) | _O(m * logn)_ | _O(n)_ | Hard | | ## Geometry | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 2f769ba0f6b8a4ae0966bf4d2b6f3c8dffaa6fec Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jan 2018 13:37:19 +0800 Subject: [PATCH 4281/4971] Update special-binary-string.py --- Python/special-binary-string.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/Python/special-binary-string.py b/Python/special-binary-string.py index 2b577a0a4..b743a60fa 100644 --- a/Python/special-binary-string.py +++ b/Python/special-binary-string.py @@ -1,7 +1,30 @@ # Time: f(n) = k * f(n/k) + n/k * klogk <= O(logn * nlogk) <= O(n^2) # n is the length of S, k is the max number of special strings in each depth # Space: O(n) - + +# Special binary strings are binary strings with the following two properties: +# +# The number of 0's is equal to the number of 1's. +# Every prefix of the binary string has at least as many 1's as 0's. +# Given a special string S, a move consists of choosing two consecutive, non-empty, +# special substrings of S, and swapping them. +# (Two strings are consecutive if the last character of the first string is +# exactly one index before the first character of the second string.) +# +# At the end of any number of moves, what is the lexicographically largest resulting string possible? +# +# Example 1: +# Input: S = "11011000" +# Output: "11100100" +# +# Explanation: +# The strings "10" [occuring at S[1]] and "1100" [at S[3]] are swapped. +# This is the lexicographically largest string possible after some number of swaps. +# +# Note: +# - S has length at most 50. +# - S is guaranteed to be a special binary string as defined above. + class Solution(object): def makeLargestSpecial(self, S): """ From e2fbf42741c6e5e0134b07fd7a353ce5af264e4d Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jan 2018 13:38:21 +0800 Subject: [PATCH 4282/4971] Update find-anagram-mappings.py --- Python/find-anagram-mappings.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Python/find-anagram-mappings.py b/Python/find-anagram-mappings.py index 6b54fa4fe..c113d42a0 100644 --- a/Python/find-anagram-mappings.py +++ b/Python/find-anagram-mappings.py @@ -1,6 +1,27 @@ # Time: O(n) # Space: O(n) +# Given two lists Aand B, and B is an anagram of A. +# B is an anagram of A means B is made by randomizing the order of the elements in A. +# +# We want to find an index mapping P, from A to B. A mapping P[i] = j +# means the ith element in A appears in B at index j. +# +# These lists A and B may contain duplicates. If there are multiple answers, output any of them. +# +# For example, given +# A = [12, 28, 46, 32, 50] +# B = [50, 12, 32, 46, 28] +# +# We should return +# [1, 4, 3, 2, 0] +# as P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 +# because the 1st element of A appears at B[4], and so on. +# +# Note: +# - A, B have equal lengths in range [1, 100]. +# - A[i], B[i] are integers in range [0, 10^5]. + class Solution(object): def anagramMappings(self, A, B): """ From aecf96d567d36f7b3446d5bd0a7a905cf6616ab6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jan 2018 13:39:46 +0800 Subject: [PATCH 4283/4971] Update employee-free-time.py --- Python/employee-free-time.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Python/employee-free-time.py b/Python/employee-free-time.py index 067a35951..e2f0779a1 100644 --- a/Python/employee-free-time.py +++ b/Python/employee-free-time.py @@ -1,6 +1,32 @@ # Time: O(m * logn), m is the number of schedule, n is the number of employees, m >= n # Space: O(n) +# We are given a list schedule of employees, which represents the working time for each employee. +# Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. +# Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order. +# +# Example 1: +# Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]] +# Output: [[3,4]] +# Explanation: +# There are a total of three employees, and all common +# free time intervals would be [-inf, 1], [3, 4], [10, inf]. +# We discard any intervals that contain inf as they aren't finite. +# +# Example 2: +# Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]] +# Output: [[5,6],[7,9]] +# (Even though we are representing Intervals in the form [x, y], +# the objects inside are Intervals, not lists or arrays. +# For example, schedule[0][0].start = 1, schedule[0][0].end = 2, +# and schedule[0][0][0] is not defined.) +# +# Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length. +# +# Note: +# - schedule and schedule[i] are lists with lengths in range [1, 50]. +# - 0 <= schedule[i].start < schedule[i].end <= 10^8. + # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): From 2118768dad311a32727a9b115c98a02e59437f42 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jan 2018 13:40:45 +0800 Subject: [PATCH 4284/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e44d7feac..cb3b9c202 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 720| [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/) | [C++](./C++/longest-word-in-dictionary.cpp) [Python](./Python/longest-word-in-dictionary.py) | _O(n)_ | _O(t)_ | Easy || Trie | 722| [Remove Comments](https://leetcode.com/problems/remove-comments/) | [C++](./C++/remove-comments.cpp) [Python](./Python/remove-comments.py) | _O(n)_ | _O(k)_ | Medium ||| 751| [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) | [C++](./C++/ip-to-cidr.cpp) [Python](./Python/ip-to-cidr.py) | _O(n)_ | _O(1)_ | Medium ||| -758| [Bold Words in String](https://leetcode.com/problems/bold-words-in-string/) | [C++](./C++/bold-words-in-string.cpp) [Python](./Python/bold-words-in-string.py) | _O(n * l)_ | _O(t)_ | Easy | variant of [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | +758| [Bold Words in String](https://leetcode.com/problems/bold-words-in-string/) | [C++](./C++/bold-words-in-string.cpp) [Python](./Python/bold-words-in-string.py) | _O(n * l)_ | _O(t)_ | Easy | 📖, variant of [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 19c2edd7c5fdb9934a6f71546d4fac7b5db1a7ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jan 2018 14:05:31 +0800 Subject: [PATCH 4285/4971] Update add-bold-tag-in-string.cpp --- C++/add-bold-tag-in-string.cpp | 73 +++++++++++++++++++++++++++++++++- 1 file changed, 71 insertions(+), 2 deletions(-) diff --git a/C++/add-bold-tag-in-string.cpp b/C++/add-bold-tag-in-string.cpp index 4cc69d754..865454eaa 100644 --- a/C++/add-bold-tag-in-string.cpp +++ b/C++/add-bold-tag-in-string.cpp @@ -1,6 +1,7 @@ -// Time: O(s * d * l), l is the average string length -// Space: O(s) +// Time: O(n * d * l), l is the average string length +// Space: O(n) +// 16ms class Solution { public: string addBoldTag(string s, vector& dict) { @@ -24,3 +25,71 @@ class Solution { return result; } }; + +// Time: O(n * l), l is the average string length +// Space: O(t) , t is the size of trie +// 142ms +class Solution2 { +public: + string addBoldTag(string s, vector& dict) { + TrieNode trie; + for (const auto& word : dict) { + trie.Insert(word); + } + + vector lookup(s.length()); + for (int i = 0; i < s.length(); ++i) { + auto curr = ≜ + int k = i - 1; + for (int j = i; j < s.length(); ++j) { + if (!curr->leaves.count(s[j])) { + break; + } + curr = curr->leaves[s[j]]; + if (curr->isString) { + k = j; + } + } + fill(lookup.begin() + i, lookup.begin() + k + 1, true); + } + + string result; + for (int i = 0; i < s.length(); ++i) { + if (lookup[i] && (i == 0 || !lookup[i - 1])) { + result += ""; + } + result.push_back(s[i]); + if (lookup[i] && (i == (s.length() - 1) || !lookup[i + 1])) { + result += ""; + } + } + return result; + } + +private: + struct TrieNode { + bool isString; + unordered_map leaves; + + TrieNode() : isString{false} {} + + void Insert(const string& s) { + auto* p = this; + for (const auto& c : s) { + if (!p->leaves[c]) { + p->leaves[c] = new TrieNode; + } + p = p->leaves[c]; + } + p->isString = true; + } + + ~TrieNode() { + for (auto& kvp : leaves) { + if (kvp.second) { + delete kvp.second; + } + } + } + }; +}; From 96a775c5960c8fa86553cb34d92e45ee67f89539 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jan 2018 14:10:22 +0800 Subject: [PATCH 4286/4971] Update add-bold-tag-in-string.py --- Python/add-bold-tag-in-string.py | 43 ++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/Python/add-bold-tag-in-string.py b/Python/add-bold-tag-in-string.py index 0c5fafd1a..def3394f3 100644 --- a/Python/add-bold-tag-in-string.py +++ b/Python/add-bold-tag-in-string.py @@ -1,6 +1,7 @@ -# Time: O(s * d * l), l is the average string length -# Space: O(s) +# Time: O(n * d * l), l is the average string length +# Space: O(n) +# 59ms class Solution(object): def addBoldTag(self, s, dict): """ @@ -23,3 +24,41 @@ def addBoldTag(self, s, dict): if lookup[i] and (i == len(s)-1 or not lookup[i+1]): result.append(""); return "".join(result) + + +# Time: O(n * l), l is the average string length +# Space: O(t) , t is the size of trie +# trie solution, 439ms +class Solution2(object): + def addBoldTag(self, s, words): + """ + :type s: str + :type words: List[str] + :rtype: str + """ + _trie = lambda: collections.defaultdict(_trie) + trie = _trie() + for i, word in enumerate(words): + reduce(dict.__getitem__, word, trie).setdefault("_end") + + lookup = [False] * len(s) + for i in xrange(len(s)): + curr = trie + k = -1 + for j in xrange(i, len(s)): + if s[j] not in curr: + break + curr = curr[s[j]] + if "_end" in curr: + k = j + for j in xrange(i, k+1): + lookup[j] = True + + result = [] + for i in xrange(len(s)): + if lookup[i] and (i == 0 or not lookup[i-1]): + result.append("") + result.append(s[i]) + if lookup[i] and (i == len(s)-1 or not lookup[i+1]): + result.append(""); + return "".join(result) From 4370f4de7260fa5376725a2abe711ec9e1149a3a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jan 2018 14:10:48 +0800 Subject: [PATCH 4287/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cb3b9c202..29e7a67a3 100644 --- a/README.md +++ b/README.md @@ -177,7 +177,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 557| [Reverse Words in a String III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) |[C++](./C++/reverse-words-in-a-string-iii.cpp) [Python](./Python/reverse-words-in-a-string-iii.py) | _O(n)_ | _O(1)_ | Easy | | 564| [Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/) |[C++](./C++/find-the-closest-palindrome.cpp) [Python](./Python/find-the-closest-palindrome.py) | _O(l)_ | _O(l)_ | Hard | | 591| [Tag Validator](https://leetcode.com/problems/tag-validator/) |[C++](./C++/tag-validator.cpp) [Python](./Python/tag-validator.py) | _O(n)_ | _O(n)_ | Hard | | -616| [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | [C++](./C++/add-bold-tag-in-string.cpp) [Python](./Python/add-bold-tag-in-string.py) | _O(s * d * l)_ | _O(s)_ | Medium | 📖 | +616| [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | [C++](./C++/add-bold-tag-in-string.cpp) [Python](./Python/add-bold-tag-in-string.py) | _O(n * d * l)_ | _O(n)_ | Medium | 📖 | 647| [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) | [C++](./C++/palindromic-substrings.cpp) [Python](./Python/palindromic-substrings.py) | _O(n)_ | _O(n)_ | Medium || `Manacher's Algorithm` 648| [Replace Words](https://leetcode.com/problems/replace-words/) | [C++](./C++/replace-words.cpp) [Python](./Python/replace-words.py) | _O(n)_ | _O(t)_ | Medium || Trie | 657| [Judge Route Circle](https://leetcode.com/problems/judge-route-circle/) |[C++](./C++/judge-route-circle.cpp) [Python](./Python/judge-route-circle.py) | _O(n)_ | _O(1)_ | Easy | | From f7fdb0b1b7c6a8d88cf71fad39f29ca60d9638f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jan 2018 14:11:06 +0800 Subject: [PATCH 4288/4971] Update add-bold-tag-in-string.cpp --- C++/add-bold-tag-in-string.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/add-bold-tag-in-string.cpp b/C++/add-bold-tag-in-string.cpp index 865454eaa..cbcf265af 100644 --- a/C++/add-bold-tag-in-string.cpp +++ b/C++/add-bold-tag-in-string.cpp @@ -28,7 +28,7 @@ class Solution { // Time: O(n * l), l is the average string length // Space: O(t) , t is the size of trie -// 142ms +// trie solution, 142ms class Solution2 { public: string addBoldTag(string s, vector& dict) { From 856773ba2f908bb16d21ccde34f8a8e7bc7847d3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 9 Jan 2018 14:12:45 +0800 Subject: [PATCH 4289/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 29e7a67a3..8b8beaac0 100644 --- a/README.md +++ b/README.md @@ -189,7 +189,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 720| [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/) | [C++](./C++/longest-word-in-dictionary.cpp) [Python](./Python/longest-word-in-dictionary.py) | _O(n)_ | _O(t)_ | Easy || Trie | 722| [Remove Comments](https://leetcode.com/problems/remove-comments/) | [C++](./C++/remove-comments.cpp) [Python](./Python/remove-comments.py) | _O(n)_ | _O(k)_ | Medium ||| 751| [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) | [C++](./C++/ip-to-cidr.cpp) [Python](./Python/ip-to-cidr.py) | _O(n)_ | _O(1)_ | Medium ||| -758| [Bold Words in String](https://leetcode.com/problems/bold-words-in-string/) | [C++](./C++/bold-words-in-string.cpp) [Python](./Python/bold-words-in-string.py) | _O(n * l)_ | _O(t)_ | Easy | 📖, variant of [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | +758| [Bold Words in String](https://leetcode.com/contest/weekly-contest-66/problems/bold-words-in-string/) | [C++](./C++/bold-words-in-string.cpp) [Python](./Python/bold-words-in-string.py) | _O(n * l)_ | _O(t)_ | Easy | 📖, variant of [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 8db281e22432943262885e2f72ece039a8d3d604 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Jan 2018 01:41:56 +0800 Subject: [PATCH 4290/4971] Update plus-one.cpp --- C++/plus-one.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/C++/plus-one.cpp b/C++/plus-one.cpp index 78d484a18..7a695fe99 100644 --- a/C++/plus-one.cpp +++ b/C++/plus-one.cpp @@ -4,16 +4,17 @@ class Solution { public: vector plusOne(vector& digits) { - vector result(digits.cbegin(), digits.cend()); + vector result(digits.rbegin(), digits.rend()); int carry = 1; - for (auto it = result.rbegin(); it != result.rend(); ++it) { - *it += carry; - carry = *it / 10; - *it %= 10; + for (auto& num : result) { + num += carry; + carry = num / 10; + num %= 10; } if (carry == 1) { - result.emplace(result.begin(), carry); + result.emplace_back(carry); } + reverse(result.begin(), result.end()); return result; } }; From 30c5e05750eb42ed4183e089ef7cba085efe4bd8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Jan 2018 01:54:33 +0800 Subject: [PATCH 4291/4971] Update plus-one.cpp --- C++/plus-one.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/C++/plus-one.cpp b/C++/plus-one.cpp index 7a695fe99..c66fb4d2b 100644 --- a/C++/plus-one.cpp +++ b/C++/plus-one.cpp @@ -1,7 +1,27 @@ // Time: O(n) // Space: O(1) +// in-place solution class Solution { +public: + vector plusOne(vector& digits) { + for (int i = digits.size() - 1; i >= 0; --i) { + if (digits[i] == 9) { + digits[i] = 0; + } else { + ++digits[i]; + return digits; + } + } + digits[0] = 1; + digits.emplace_back(0); + return digits; + } +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { public: vector plusOne(vector& digits) { vector result(digits.rbegin(), digits.rend()); From f756a8948c1ad7b94c877e7d967558637f7297fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 10 Jan 2018 01:58:30 +0800 Subject: [PATCH 4292/4971] Update plus-one.py --- Python/plus-one.py | 53 +++++++++++++++++++++++++++------------------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/Python/plus-one.py b/Python/plus-one.py index c708ff120..d7cfb5fe2 100644 --- a/Python/plus-one.py +++ b/Python/plus-one.py @@ -1,36 +1,45 @@ # Time: O(n) # Space: O(1) -# -# Given a non-negative number represented as an array of digits, plus one to the number. -# -# The digits are stored such that the most significant digit is at the head of the list. +# Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. +# You may assume the integer do not contain any leading zero, except the number 0 itself. +# The digits are stored such that the most significant digit is at the head of the list. -class Solution: - """ - :type digits: List[int] - :rtype: List[int] - """ +# in-place solution +class Solution(object): def plusOne(self, digits): - carry = 1 + """ + :type digits: List[int] + :rtype: List[int] + """ for i in reversed(xrange(len(digits))): - digits[i] += carry - carry = digits[i] / 10 - digits[i] %= 10 - - if carry: - digits = [1] + digits - + if digits[i] == 9: + digits[i] = 0 + else: + digits[i] += 1 + return digits + digits[0] = 1 + digits.append(0) return digits - def plusOne2(self, digits): + +# Time: O(n) +# Space: O(n) +class Solution2(object): + def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ - digits = [str(x) for x in digits] - num = int(''.join(digits)) + 1 - return [int(x) for x in str(num)] + result = digits[::-1] + carry = 1 + for i in xrange(len(result)): + result[i] += carry + carry, result[i] = divmod(result[i], 10) + if carry: + result.append(carry) + return result[::-1] + if __name__ == "__main__": - print Solution().plusOne([9, 9, 9, 9]) \ No newline at end of file + print Solution().plusOne([9, 9, 9, 9]) From ff94da6d6aa5a93e8f11282bdeb6595a24404963 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 11 Jan 2018 13:18:57 +0800 Subject: [PATCH 4293/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 8b8beaac0..bd16c40c8 100644 --- a/README.md +++ b/README.md @@ -393,6 +393,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/) | [C++](./C++/minimum-moves-to-equal-array-elements.cpp) [Python](./Python/minimum-moves-to-equal-array-elements.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +537 | [Complex Number Multiplication](https://leetcode.com/problems/complex-number-multiplication/) | [C++](./C++/complex-number-multiplication.cpp) [Python](./Python/complex-number-multiplication.py) | _O(1)_ | _O(1)_ | Medium ||| 553 | [Optimal Division](https://leetcode.com/problems/optimal-division/) | [C++](./C++/optimal-division.cpp) [Python](./Python/optimal-division.py) | _O(n)_ | _O(1)_ | Medium ||| 573 | [Squirrel Simulation](https://leetcode.com/problems/squirrel-simulation/) | [C++](./C++/squirrel-simulation.cpp) [Python](./Python/squirrel-simulation.py) | _O(n)_ | _O(1)_ | Medium |📖|| 592 | [Fraction Addition and Subtraction](https://leetcode.com/problems/fraction-addition-and-subtraction/) | [C++](./C++/fraction-addition-and-subtraction.cpp) [Python](./Python/fraction-addition-and-subtraction.py) | _O(nlogx)_ | _O(n)_ | Medium ||| From 8a06668ada7c8b41d5ec8034dde63607c6f66aa9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 12 Jan 2018 23:23:01 +0800 Subject: [PATCH 4294/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index bd16c40c8..32910aa93 100644 --- a/README.md +++ b/README.md @@ -277,6 +277,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 | +536 | [Construct Binary Tree from String](https://leetcode.com/problems/construct-binary-tree-from-string/) | [C++](./C++/construct-binary-tree-from-string.cpp) [Python](./Python/construct-binary-tree-from-string.py) | _O(n)_ | _O(h)_ | Medium | 📖 | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [C++](./C++/convert-bst-to-greater-tree.cpp) [Python](./Python/convert-bst-to-greater-tree.py) | _O(n)_ | _O(h)_ | Easy || 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [C++](./C++/diameter-of-binary-tree.cpp) [Python](./Python/diameter-of-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || 545 | [Boundary of Binary Tree](https://leetcode.com/problems/boundary-of-binary-tree/) | [C++](./C++/boundary-of-binary-tree.cpp) [Python](./Python/boundary-of-binary-tree.py) | _O(n)_ | _O(h)_ | Medium |📖| From 865d1172e8f4a0e1e4db3ae518c865f88a105084 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 13 Jan 2018 23:42:35 +0800 Subject: [PATCH 4295/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 32910aa93..9e17f4d69 100644 --- a/README.md +++ b/README.md @@ -748,6 +748,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 381| [Insert Delete GetRandom O(1) - Duplicates allowed](https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/) | [C++](./C++/insert-delete-getrandom-o1-duplicates-allowed.cpp) [Python](./Python/insert-delete-getrandom-o1-duplicates-allowed.py) | _O(1)_ | _O(n)_ | Hard || | 432| [All O\`one Data Structure](https://leetcode.com/problems/all-oone-data-structure/) | [C++](./C++/all-oone-data-structure.cpp) [Python](./Python/all-oone-data-structure.py) | _O(1)_ | _O(n)_| Hard || | 460| [LFU Cache](https://leetcode.com/problems/lfu-cache/) | [C++](./C++/lfu-cache.cpp) [Python](./Python/lfu-cache.py) | _O(1)_ | _O(k)_ | Hard || | +535| [Encode and Decode TinyURL](https://leetcode.com/problems/encode-and-decode-tinyurl/) | [C++](./C++/encode-and-decode-tinyurl.cpp) [Python](./Python/encode-and-decode-tinyurl.py) | _O(1)_ | _O(n)_ | Medium || | 588| [Design In-Memory File System](https://leetcode.com/problems/design-in-memory-file-system/) | [C++](./C++/design-in-memory-file-system.cpp) [Python](./Python/design-in-memory-file-system.py) | ls: _O(l + klogk)_
mkdir: _O(l)_
addContentToFile: _O(l + c)_
readContentFromFile: _O(l + c)_ | _O(n + s)_ | Hard |📖| | 604| [Design Compressed String Iterator](https://leetcode.com/problems/design-compressed-string-iterator/) | [C++](./C++/design-compressed-string-iterator.cpp) [Python](./Python/design-compressed-string-iterator.py) | _O(1)_ | _O(1)_ | Easy |📖| | 631| [Design Excel Sum Formula](https://leetcode.com/problems/design-excel-sum-formula/) | [C++](./C++/design-excel-sum-formula.cpp) [Python](./Python/design-excel-sum-formula.py) | set: _O((r * c)^2)_
get: _O(1)_
sum: _O((r * c)^2)_ | _O(r * c)_ | Hard |📖| | From 135b24b5a88e435ee4cbfd14753492f3be265c4a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 18:26:30 +0800 Subject: [PATCH 4296/4971] Create prime-number-of-set-bits-in-binary-representation.cpp --- ...r-of-set-bits-in-binary-representation.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/prime-number-of-set-bits-in-binary-representation.cpp diff --git a/C++/prime-number-of-set-bits-in-binary-representation.cpp b/C++/prime-number-of-set-bits-in-binary-representation.cpp new file mode 100644 index 000000000..539d9d281 --- /dev/null +++ b/C++/prime-number-of-set-bits-in-binary-representation.cpp @@ -0,0 +1,23 @@ +// Time: O(log(R - L)) = O(1) +// Space: O(1) + +class Solution { +public: + int countPrimeSetBits(int L, int R) { + static const unordered_set primes{2, 3, 5, 7, 11, 13, 17, 19}; + int result = 0; + for (int i = L; i <= R; ++i) { + result += primes.count(bitCount(i)); + } + return result; + } + +private: + int bitCount(uint32_t n) { + int count = 0; + for (; n; n &= n - 1) { + ++count; + } + return count; + } +}; From ffe6325b569cfa47a0d5b217e7d8313d34d62dc8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 18:30:38 +0800 Subject: [PATCH 4297/4971] Create prime-number-of-set-bits-in-binary-representation.py --- ...er-of-set-bits-in-binary-representation.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Python/prime-number-of-set-bits-in-binary-representation.py diff --git a/Python/prime-number-of-set-bits-in-binary-representation.py b/Python/prime-number-of-set-bits-in-binary-representation.py new file mode 100644 index 000000000..ce38e8afd --- /dev/null +++ b/Python/prime-number-of-set-bits-in-binary-representation.py @@ -0,0 +1,20 @@ +# Time: O(log(R - L)) = O(1) +# Space: O(1) + +class Solution(object): + def countPrimeSetBits(self, L, R): + """ + :type L: int + :type R: int + :rtype: int + """ + def bitCount(n): + result = 0 + while n: + n &= n-1 + result += 1 + return result + + primes = {2, 3, 5, 7, 11, 13, 17, 19} + return sum(bitCount(i) in primes + for i in xrange(L, R+1)) From 2e1f778d98410dc055503d4cafee725a3a7aff24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 18:48:39 +0800 Subject: [PATCH 4298/4971] Create partition-labels.cpp --- C++/partition-labels.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/partition-labels.cpp diff --git a/C++/partition-labels.cpp b/C++/partition-labels.cpp new file mode 100644 index 000000000..5989631ed --- /dev/null +++ b/C++/partition-labels.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector partitionLabels(string S) { + unordered_map lookup; + for (int i = 0; i < S.length(); ++i) { + lookup[S[i]] = i; + } + int first = 0, last = 0; + vector result; + for (int i = 0; i < S.length(); ++i) { + last = max(last, lookup[S[i]]); + if (i == last) { + result.emplace_back(i - first + 1); + first = i + 1; + } + } + return result; + } +}; From b0756ac2f4d736b35d32b16506cfef97dcdeb867 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 18:49:55 +0800 Subject: [PATCH 4299/4971] Create partition-labels.py --- Python/partition-labels.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Python/partition-labels.py diff --git a/Python/partition-labels.py b/Python/partition-labels.py new file mode 100644 index 000000000..db4e03ec2 --- /dev/null +++ b/Python/partition-labels.py @@ -0,0 +1,18 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def partitionLabels(self, S): + """ + :type S: str + :rtype: List[int] + """ + lookup = {c: i for i, c in enumerate(S)} + first, last = 0, 0 + result = [] + for i, c in enumerate(S): + last = max(last, lookup[c]) + if i == last: + result.append(i-first+1) + first = i+1 + return result From b05c9236947df91e303fc90584de8de10850afdc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 19:23:47 +0800 Subject: [PATCH 4300/4971] Create largest-plus-sign.cpp --- C++/largest-plus-sign.cpp | 48 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 C++/largest-plus-sign.cpp diff --git a/C++/largest-plus-sign.cpp b/C++/largest-plus-sign.cpp new file mode 100644 index 000000000..a89efde1d --- /dev/null +++ b/C++/largest-plus-sign.cpp @@ -0,0 +1,48 @@ +// Time: O(n^2) +// Space: O(n^2) + +class Solution { +public: + int orderOfLargestPlusSign(int N, vector>& mines) { + unordered_set, PairHash> lookup; + for (const auto& mine : mines) { + lookup.emplace(mine[0], mine[1]); + } + vector> dp(N, vector(N)); + int result = 0; + for (int i = 0; i < N; ++i) { + for (int j = 0, l = 0; j < N; ++j) { + l = lookup.count(make_pair(i, j)) ? 0 : l + 1; + dp[i][j] = l; + } + for (int j = N - 1, l = 0; j >= 0; --j) { + l = lookup.count(make_pair(i, j)) ? 0 : l + 1; + dp[i][j] = min(dp[i][j], l); + } + } + + for (int j = 0; j < N; ++j) { + for (int i = 0, l = 0; i < N; ++i) { + l = lookup.count(make_pair(i, j)) ? 0 : l + 1; + dp[i][j] = min(dp[i][j], l); + } + for (int i = N - 1, l = 0; i >= 0; --i) { + l = lookup.count(make_pair(i, j)) ? 0 : l + 1; + dp[i][j] = min(dp[i][j], l); + result = max(result, dp[i][j]); + } + } + return result; + } + +private: + template + struct PairHash { + size_t operator()(const pair& p) const { + size_t seed = 0; + seed ^= std::hash{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2); + seed ^= std::hash{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2); + return seed; + } + }; +}; From a1b491c5d3dd864521a8d8a1ef284df6bbb661c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 19:23:51 +0800 Subject: [PATCH 4301/4971] Create largest-plus-sign.py --- Python/largest-plus-sign.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Python/largest-plus-sign.py diff --git a/Python/largest-plus-sign.py b/Python/largest-plus-sign.py new file mode 100644 index 000000000..5b47e514b --- /dev/null +++ b/Python/largest-plus-sign.py @@ -0,0 +1,34 @@ +# Time: O(n^2) +# Space: O(n^2) + +class Solution(object): + def orderOfLargestPlusSign(self, N, mines): + """ + :type N: int + :type mines: List[List[int]] + :rtype: int + """ + lookup = {tuple(mine) for mine in mines} + dp = [[0] * N for _ in xrange(N)] + result = 0 + for i in xrange(N): + l = 0 + for j in xrange(N): + l = 0 if (i, j) in lookup else l+1 + dp[i][j] = l + l = 0 + for j in reversed(xrange(N)): + l = 0 if (i, j) in lookup else l+1 + dp[i][j] = min(dp[i][j], l) + + for j in xrange(N): + l = 0 + for i in xrange(N): + l = 0 if (i, j) in lookup else l+1 + dp[i][j] = min(dp[i][j], l) + l = 0 + for i in reversed(xrange(N)): + l = 0 if (i, j) in lookup else l+1 + dp[i][j] = min(dp[i][j], l) + result = max(result, dp[i][j]) + return result From a32effef65679e3744713509bd294cb3ca277003 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 20:39:16 +0800 Subject: [PATCH 4302/4971] Create couples-holding-hands.cpp --- C++/couples-holding-hands.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/couples-holding-hands.cpp diff --git a/C++/couples-holding-hands.cpp b/C++/couples-holding-hands.cpp new file mode 100644 index 000000000..20f2a956e --- /dev/null +++ b/C++/couples-holding-hands.cpp @@ -0,0 +1,33 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int minSwapsCouples(vector& row) { + int N = row.size() / 2; + vector> couples(N); + for (int seat = 0; seat < row.size(); ++seat) { + couples[row[seat] / 2].emplace_back(seat / 2); + } + vector> adj(N); + for (const auto& couple : couples) { + adj[couple[0]].emplace_back(couple[1]); + adj[couple[1]].emplace_back(couple[0]); + } + int result = N; + for (int couch = 0; couch < N; ++couch) { + if (adj[couch].empty()) { + continue; + } + --result; + int couch1 = couch; + int couch2 = adj[couch1].back(); adj[couch1].pop_back(); + while (couch2 != couch) { + adj[couch2].erase(find(adj[couch2].begin(), adj[couch2].end(), couch1)); + couch1 = couch2; + couch2 = adj[couch1].back(); adj[couch1].pop_back(); + } + } + return result; + } +}; From 64b03bd53f6f494398818199caabe10138469719 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 20:40:22 +0800 Subject: [PATCH 4303/4971] Create couples-holding-hands.py --- Python/couples-holding-hands.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/couples-holding-hands.py diff --git a/Python/couples-holding-hands.py b/Python/couples-holding-hands.py new file mode 100644 index 000000000..133897118 --- /dev/null +++ b/Python/couples-holding-hands.py @@ -0,0 +1,27 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def minSwapsCouples(self, row): + """ + :type row: List[int] + :rtype: int + """ + N = len(row)//2 + couples = [[] for _ in xrange(N)] + for seat, num in enumerate(row): + couples[num//2].append(seat//2) + adj = [[] for _ in xrange(N)] + for couch1, couch2 in couples: + adj[couch1].append(couch2) + adj[couch2].append(couch1) + + result = N + for couch in xrange(N): + if not adj[couch]: continue + result -= 1 + couch1, couch2 = couch, adj[couch].pop() + while couch2 != couch: + adj[couch2].remove(couch1) + couch1, couch2 = couch2, adj[couch2].pop() + return result From ef1d52cefe6ccfc8387d114d70890b2688b230fe Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 20:46:50 +0800 Subject: [PATCH 4304/4971] Update couples-holding-hands.cpp --- C++/couples-holding-hands.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/C++/couples-holding-hands.cpp b/C++/couples-holding-hands.cpp index 20f2a956e..012547f16 100644 --- a/C++/couples-holding-hands.cpp +++ b/C++/couples-holding-hands.cpp @@ -14,15 +14,16 @@ class Solution { adj[couple[0]].emplace_back(couple[1]); adj[couple[1]].emplace_back(couple[0]); } - int result = N; + + int result = 0; for (int couch = 0; couch < N; ++couch) { if (adj[couch].empty()) { continue; } - --result; int couch1 = couch; int couch2 = adj[couch1].back(); adj[couch1].pop_back(); while (couch2 != couch) { + ++result; adj[couch2].erase(find(adj[couch2].begin(), adj[couch2].end(), couch1)); couch1 = couch2; couch2 = adj[couch1].back(); adj[couch1].pop_back(); From c2011ec5e802d50c780138b0472f417a64bb35ef Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 20:47:56 +0800 Subject: [PATCH 4305/4971] Update couples-holding-hands.py --- Python/couples-holding-hands.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/couples-holding-hands.py b/Python/couples-holding-hands.py index 133897118..0e632c47c 100644 --- a/Python/couples-holding-hands.py +++ b/Python/couples-holding-hands.py @@ -16,12 +16,12 @@ def minSwapsCouples(self, row): adj[couch1].append(couch2) adj[couch2].append(couch1) - result = N + result = 0 for couch in xrange(N): if not adj[couch]: continue - result -= 1 couch1, couch2 = couch, adj[couch].pop() while couch2 != couch: + result += 1 adj[couch2].remove(couch1) couch1, couch2 = couch2, adj[couch2].pop() return result From 31cb1e0313847b68b22bedee1933eca85f7fa361 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 20:49:10 +0800 Subject: [PATCH 4306/4971] Update couples-holding-hands.py --- Python/couples-holding-hands.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/couples-holding-hands.py b/Python/couples-holding-hands.py index 0e632c47c..2348c41c8 100644 --- a/Python/couples-holding-hands.py +++ b/Python/couples-holding-hands.py @@ -24,4 +24,4 @@ def minSwapsCouples(self, row): result += 1 adj[couch2].remove(couch1) couch1, couch2 = couch2, adj[couch2].pop() - return result + return result # also equals to N - (# of cycles) From 90d42dcc3986e698198ed310e150c63be2d08b26 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 14 Jan 2018 20:49:35 +0800 Subject: [PATCH 4307/4971] Update couples-holding-hands.cpp --- C++/couples-holding-hands.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/couples-holding-hands.cpp b/C++/couples-holding-hands.cpp index 012547f16..e0a353055 100644 --- a/C++/couples-holding-hands.cpp +++ b/C++/couples-holding-hands.cpp @@ -29,6 +29,6 @@ class Solution { couch2 = adj[couch1].back(); adj[couch1].pop_back(); } } - return result; + return result; // also equals to N - (# of cycles) } }; From 477916baf8b5342f235f27b48380dfd47557aa20 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 15 Jan 2018 22:19:36 +0800 Subject: [PATCH 4308/4971] Update README.md --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index 9e17f4d69..d4238ca0c 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates * [Backtracking](https://github.com/kamyu104/LeetCode#backtracking) * [Dynamic Programming](https://github.com/kamyu104/LeetCode#dynamic-programming) * [Greedy](https://github.com/kamyu104/LeetCode#greedy) +* [Graph](https://github.com/kamyu104/LeetCode#graph) * [Geometry](https://github.com/kamyu104/LeetCode#geometry) * [Design](https://github.com/kamyu104/LeetCode#design) @@ -64,6 +65,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 477 | [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./C++/total-hamming-distance.cpp) [Python](./Python/total-hamming-distance.py) | _O(n)_ | _O(1)_ | Medium || 645 | [Set Mismatch](https://leetcode.com/problems/set-mismatch/) | [C++](./C++/set-mismatch.cpp) [Python](./Python/set-mismatch.py) | _O(n)_ | _O(1)_ | Easy || 693 | [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/) | [C++](./C++/binary-number-with-alternating-bits.cpp) [Python](./Python/binary-number-with-alternating-bits.py) | _O(1)_ | _O(1)_ | Easy || +762 | [Prime Number of Set Bits in Binary Representation](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/) | [C++](./C++/prime-number-of-set-bits-in-binary-representation.cpp) [Python](./Python/prime-number-of-set-bits-in-binary-representation.py) | _O(1)_ | _O(1)_ | Easy || ## Array | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -696,6 +698,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 741 | [Cherry Pickup](https://leetcode.com/problems/cherry-pickup/) | [C++](./C++/cherry-pickup.cpp) [Python](./Python/cherry-pickup.py) | _O(n^3)_ | _O(n^2)_ | Hard || 746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) | [C++](./C++/min-cost-climbing-stairs.cpp) [Python](./Python/min-cost-climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || 750 | [Number Of Corner Rectangles](https://leetcode.com/problems/number-of-corner-rectangles/) | [C++](./C++/number-of-corner-rectangles.cpp) [Python](./Python/number-of-corner-rectangles.py) | _O(n * m^2)_ | _O(n * m)_ | Medium || +764 | [Largest Plus Sign](https://leetcode.com/problems/largest-plus-sign/) | [C++](./C++/largest-plus-sign.cpp) [Python](./Python/largest-plus-sign.py) | _O(n^2)_ | _O(n^2)_ | Medium || ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -726,6 +729,13 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 738 | [Monotone Increasing Digits](https://leetcode.com/problems/monotone-increasing-digits/) | [C++](./C++/monotone-increasing-digits.cpp) [Python](./Python/monotone-increasing-digits.py) | _O(1)_ | _O(1)_ | Medium | | 757 | [Set Intersection Size At Least Two](https://leetcode.com/problems/set-intersection-size-at-least-two/) | [C++](./C++/set-intersection-size-at-least-two.cpp) [Python](./Python/set-intersection-size-at-least-two.py) | _O(nlogn)_ | _O(n)_ | Hard | | 759 | [Employee Free Time](https://leetcode.com/problems/employee-free-time/) | [C++](./C++/employee-free-time.cpp) [Python](./Python/employee-free-time.py) | _O(m * logn)_ | _O(n)_ | Hard | | +763 | [Partition Labels](https://leetcode.com/problems/partition-labels/) | [C++](./C++/partition-labels.cpp) [Python](./Python/partition-labels.py) | _O(n)_ | _O(n)_ | Medium | | + +## Graph +| # | Title | Solution | Time | Space | Difficulty | Tag | Note| +|-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| +765 | [Couples Holding Hands](https://leetcode.com/problems/couples-holding-hands/) | [C++](./C++/couples-holding-hands.cpp) [Python](./Python/couples-holding-hands.py) | _O(n)_| _O(n)_| Hard ||| + ## Geometry | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 1ba7b5f43e5a20c0afcfbf31a40e0aa5bcbb1600 Mon Sep 17 00:00:00 2001 From: SangHee Kim Date: Mon, 15 Jan 2018 12:22:22 -0500 Subject: [PATCH 4309/4971] Update sqrtx.py error due to the wrong method name --- Python/sqrtx.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/sqrtx.py b/Python/sqrtx.py index 6429b9180..8ac7af2c8 100644 --- a/Python/sqrtx.py +++ b/Python/sqrtx.py @@ -26,5 +26,5 @@ def mySqrt(self, x): if __name__ == "__main__": - print Solution().sqrt(10) + print Solution().mySqrt(10) From 5dec32b5c8e88dc319edc6926404056bf5a89e52 Mon Sep 17 00:00:00 2001 From: JXZGitHub <35183837+JXZGitHub@users.noreply.github.com> Date: Mon, 15 Jan 2018 22:07:56 -0500 Subject: [PATCH 4310/4971] Eliminate unnecessary len() operations No need to keep finding row and col lengths, can just keep size as its always a square. --- Python/design-tic-tac-toe.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Python/design-tic-tac-toe.py b/Python/design-tic-tac-toe.py index 6d40a6f2d..6ceb9628c 100644 --- a/Python/design-tic-tac-toe.py +++ b/Python/design-tic-tac-toe.py @@ -8,6 +8,7 @@ def __init__(self, n): Initialize your data structure here. :type n: int """ + self.size = n self.__rows = [[0, 0] for _ in xrange(n)] self.__cols = [[0, 0] for _ in xrange(n)] self.__diagonal = [0, 0] @@ -36,10 +37,10 @@ def move(self, row, col, player): self.__diagonal[i] += 1 if col == len(self.__rows) - row - 1: self.__anti_diagonal[i] += 1 - if any([self.__rows[row][i] == len(self.__rows), \ - self.__cols[col][i] == len(self.__cols), \ - self.__diagonal[i] == len(self.__rows), \ - self.__anti_diagonal[i] == len(self.__cols)]): + if any([self.__rows[row][i] == self.size), \ + self.__cols[col][i] == self.size, \ + self.__diagonal[i] == self.size, \ + self.__anti_diagonal[i] == self.size]): return player return 0 From 9f166a37f1b196a33d48be021feac94f6ef703d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 16 Jan 2018 21:56:16 +0800 Subject: [PATCH 4311/4971] Update design-tic-tac-toe.py --- Python/design-tic-tac-toe.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/design-tic-tac-toe.py b/Python/design-tic-tac-toe.py index 6ceb9628c..cf4b1384f 100644 --- a/Python/design-tic-tac-toe.py +++ b/Python/design-tic-tac-toe.py @@ -8,7 +8,7 @@ def __init__(self, n): Initialize your data structure here. :type n: int """ - self.size = n + self.__size = n self.__rows = [[0, 0] for _ in xrange(n)] self.__cols = [[0, 0] for _ in xrange(n)] self.__diagonal = [0, 0] @@ -37,10 +37,10 @@ def move(self, row, col, player): self.__diagonal[i] += 1 if col == len(self.__rows) - row - 1: self.__anti_diagonal[i] += 1 - if any([self.__rows[row][i] == self.size), \ - self.__cols[col][i] == self.size, \ - self.__diagonal[i] == self.size, \ - self.__anti_diagonal[i] == self.size]): + if any([self.__rows[row][i] == self.__size), \ + self.__cols[col][i] == self.__size, \ + self.__diagonal[i] == self.__size, \ + self.__anti_diagonal[i] == self.__size]): return player return 0 From dae98754eb02d68139028f72f894411a3ed12305 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 17 Jan 2018 22:14:39 +0800 Subject: [PATCH 4312/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d4238ca0c..aadd3172c 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| +533 | [Lonely Pixel II](https://leetcode.com/problems/lonely-pixel-ii/) | [C++](./C++/lonely-pixel-ii.cpp) [Python](./Python/lonely-pixel-ii.py) | _O(m * n)_ | _O(m * n)_ | Medium |📖|| 565 | [Array Nesting](https://leetcode.com/problems/array-nesting/) | [C++](./C++/array-nesting.cpp) [Python](./Python/array-nesting.py) | _O(n)_ | _O(1)_ | Medium ||| 566 | [Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix/) | [C++](./C++/reshape-the-matrix.cpp) [Python](./Python/reshape-the-matrix.py) | _O(m * n)_ | _O(m * n)_ | Easy ||| 581 | [Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray/) | [C++](./C++/shortest-unsorted-continuous-subarray.cpp) [Python](./Python/shortest-unsorted-continuous-subarray.py) | _O(n)_ | _O(1)_ | Easy ||| From edda301444edaf3df0e6f3b5a1fb8ad6a140de17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 18 Jan 2018 23:44:26 +0800 Subject: [PATCH 4313/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index aadd3172c..d218e0267 100644 --- a/README.md +++ b/README.md @@ -343,6 +343,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 447| [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/) | [C++](./C++/number-of-boomerangs.cpp) [Python](./Python/number-of-boomerangs.py) | _O(n^2)_ | _O(n)_ | Easy || 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || +532| [K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) |[C++](./C++/k-diff-pairs-in-an-array.cpp) [Python](./Python/k-diff-pairs-in-an-array.py) | _O(n)_ | _O(n)_ | Easy | | 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | 560| [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) |[C++](./C++/subarray-sum-equals-k.cpp) [Python](./Python/subarray-sum-equals-k.py) | _O(n)_ | _O(n)_ | Medium | | 561| [Array Partition I](https://leetcode.com/problems/array-partition-i/) |[C++](./C++/array-partition-i.cpp) [Python](./Python/array-partition-i.py) | _O(r)_ | _O(r)_ | Easy | | From 96522b7423a07c55cfeaab58dd696fb7c2fa1148 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 19 Jan 2018 23:58:30 +0800 Subject: [PATCH 4314/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d218e0267..7be0233b5 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 422| [Valid Word Square](https://leetcode.com/problems/valid-word-square/) | [C++](./C++/valid-word-square.cpp) [Python](./Python/valid-word-square.py) | _O(m * n)_ | _O(1)_ | Easy |📖|| 442| [Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/) | [C++](./C++/find-all-duplicates-in-an-array.cpp) [Python](./Python/find-all-duplicates-in-an-array.py) | _O(n)_ | _O(1)_ | Medium ||| 448| [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | [C++](./C++/find-all-numbers-disappeared-in-an-array.cpp) [Python](./Python/find-all-numbers-disappeared-in-an-array.py) | _O(n)_ | _O(1)_ | Easy ||| +531 | [Lonely Pixel I](https://leetcode.com/problems/lonely-pixel-i/) | [C++](./C++/lonely-pixel-i.cpp) [Python](./Python/lonely-pixel-i.py) | _O(m * n)_ | _O(m + n)_ | Medium |📖|| 533 | [Lonely Pixel II](https://leetcode.com/problems/lonely-pixel-ii/) | [C++](./C++/lonely-pixel-ii.cpp) [Python](./Python/lonely-pixel-ii.py) | _O(m * n)_ | _O(m * n)_ | Medium |📖|| 565 | [Array Nesting](https://leetcode.com/problems/array-nesting/) | [C++](./C++/array-nesting.cpp) [Python](./Python/array-nesting.py) | _O(n)_ | _O(1)_ | Medium ||| 566 | [Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix/) | [C++](./C++/reshape-the-matrix.cpp) [Python](./Python/reshape-the-matrix.py) | _O(m * n)_ | _O(m * n)_ | Easy ||| From 8674f46ea58afdd62d72e618b3f5bdd048c2a8f5 Mon Sep 17 00:00:00 2001 From: JXZGitHub <35183837+JXZGitHub@users.noreply.github.com> Date: Fri, 19 Jan 2018 23:36:16 -0500 Subject: [PATCH 4315/4971] Remove unnecessary 'used' grid, just mark each visited node as '1' --- Python/number-of-islands.py | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/Python/number-of-islands.py b/Python/number-of-islands.py index 03d93dd0b..89bff89d1 100644 --- a/Python/number-of-islands.py +++ b/Python/number-of-islands.py @@ -30,27 +30,25 @@ def numIslands(self, grid): return 0 row = len(grid) - col = len(grid[0]) - used = [[False for j in xrange(col)] for i in xrange(row)] - + col = len(grid[0]) 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) + if grid[i][j] == '1': + self.dfs(grid, 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]: + def dfs(self, grid, row, col, x, y): + if grid[x][y] == '0': return - used[x][y] = True + grid[x][y] = '0' if x != 0: - self.dfs(grid, used, row, col, x - 1, y) + self.dfs(grid, row, col, x - 1, y) if x != row - 1: - self.dfs(grid, used, row, col, x + 1, y) + self.dfs(grid, row, col, x + 1, y) if y != 0: - self.dfs(grid, used, row, col, x, y - 1) + self.dfs(grid, row, col, x, y - 1) if y != col - 1: - self.dfs(grid, used, row, col, x, y + 1) + self.dfs(grid, row, col, x, y + 1) From 399362c88d67d45f5c612f320c4356d7c64be414 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Jan 2018 23:27:48 +0800 Subject: [PATCH 4316/4971] Create toeplitz-matrix.cpp --- C++/toeplitz-matrix.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/toeplitz-matrix.cpp diff --git a/C++/toeplitz-matrix.cpp b/C++/toeplitz-matrix.cpp new file mode 100644 index 000000000..febae4902 --- /dev/null +++ b/C++/toeplitz-matrix.cpp @@ -0,0 +1,17 @@ +// Time: O(m * n) +// Space: O(1) + +class Solution { +public: + bool isToeplitzMatrix(vector>& matrix) { + for (int i = 0; i < matrix.size(); ++i) { + for (int j = 0; j < matrix[i].size(); ++j) { + if (i != 0 && j != 0 && + matrix[i - 1][j - 1] != matrix[i][j]) { + return false; + } + } + } + return true; + } +}; From 6f8699288f79ff856ed58595169cb08956cd210d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Jan 2018 23:28:44 +0800 Subject: [PATCH 4317/4971] Create toeplitz-matrix.py --- Python/toeplitz-matrix.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Python/toeplitz-matrix.py diff --git a/Python/toeplitz-matrix.py b/Python/toeplitz-matrix.py new file mode 100644 index 000000000..ce7411096 --- /dev/null +++ b/Python/toeplitz-matrix.py @@ -0,0 +1,12 @@ +# Time: O(m * n) +# Space: O(1) + +class Solution(object): + def isToeplitzMatrix(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: bool + """ + return all(i == 0 or j == 0 or matrix[i-1][j-1] == val + for i, row in enumerate(matrix) + for j, val in enumerate(row)) From ec0db07d5af39b3e9f06160f7cc24d70e32ca778 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Jan 2018 23:54:22 +0800 Subject: [PATCH 4318/4971] Create reorganized-string.cpp --- C++/reorganized-string.cpp | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 C++/reorganized-string.cpp diff --git a/C++/reorganized-string.cpp b/C++/reorganized-string.cpp new file mode 100644 index 000000000..d835640dc --- /dev/null +++ b/C++/reorganized-string.cpp @@ -0,0 +1,41 @@ +// Time: O(nloga) = O(n), a is the size of alphabet +// Space: O(a) = O(1) + +class Solution { +public: + string reorganizeString(string S) { + unordered_map counts; + for (const auto& c : S) { + ++counts[c]; + } + if (any_of(counts.cbegin(), counts.cend(), + [&](const pair& kvp) { + return kvp.second > (S.length() + 1) / 2; + })) { + return ""; + } + + string result; + priority_queue> max_heap; + for (const auto& kvp : counts) { + max_heap.emplace(kvp.second, kvp.first); + } + while (max_heap.size() > 1) { + char c1, c2; + int count1, count2; + tie(count1, c1) = max_heap.top(); max_heap.pop(); + tie(count2, c2) = max_heap.top(); max_heap.pop(); + if (result.empty() || c1 != result.back()) { + result.push_back(c1); + result.push_back(c2); + if (count1 - 1 > 0) { + max_heap.emplace(count1 - 1, c1); + } + if (count2 - 1 > 0) { + max_heap.emplace(count2 - 1, c2); + } + } + } + return max_heap.empty() ? result : result + max_heap.top().second; + } +}; From 49bead4009365391db514b942c989747674c6d87 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 21 Jan 2018 23:55:17 +0800 Subject: [PATCH 4319/4971] Create reorganized-string.py --- Python/reorganized-string.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Python/reorganized-string.py diff --git a/Python/reorganized-string.py b/Python/reorganized-string.py new file mode 100644 index 000000000..86d403867 --- /dev/null +++ b/Python/reorganized-string.py @@ -0,0 +1,25 @@ +# Time: O(nloga) = O(n), a is the size of alphabet +# Space: O(a) = O(1) + +class Solution(object): + def reorganizeString(self, S): + """ + :type S: str + :rtype: str + """ + counts = collections.Counter(S) + if any(v > (len(S)+1)/2 for k, v in counts.iteritems()): + return "" + + result = [] + max_heap = [] + for k, v in counts.iteritems(): + heapq.heappush(max_heap, (-v, k)) + while len(max_heap) > 1: + count1, c1 = heapq.heappop(max_heap) + count2, c2 = heapq.heappop(max_heap) + if not result or c1 != result[-1]: + result.extend([c1, c2]) + if count1+1: heapq.heappush(max_heap, (count1+1, c1)) + if count2+1: heapq.heappush(max_heap, (count2+1, c2)) + return "".join(result) + (max_heap[0][1] if max_heap else '') From 1ce9874184f30786b6101b12ab7153a563abd12b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Jan 2018 00:46:40 +0800 Subject: [PATCH 4320/4971] Create max-chunks-to-make-sorted-ver-1.cpp --- C++/max-chunks-to-make-sorted-ver-1.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/max-chunks-to-make-sorted-ver-1.cpp diff --git a/C++/max-chunks-to-make-sorted-ver-1.cpp b/C++/max-chunks-to-make-sorted-ver-1.cpp new file mode 100644 index 000000000..822cf69e5 --- /dev/null +++ b/C++/max-chunks-to-make-sorted-ver-1.cpp @@ -0,0 +1,14 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int maxChunksToSorted(vector& arr) { + int result = 0; + for (int i = 0, max_i = 0; i < arr.size(); ++i) { + max_i = max(max_i, arr[i]); + if (max_i == i) ++result; + } + return result; + } +}; From db7775505a02bd1f4e2b84c37240b8efecc328fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Jan 2018 00:47:08 +0800 Subject: [PATCH 4321/4971] Create max-chunks-to-make-sorted-ver-1.py --- Python/max-chunks-to-make-sorted-ver-1.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Python/max-chunks-to-make-sorted-ver-1.py diff --git a/Python/max-chunks-to-make-sorted-ver-1.py b/Python/max-chunks-to-make-sorted-ver-1.py new file mode 100644 index 000000000..4e957fd38 --- /dev/null +++ b/Python/max-chunks-to-make-sorted-ver-1.py @@ -0,0 +1,15 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def maxChunksToSorted(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + result, max_i = 0, 0 + for i, v in enumerate(arr): + max_i = max(max_i, v) + if max_i == i: + result += 1 + return result From ce393bf99608c92f3fd81fd9c2d36bf2db4ccf37 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Jan 2018 00:54:46 +0800 Subject: [PATCH 4322/4971] Create max-chunks-to-make-sorted-ver-2.cpp --- C++/max-chunks-to-make-sorted-ver-2.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/max-chunks-to-make-sorted-ver-2.cpp diff --git a/C++/max-chunks-to-make-sorted-ver-2.cpp b/C++/max-chunks-to-make-sorted-ver-2.cpp new file mode 100644 index 000000000..6eaef9ab0 --- /dev/null +++ b/C++/max-chunks-to-make-sorted-ver-2.cpp @@ -0,0 +1,21 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + int maxChunksToSorted(vector& arr) { + vector idxs(arr.size()); + iota(idxs.begin(), idxs.end(), 0); + sort(idxs.begin(), idxs.end(), + [&](int i1, int i2) { + return arr[i1] != arr[i2] ? arr[i1] < arr[i2] : i1 < i2; + }); + + int result = 0; + for (auto i = 0, max_i = 0; i < idxs.size(); ++i) { + max_i = max(max_i, idxs[i]); + if (max_i == i) ++result; + } + return result; + } +}; From 24bea72465f5d4a5d005dee22a1c7953ac2536c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Jan 2018 00:55:31 +0800 Subject: [PATCH 4323/4971] Create max-chunks-to-make-sorted-ver-2.py --- Python/max-chunks-to-make-sorted-ver-2.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Python/max-chunks-to-make-sorted-ver-2.py diff --git a/Python/max-chunks-to-make-sorted-ver-2.py b/Python/max-chunks-to-make-sorted-ver-2.py new file mode 100644 index 000000000..daf6a256c --- /dev/null +++ b/Python/max-chunks-to-make-sorted-ver-2.py @@ -0,0 +1,19 @@ +# Time: O(nlogn) +# Space: O(n) + +class Solution(object): + def maxChunksToSorted(self, arr): + """ + :type arr: List[int] + :rtype: int + """ + def compare(i1, i2): + return arr[i1]-arr[i2] if arr[i1] != arr[i2] else i1-i2 + + idxs = [i for i in xrange(len(arr))] + result, max_i = 0, 0 + for i, v in enumerate(sorted(idxs, cmp=compare)): + max_i = max(max_i, v) + if max_i == i: + result += 1 + return result From 52ceeee0cc415e702e9c0e76a4d8378ef2c07f5e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Jan 2018 01:40:08 +0800 Subject: [PATCH 4324/4971] Create basic-calculator-iv.py --- Python/basic-calculator-iv.py | 97 +++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 Python/basic-calculator-iv.py diff --git a/Python/basic-calculator-iv.py b/Python/basic-calculator-iv.py new file mode 100644 index 000000000..e0a5b3cc0 --- /dev/null +++ b/Python/basic-calculator-iv.py @@ -0,0 +1,97 @@ +# Time: O(m + n^3 * logn) +# Space: O(m + n) + +class Poly(collections.Counter): + def __add__(self, other): + self.update(other) + return self + + def __sub__(self, other): + self.update({k: -v for k, v in other.items()}) + return self + + def __mul__(self, other): + result = Poly() + for k1, v1 in self.items(): + for k2, v2 in other.items(): + result.update({tuple(sorted(k1+k2)): v1*v2}) + return result + + def evaluate(self, lookup): + result = Poly() + for k, c in self.items(): + poly = [] + for token in k: + if token in lookup: + c *= lookup[token] + else: + poly.append(token) + result[tuple(poly)] += c + return result + + def to_list(self): + return ["*".join((str(v),) + k) \ + for k, v in sorted(self.items(), key=lambda(k, v): (-len(k), k, v)) \ + if v] + + +class Solution(object): + def basicCalculatorIV(self, expression, evalvars, evalints): + """ + :type expression: str + :type evalvars: List[str] + :type evalints: List[int] + :rtype: List[str] + """ + lookup = dict(itertools.izip(evalvars, evalints)) + + def do_operator(left, right, operator): + if operator == '+': return left + right + if operator == '-': return left - right + if operator == '*': return left * right + raise + + def make_operand(expr): + result = Poly() + if expr.isdigit(): + result.update({(): int(expr)}) + else: + result[(expr,)] += 1 + return result + + def parse(expr): + operands, operators = [], [] + i = 0 + while i < len(expr): + if expr[i] == '(': + cnt = 0 + for j in xrange(i, len(expr)): + if expr[j] == '(': cnt += 1 + if expr[j] == ')': cnt -= 1 + if cnt == 0: break + operands.append(parse(expr[i+1:j])) + i = j + elif expr[i].isalnum(): + for j in xrange(i, len(expr)): + if expr[j] == ' ': + operands.append(make_operand(expr[i:j])) + break + else: + operands.append(make_operand(expr[i:])) + i = j + elif expr[i] in '+-*': + operators.append(expr[i]) + i += 1 + + for i in reversed(xrange(len(operators))): + if operators[i] == '*': + operands[i] = do_operator(operands[i], operands.pop(i+1), \ + operators.pop(i)) + + if not operands: return Poly() + result = operands[0] + for i, operator in enumerate(operators, 1): + result = do_operator(result, operands[i], operator) + return result + + return parse(expression).evaluate(lookup).to_list() From 074d03498a84841a9c528dc97b32df2a1ea5c7e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Jan 2018 22:22:58 +0800 Subject: [PATCH 4325/4971] Rename max-chunks-to-make-sorted-ver-2.cpp to max-chunks-to-make-sorted-ii.cpp --- ...-to-make-sorted-ver-2.cpp => max-chunks-to-make-sorted-ii.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{max-chunks-to-make-sorted-ver-2.cpp => max-chunks-to-make-sorted-ii.cpp} (100%) diff --git a/C++/max-chunks-to-make-sorted-ver-2.cpp b/C++/max-chunks-to-make-sorted-ii.cpp similarity index 100% rename from C++/max-chunks-to-make-sorted-ver-2.cpp rename to C++/max-chunks-to-make-sorted-ii.cpp From 8a27d7783f359bf12e342d412b2e4e9c61927e73 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Jan 2018 22:23:17 +0800 Subject: [PATCH 4326/4971] Rename max-chunks-to-make-sorted-ver-1.cpp to max-chunks-to-make-sorted-i.cpp --- ...s-to-make-sorted-ver-1.cpp => max-chunks-to-make-sorted-i.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{max-chunks-to-make-sorted-ver-1.cpp => max-chunks-to-make-sorted-i.cpp} (100%) diff --git a/C++/max-chunks-to-make-sorted-ver-1.cpp b/C++/max-chunks-to-make-sorted-i.cpp similarity index 100% rename from C++/max-chunks-to-make-sorted-ver-1.cpp rename to C++/max-chunks-to-make-sorted-i.cpp From cbddbccc8010ac9576d9cc663f9437dfcd079be9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Jan 2018 22:23:39 +0800 Subject: [PATCH 4327/4971] Rename max-chunks-to-make-sorted-ver-1.py to max-chunks-to-make-sorted-i.py --- ...nks-to-make-sorted-ver-1.py => max-chunks-to-make-sorted-i.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{max-chunks-to-make-sorted-ver-1.py => max-chunks-to-make-sorted-i.py} (100%) diff --git a/Python/max-chunks-to-make-sorted-ver-1.py b/Python/max-chunks-to-make-sorted-i.py similarity index 100% rename from Python/max-chunks-to-make-sorted-ver-1.py rename to Python/max-chunks-to-make-sorted-i.py From 624d0aae3b5ed038cf2ee055b9b317a0db2c9d2a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Jan 2018 22:24:02 +0800 Subject: [PATCH 4328/4971] Rename max-chunks-to-make-sorted-ver-2.py to max-chunks-to-make-sorted-ii.py --- ...ks-to-make-sorted-ver-2.py => max-chunks-to-make-sorted-ii.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{max-chunks-to-make-sorted-ver-2.py => max-chunks-to-make-sorted-ii.py} (100%) diff --git a/Python/max-chunks-to-make-sorted-ver-2.py b/Python/max-chunks-to-make-sorted-ii.py similarity index 100% rename from Python/max-chunks-to-make-sorted-ver-2.py rename to Python/max-chunks-to-make-sorted-ii.py From 70203727112c070c30dc506e42559c0f5ebf7d71 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 22 Jan 2018 22:45:22 +0800 Subject: [PATCH 4329/4971] Update basic-calculator-iv.py --- Python/basic-calculator-iv.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/Python/basic-calculator-iv.py b/Python/basic-calculator-iv.py index e0a5b3cc0..2472b51f0 100644 --- a/Python/basic-calculator-iv.py +++ b/Python/basic-calculator-iv.py @@ -2,6 +2,14 @@ # Space: O(m + n) class Poly(collections.Counter): + def __init__(self, expr=""): + if not expr: + return + if expr.isdigit(): + self.update({(): int(expr)}) + else: + self[(expr,)] += 1 + def __add__(self, other): self.update(other) return self @@ -51,16 +59,9 @@ def do_operator(left, right, operator): if operator == '*': return left * right raise - def make_operand(expr): - result = Poly() - if expr.isdigit(): - result.update({(): int(expr)}) - else: - result[(expr,)] += 1 - return result - def parse(expr): - operands, operators = [], [] + operands = [] + operators = [] i = 0 while i < len(expr): if expr[i] == '(': @@ -74,10 +75,10 @@ def parse(expr): elif expr[i].isalnum(): for j in xrange(i, len(expr)): if expr[j] == ' ': - operands.append(make_operand(expr[i:j])) + operands.append(Poly(expr[i:j])) break else: - operands.append(make_operand(expr[i:])) + operands.append(Poly(expr[i:])) i = j elif expr[i] in '+-*': operators.append(expr[i]) From e52bc940e2c6a2992e26eacbfaf1b759fa1c4d48 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jan 2018 02:31:53 +0800 Subject: [PATCH 4330/4971] Create basic-calculator-iv.cpp --- C++/basic-calculator-iv.cpp | 206 ++++++++++++++++++++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 C++/basic-calculator-iv.cpp diff --git a/C++/basic-calculator-iv.cpp b/C++/basic-calculator-iv.cpp new file mode 100644 index 000000000..ffd6242a2 --- /dev/null +++ b/C++/basic-calculator-iv.cpp @@ -0,0 +1,206 @@ +// Time: +: O(d * t), t is the number of terms, d is the average degree of terms +// -: O(d * t) +// *: O(d * t^2) +// eval: O(d * t) +// to_list: O(d * tlogt) +// Space: O(e + d * t), e is the number of evalvars + +class Poly { +public: + Poly() {} + + Poly(const string& expr) { + vector key; + if (is_number(expr)) { + polies_[key] = stoi(expr); + } else { + key.emplace_back(expr); + ++polies_[key]; + } + } + + void update(const vector& key, int val) { + polies_[key] += val; + if (polies_[key] == 0) { + polies_.erase(key); + } + } + + operator vector() { // Time: O(d * tlogt) + map, int, Compare>> sorted(polies_.begin(), polies_.end()); + vector result; + for (const auto& kvp : sorted) { + vector tmp(kvp.first); + tmp.emplace(tmp.begin(), to_string(kvp.second)); + result.emplace_back(join(tmp, "*")); + } + return result; + } + + Poly operator+(const Poly &rhs) const { // Time: O(d * t) + Poly result; + for (const auto& kvp : polies_) { + result.update(kvp.first, kvp.second); + } + for (const auto& kvp : rhs.polies_) { + result.update(kvp.first, kvp.second); + } + return result; + } + + Poly operator-(const Poly &rhs) const { // Time: O(d * t) + Poly result; + for (const auto& kvp : polies_) { + result.update(kvp.first, kvp.second); + } + for (const auto& kvp : rhs.polies_) { + result.update(kvp.first, -kvp.second); + } + return result; + } + + Poly operator*(const Poly &rhs) const { // Time: O(d * t^2) + Poly result; + for (const auto& kvp1 : polies_) { + for (const auto& kvp2 : rhs.polies_) { + result.update(merge(kvp1.first, kvp2.first), + kvp1.second * kvp2.second); + } + } + return result; + } + + Poly eval(const unordered_map& lookup) const { // Time: O(d * t) + Poly result; + for (const auto& kvp : polies_) { + vector key; + int c = kvp.second; + for (const auto& token : kvp.first) { + if (lookup.count(token)) { + c *= lookup.at(token); + } else { + key.emplace_back(token); + } + } + result.update(key, c); + } + return result; + } + +private: + bool is_number(const std::string &s) { + return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit); + } + + vector merge(const vector& arr1, const vector& arr2) const { + vector result; + int i = 0, j = 0; + while (i < arr1.size() || j < arr2.size()) { + if (j == arr2.size()) { + result.emplace_back(arr1[i++]); + } else if (i == arr1.size()) { + result.emplace_back(arr2[j++]); + } else if (arr1[i] < arr2[j]) { + result.emplace_back(arr1[i++]); + } else { + result.emplace_back(arr2[j++]); + } + } + return result; + } + + 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()); + } + + template + class Compare { + public: + bool operator() + (const ContType& x,const ContType& y) { + return x.size() != y.size() ? x.size() > y.size() : x < y; + } + }; + + template + struct Hash { + size_t operator()(const ContType& v) const { + size_t seed = 0; + for (const auto& i : v) { + seed ^= std::hash{}(i) + 0x9e3779b9 + (seed<<6) + (seed>>2); + } + return seed; + } + }; + + unordered_map, int, Hash>> polies_; +}; + +class Solution { +public: + vector basicCalculatorIV(string expression, vector& evalvars, vector& evalints) { + unordered_map lookup; + for (int i = 0; i < evalvars.size(); ++i) { + lookup[evalvars[i]] = evalints[i]; + } + return parse(expression).eval(lookup); + } + +private: + Poly parse(const string& s) { + if (s.empty()) { + return Poly(); + } + stack operands; + stack operators; + string operand; + for (int i = s.length() - 1; i >= 0; --i) { + if (isalnum(s[i])) { + operand.push_back(s[i]); + if (i == 0 || !isalnum(s[i - 1])) { + reverse(operand.begin(), operand.end()); + operands.emplace(Poly(operand)); + operand.clear(); + } + } else if (s[i] == ')' || s[i] == '*') { + operators.emplace(s[i]); + } else if (s[i] == '+' || s[i] == '-') { + while (!operators.empty() && operators.top() == '*') { + compute(operands, operators); + } + 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(); + } + + template + void compute(stack& operands, stack& operators) { + const auto left = operands.top(); + operands.pop(); + const auto right = operands.top(); + operands.pop(); + const char op = operators.top(); + operators.pop(); + if (op == '+') { + operands.emplace(left + right); + } else if (op == '-') { + operands.emplace(left - right); + } else if (op == '*') { + operands.emplace(left * right); + } + } +}; From 28a1893ae5d3ac93c737523e8d18f271aaee8eac Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jan 2018 02:33:01 +0800 Subject: [PATCH 4331/4971] Update basic-calculator-iv.cpp --- C++/basic-calculator-iv.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/basic-calculator-iv.cpp b/C++/basic-calculator-iv.cpp index ffd6242a2..3efb56c63 100644 --- a/C++/basic-calculator-iv.cpp +++ b/C++/basic-calculator-iv.cpp @@ -92,7 +92,7 @@ class Poly { return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit); } - vector merge(const vector& arr1, const vector& arr2) const { + vector merge(const vector& arr1, const vector& arr2) const { // Time: O(d) vector result; int i = 0, j = 0; while (i < arr1.size() || j < arr2.size()) { From 07e1520b27ee95297c985ca596e1506bb6896cd9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jan 2018 02:46:58 +0800 Subject: [PATCH 4332/4971] Update basic-calculator-iv.py --- Python/basic-calculator-iv.py | 128 +++++++++++++++++++--------------- 1 file changed, 72 insertions(+), 56 deletions(-) diff --git a/Python/basic-calculator-iv.py b/Python/basic-calculator-iv.py index 2472b51f0..90b9b649b 100644 --- a/Python/basic-calculator-iv.py +++ b/Python/basic-calculator-iv.py @@ -1,5 +1,9 @@ -# Time: O(m + n^3 * logn) -# Space: O(m + n) +# Time: +: O(d * t), t is the number of terms, d is the average degree of terms +# -: O(d * t) +# *: O(d * t^2) +# eval: O(d * t) +# to_list: O(d * tlogt) +# Space: O(e + d * t), e is the number of evalvars class Poly(collections.Counter): def __init__(self, expr=""): @@ -19,27 +23,45 @@ def __sub__(self, other): return self def __mul__(self, other): + def merge(k1, k2): + result = [] + i, j = 0, 0 + while i != len(k1) or j != len(k2): + if j == len(k2): + result.append(k1[i]) + i += 1 + elif i == len(k1): + result.append(k2[j]) + j += 1 + elif k1[i] < k2[j]: + result.append(k1[i]) + i += 1 + else: + result.append(k2[j]) + j += 1 + return result + result = Poly() for k1, v1 in self.items(): for k2, v2 in other.items(): - result.update({tuple(sorted(k1+k2)): v1*v2}) + result.update({tuple(merge(k1, k2)): v1*v2}) return result - def evaluate(self, lookup): + def eval(self, lookup): result = Poly() - for k, c in self.items(): - poly = [] - for token in k: - if token in lookup: - c *= lookup[token] + for polies, c in self.items(): + key = [] + for var in polies: + if var in lookup: + c *= lookup[var] else: - poly.append(token) - result[tuple(poly)] += c + key.append(var) + result[tuple(key)] += c return result def to_list(self): return ["*".join((str(v),) + k) \ - for k, v in sorted(self.items(), key=lambda(k, v): (-len(k), k, v)) \ + for k, v in sorted(self.items(), key=lambda(k, _): (-len(k), k)) \ if v] @@ -51,48 +73,42 @@ def basicCalculatorIV(self, expression, evalvars, evalints): :type evalints: List[int] :rtype: List[str] """ + def compute(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) + + def parse(s): + if not s: + return Poly() + operands, operators = [], [] + operand = "" + for i in reversed(xrange(len(s))): + if s[i].isalnum(): + operand += s[i] + if i == 0 or not s[i-1].isalnum(): + operands.append(Poly(operand[::-1])) + operand = "" + elif s[i] == ')' or s[i] == '*': + operators.append(s[i]) + elif s[i] == '+' or s[i] == '-': + while operators and operators[-1] == '*': + compute(operands, operators) + operators.append(s[i]) + elif s[i] == '(': + while operators[-1] != ')': + compute(operands, operators) + operators.pop() + while operators: + compute(operands, operators) + return operands[-1] + lookup = dict(itertools.izip(evalvars, evalints)) - - def do_operator(left, right, operator): - if operator == '+': return left + right - if operator == '-': return left - right - if operator == '*': return left * right - raise - - def parse(expr): - operands = [] - operators = [] - i = 0 - while i < len(expr): - if expr[i] == '(': - cnt = 0 - for j in xrange(i, len(expr)): - if expr[j] == '(': cnt += 1 - if expr[j] == ')': cnt -= 1 - if cnt == 0: break - operands.append(parse(expr[i+1:j])) - i = j - elif expr[i].isalnum(): - for j in xrange(i, len(expr)): - if expr[j] == ' ': - operands.append(Poly(expr[i:j])) - break - else: - operands.append(Poly(expr[i:])) - i = j - elif expr[i] in '+-*': - operators.append(expr[i]) - i += 1 - - for i in reversed(xrange(len(operators))): - if operators[i] == '*': - operands[i] = do_operator(operands[i], operands.pop(i+1), \ - operators.pop(i)) - - if not operands: return Poly() - result = operands[0] - for i, operator in enumerate(operators, 1): - result = do_operator(result, operands[i], operator) - return result - - return parse(expression).evaluate(lookup).to_list() + return parse(expression).eval(lookup).to_list() From 111092a26c546094323979a96f5e62ff7e7d834b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jan 2018 02:47:26 +0800 Subject: [PATCH 4333/4971] Update basic-calculator-iv.py --- Python/basic-calculator-iv.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/Python/basic-calculator-iv.py b/Python/basic-calculator-iv.py index 90b9b649b..0f8a96eb5 100644 --- a/Python/basic-calculator-iv.py +++ b/Python/basic-calculator-iv.py @@ -82,8 +82,6 @@ def compute(operands, operators): operands.append(left - right) elif op == '*': operands.append(left * right) - elif op == '/': - operands.append(left / right) def parse(s): if not s: From 8f18cdcce645f8fbf23c52d741ae96065354a6ac Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jan 2018 02:49:02 +0800 Subject: [PATCH 4334/4971] Update basic-calculator-iv.py --- Python/basic-calculator-iv.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/basic-calculator-iv.py b/Python/basic-calculator-iv.py index 0f8a96eb5..7a5ce3665 100644 --- a/Python/basic-calculator-iv.py +++ b/Python/basic-calculator-iv.py @@ -6,8 +6,8 @@ # Space: O(e + d * t), e is the number of evalvars class Poly(collections.Counter): - def __init__(self, expr=""): - if not expr: + def __init__(self, expr=None): + if expr is None: return if expr.isdigit(): self.update({(): int(expr)}) From 000fc12a5a0c4192bc9e0ac2b09e23f404fadc4a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jan 2018 02:51:55 +0800 Subject: [PATCH 4335/4971] Update basic-calculator-iv.cpp --- C++/basic-calculator-iv.cpp | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/C++/basic-calculator-iv.cpp b/C++/basic-calculator-iv.cpp index 3efb56c63..758f40857 100644 --- a/C++/basic-calculator-iv.cpp +++ b/C++/basic-calculator-iv.cpp @@ -18,24 +18,6 @@ class Poly { ++polies_[key]; } } - - void update(const vector& key, int val) { - polies_[key] += val; - if (polies_[key] == 0) { - polies_.erase(key); - } - } - - operator vector() { // Time: O(d * tlogt) - map, int, Compare>> sorted(polies_.begin(), polies_.end()); - vector result; - for (const auto& kvp : sorted) { - vector tmp(kvp.first); - tmp.emplace(tmp.begin(), to_string(kvp.second)); - result.emplace_back(join(tmp, "*")); - } - return result; - } Poly operator+(const Poly &rhs) const { // Time: O(d * t) Poly result; @@ -87,10 +69,28 @@ class Poly { return result; } + operator vector() { // Time: O(d * tlogt) + map, int, Compare>> sorted(polies_.begin(), polies_.end()); + vector result; + for (const auto& kvp : sorted) { + vector tmp(kvp.first); + tmp.emplace(tmp.begin(), to_string(kvp.second)); + result.emplace_back(join(tmp, "*")); + } + return result; + } + private: bool is_number(const std::string &s) { return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit); } + + void update(const vector& key, int val) { + polies_[key] += val; + if (polies_[key] == 0) { + polies_.erase(key); + } + } vector merge(const vector& arr1, const vector& arr2) const { // Time: O(d) vector result; From d782add98711afda91534885c4f5e66e701095b9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jan 2018 03:01:23 +0800 Subject: [PATCH 4336/4971] Update basic-calculator-iv.cpp --- C++/basic-calculator-iv.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/basic-calculator-iv.cpp b/C++/basic-calculator-iv.cpp index 758f40857..176363b12 100644 --- a/C++/basic-calculator-iv.cpp +++ b/C++/basic-calculator-iv.cpp @@ -69,7 +69,7 @@ class Poly { return result; } - operator vector() { // Time: O(d * tlogt) + operator vector() const { // Time: O(d * tlogt) map, int, Compare>> sorted(polies_.begin(), polies_.end()); vector result; for (const auto& kvp : sorted) { @@ -109,7 +109,7 @@ class Poly { return result; } - string join(const vector& strings, const string& delim) { + string join(const vector& strings, const string& delim) const { if (strings.empty()) { return ""; } From 18f39a3b30b77b754326d804b104817c44c52e15 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jan 2018 03:02:11 +0800 Subject: [PATCH 4337/4971] Update basic-calculator-iv.cpp --- C++/basic-calculator-iv.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/basic-calculator-iv.cpp b/C++/basic-calculator-iv.cpp index 176363b12..ac1904426 100644 --- a/C++/basic-calculator-iv.cpp +++ b/C++/basic-calculator-iv.cpp @@ -81,7 +81,7 @@ class Poly { } private: - bool is_number(const std::string &s) { + bool is_number(const std::string &s) const { return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit); } From a4383f04f7c3b509dd6066d949350a7e7a452aa3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jan 2018 23:02:04 +0800 Subject: [PATCH 4338/4971] Create basic-calculator-iii.py --- Python/basic-calculator-iii.py | 46 ++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/basic-calculator-iii.py diff --git a/Python/basic-calculator-iii.py b/Python/basic-calculator-iii.py new file mode 100644 index 000000000..7bb6cae9a --- /dev/null +++ b/Python/basic-calculator-iii.py @@ -0,0 +1,46 @@ +# Time: O(n) +# Space: O(n) + +class Solution(object): + def calculate(self, s): + """ + :type s: str + :rtype: int + """ + 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 788e2d919bdc8f06dc40d23770929e4b3e51af23 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 23 Jan 2018 23:03:57 +0800 Subject: [PATCH 4339/4971] Create basic-calculator-iii.cpp --- C++/basic-calculator-iii.cpp | 59 ++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 C++/basic-calculator-iii.cpp diff --git a/C++/basic-calculator-iii.cpp b/C++/basic-calculator-iii.cpp new file mode 100644 index 000000000..e9cb14484 --- /dev/null +++ b/C++/basic-calculator-iii.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.emplace(left + right); + } else if (op == '-') { + operands.emplace(left - right); + } else if (op == '*') { + operands.emplace(left * right); + } else if (op == '/') { + operands.emplace(left / right); + } + } +}; From 2cb31e6244fc5805d86b9515c6883b7939255cd2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 00:27:16 +0800 Subject: [PATCH 4340/4971] Update toeplitz-matrix.py --- Python/toeplitz-matrix.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Python/toeplitz-matrix.py b/Python/toeplitz-matrix.py index ce7411096..605447981 100644 --- a/Python/toeplitz-matrix.py +++ b/Python/toeplitz-matrix.py @@ -1,6 +1,34 @@ # Time: O(m * n) # Space: O(1) +# A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. +# Now given an M x N matrix, return True if and only if the matrix is Toeplitz. +# +# Example 1: +# +# Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] +# Output: True +# Explanation: +# 1234 +# 5123 +# 9512 +# +# In the above grid, the diagonals are +# "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", +# and in each diagonal all elements are the same, so the answer is True. +# +# Example 2: +# +# Input: matrix = [[1,2],[2,2]] +# Output: False +# Explanation: +# The diagonal "[1, 2]" has different elements. +# +# Note: +# - matrix will be a 2D array of integers. +# - matrix will have a number of rows and columns in range [1, 20]. +# - matrix[i][j] will be integers in range [0, 99]. + class Solution(object): def isToeplitzMatrix(self, matrix): """ From 39874a0ddb65582a04ea32fa2b05bacc968f56f3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 00:29:34 +0800 Subject: [PATCH 4341/4971] Update max-chunks-to-make-sorted-ii.py --- Python/max-chunks-to-make-sorted-ii.py | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Python/max-chunks-to-make-sorted-ii.py b/Python/max-chunks-to-make-sorted-ii.py index daf6a256c..363d313f9 100644 --- a/Python/max-chunks-to-make-sorted-ii.py +++ b/Python/max-chunks-to-make-sorted-ii.py @@ -1,6 +1,36 @@ # Time: O(nlogn) # Space: O(n) +# This question is the same as "Max Chunks to Make Sorted" +# except the integers of the given array are not necessarily distinct, +# the input array could be up to length 2000, and the elements could be up to 10**8. +# +# Given an array arr of integers (not necessarily distinct), +# we split the array into some number of "chunks" (partitions), +# and individually sort each chunk. +# After concatenating them, the result equals the sorted array. +# +# What is the most number of chunks we could have made? +# +# Example 1: +# +# Input: arr = [5,4,3,2,1] +# Output: 1 +# Explanation: +# Splitting into two or more chunks will not return the required result. +# For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted. +# Example 2: +# +# Input: arr = [2,1,3,4,4] +# Output: 4 +# Explanation: +# We can split into two chunks, such as [2, 1], [3, 4, 4]. +# However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible. +# +# Note: +# - arr will have length in range [1, 2000]. +# - arr[i] will be an integer in range [0, 10**8]. + class Solution(object): def maxChunksToSorted(self, arr): """ From 6fe26f2e8e7c8cc7961a62fdfbb13f6261ce23fa Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 00:30:55 +0800 Subject: [PATCH 4342/4971] Update reorganized-string.py --- Python/reorganized-string.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Python/reorganized-string.py b/Python/reorganized-string.py index 86d403867..aa2dca926 100644 --- a/Python/reorganized-string.py +++ b/Python/reorganized-string.py @@ -1,6 +1,23 @@ # Time: O(nloga) = O(n), a is the size of alphabet # Space: O(a) = O(1) +# Given a string S, check if the letters can be rearranged +# so that two characters that are adjacent to each other are not the same. +# +# If possible, output any possible result. If not possible, return the empty string. +# +# Example 1: +# +# Input: S = "aab" +# Output: "aba" +# Example 2: +# +# Input: S = "aaab" +# Output: "" +# +# Note: +# - S will consist of lowercase letters and have length in range [1, 500]. + class Solution(object): def reorganizeString(self, S): """ From de3b4775b7dbcecc9c42e18c59b35485f83ca74a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 00:32:09 +0800 Subject: [PATCH 4343/4971] Update max-chunks-to-make-sorted-i.py --- Python/max-chunks-to-make-sorted-i.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Python/max-chunks-to-make-sorted-i.py b/Python/max-chunks-to-make-sorted-i.py index 4e957fd38..2677bb63b 100644 --- a/Python/max-chunks-to-make-sorted-i.py +++ b/Python/max-chunks-to-make-sorted-i.py @@ -1,6 +1,32 @@ # Time: O(n) # Space: O(1) +# Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], +# we split the array into some number of "chunks" (partitions), and individually sort each chunk. +# After concatenating them, the result equals the sorted array. +# +# What is the most number of chunks we could have made? +# +# Example 1: +# +# Input: arr = [4,3,2,1,0] +# Output: 1 +# Explanation: +# Splitting into two or more chunks will not return the required result. +# For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted. +# +# Example 2: +# +# Input: arr = [1,0,2,3,4] +# Output: 4 +# Explanation: +# We can split into two chunks, such as [1, 0], [2, 3, 4]. +# However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible. +# +# Note: +# - arr will have length in range [1, 10]. +# - arr[i] will be a permutation of [0, 1, ..., arr.length - 1]. + class Solution(object): def maxChunksToSorted(self, arr): """ From 8aa59ef8be0d59608c9e32fdc03db102121f7c7a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 00:37:30 +0800 Subject: [PATCH 4344/4971] Update basic-calculator-iv.py --- Python/basic-calculator-iv.py | 56 +++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/Python/basic-calculator-iv.py b/Python/basic-calculator-iv.py index 7a5ce3665..cdf693a0b 100644 --- a/Python/basic-calculator-iv.py +++ b/Python/basic-calculator-iv.py @@ -5,6 +5,62 @@ # to_list: O(d * tlogt) # Space: O(e + d * t), e is the number of evalvars +# Given an expression such as expression = "e + 8 - a + 5" and +# an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), +# return a list of tokens representing the simplified expression, such as ["-1*a","14"] +# - An expression alternates chunks and symbols, with a space separating each chunk and symbol. +# - A chunk is either an expression in parentheses, a variable, or a non-negative integer. +# - A variable is a string of lowercase letters (not including digits.) +# Note that variables can be multiple letters, and note that variables never +# have a leading coefficient or unary operator like "2x" or "-x". +# +# Expressions are evaluated in the usual order: +# brackets first, then multiplication, then addition and subtraction. +# For example, expression = "1 + 2 * 3" has an answer of ["7"]. +# +# The format of the output is as follows: +# - For each term of free variables with non-zero coefficient, +# we write the free variables within a term in sorted order lexicographically. +# For example, we would never write a term like "b*a*c", only "a*b*c". +# - Terms have degree equal to the number of free variables being multiplied, +# counting multiplicity. (For example, "a*a*b*c" has degree 4.) +# We write the largest degree terms of our answer first, +# breaking ties by lexicographic order ignoring the leading coefficient of the term. +# - The leading coefficient of the term is placed directly to the left with an asterisk separating it +# from the variables (if they exist.) A leading coefficient of 1 is still printed. +# - An example of a well formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] +# - Terms (including constant terms) with coefficient 0 are not included. +# For example, an expression of "0" has an output of []. +# +# Examples: +# +# Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1] +# Output: ["-1*a","14"] +# +# Input: expression = "e - 8 + temperature - pressure", +# evalvars = ["e", "temperature"], evalints = [1, 12] +# Output: ["-1*pressure","5"] +# +# Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = [] +# Output: ["1*e*e","-64"] +# +# Input: expression = "7 - 7", evalvars = [], evalints = [] +# Output: [] +# +# Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = [] +# Output: ["5*a*b*c"] +# +# Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))", +# evalvars = [], evalints = [] +# Output: +# ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c", +# "1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b", +# "2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"] +# +# Note: +# - expression will have length in range [1, 1000]. +# - evalvars, evalints will have equal lengths in range [0, 1000]. + class Poly(collections.Counter): def __init__(self, expr=None): if expr is None: From a421f88139a2dad88378de2f62c8b73511a0b513 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 00:38:38 +0800 Subject: [PATCH 4345/4971] Update basic-calculator-iii.py --- Python/basic-calculator-iii.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Python/basic-calculator-iii.py b/Python/basic-calculator-iii.py index 7bb6cae9a..0010d2a4d 100644 --- a/Python/basic-calculator-iii.py +++ b/Python/basic-calculator-iii.py @@ -1,6 +1,26 @@ # 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 . +# +# The expression string contains only non-negative integers, +, -, *, / operators , +# open ( and closing parentheses ) and empty spaces . +# The integer division should truncate toward zero. +# +# You may assume that the given expression is always valid. +# +# Some examples: +# +# "1 + 1" = 2 +# " 6-4 / 2 " = 4 +# "2*(5+5*2)/3+(6/2+8)" = 21 +# "(2+6* 3+5- (3*14/7+2)*5)+3"=-12 +# +# Note: Do not use the eval built-in library function. + class Solution(object): def calculate(self, s): """ From 6238afd7d2cb10c467b2c1bba08d749775a82b9e Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 22:33:02 +0800 Subject: [PATCH 4346/4971] Rename reorganized-string.cpp to reorganize-string.cpp --- C++/{reorganized-string.cpp => reorganize-string.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{reorganized-string.cpp => reorganize-string.cpp} (100%) diff --git a/C++/reorganized-string.cpp b/C++/reorganize-string.cpp similarity index 100% rename from C++/reorganized-string.cpp rename to C++/reorganize-string.cpp From 89a4ccf5291808d335c53fa8ab15661522506fa6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 22:33:31 +0800 Subject: [PATCH 4347/4971] Rename reorganized-string.py to reorganize-string.py --- Python/{reorganized-string.py => reorganize-string.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{reorganized-string.py => reorganize-string.py} (100%) diff --git a/Python/reorganized-string.py b/Python/reorganize-string.py similarity index 100% rename from Python/reorganized-string.py rename to Python/reorganize-string.py From 64c344253b9fb7f4f41f44a7903eceb908a3bc32 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 22:39:56 +0800 Subject: [PATCH 4348/4971] Rename max-chunks-to-make-sorted-i.py to max-chunks-to-make-sorted.py --- ...ax-chunks-to-make-sorted-i.py => max-chunks-to-make-sorted.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Python/{max-chunks-to-make-sorted-i.py => max-chunks-to-make-sorted.py} (100%) diff --git a/Python/max-chunks-to-make-sorted-i.py b/Python/max-chunks-to-make-sorted.py similarity index 100% rename from Python/max-chunks-to-make-sorted-i.py rename to Python/max-chunks-to-make-sorted.py From bdd3d0a2d1d3a18021fa7d0e805df440d3e99b85 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 22:40:24 +0800 Subject: [PATCH 4349/4971] Rename max-chunks-to-make-sorted-i.cpp to max-chunks-to-make-sorted.cpp --- ...-chunks-to-make-sorted-i.cpp => max-chunks-to-make-sorted.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename C++/{max-chunks-to-make-sorted-i.cpp => max-chunks-to-make-sorted.cpp} (100%) diff --git a/C++/max-chunks-to-make-sorted-i.cpp b/C++/max-chunks-to-make-sorted.cpp similarity index 100% rename from C++/max-chunks-to-make-sorted-i.cpp rename to C++/max-chunks-to-make-sorted.cpp From b7da433424058868cf228d8b44c49dd9c51d6bfa Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 22:51:05 +0800 Subject: [PATCH 4350/4971] Update README.md --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 7be0233b5..9790ad137 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,9 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 732 | [My Calendar III](https://leetcode.com/problems/my-calendar-iii/) | [C++](./C++/my-calendar-iii.cpp) [Python](./Python/my-calendar-iii.py) | _O(n^2)_ | _O(n)_ | Hard || 747 | [Largest Number At Least Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others/) | [C++](./C++/largest-number-at-least-twice-of-others.cpp) [Python](./Python/largest-number-at-least-twice-of-others.py) | _O(n)_ | _O(1)_ | Easy || 755 | [Pour Water](https://leetcode.com/problems/pour-water/) | [C++](./C++/pour-water.cpp) [Python](./Python/pour-water.py) | _O(v * n)_ | _O(1)_ | Medium || +766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/) | [C++](./C++/toeplitz-matrix.cpp) [Python](./Python/toeplitz-matrix.py) | _O(m * n)_ | _O(1)_ | Easy || +768 | [Max Chunks To Make Sorted II](https://leetcode.com/problems/max-chunks-to-make-sorted-ii/) | [C++](./C++/max-chunks-to-make-sorted-ii.cpp) [Python](./Python/max-chunks-to-make-sorted-ii.py) | _O(nlogn)_ | _O(n)_ | Hard || +769 | [Max Chunks To Make Sorted](https://leetcode.com/problems/max-chunks-to-make-sorted/) | [C++](./C++/max-chunks-to-make-sorted.cpp) [Python](./Python/max-chunks-to-make-sorted.py) | _O(n)_ | _O(1)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -247,6 +250,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 735| [Asteroid Collision](https://leetcode.com/problems/asteroid-collision/) | [C++](./C++/asteroid-collision.cpp) [Python](./Python/asteroid-collision.py) | _O(n)_ | _O(n)_ | Medium || 736| [Parse Lisp Expression](https://leetcode.com/problems/parse-lisp-expression/) | [C++](./C++/parse-lisp-expression.cpp) [Python](./Python/parse-lisp-expression.py) | _O(n^2)_ | _O(n^2)_ | Hard || 739| [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) | [C++](./C++/daily-temperatures.cpp) [Python](./Python/daily-temperatures.py) | _O(n)_ | _O(n)_ | Medium || +770| [Basic Calculator IV](https://leetcode.com/problems/basic-calculator-iv/) | [C++](./C++/basic-calculator-iv.cpp) [Python](./Python/basic-calculator-iv.py) | _O(n)_ | add: _O(d * t)_
sub: _O(d * t)_
mul: _O(d * t^2)_
eval: _O(d * t)_
to_list: _O(d * tlogt)_ | Hard || +772| [Basic Calculator III](https://leetcode.com/problems/basic-calculator-iii/) | [C++](./C++/basic-calculator-iii.cpp) [Python](./Python/basic-calculator-iii.py) | _O(n)_ | _O(n)_ | Hard || ## Queue | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -733,6 +738,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 757 | [Set Intersection Size At Least Two](https://leetcode.com/problems/set-intersection-size-at-least-two/) | [C++](./C++/set-intersection-size-at-least-two.cpp) [Python](./Python/set-intersection-size-at-least-two.py) | _O(nlogn)_ | _O(n)_ | Hard | | 759 | [Employee Free Time](https://leetcode.com/problems/employee-free-time/) | [C++](./C++/employee-free-time.cpp) [Python](./Python/employee-free-time.py) | _O(m * logn)_ | _O(n)_ | Hard | | 763 | [Partition Labels](https://leetcode.com/problems/partition-labels/) | [C++](./C++/partition-labels.cpp) [Python](./Python/partition-labels.py) | _O(n)_ | _O(n)_ | Medium | | +767 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | [C++](./C++/reorganize-string.cpp) [Python](./Python/reorganize-string.py) | _O(n)_ | _O(1)_ | Medium | | ## Graph | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 5d93c2dbcdc6490d334fbc3353a1c1be5b68d6e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 24 Jan 2018 22:52:16 +0800 Subject: [PATCH 4351/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9790ad137..d0be537da 100644 --- a/README.md +++ b/README.md @@ -250,7 +250,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 735| [Asteroid Collision](https://leetcode.com/problems/asteroid-collision/) | [C++](./C++/asteroid-collision.cpp) [Python](./Python/asteroid-collision.py) | _O(n)_ | _O(n)_ | Medium || 736| [Parse Lisp Expression](https://leetcode.com/problems/parse-lisp-expression/) | [C++](./C++/parse-lisp-expression.cpp) [Python](./Python/parse-lisp-expression.py) | _O(n^2)_ | _O(n^2)_ | Hard || 739| [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) | [C++](./C++/daily-temperatures.cpp) [Python](./Python/daily-temperatures.py) | _O(n)_ | _O(n)_ | Medium || -770| [Basic Calculator IV](https://leetcode.com/problems/basic-calculator-iv/) | [C++](./C++/basic-calculator-iv.cpp) [Python](./Python/basic-calculator-iv.py) | _O(n)_ | add: _O(d * t)_
sub: _O(d * t)_
mul: _O(d * t^2)_
eval: _O(d * t)_
to_list: _O(d * tlogt)_ | Hard || +770| [Basic Calculator IV](https://leetcode.com/problems/basic-calculator-iv/) | [C++](./C++/basic-calculator-iv.cpp) [Python](./Python/basic-calculator-iv.py) | add: _O(d * t)_
sub: _O(d * t)_
mul: _O(d * t^2)_
eval: _O(d * t)_
to_list: _O(d * tlogt)_ | _O(e + d * t)_ | Hard || 772| [Basic Calculator III](https://leetcode.com/problems/basic-calculator-iii/) | [C++](./C++/basic-calculator-iii.cpp) [Python](./Python/basic-calculator-iii.py) | _O(n)_ | _O(n)_ | Hard || ## Queue From 188d8dbec87a82c43b2e6986c13e77d5bfaa7d6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 25 Jan 2018 00:24:09 +0800 Subject: [PATCH 4352/4971] Update basic-calculator-iii.cpp --- C++/basic-calculator-iii.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/C++/basic-calculator-iii.cpp b/C++/basic-calculator-iii.cpp index e9cb14484..2461788f6 100644 --- a/C++/basic-calculator-iii.cpp +++ b/C++/basic-calculator-iii.cpp @@ -39,10 +39,11 @@ class Solution { return operands.top(); } - void compute(stack& operands, stack& operators) { - const int64_t left = operands.top(); + template + void compute(stack& operands, stack& operators) { + const auto left = operands.top(); operands.pop(); - const int64_t right = operands.top(); + const auto right = operands.top(); operands.pop(); const char op = operators.top(); operators.pop(); From d427b75cd83d1817ae9b036d62f9cea2a91527ab Mon Sep 17 00:00:00 2001 From: jxie0755 <30805062+jxie0755@users.noreply.github.com> Date: Wed, 24 Jan 2018 11:46:01 -0500 Subject: [PATCH 4353/4971] Python 3 compatibility Hello, I found that the first method `reverse` only runs in python 2. I've made a python 3 compatible version under it, called reverse_py3. Thanks, --- Python/reverse-integer.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py index 014a66fee..8382ba25b 100644 --- a/Python/reverse-integer.py +++ b/Python/reverse-integer.py @@ -34,7 +34,21 @@ def reverse(self, x): result = result * 10 + x % 10 x /= 10 return result if result <= 0x7fffffff else 0 # Handle overflow. - + + def reverse_py3(self, x): # Same principle as above, but python3 compatible + """ + :type x: int + :rtype: int + """ + absX = abs(x) + result = 0 + while absX > 0: + result = result * 10 + absX % 10 + absX //= 10 + if x < 0: + result = -result + return result if 2147483647 > result > -2147483648 else 0 + def reverse2(self, x): """ :type x: int From 854da1627a78e6a6198279f87dd0dbe3c049ad0e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 25 Jan 2018 00:57:03 +0800 Subject: [PATCH 4354/4971] Update add-two-numbers.py --- Python/add-two-numbers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/add-two-numbers.py b/Python/add-two-numbers.py index 11061b81a..6235ca22d 100644 --- a/Python/add-two-numbers.py +++ b/Python/add-two-numbers.py @@ -32,7 +32,7 @@ def addTwoNumbers(self, l1, l2): if l2: val += l2.val l2 = l2.next - carry, val = val / 10, val % 10 # val = val//10 if python 3 + carry, val = divmod(val, 10) current.next = ListNode(val) current = current.next From 424ca6f15e5959e83a04f56678e35fa6717f8b6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 25 Jan 2018 01:02:50 +0800 Subject: [PATCH 4355/4971] Update reverse-integer.py --- Python/reverse-integer.py | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py index 8382ba25b..6b213a576 100644 --- a/Python/reverse-integer.py +++ b/Python/reverse-integer.py @@ -32,22 +32,8 @@ def reverse(self, x): result = 0 while x: result = result * 10 + x % 10 - x /= 10 + x //= 10 return result if result <= 0x7fffffff else 0 # Handle overflow. - - def reverse_py3(self, x): # Same principle as above, but python3 compatible - """ - :type x: int - :rtype: int - """ - absX = abs(x) - result = 0 - while absX > 0: - result = result * 10 + absX % 10 - absX //= 10 - if x < 0: - result = -result - return result if 2147483647 > result > -2147483648 else 0 def reverse2(self, x): """ From 27cc0b57e68202ec4a506f30a78d58b976377dcc Mon Sep 17 00:00:00 2001 From: jxie0755 <30805062+jxie0755@users.noreply.github.com> Date: Wed, 24 Jan 2018 13:58:13 -0500 Subject: [PATCH 4356/4971] Fill all question number to 3 digits Hi, for easier searching, I would like to make all question number to XXX. which means question 1 will be 001, question 11 will be 011, etc. --- README.md | 198 +++++++++++++++++++++++++++--------------------------- 1 file changed, 99 insertions(+), 99 deletions(-) diff --git a/README.md b/README.md index d0be537da..063dca3e9 100644 --- a/README.md +++ b/README.md @@ -70,19 +70,19 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Array | # | 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 || Two Pointers -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 || Two Pointers -18| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(1)_ | Medium || Two Pointers -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 -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 || -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 +015 | [3 Sum](https://leetcode.com/problems/3sum/) | [C++](./C++/3sum.cpp) [Python](./Python/3sum.py) | _O(n^2)_ | _O(1)_ | Medium || Two Pointers +016 | [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 || Two Pointers +018| [4 Sum](https://leetcode.com/problems/4sum/) | [C++](./C++/4sum.cpp) [Python](./Python/4sum.py) | _O(n^3)_ | _O(1)_ | Medium || Two Pointers +026 | [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 +027 | [Remove Element](https://leetcode.com/problems/remove-element/) | [C++](./C++/remove-element.cpp) [Python](./Python/remove-element.py) | _O(n)_ | _O(1)_ | Easy || +031 | [Next Permutation](https://leetcode.com/problems/next-permutation/)| [C++](./C++/next-permutation.cpp) [Python](./Python/next-permutation.py) | _O(n)_ | _O(1)_ | Medium || Tricky +041 | [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 +048 | [Rotate Image](https://leetcode.com/problems/rotate-image/) | [C++](./C++/rotate-image.cpp) [Python](./Python/rotate-image.py) | _O(n^2)_ | _O(1)_ | Medium || +054 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/spiral-matrix.cpp) [Python](./Python/spiral-matrix.py) | _O(m * n)_ | _O(1)_ | Medium || +059 | [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 || +066 | [Plus One](https://leetcode.com/problems/plus-one/) | [C++](./C++/plus-one.cpp) [Python](./Python/plus-one.py) | _O(n)_ | _O(1)_ | Easy || +073 | [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 || +080 | [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/)| [C++](./C++/best-time-to-buy-and-sell-stock.cpp) [Python](./Python/best-time-to-buy-and-sell-stock.py) | _O(n)_ | _O(1)_ | Easy || @@ -148,16 +148,16 @@ 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/) | [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/) | [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/) | [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 || +005| [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` +006| [ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) | [C++](./C++/zigzag-conversion.cpp) [Python](./Python/zigzag-conversion.py) | _O(n)_ | _O(1)_ | Easy || +008| [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 || +014| [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 || +028| [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` +038| [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 || +043| [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 || +058| [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 || +067| [Add Binary](https://leetcode.com/problems/add-binary/) | [C++](./C++/add-binary.cpp) [Python](./Python/add-binary.py) | _O(n)_ | _O(1)_ | Easy || +068| [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/) | [C++](./C++/one-edit-distance.cpp) [Python](./Python/one-edit-distance.py) | _O(m + n)_ | _O(1)_ | Medium |📖 | @@ -201,15 +201,15 @@ 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/) | [C++](./C++/add-two-numbers.cpp) [Python](./Python/add-two-numbers.py) | _O(n)_ | _O(1)_ | Medium || -21| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./C++/merge-two-sorted-lists.cpp) [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || -23| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | | Heap, Divide and Conquer -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)_ | Easy || -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/)| [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 || +002| [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 || +021| [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [C++](./C++/merge-two-sorted-lists.cpp) [Python](./Python/merge-two-sorted-lists.py) | _O(n)_ | _O(1)_ | Easy || +023| [Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | [C++](./C++/merge-k-sorted-lists.cpp) [Python](./Python/merge-k-sorted-lists.py) | _O(nlogk)_| _O(1)_| Hard | | Heap, Divide and Conquer +024| [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)_ | Easy || +025| [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 || +061| [Rotate List](https://leetcode.com/problems/rotate-list/)| [C++](./C++/rotate-list.cpp) [Python](./Python/rotate-list.py) | _O(n)_ | _O(1)_ | Medium || +082| [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 || +083| [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 || +092| [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/)| [C++](./C++/remove-linked-list-elements.cpp) [Python](./Python/remove-linked-list-elements.py) | _O(n)_ | _O(1)_ | Easy || @@ -224,11 +224,11 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Stack | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| -20| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || -32| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./C++/longest-valid-parentheses.cpp) [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || -71| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./C++/simplify-path.cpp) [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || -84| [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | [C++](./C++/largest-rectangle-in-histogram.cpp) [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Ascending Stack, DP -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 | EPI | Ascending Stack +020| [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [C++](./C++/valid-parentheses.cpp) [Python](./Python/valid-parentheses.py) | _O(n)_ | _O(n)_ | Easy || +032| [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)| [C++](./C++/longest-valid-parentheses.cpp) [Python](./Python/longest-valid-parentheses.py) | _O(n)_ | _O(1)_ | Hard || +071| [Simplify Path](https://leetcode.com/problems/simplify-path/)| [C++](./C++/simplify-path.cpp) [Python](./Python/simplify-path.py) | _O(n)_ | _O(n)_ | Medium || +084| [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | [C++](./C++/largest-rectangle-in-histogram.cpp) [Python](./Python/largest-rectangle-in-histogram.py) | _O(n)_ | _O(n)_ | Hard || Ascending Stack, DP +085| [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)| [C++](./C++/maximal-rectangle.cpp) [Python](./Python/maximal-rectangle.py)| _O(m * n)_ | _O(n)_ | Hard | EPI | Ascending Stack 101| [Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [C++](./C++/symmetric-tree.cpp) [Python](./Python/symmetric-tree.py) | _O(n)_ | _O(h)_ | Easy || 150| [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| [C++](./C++/evaluate-reverse-polish-notation.cpp) [Python](./Python/evaluate-reverse-polish-notation.py)| _O(n)_| _O(n)_| Medium || 155| [Min Stack](https://leetcode.com/problems/min-stack/) | [C++](./C++/min-stack.cpp) [Python](./Python/min-stack.py) | _O(n)_ | _O(1)_ | Easy || @@ -275,8 +275,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| -94 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C++](./C++/binary-tree-inorder-traversal.cpp) [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/) | [C++](./C++/recover-binary-search-tree.cpp) [Python](./Python/recover-binary-search-tree.py) | _O(n)_| _O(1)_| Hard || `Morris Traversal` +094 | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | [C++](./C++/binary-tree-inorder-traversal.cpp) [Python](./Python/binary-tree-inorder-traversal.py) | _O(n)_| _O(1)_| Medium || `Morris Traversal` | +099 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree/) | [C++](./C++/recover-binary-search-tree.cpp) [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/) | [C++](./C++/binary-tree-preorder-traversal.cpp) [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/) | [C++](./C++/binary-tree-postorder-traversal.cpp) [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/) | [C++](./C++/implement-trie-prefix-tree.cpp) [Python](./Python/implement-trie-prefix-tree.py) | _O(n)_ | _O(1)_ | Medium || Trie @@ -312,12 +312,12 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| -1| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Easy || -3| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || -30| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [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/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || -49| [Group Anagrams](https://leetcode.com/problems/group-anagrams/) | [C++](./C++/group-anagrams.cpp) [Python](./Python/group-anagrams.py) | _O(n * glogg)_ | _O(n)_ | Medium || -76| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [C++](./C++/minimum-window-substring.cpp) [Python](./Python/minimum-window-substring.py) | _O(n)_ | _O(k)_ | Hard || +001| [Two Sum](https://leetcode.com/problems/two-sum/) | [C++](./C++/two-sum.cpp) [Python](./Python/two-sum.py) | _O(n)_ | _O(n)_ | Easy || +003| [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C++](./C++/longest-substring-without-repeating-characters.cpp) [Python](./Python/longest-substring-without-repeating-characters.py) | _O(n)_ | _O(1)_ | Medium || +030| [Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [C++](./C++/substring-with-concatenation-of-all-words.cpp) [Python](./Python/substring-with-concatenation-of-all-words.py) | _O((m + n) * k)_ | _O(n * k)_ | Hard || +036| [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [C++](./C++/valid-sudoku.cpp) [Python](./Python/valid-sudoku.py) | _O(9^2)_ | _O(9)_ | Easy || +049| [Group Anagrams](https://leetcode.com/problems/group-anagrams/) | [C++](./C++/group-anagrams.cpp) [Python](./Python/group-anagrams.py) | _O(n * glogg)_ | _O(n)_ | Medium || +076| [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | [C++](./C++/minimum-window-substring.cpp) [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/) | [C++](./C++/max-points-on-a-line.cpp) [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/)| [C++](./C++/longest-substring-with-at-most-two-distinct-characters.cpp) [Python](./Python/longest-substring-with-at-most-two-distinct-characters.py) | _O(n)_ | _O(1)_ | Hard |📖| 170| [Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design/) | [C++](./C++/two-sum-iii-data-structure-design.cpp) [Python](./Python/two-sum-iii-data-structure-design.py) | _O(n)_ | _O(n)_ | Easy | 📖 | @@ -366,15 +366,15 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| -7| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [Python](./Python/reverse-integer.py) | _O(1)_ | _O(1)_ | Easy || -9| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C++](./C++/palindrome-number.cpp) [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || -12| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [C++](./C++/integer-to-roman.cpp) [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || -13| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [C++](./C++/roman-to-integer.cpp) [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || -29| [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C++](./C++/divide-two-integers.cpp) [Python](./Python/divide-two-integers.py) | _O(1)_ | _O(1)_ | Medium || -50| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(1)_ | _O(1)_ | Medium || -60| [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | [C++](./C++/permutation-sequence.cpp) [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` -65| [Valid Number](https://leetcode.com/problems/valid-number/) | [C++](./C++/valid-number.cpp) [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` -89| [Gray Code](https://leetcode.com/problems/gray-code/) | [C++](./C++/gray-code.cpp) [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || +007| [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | [C++](./C++/reverse-integer.cpp) [Python](./Python/reverse-integer.py) | _O(1)_ | _O(1)_ | Easy || +009| [Palindrome Number](https://leetcode.com/problems/palindrome-number/) | [C++](./C++/palindrome-number.cpp) [Python](./Python/palindrome-number.py) | _O(1)_ | _O(1)_ | Easy || +012| [Integer to Roman](https://leetcode.com/problems/integer-to-roman/) | [C++](./C++/integer-to-roman.cpp) [Python](./Python/integer-to-roman.py) | _O(n)_ | _O(1)_ | Medium || +013| [Roman to Integer](https://leetcode.com/problems/roman-to-integer/) | [C++](./C++/roman-to-integer.cpp) [Python](./Python/roman-to-integer.py) | _O(n)_ | _O(1)_ | Easy || +029| [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C++](./C++/divide-two-integers.cpp) [Python](./Python/divide-two-integers.py) | _O(1)_ | _O(1)_ | Medium || +050| [Pow(x, n)](https://leetcode.com/problems/powx-n/) | [C++](./C++/powx-n.cpp) [Python](./Python/powx-n.py) | _O(1)_ | _O(1)_ | Medium || +060| [Permutation Sequence](https://leetcode.com/problems/permutation-sequence/) | [C++](./C++/permutation-sequence.cpp) [Python](./Python/permutation-sequence.py) | _O(n^2)_ | _O(n)_ | Medium || `Cantor Ordering` +065| [Valid Number](https://leetcode.com/problems/valid-number/) | [C++](./C++/valid-number.cpp) [Python](./Python/valid-number.py) | _O(n)_ | _O(1)_ | Hard || `Automata` +089| [Gray Code](https://leetcode.com/problems/gray-code/) | [C++](./C++/gray-code.cpp) [Python](./Python/gray-code.py) | _O(2^n)_ | _O(1)_ | Medium || 166| [Fraction to Recurring Decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [C++](./C++/fraction-to-recurring-decimal.cpp) [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/) | [C++](./C++/excel-sheet-column-title.cpp) [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/) | [C++](./C++/excel-sheet-column-number.cpp) [Python](./Python/excel-sheet-column-number.py) | _O(n)_ | _O(1)_ | Easy || @@ -424,10 +424,10 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| -56| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [C++](./C++/merge-intervals.cpp) [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || -57| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [C++](./C++/insert-interval.cpp) [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || -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/)| [C++](./C++/merge-sorted-array.cpp) [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || +056| [Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [C++](./C++/merge-intervals.cpp) [Python](./Python/merge-intervals.py) | _O(nlogn)_ | _O(1)_ | Hard || +057| [Insert Interval](https://leetcode.com/problems/insert-interval/)| [C++](./C++/insert-interval.cpp) [Python](./Python/insert-interval.py) | _O(n)_ | _O(1)_ | Hard || +075| [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 +088| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [C++](./C++/merge-sorted-array.cpp) [Python](./Python/merge-sorted-array.py) | _O(n)_ | _O(1)_ | Easy || 147| [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/)|[C++](./C++/insertion-sort-list.cpp) [Python](./Python/insertion-sort-list.py) | _O(n^2)_ | _O(1)_ | Medium || 148| [Sort List](https://leetcode.com/problems/sort-list/) | [C++](./C++/sort-list.cpp) [Python](./Python/sort-list.py) | _O(nlogn)_ | _O(logn)_ | Medium || 164| [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [C++](./C++/maximum-gap.cpp) [Python](./Python/maximum-gap.py)| _O(n)_ | _O(n)_ | Hard || Tricky @@ -446,8 +446,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Two Pointers | # | 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/)| [C++](./C++/remove-nth-node-from-end-of-list.cpp) [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || -86| [Partition List](https://leetcode.com/problems/partition-list/)| [C++](./C++/partition-list.cpp) [Python](./Python/partition-list.py) | _O(n)_ | _O(1)_ | Medium || +019| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)| [C++](./C++/remove-nth-node-from-end-of-list.cpp) [Python](./Python/remove-nth-node-from-end-of-list.py) | _O(n)_ | _O(1)_ | Easy || +086| [Partition List](https://leetcode.com/problems/partition-list/)| [C++](./C++/partition-list.cpp) [Python](./Python/partition-list.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)_ | Easy || 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/)| [C++](./C++/reorder-list.cpp) [Python](./Python/reorder-list.py) | _O(n)_ | _O(1)_ | Medium || @@ -467,8 +467,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Recursion | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| -95| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [C++](./C++/unique-binary-search-trees-ii.cpp) [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/)|[C++](./C++/validate-binary-search-tree.cpp) [Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || +095| [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) | [C++](./C++/unique-binary-search-trees-ii.cpp) [Python](./Python/unique-binary-search-trees-ii.py) | _O(4^n / n^(3/2)_ | _O(4^n / n^(3/2)_ | Medium || +098| [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|[C++](./C++/validate-binary-search-tree.cpp) [Python](./Python/validate-binary-search-tree.py)| _O(n)_ | _O(1)_ | Medium || 100| [Same Tree](https://leetcode.com/problems/same-tree/) |[C+](./C++/same-tree.cpp) [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/)| [C++](./C++/maximum-depth-of-binary-tree.cpp) [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/) | [C++](./C++/construct-binary-tree-from-preorder-and-inorder-traversal.cpp) [Python](./Python/construct-binary-tree-from-preorder-and-inorder-traversal.py) | _O(n)_ | _O(n)_ | Medium || @@ -499,13 +499,13 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Binary Search | # | 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/) | [C++](./C++/search-in-rotated-sorted-array.cpp) [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/) | [C++](./C++/search-for-a-range.cpp) [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || -35| [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [C++](./C++/search-insert-position.cpp) [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || -69| [Sqrt(x)](https://leetcode.com/problems/sqrtx/) | [C++](./C++/sqrtx.cpp) [Python](./Python/sqrtx.py) | _O(logn)_ | _O(1)_ | Medium || -74| [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | [C++](./C++/search-a-2d-matrix.cpp) [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/) | [C++](./C++/search-in-rotated-sorted-array-ii.cpp) [Python](./Python/search-in-rotated-sorted-array-ii.py) | _O(logn)_ | _O(1)_ | Medium || +004| [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 || +033| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [C++](./C++/search-in-rotated-sorted-array.cpp) [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Hard || +034| [Search for a Range](https://leetcode.com/problems/search-for-a-range/) | [C++](./C++/search-for-a-range.cpp) [Python](./Python/search-for-a-range.py) | _O(logn)_ | _O(1)_ | Medium || +305| [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [C++](./C++/search-insert-position.cpp) [Python](./Python/search-insert-position.py) | _O(logn)_ | _O(1)_ | Medium || +069| [Sqrt(x)](https://leetcode.com/problems/sqrtx/) | [C++](./C++/sqrtx.cpp) [Python](./Python/sqrtx.py) | _O(logn)_ | _O(1)_ | Medium || +074| [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | [C++](./C++/search-a-2d-matrix.cpp) [Python](./Python/search-a-2d-matrix.py) | _O(logm + logn)_ | _O(1)_ | Medium || +081| [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) | [C++](./C++/search-in-rotated-sorted-array-ii.cpp) [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/) | [C++](./C++/find-minimum-in-rotated-sorted-array.cpp) [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/) | [C++](./C++/find-minimum-in-rotated-sorted-array-ii.cpp) [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/) | [C++](./C++/find-peak-element.cpp) [Python](./Python/find-peak-element.py) | _O(logn)_ | _O(1)_ | Medium || @@ -602,20 +602,20 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Backtracking | # | 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 || -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)_ | 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 || -78| [Subsets](https://leetcode.com/problems/subsets/) | [C++](./C++/subsets.cpp) [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || -90| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [C++](./C++/subsets-ii.cpp) [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +017| [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 || +022| [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](./Python/generate-parentheses.py)| _O(4^n / n^(3/2))_ | _O(n)_ | Medium || +037| [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | [Python](./Python/sudoku-solver.py) | _O((9!)^9)_ | _O(1)_ | Hard || +039| [Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](./Python/combination-sum.py) | _O(k * n^k)_ | _O(k)_ | Medium || +040| [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)| [Python](./Python/combination-sum-ii.py)| _O(k * C(n, k))_| _O(k)_ | Medium || +046| [Permutations](https://leetcode.com/problems/permutations/)| [Python](./Python/permutations.py) | _O(n * n!)_ | _O(n)_ | Medium || +047| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | Medium || +051| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || +052| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || +077| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || +079| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || +093| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(1)_ | _O(1)_ | Medium || +078| [Subsets](https://leetcode.com/problems/subsets/) | [C++](./C++/subsets.cpp) [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || +090| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [C++](./C++/subsets-ii.cpp) [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/) | [C++](./C++/word-break-ii.cpp) [Python](./Python/word-break-ii.py) | _O(n * l^2 + n * r)_ | _O(n^2)_ | Hard || @@ -635,17 +635,17 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Dynamic Programming | # | 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 || -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 || -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/) | [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 || +010| [Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) | [Python](./Python/regular-expression-matching.py) | _O(m * n)_ | _O(n)_ | Hard || +053| [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)|[Python](./Python/maximum-subarray.py)| _O(n)_ | _O(1)_ | Medium || +062| [Unique Paths](https://leetcode.com/problems/unique-paths/) | [Python](./Python/unique-paths.py)| _O(m * n)_ | _O(m + n)_ | Medium || +063| [Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) | [Python](./Python/unique-paths-ii.py) | _O(m * n)_ | _O(m + n)_ | Medium || +064| [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/)| [Python](./Python/minimum-path-sum.py)| _O(m * n)_ | _O(m + n)_ | Medium || +070| [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)| [Python](./Python/climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || +072| [Edit Distance](https://leetcode.com/problems/edit-distance/)|[Python](./Python/edit-distance.py)| _O(m * n)_ | _O(m + n)_ | Hard || +087| [Scramble String](https://leetcode.com/problems/scramble-string/) | [Python](./Python/scramble-string.py) | _O(n^4)_ | _O(n^3)_ | Hard || +091| [Decode Ways](https://leetcode.com/problems/decode-ways/) | [C++](./Python/decode-ways.cpp) [Python](./Python/decode-ways.py)| _O(n)_ | _O(1)_ | Medium || +096| [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 +097| [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 || @@ -711,11 +711,11 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| -11| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [C++](./C++/container-with-most-water.cpp) [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || -42| [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [C++](./C++/trapping-rain-water.cpp) [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 || +011| [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)| [C++](./C++/container-with-most-water.cpp) [Python](./Python/container-with-most-water.py) | _O(n)_ | _O(1)_ | Medium || +042| [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [C++](./C++/trapping-rain-water.cpp) [Python](./Python/trapping-rain-water.py) | _O(n)_ | _O(1)_ | Hard || Tricky +044| [Wildcard Matching](https://leetcode.com/problems/wildcard-matching/) | [Python](./Python/wildcard-matching.py) | _O(m + n)_ | _O(1)_ | Hard || Tricky +045| [Jump Game II](https://leetcode.com/problems/jump-game-ii/) | [Python](./Python/jump-game-ii.py) | _O(n)_ | _O(1)_ | Hard || +055| [Jump Game](https://leetcode.com/problems/jump-game/) | [Python](./Python/jump-game.py) | _O(n)_ | _O(1)_ | Medium || 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/)| [C++](./C++/candy.cpp) [Python](./Python/candy.py) | _O(n)_ | _O(n)_ | Hard || From 71afc1974cfd40b3e291474c2579ebcb88fcfa7c Mon Sep 17 00:00:00 2001 From: jxie0755 <30805062+jxie0755@users.noreply.github.com> Date: Wed, 24 Jan 2018 14:29:16 -0500 Subject: [PATCH 4357/4971] Update palindrome-number.py --- Python/palindrome-number.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/palindrome-number.py b/Python/palindrome-number.py index ab1a797c6..f7745350e 100644 --- a/Python/palindrome-number.py +++ b/Python/palindrome-number.py @@ -24,11 +24,11 @@ def isPalindrome(self, x): while copy: reverse *= 10 reverse += copy % 10 - copy /= 10 + copy //= 10 return x == reverse if __name__ == "__main__": print Solution().isPalindrome(12321) print Solution().isPalindrome(12320) - print Solution().isPalindrome(-12321) \ No newline at end of file + print Solution().isPalindrome(-12321) From a19b432d6d2af6254c1c49a061d5f73a96617544 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 26 Jan 2018 22:26:58 +0800 Subject: [PATCH 4358/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 063dca3e9..2436e3282 100644 --- a/README.md +++ b/README.md @@ -538,6 +538,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 352 | [Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/) | [C++](./C++/data-stream-as-disjoint-intervals.cpp) [Python](./Python/data-stream-as-disjoint-intervals.py) | _O(logn)_ | _O(n)_ | Hard | | 449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/)| [C++](./C++/serialize-and-deserialize-bst.cpp) [Python](./Python/serialize-and-deserialize-bst.py)| _O(n)_ | _O(h)_ | Medium | | | 450|[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/)| [C++](./C++/delete-node-in-a-bst.cpp) [Python](./Python/delete-node-in-a-bst.py)| _O(h)_ | _O(h)_ | Medium | | | +530|[Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)| [C++](./C++/minimum-absolute-difference-in-bst.cpp) [Python](./Python/minimum-absolute-difference-in-bst.py)| _O(n)_ | _O(h)_ | Easy | | | ## Breadth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 241df5d08407cd1162f2a1e46c61c2b133605f8c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 27 Jan 2018 23:59:31 +0800 Subject: [PATCH 4359/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2436e3282..3bfed3c83 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,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 | +530 | [Minesweeper](https://leetcode.com/problems/minesweeper/) | [C++](./C++/minesweeper.cpp) [Python](./Python/minesweeper.py) | _O(m * n)_ | _O(m + n)_ | Medium || 536 | [Construct Binary Tree from String](https://leetcode.com/problems/construct-binary-tree-from-string/) | [C++](./C++/construct-binary-tree-from-string.cpp) [Python](./Python/construct-binary-tree-from-string.py) | _O(n)_ | _O(h)_ | Medium | 📖 | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [C++](./C++/convert-bst-to-greater-tree.cpp) [Python](./Python/convert-bst-to-greater-tree.py) | _O(n)_ | _O(h)_ | Easy || 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [C++](./C++/diameter-of-binary-tree.cpp) [Python](./Python/diameter-of-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || From bbf715a62b4a249d244b7fe8375faf7abd99b01b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 00:00:04 +0800 Subject: [PATCH 4360/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3bfed3c83..60a1f7598 100644 --- a/README.md +++ b/README.md @@ -286,7 +286,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 | -530 | [Minesweeper](https://leetcode.com/problems/minesweeper/) | [C++](./C++/minesweeper.cpp) [Python](./Python/minesweeper.py) | _O(m * n)_ | _O(m + n)_ | Medium || +529 | [Minesweeper](https://leetcode.com/problems/minesweeper/) | [C++](./C++/minesweeper.cpp) [Python](./Python/minesweeper.py) | _O(m * n)_ | _O(m + n)_ | Medium || 536 | [Construct Binary Tree from String](https://leetcode.com/problems/construct-binary-tree-from-string/) | [C++](./C++/construct-binary-tree-from-string.cpp) [Python](./Python/construct-binary-tree-from-string.py) | _O(n)_ | _O(h)_ | Medium | 📖 | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [C++](./C++/convert-bst-to-greater-tree.cpp) [Python](./Python/convert-bst-to-greater-tree.py) | _O(n)_ | _O(h)_ | Easy || 543 | [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) | [C++](./C++/diameter-of-binary-tree.cpp) [Python](./Python/diameter-of-binary-tree.py) | _O(n)_ | _O(h)_ | Easy || From bce19808d39d99191205a27888650fee9291648a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 19:30:07 +0800 Subject: [PATCH 4361/4971] Create jewels-and-stones.cpp --- C++/jewels-and-stones.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/jewels-and-stones.cpp diff --git a/C++/jewels-and-stones.cpp b/C++/jewels-and-stones.cpp new file mode 100644 index 000000000..7b6c21e6d --- /dev/null +++ b/C++/jewels-and-stones.cpp @@ -0,0 +1,17 @@ +// Time: O(m + n) +// Space: O(n) + +class Solution { +public: + int numJewelsInStones(string J, string S) { + unordered_set lookup; + for (const auto& j : J) { + lookup.emplace(j); + } + int result = 0; + for (const auto& s : S) { + result += lookup.count(s); + } + return result; + } +}; From e3019f021b982f1ea19f69bda829ba7a80beaac5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 19:31:02 +0800 Subject: [PATCH 4362/4971] Create jewels-and-stones.py --- Python/jewels-and-stones.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Python/jewels-and-stones.py diff --git a/Python/jewels-and-stones.py b/Python/jewels-and-stones.py new file mode 100644 index 000000000..f55beaa3b --- /dev/null +++ b/Python/jewels-and-stones.py @@ -0,0 +1,13 @@ +# Time: O(m + n) +# Space: O(n) + +class Solution(object): + def numJewelsInStones(self, J, S): + """ + :type J: str + :type S: str + :rtype: int + """ + lookup = set(J) + return sum(s in lookup for s in S) + From 8144f2943aa979448987ec66d1fa48ef19c00380 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 19:55:37 +0800 Subject: [PATCH 4363/4971] Create global-and-local-inversions.cpp --- C++/global-and-local-inversions.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 C++/global-and-local-inversions.cpp diff --git a/C++/global-and-local-inversions.cpp b/C++/global-and-local-inversions.cpp new file mode 100644 index 000000000..560d49fd8 --- /dev/null +++ b/C++/global-and-local-inversions.cpp @@ -0,0 +1,14 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool isIdealPermutation(vector& A) { + for (int i = 0; i < A.size(); ++i) { + if (abs(A[i] - i) > 1) { + return false; + } + } + return true; + } +}; From 0828e34425e43a24483264b0f4eb62bc5bcd4fed Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 19:56:26 +0800 Subject: [PATCH 4364/4971] Create global-and-local-inversions.py --- Python/global-and-local-inversions.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Python/global-and-local-inversions.py diff --git a/Python/global-and-local-inversions.py b/Python/global-and-local-inversions.py new file mode 100644 index 000000000..32a96dd62 --- /dev/null +++ b/Python/global-and-local-inversions.py @@ -0,0 +1,11 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def isIdealPermutation(self, A): + """ + :type A: List[int] + :rtype: bool + """ + return all(abs(v-i) <= 1 for i,v in enumerate(A)) + From ab9134901390de53f5dc3a965a7f67959c90b645 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 20:36:15 +0800 Subject: [PATCH 4365/4971] Create minimize-max-distance-to-gas-station.cpp --- C++/minimize-max-distance-to-gas-station.cpp | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/minimize-max-distance-to-gas-station.cpp diff --git a/C++/minimize-max-distance-to-gas-station.cpp b/C++/minimize-max-distance-to-gas-station.cpp new file mode 100644 index 000000000..50998593a --- /dev/null +++ b/C++/minimize-max-distance-to-gas-station.cpp @@ -0,0 +1,28 @@ +// Time: O(nlogr) +// Space: O(1) + +class Solution { +public: + double minmaxGasDist(vector& stations, int K) { + double left = 0.0; + double right = 1e8; + while (right - left > 1e-6) { + const auto mid = left + (right - left) / 2.0; + if (possible(stations, K, mid)) { + right = mid; + } else { + left = mid; + } + } + return left; + } + +private: + bool possible(const vector& stations, int K, double guess) { + int sum = 0; + for (int i = 0; i + 1 < stations.size(); ++i) { + sum += int((stations[i + 1] - stations[i]) / guess); + } + return sum <= K; + } +}; From 4060d8158e73819fee03ef2e066e9ceab5ca389b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 20:37:01 +0800 Subject: [PATCH 4366/4971] Create minimize-max-distance-to-gas-station.py --- .../minimize-max-distance-to-gas-station.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Python/minimize-max-distance-to-gas-station.py diff --git a/Python/minimize-max-distance-to-gas-station.py b/Python/minimize-max-distance-to-gas-station.py new file mode 100644 index 000000000..b90a9e4c4 --- /dev/null +++ b/Python/minimize-max-distance-to-gas-station.py @@ -0,0 +1,22 @@ +# Time: O(nlogr) +# Space: O(1) + +class Solution(object): + def minmaxGasDist(self, stations, K): + """ + :type stations: List[int] + :type K: int + :rtype: float + """ + def possible(stations, K, guess): + return sum(int((stations[i+1]-stations[i]) / guess) + for i in xrange(len(stations)-1)) <= K + + left, right = 0, 10**8 + while right-left > 1e-6: + mid = left + (right-left)/2.0 + if possible(mid): + right = mid + else: + left = mid + return left From 255d95691c7febe5c5bc7d203fbc98c60afe417c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 23:13:33 +0800 Subject: [PATCH 4367/4971] Create sliding-puzzle.cpp --- C++/sliding-puzzle.cpp | 91 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 C++/sliding-puzzle.cpp diff --git a/C++/sliding-puzzle.cpp b/C++/sliding-puzzle.cpp new file mode 100644 index 000000000..d6f81f9c0 --- /dev/null +++ b/C++/sliding-puzzle.cpp @@ -0,0 +1,91 @@ +// Time: O((m * n) * (m * n)!) +// Space: O((m * n) * (m * n)!) + +class Solution { +public: + int slidingPuzzle(vector>& board) { + const auto& R = board.size(), C = board[0].size(); + vector begin, end; + unordered_map> expected; + int zero_idx = 0; + for (int i = 0; i < R; ++i) { + for (int j = 0; j < C; ++j) { + auto val = (C * i + j + 1) % (R * C); + expected[val] = {i, j}; + if (board[i][j] == 0) { + zero_idx = begin.size(); + } + begin.emplace_back(board[i][j]); + end.emplace_back(val); + } + } + vector end_wrong(end); + swap(end_wrong[end_wrong.size() - 2], end_wrong[end_wrong.size() - 3]); + + using P = tuple>; + priority_queue, greater

> min_heap; + min_heap.emplace(make_tuple(0, 0, zero_idx, begin)); + unordered_map, int, Hash>> lookup; + lookup[begin] = 0; + while (!min_heap.empty()) { + int f, g, zero; + vector board; + tie(f, g, zero, board) = min_heap.top(); min_heap.pop(); + if (board == end) { + return g; + } + if (board == end_wrong) { + return -1; + } + if (f > lookup[board]) { + continue; + } + int r = zero / C; + int c = zero % C; + static const vector> directions{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + for (const auto& direction : directions) { + int i = r + direction.first; + int j = c + direction.second; + if (0 <= i && i < R && 0 <= j && j < C) { + auto new_zero = C * i + j; + auto new_board = board; + swap(new_board[zero], new_board[new_zero]); + f = g + 1 + heuristic_estimate(new_board, R, C, expected); + if (!lookup.count(new_board) || f < lookup[new_board]) { + lookup[new_board] = f; + min_heap.emplace(make_tuple(f, g + 1, new_zero, new_board)); + } + } + } + } + return -1; + } + +private: + int heuristic_estimate(const vector& board, int R, int C, const unordered_map>& expected) { + int result = 0; + for (int i = 0; i < R; ++i) { + for (int j = 0; j < C; ++j) { + const auto& val = board[C * i + j]; + if (val == 0) { + continue; + } + int r, c; + tie(r, c) = expected.at(val); + result += abs(r - i) + abs(c - j); + } + } + return result; + } + + template + struct Hash { + size_t operator()(const ContType& v) const { + size_t seed = 0; + for (const auto& i : v) { + seed ^= std::hash{}(i) + 0x9e3779b9 + (seed<<6) + (seed>>2); + } + return seed; + } + }; +}; From e47aeea4415183f62d9b76014ad37bb78c7d2dc5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 23:14:17 +0800 Subject: [PATCH 4368/4971] Create sliding-puzzle.py --- Python/sliding-puzzle.py | 47 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/sliding-puzzle.py diff --git a/Python/sliding-puzzle.py b/Python/sliding-puzzle.py new file mode 100644 index 000000000..54010ef48 --- /dev/null +++ b/Python/sliding-puzzle.py @@ -0,0 +1,47 @@ +# Time: O((m * n) * (m * n)!) +# Space: O((m * n) * (m * n)!) + +class Solution(object): + def slidingPuzzle(self, board): + """ + :type board: List[List[int]] + :rtype: int + """ + def heuristic_estimate(board, R, C, expected): + result = 0 + for i in xrange(R): + for j in xrange(C): + val = board[C*i + j] + if val == 0: continue + r, c = expected[val] + result += abs(r-i) + abs(c-j) + return result + + R, C = len(board), len(board[0]) + begin = tuple(itertools.chain(*board)) + end = tuple(range(1, R*C) + [0]) + end_wrong = tuple(range(1, R*C-2) + [R*C-1, R*C-2, 0]) + expected = {(C*i+j+1) % (R*C) : (i, j) + for i in xrange(R) for j in xrange(C)} + + min_heap = [(0, 0, begin.index(0), begin)] + lookup = {begin: 0} + while min_heap: + f, g, zero, board = heapq.heappop(min_heap) + if board == end: return g + if board == end_wrong: return -1 + if f > lookup[board]: continue + + r, c = divmod(zero, C) + for direction in ((-1, 0), (1, 0), (0, -1), (0, 1)): + i, j = r+direction[0], c+direction[1] + if 0 <= i < R and 0 <= j < C: + new_zero = C*i+j + tmp = list(board) + tmp[zero], tmp[new_zero] = tmp[new_zero], tmp[zero] + new_board = tuple(tmp) + f = g+1+heuristic_estimate(new_board, R, C, expected) + if f < lookup.get(new_board, float('inf')): + lookup[new_board] = f + heapq.heappush(min_heap, (f, g+1, new_zero, new_board)) + return -1 From 17fd79e76a7e45e9c691cebe44edaadd20a1afee Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 23:15:10 +0800 Subject: [PATCH 4369/4971] Update sliding-puzzle.cpp --- C++/sliding-puzzle.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/C++/sliding-puzzle.cpp b/C++/sliding-puzzle.cpp index d6f81f9c0..e84727020 100644 --- a/C++/sliding-puzzle.cpp +++ b/C++/sliding-puzzle.cpp @@ -1,6 +1,7 @@ // Time: O((m * n) * (m * n)!) // Space: O((m * n) * (m * n)!) +// A* Search Algorithm class Solution { public: int slidingPuzzle(vector>& board) { From 6c1dd1ae58687aecd5fbdc3dacaf27fab89f55c5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 23:15:31 +0800 Subject: [PATCH 4370/4971] Update sliding-puzzle.py --- Python/sliding-puzzle.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/sliding-puzzle.py b/Python/sliding-puzzle.py index 54010ef48..ae8b8e322 100644 --- a/Python/sliding-puzzle.py +++ b/Python/sliding-puzzle.py @@ -1,6 +1,7 @@ # Time: O((m * n) * (m * n)!) # Space: O((m * n) * (m * n)!) +# A* Search Algorithm class Solution(object): def slidingPuzzle(self, board): """ From a6644f8d386ae6b58e7f20524c37214dc70352e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 23:25:54 +0800 Subject: [PATCH 4371/4971] Update sliding-puzzle.cpp --- C++/sliding-puzzle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/sliding-puzzle.cpp b/C++/sliding-puzzle.cpp index e84727020..6c9a4f834 100644 --- a/C++/sliding-puzzle.cpp +++ b/C++/sliding-puzzle.cpp @@ -52,7 +52,7 @@ class Solution { auto new_board = board; swap(new_board[zero], new_board[new_zero]); f = g + 1 + heuristic_estimate(new_board, R, C, expected); - if (!lookup.count(new_board) || f < lookup[new_board]) { + if (!lookup.count(new_board)) { lookup[new_board] = f; min_heap.emplace(make_tuple(f, g + 1, new_zero, new_board)); } From 332cb2f0ed4b97e213d9f4d9399e4d2568f96c23 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 23:26:57 +0800 Subject: [PATCH 4372/4971] Update sliding-puzzle.py --- Python/sliding-puzzle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/sliding-puzzle.py b/Python/sliding-puzzle.py index ae8b8e322..bcfbc4ad5 100644 --- a/Python/sliding-puzzle.py +++ b/Python/sliding-puzzle.py @@ -42,7 +42,7 @@ def heuristic_estimate(board, R, C, expected): tmp[zero], tmp[new_zero] = tmp[new_zero], tmp[zero] new_board = tuple(tmp) f = g+1+heuristic_estimate(new_board, R, C, expected) - if f < lookup.get(new_board, float('inf')): + if new_board not in lookup: lookup[new_board] = f heapq.heappush(min_heap, (f, g+1, new_zero, new_board)) return -1 From 8b6b8e250288502200d01e2d1bc1cf4a3319ed24 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 23:46:49 +0800 Subject: [PATCH 4373/4971] Update sliding-puzzle.py --- Python/sliding-puzzle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/sliding-puzzle.py b/Python/sliding-puzzle.py index bcfbc4ad5..f9b55787b 100644 --- a/Python/sliding-puzzle.py +++ b/Python/sliding-puzzle.py @@ -42,7 +42,7 @@ def heuristic_estimate(board, R, C, expected): tmp[zero], tmp[new_zero] = tmp[new_zero], tmp[zero] new_board = tuple(tmp) f = g+1+heuristic_estimate(new_board, R, C, expected) - if new_board not in lookup: + if f < lookup.get(new_board, float("inf")): lookup[new_board] = f heapq.heappush(min_heap, (f, g+1, new_zero, new_board)) return -1 From c80c91e37218005ab71bd6ac0f01f864210a187b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 28 Jan 2018 23:57:02 +0800 Subject: [PATCH 4374/4971] Update sliding-puzzle.cpp --- C++/sliding-puzzle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/sliding-puzzle.cpp b/C++/sliding-puzzle.cpp index 6c9a4f834..9b2496130 100644 --- a/C++/sliding-puzzle.cpp +++ b/C++/sliding-puzzle.cpp @@ -52,7 +52,7 @@ class Solution { auto new_board = board; swap(new_board[zero], new_board[new_zero]); f = g + 1 + heuristic_estimate(new_board, R, C, expected); - if (!lookup.count(new_board)) { + if (!lookup.count(new_board) || f < lookup[new_board]) lookup[new_board] = f; min_heap.emplace(make_tuple(f, g + 1, new_zero, new_board)); } From 06a269fbea8533f7771454710ce2fbaf4a91a8fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jan 2018 00:02:16 +0800 Subject: [PATCH 4375/4971] Update sliding-puzzle.cpp --- C++/sliding-puzzle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/sliding-puzzle.cpp b/C++/sliding-puzzle.cpp index 9b2496130..591e574d0 100644 --- a/C++/sliding-puzzle.cpp +++ b/C++/sliding-puzzle.cpp @@ -1,4 +1,4 @@ -// Time: O((m * n) * (m * n)!) +// Time: O((m * n) * (m * n)! * log((m * n)!)) // Space: O((m * n) * (m * n)!) // A* Search Algorithm From 28ac1c6a233ad725ae71b57d98b53fad4a5b3d84 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jan 2018 00:02:44 +0800 Subject: [PATCH 4376/4971] Update sliding-puzzle.py --- Python/sliding-puzzle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/sliding-puzzle.py b/Python/sliding-puzzle.py index f9b55787b..83f446cc2 100644 --- a/Python/sliding-puzzle.py +++ b/Python/sliding-puzzle.py @@ -1,4 +1,4 @@ -# Time: O((m * n) * (m * n)!) +# Time: O((m * n) * (m * n)! * log((m * n)!)) # Space: O((m * n) * (m * n)!) # A* Search Algorithm From 610915acda146b7a241403b38f2a85cd579ae7d9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jan 2018 01:34:21 +0800 Subject: [PATCH 4377/4971] Update sliding-puzzle.py --- Python/sliding-puzzle.py | 60 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/Python/sliding-puzzle.py b/Python/sliding-puzzle.py index 83f446cc2..1beaf1b61 100644 --- a/Python/sliding-puzzle.py +++ b/Python/sliding-puzzle.py @@ -1,8 +1,66 @@ -# Time: O((m * n) * (m * n)! * log((m * n)!)) +# Time: O((m * n) * (m * n)!) # Space: O((m * n) * (m * n)!) # A* Search Algorithm class Solution(object): + def slidingPuzzle(self, board): + """ + :type board: List[List[int]] + :rtype: int + """ + def dot(p1, p2): + return p1[0]*p2[0]+p1[1]*p2[1] + + def heuristic_estimate(board, R, C, expected): + result = 0 + for i in xrange(R): + for j in xrange(C): + val = board[C*i + j] + if val == 0: continue + r, c = expected[val] + result += abs(r-i) + abs(c-j) + return result + + R, C = len(board), len(board[0]) + begin = tuple(itertools.chain(*board)) + end = tuple(range(1, R*C) + [0]) + expected = {(C*i+j+1) % (R*C) : (i, j) + for i in xrange(R) for j in xrange(C)} + + min_steps = heuristic_estimate(begin, R, C, expected) + closer, detour = [(begin.index(0), begin)], [] + lookup = set() + while True: + if not closer: + if not detour: + return -1 + min_steps += 2 + closer, detour = detour, closer + zero, board = closer.pop() + if board == end: + return min_steps + if board not in lookup: + lookup.add(board) + r, c = divmod(zero, C) + for direction in ((-1, 0), (1, 0), (0, -1), (0, 1)): + i, j = r+direction[0], c+direction[1] + if 0 <= i < R and 0 <= j < C: + new_zero = i*C+j + tmp = list(board) + tmp[zero], tmp[new_zero] = tmp[new_zero], tmp[zero] + new_board = tuple(tmp) + r2, c2 = expected[board[new_zero]] + r1, c1 = divmod(zero, C) + r0, c0 = divmod(new_zero, C) + is_closer = dot((r1-r0, c1-c0), (r2-r0, c2-c0)) > 0 + (closer if is_closer else detour).append((new_zero, new_board)) + return min_steps + + +# Time: O((m * n) * (m * n)! * log((m * n)!)) +# Space: O((m * n) * (m * n)!) +# A* Search Algorithm +class Solution2(object): def slidingPuzzle(self, board): """ :type board: List[List[int]] From 3b6c7aff6d2e3f4e58abd6c44f7552ce4fabb325 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jan 2018 01:48:21 +0800 Subject: [PATCH 4378/4971] Update sliding-puzzle.cpp --- C++/sliding-puzzle.cpp | 102 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 101 insertions(+), 1 deletion(-) diff --git a/C++/sliding-puzzle.cpp b/C++/sliding-puzzle.cpp index 591e574d0..0330880f9 100644 --- a/C++/sliding-puzzle.cpp +++ b/C++/sliding-puzzle.cpp @@ -1,8 +1,108 @@ -// Time: O((m * n) * (m * n)! * log((m * n)!)) +// Time: O((m * n) * (m * n)!) // Space: O((m * n) * (m * n)!) // A* Search Algorithm class Solution { +public: + int slidingPuzzle(vector>& board) { + const auto& R = board.size(), C = board[0].size(); + vector begin, end; + unordered_map> expected; + int zero_idx = 0; + for (int i = 0; i < R; ++i) { + for (int j = 0; j < C; ++j) { + auto val = (C * i + j + 1) % (R * C); + expected[val] = {i, j}; + if (board[i][j] == 0) { + zero_idx = begin.size(); + } + begin.emplace_back(board[i][j]); + end.emplace_back(val); + } + } + + int min_steps = heuristic_estimate(begin, R, C, expected); + unordered_set, Hash>> lookup; + vector>> closer{make_pair(zero_idx, begin)}, detour; + while (true) { + if (closer.empty()) { + if (detour.empty()) { + return -1; + } + min_steps += 2; + swap(closer, detour); + } + int zero; + vector board; + tie(zero, board) = closer.back(); closer.pop_back(); + if (board == end) { + return min_steps; + } + if (!lookup.count(board)) { + lookup.emplace(board); + int r = zero / C; + int c = zero % C; + static const vector> directions{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + for (const auto& direction : directions) { + int i = r + direction.first; + int j = c + direction.second; + if (0 <= i && i < R && 0 <= j && j < C) { + auto new_zero = C * i + j; + auto new_board = board; + swap(new_board[zero], new_board[new_zero]); + int r2, c2; + tie(r2, c2) = expected[board[new_zero]]; + int r1 = zero / C; + int c1 = zero % C; + int r0 = new_zero / C; + int c0 = new_zero % C; + bool is_closer = dot({r1 - r0, c1 - c0}, {r2 - r0, c2 - c0}) > 0; + is_closer ? closer.emplace_back(new_zero, new_board) : detour.emplace_back(new_zero, new_board); + } + } + } + } + + return min_steps; + } + +private: + int heuristic_estimate(const vector& board, int R, int C, const unordered_map>& expected) { + int result = 0; + for (int i = 0; i < R; ++i) { + for (int j = 0; j < C; ++j) { + const auto& val = board[C * i + j]; + if (val == 0) { + continue; + } + int r, c; + tie(r, c) = expected.at(val); + result += abs(r - i) + abs(c - j); + } + } + return result; + } + + inline int dot(const pair& a, const pair& b) { + return a.first * b.first + a.second * b.second; + } + + template + struct Hash { + size_t operator()(const ContType& v) const { + size_t seed = 0; + for (const auto& i : v) { + seed ^= std::hash{}(i) + 0x9e3779b9 + (seed<<6) + (seed>>2); + } + return seed; + } + }; +}; + +// Time: O((m * n) * (m * n)! * log((m * n)!)) +// Space: O((m * n) * (m * n)!) +// A* Search Algorithm +class Solution2 { public: int slidingPuzzle(vector>& board) { const auto& R = board.size(), C = board[0].size(); From f57b00ad6d5d5671cf7f0eaf2f9ee741326abac8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 29 Jan 2018 01:54:58 +0800 Subject: [PATCH 4379/4971] Update sliding-puzzle.cpp --- C++/sliding-puzzle.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/sliding-puzzle.cpp b/C++/sliding-puzzle.cpp index 0330880f9..e445c5ca8 100644 --- a/C++/sliding-puzzle.cpp +++ b/C++/sliding-puzzle.cpp @@ -5,7 +5,7 @@ class Solution { public: int slidingPuzzle(vector>& board) { - const auto& R = board.size(), C = board[0].size(); + const auto& R = board.size(), &C = board[0].size(); vector begin, end; unordered_map> expected; int zero_idx = 0; @@ -105,7 +105,7 @@ class Solution { class Solution2 { public: int slidingPuzzle(vector>& board) { - const auto& R = board.size(), C = board[0].size(); + const auto& R = board.size(), &C = board[0].size(); vector begin, end; unordered_map> expected; int zero_idx = 0; From 76ca976a8658c20151d5177b341b5b00aa8cd50e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 30 Jan 2018 00:01:35 +0800 Subject: [PATCH 4380/4971] Update jewels-and-stones.py --- Python/jewels-and-stones.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Python/jewels-and-stones.py b/Python/jewels-and-stones.py index f55beaa3b..18fbbd812 100644 --- a/Python/jewels-and-stones.py +++ b/Python/jewels-and-stones.py @@ -1,6 +1,26 @@ # Time: O(m + n) # Space: O(n) +# You're given strings J representing the types of stones that are jewels, +# and S representing the stones you have. +# Each character in S is a type of stone you have. +# You want to know how many of the stones you have are also jewels. +# +# The letters in J are guaranteed distinct, and all characters in J and S are letters. +# Letters are case sensitive, so "a" is considered a different type of stone from "A". +# +# Example 1: +# Input: J = "aA", S = "aAAbbbb" +# Output: 3 +# Example 2: +# +# Input: J = "z", S = "ZZ" +# Output: 0 +# +# Note: +# - S and J will consist of letters and have length at most 50. +# - The characters in J are distinct. + class Solution(object): def numJewelsInStones(self, J, S): """ From 05a0d024aca235dd9ecaff67029b0750acd44bc2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 30 Jan 2018 00:03:44 +0800 Subject: [PATCH 4381/4971] Update sliding-puzzle.py --- Python/sliding-puzzle.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/Python/sliding-puzzle.py b/Python/sliding-puzzle.py index 1beaf1b61..25ba2b692 100644 --- a/Python/sliding-puzzle.py +++ b/Python/sliding-puzzle.py @@ -1,6 +1,42 @@ # Time: O((m * n) * (m * n)!) # Space: O((m * n) * (m * n)!) +# On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, +# and an empty square represented by 0. +# +# A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. +# +# The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. +# +# Given a puzzle board, return the least number of moves required +# so that the state of the board is solved. If it is impossible +# for the state of the board to be solved, return -1. +# +# Examples: +# +# Input: board = [[1,2,3],[4,0,5]] +# Output: 1 +# Explanation: Swap the 0 and the 5 in one move. +# Input: board = [[1,2,3],[5,4,0]] +# Output: -1 +# Explanation: No number of moves will make the board solved. +# Input: board = [[4,1,2],[5,0,3]] +# Output: 5 +# Explanation: 5 is the smallest number of moves that solves the board. +# An example path: +# After move 0: [[4,1,2],[5,0,3]] +# After move 1: [[4,1,2],[0,5,3]] +# After move 2: [[0,1,2],[4,5,3]] +# After move 3: [[1,0,2],[4,5,3]] +# After move 4: [[1,2,0],[4,5,3]] +# After move 5: [[1,2,3],[4,5,0]] +# Input: board = [[3,2,4],[1,5,0]] +# Output: 14 +# +# Note: +# - board will be a 2 x 3 array as described above. +# - board[i][j] will be a permutation of [0, 1, 2, 3, 4, 5]. + # A* Search Algorithm class Solution(object): def slidingPuzzle(self, board): From 7610c24546f4048d2be4f22a508d32cbe139eee5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 30 Jan 2018 00:05:02 +0800 Subject: [PATCH 4382/4971] Update minimize-max-distance-to-gas-station.py --- .../minimize-max-distance-to-gas-station.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Python/minimize-max-distance-to-gas-station.py b/Python/minimize-max-distance-to-gas-station.py index b90a9e4c4..4b56a68e8 100644 --- a/Python/minimize-max-distance-to-gas-station.py +++ b/Python/minimize-max-distance-to-gas-station.py @@ -1,6 +1,25 @@ # Time: O(nlogr) # Space: O(1) +# On a horizontal number line, we have gas stations at positions +# stations[0], stations[1], ..., stations[N-1], where N = stations.length. +# +# Now, we add K more gas stations so that D, +# the maximum distance between adjacent gas stations, is minimized. +# +# Return the smallest possible value of D. +# +# Example: +# +# Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9 +# Output: 0.500000 +# +# Note: +# - stations.length will be an integer in range [10, 2000]. +# - stations[i] will be an integer in range [0, 10^8]. +# - K will be an integer in range [1, 10^6]. +# - Answers within 10^-6 of the true value will be accepted as correct. + class Solution(object): def minmaxGasDist(self, stations, K): """ From d0cde2c8b12b68230e6391002eda14efb8ed420a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 30 Jan 2018 00:06:20 +0800 Subject: [PATCH 4383/4971] Update global-and-local-inversions.py --- Python/global-and-local-inversions.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Python/global-and-local-inversions.py b/Python/global-and-local-inversions.py index 32a96dd62..901d9616e 100644 --- a/Python/global-and-local-inversions.py +++ b/Python/global-and-local-inversions.py @@ -1,6 +1,27 @@ # Time: O(n) # Space: O(1) +# We have some permutation A of [0, 1, ..., N - 1], where N is the length of A. +# The number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j]. +# The number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1]. +# Return true if and only if the number of global inversions is equal to the number of local inversions. +# +# Example 1: +# +# Input: A = [1,0,2] +# Output: true +# Explanation: There is 1 global inversion, and 1 local inversion. +# Example 2: +# +# Input: A = [1,2,0] +# Output: false +# Explanation: There are 2 global inversions, and 1 local inversion. +# +# Note: +# - A will be a permutation of [0, 1, ..., A.length - 1]. +# - A will have length in range [1, 5000]. +# - The time limit for this problem has been reduced. + class Solution(object): def isIdealPermutation(self, A): """ From 20f8b9332507b44f3448a5e917bdef91d61b5027 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 30 Jan 2018 23:09:49 +0800 Subject: [PATCH 4384/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 60a1f7598..b4867bcbf 100644 --- a/README.md +++ b/README.md @@ -363,6 +363,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 737| [Sentence Similarity II](https://leetcode.com/problems/sentence-similarity-ii/) | [C++](./C++/sentence-similarity-ii.cpp) [Python](./Python/sentence-similarity-ii.py) | _O(n + p)_ | _O(p)_| Medium || Union Find 748 | [Shortest Completing Word](https://leetcode.com/problems/shortest-completing-word/) | [C++](./C++/shortest-completing-word.cpp) [Python](./Python/shortest-completing-word.py) | _O(n)_ | _O(1)_ | Easy || 760 | [Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings/) | [C++](./C++/find-anagram-mappings.cpp) [Python](./Python/find-anagram-mappings.py) | _O(n)_ | _O(n)_ | Easy || +771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/) | [C++](./C++/jewels-and-stones.cpp) [Python](./Python/jewels-and-stones.py) | _O(m + n)_ | _O(n)_ | Easy || ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -421,6 +422,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 672 | [Bulb Switcher II](https://leetcode.com/problems/bulb-switcher-ii/) | [C++](./C++/bulb-switcher-ii.cpp) [Python](./Python/bulb-switcher-ii.py) | _O(1)_ | _O(1)_ | Medium ||| 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/) | [C++](./C++/self-dividing-numbers.cpp) [Python](./Python/self-dividing-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| 754 | [Reach a Number](https://leetcode.com/problems/reach-a-number/) | [C++](./C++/reach-a-number.cpp) [Python](./Python/reach-a-number.py) | _O(logn)_ | _O(1)_ | Medium ||| +775 | [Global and Local Inversions](https://leetcode.com/problems/global-and-local-inversions/) | [C++](./C++/global-and-local-inversions.cpp) [Python](./Python/global-and-local-inversions.py) | _O(n)_ | _O(1)_ | Medium ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -527,6 +529,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 668 | [Kth Smallest Number in Multiplication Table](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/) | [C++](./C++/kth-smallest-number-in-multiplication-table.cpp) [Python](./Python/kth-smallest-number-in-multiplication-table.py) | _O(m * log(m * n))_ | _O(1)_ | Hard | | 719 | [Find K-th Smallest Pair Distance](https://leetcode.com/problems/find-k-th-smallest-pair-distance/) | [C++](./C++/find-k-th-smallest-pair-distance.cpp) [Python](./Python/find-k-th-smallest-pair-distance.py) | _O(nlogn + nlogw)_ | _O(1)_ | Hard | | 744 | [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/) | [C++](./C++/find-smallest-letter-greater-than-target.cpp) [Python](./Python/find-smallest-letter-greater-than-target.py) | _O(logn)_ | _O(1)_ | Easy | | +774 | [Minimize Max Distance to Gas Station](https://leetcode.com/problems/minimize-max-distance-to-gas-station/) | [C++](./C++/minimize-max-distance-to-gas-station.cpp) [Python](./Python/minimize-max-distance-to-gas-station.py) | _O(nlogr)_ | _O(1)_ | Hard | | ## Binary Search Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -566,6 +569,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 742|[Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree/)| [C++](./C++/closest-leaf-in-a-binary-tree.cpp) [Python](./Python/closest-leaf-in-a-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | | | 743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O(\|E\| + \|V\|log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | 752|[Open the Lock](https://leetcode.com/problems/open-the-lock/)| [C++](./C++/open-the-lock.cpp) [Python](./Python/open-the-lock.py)| _O(k * n^k + d)_ | _O(k * n^k + d)_ | Medium | | | +773|[Sliding Puzzle](https://leetcode.com/problems/sliding-puzzle/)| [C++](./C++/sliding-puzzle.cpp) [Python](./Python/sliding-puzzle.py)| _O((m * n) * (m * n)!)_ | _O((m * n) * (m * n)!)_ | Hard | | `A* Search Algorithm` | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 0ccdfb26a0998e0aaf81deecd633ab6566c008c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 31 Jan 2018 01:15:37 +0800 Subject: [PATCH 4385/4971] Update global-and-local-inversions.py --- Python/global-and-local-inversions.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/global-and-local-inversions.py b/Python/global-and-local-inversions.py index 901d9616e..2ee8525b0 100644 --- a/Python/global-and-local-inversions.py +++ b/Python/global-and-local-inversions.py @@ -11,6 +11,7 @@ # Input: A = [1,0,2] # Output: true # Explanation: There is 1 global inversion, and 1 local inversion. +# # Example 2: # # Input: A = [1,2,0] From b5402ea68127438c4c9056ee387f49af1146736f Mon Sep 17 00:00:00 2001 From: SangHee Kim Date: Wed, 31 Jan 2018 11:57:51 -0500 Subject: [PATCH 4386/4971] Update search-a-2d-matrix-ii.py count variable is not required in this case. --- Python/search-a-2d-matrix-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/search-a-2d-matrix-ii.py b/Python/search-a-2d-matrix-ii.py index 520f7030a..3540dfd6c 100644 --- a/Python/search-a-2d-matrix-ii.py +++ b/Python/search-a-2d-matrix-ii.py @@ -35,7 +35,7 @@ def searchMatrix(self, matrix, target): if n == 0: return False - count, i, j = 0, 0, n - 1 + i, j = 0, n - 1 while i < m and j >= 0: if matrix[i][j] == target: return True From 15fbe74c42866a5fbdd567f30c66439df5aa51cb Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 2 Feb 2018 22:45:00 +0800 Subject: [PATCH 4387/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b4867bcbf..836e15875 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | +527| [Word Abbreviation](https://leetcode.com/problems/word-abbreviation/) | [C++](./C++/word-abbreviation.cpp) [Python](./Python/word-abbreviation.py) | _O(n * l)_ ~ _O(n^2 * l^2)_ | _O(n * l)_ | Hard |📖| 539| [Minimum Time Difference](https://leetcode.com/problems/minimum-time-difference/) | [C++](./C++/minimum-time-difference.cpp) [Python](./Python/minimum-time-difference.py) | _O(nlogn)_ | _O(n)_ | Medium | | 541| [Reverse String II](https://leetcode.com/problems/reverse-string-ii/) | [C++](./C++/reverse-string-ii.cpp) [Python](./Python/reverse-string-ii.py) | _O(n)_ | _O(1)_ | Easy | | 551 | [Student Attendance Record I](https://leetcode.com/problems/student-attendance-record-i/) | [C++](./C++/student-attendance-record-i.cpp) [Python](./Python/student-attendance-record-i.py) | _O(n)_ | _O(1)_ | Easy ||| From 66d9ac19bfaa58487127f323841c081150d0ac1b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 3 Feb 2018 05:24:49 +0800 Subject: [PATCH 4388/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 836e15875..382d8d4a2 100644 --- a/README.md +++ b/README.md @@ -634,6 +634,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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(n * 2^n)_ | _O(n)_ | Medium |📖|| 425| [Word Squares](https://leetcode.com/problems/word-squares/) | [C++](./C++/word-squares.cpp) [Python](./Python/word-squares.py) | _O(n^2 * n!)_ | _O(n^2)_ | Hard |📖|| +526| [Beautiful Arrangement](https://leetcode.com/problems/beautiful-arrangement/) | [C++](./C++/beautiful-arrangement.cpp) [Python](./Python/beautiful-arrangement.py) | _O(n!)_ | _O(n)_ | Medium || 676| [Implement Magic Dictionary](https://leetcode.com/problems/implement-magic-dictionary/) | [C++](./C++/implement-magic-dictionary.cpp) [Python](./Python/implement-magic-dictionary.py) | _O(n)_ | _O(d)_ | Medium || Trie, DFS 679| [24 Game](https://leetcode.com/problems/24-game/) | [C++](./C++/24-game.cpp) [Python](./Python/24-game.py) | _O(1)_ | _O(1)_ | Hard || DFS 698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_ | _O(2^n)_ | Medium || DFS, DP, Memoization From 0815c89dba1a014c08a2d43cfaeea1bdfd649006 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Feb 2018 09:00:37 +0800 Subject: [PATCH 4389/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 382d8d4a2..930e6249b 100644 --- a/README.md +++ b/README.md @@ -287,6 +287,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 | +525| [Contiguous Array](https://leetcode.com/problems/contiguous-array/) |[C++](./C++/contiguous-array.cpp) [Python](./Python/contiguous-array.py) | _O(n)_ | _O(n)_ | Medium | | 529 | [Minesweeper](https://leetcode.com/problems/minesweeper/) | [C++](./C++/minesweeper.cpp) [Python](./Python/minesweeper.py) | _O(m * n)_ | _O(m + n)_ | Medium || 536 | [Construct Binary Tree from String](https://leetcode.com/problems/construct-binary-tree-from-string/) | [C++](./C++/construct-binary-tree-from-string.cpp) [Python](./Python/construct-binary-tree-from-string.py) | _O(n)_ | _O(h)_ | Medium | 📖 | 538 | [Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [C++](./C++/convert-bst-to-greater-tree.cpp) [Python](./Python/convert-bst-to-greater-tree.py) | _O(n)_ | _O(h)_ | Easy || From 0062f44517c792b33191bc155c630199b80ebda1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 5 Feb 2018 11:42:07 +0800 Subject: [PATCH 4390/4971] Create k-th-symbol-in-grammar.cpp --- C++/k-th-symbol-in-grammar.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/k-th-symbol-in-grammar.cpp diff --git a/C++/k-th-symbol-in-grammar.cpp b/C++/k-th-symbol-in-grammar.cpp new file mode 100644 index 000000000..fce42bacd --- /dev/null +++ b/C++/k-th-symbol-in-grammar.cpp @@ -0,0 +1,18 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int kthGrammar(int N, int K) { + return bitCount(K - 1) % 2; + } + +private: + int bitCount(int n) { + int count = 0; + for (; n; n &= n - 1) { + ++count; + } + return count; + } +}; From c163fbf0239588331c15d4dc9ba90ea7afb0c148 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 6 Feb 2018 10:52:11 +0800 Subject: [PATCH 4391/4971] Create k-th-symbol-in-grammar.py --- Python/k-th-symbol-in-grammar.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Python/k-th-symbol-in-grammar.py diff --git a/Python/k-th-symbol-in-grammar.py b/Python/k-th-symbol-in-grammar.py new file mode 100644 index 000000000..f26879ff8 --- /dev/null +++ b/Python/k-th-symbol-in-grammar.py @@ -0,0 +1,18 @@ +# Time: O(logn) +# Space: O(1) + +class Solution(object): + def kthGrammar(self, N, K): + """ + :type N: int + :type K: int + :rtype: int + """ + def bitCount(n): + result = 0 + while n: + n &= n - 1 + result += 1 + return result + + return bitCount(K-1) % 2 From 990d59787e936034dd4ba5e599cb8550f0803cff Mon Sep 17 00:00:00 2001 From: jxie0755 <30805062+jxie0755@users.noreply.github.com> Date: Tue, 6 Feb 2018 15:35:10 -0500 Subject: [PATCH 4392/4971] set global_max start with 0 --- Python/maximum-subarray.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/maximum-subarray.py b/Python/maximum-subarray.py index 9c5f5ede9..35fcd74ae 100644 --- a/Python/maximum-subarray.py +++ b/Python/maximum-subarray.py @@ -20,7 +20,7 @@ def maxSubArray(self, nums): """ if max(nums) < 0: return max(nums) - global_max, local_max = float("-inf"), 0 + global_max, local_max = 0, 0 for x in nums: local_max = max(0, local_max + x) global_max = max(global_max, local_max) From 6398d1db9b55aed79b4ee00944218136bab7cf59 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Feb 2018 21:27:59 +0800 Subject: [PATCH 4393/4971] Create swap-adjacent-in-lr-string.cpp --- C++/swap-adjacent-in-lr-string.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/swap-adjacent-in-lr-string.cpp diff --git a/C++/swap-adjacent-in-lr-string.cpp b/C++/swap-adjacent-in-lr-string.cpp new file mode 100644 index 000000000..8a5662203 --- /dev/null +++ b/C++/swap-adjacent-in-lr-string.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool canTransform(string start, string end) { + int N = start.length(); + for (int i = 0, j = 0; i < N && j < N; ++i, ++j) { + while (i < N && start[i] == 'X') ++i; + while (j < N && end[j] == 'X') ++j; + if ((i < N) != (j < N)) { + return false; + } else if (i < N && j < N) { + if (start[i] != end[j] || + (start[i] == 'L' && i < j) || + (start[i] == 'R' && i > j)) { + return false; + } + } + } + return true; + } +}; From b2d49897dfca03d9daf48d3365fe0898eb70d0b3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Feb 2018 21:33:33 +0800 Subject: [PATCH 4394/4971] Create swap-adjacent-in-lr-string.py --- Python/swap-adjacent-in-lr-string.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/swap-adjacent-in-lr-string.py diff --git a/Python/swap-adjacent-in-lr-string.py b/Python/swap-adjacent-in-lr-string.py new file mode 100644 index 000000000..1fb80cafd --- /dev/null +++ b/Python/swap-adjacent-in-lr-string.py @@ -0,0 +1,27 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def canTransform(self, start, end): + """ + :type start: str + :type end: str + :rtype: bool + """ + N = len(start) + i, j = 0, 0 + while i < N and j < N: + while i < N and start[i] == 'X': + i += 1 + while j < N and end[j] == 'X': + j += 1 + if (i < N) != (j < N): + return False + elif i < N and j < N: + if start[i] != end[j] or \ + (start[i] == 'L' and i < j) or \ + (start[i] == 'R' and i > j): + return False + i += 1 + j += 1 + return True From d6f19ee076c6256fcf672cd78bd2c2febdeb4401 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Feb 2018 21:42:16 +0800 Subject: [PATCH 4395/4971] Create split-bst.cpp --- C++/split-bst.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/split-bst.cpp diff --git a/C++/split-bst.cpp b/C++/split-bst.cpp new file mode 100644 index 000000000..8c88d6686 --- /dev/null +++ b/C++/split-bst.cpp @@ -0,0 +1,28 @@ +// 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: + vector splitBST(TreeNode* root, int V) { + if (!root) { + return {nullptr, nullptr}; + } else if (root->val <= V) { + const auto& result = splitBST(root->right, V); + root->right = result[0]; + return {root, result[1]}; + } else { + const auto& result = splitBST(root->left, V); + root->left = result[1]; + return {result[0], root}; + } + } +}; From 360c4995f96f88031cb4d4176518dd358bf6410f Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Feb 2018 21:42:45 +0800 Subject: [PATCH 4396/4971] Create split-bst.py --- Python/split-bst.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/split-bst.py diff --git a/Python/split-bst.py b/Python/split-bst.py new file mode 100644 index 000000000..ced0963bc --- /dev/null +++ b/Python/split-bst.py @@ -0,0 +1,27 @@ +# 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 splitBST(self, root, V): + """ + :type root: TreeNode + :type V: int + :rtype: List[TreeNode] + """ + if not root: + return None, None + elif root.val <= V: + result = self.splitBST(root.right, V) + root.right = result[0] + return root, result[1] + else: + result = self.splitBST(root.left, V) + root.left = result[1] + return result[0], root From 7461c57df97d4b50d37c0287338fb5f04124b218 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Feb 2018 22:38:13 +0800 Subject: [PATCH 4397/4971] Create swim-in-rising-water.cpp --- C++/swim-in-rising-water.cpp | 59 ++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 C++/swim-in-rising-water.cpp diff --git a/C++/swim-in-rising-water.cpp b/C++/swim-in-rising-water.cpp new file mode 100644 index 000000000..c9eb0fc52 --- /dev/null +++ b/C++/swim-in-rising-water.cpp @@ -0,0 +1,59 @@ +// Time: O(n^2) +// Space: O(n^2) + +class Solution { +public: + int swimInWater(vector>& grid) { + const int m = grid.size(), n = grid[0].size(); + vector> positions(m * n); + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + positions[grid[i][j]] = {i, j}; + } + } + static const vector> directions{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + UnionFind union_find(m * n); + for (int elevation = 0; elevation < positions.size(); ++elevation) { + int i, j; + tie(i, j) = positions[elevation]; + for (const auto& dir : directions) { + int x = i + dir.first; + int y = j + dir.second; + if (0 <= x && x < m && + 0 <= y && y < n && + grid[x][y] <= elevation) { + union_find.union_set(i * n + j, x * n + y); + if (union_find.find_set(0) == union_find.find_set(m * n - 1)) { + return elevation; + } + } + } + } + return m * n - 1; + } + +private: + class UnionFind { + public: + UnionFind(const int n) : set_(n) { + iota(set_.begin(), set_.end(), 0); + } + + int find_set(const 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); + } + } + + private: + vector set_; + }; +}; From c633092cae28969d66c9dd0589e2e6d50cd17901 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Feb 2018 22:45:20 +0800 Subject: [PATCH 4398/4971] Update swim-in-rising-water.cpp --- C++/swim-in-rising-water.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/C++/swim-in-rising-water.cpp b/C++/swim-in-rising-water.cpp index c9eb0fc52..0d950b690 100644 --- a/C++/swim-in-rising-water.cpp +++ b/C++/swim-in-rising-water.cpp @@ -4,32 +4,32 @@ class Solution { public: int swimInWater(vector>& grid) { - const int m = grid.size(), n = grid[0].size(); - vector> positions(m * n); - for (int i = 0; i < m; ++i) { + const int n = grid.size(); + vector> positions(n * n); + for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { positions[grid[i][j]] = {i, j}; } } static const vector> directions{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; - UnionFind union_find(m * n); + UnionFind union_find(n * n); for (int elevation = 0; elevation < positions.size(); ++elevation) { int i, j; tie(i, j) = positions[elevation]; for (const auto& dir : directions) { int x = i + dir.first; int y = j + dir.second; - if (0 <= x && x < m && + if (0 <= x && x < n && 0 <= y && y < n && grid[x][y] <= elevation) { union_find.union_set(i * n + j, x * n + y); - if (union_find.find_set(0) == union_find.find_set(m * n - 1)) { + if (union_find.find_set(0) == union_find.find_set(n * n - 1)) { return elevation; } } } } - return m * n - 1; + return n * n - 1; } private: From ba16d07ca8bd3609de00880c121111fe7f290b3c Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Feb 2018 22:46:54 +0800 Subject: [PATCH 4399/4971] Create swim-in-rising-water.py --- Python/swim-in-rising-water.py | 44 ++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/swim-in-rising-water.py diff --git a/Python/swim-in-rising-water.py b/Python/swim-in-rising-water.py new file mode 100644 index 000000000..7a60846f0 --- /dev/null +++ b/Python/swim-in-rising-water.py @@ -0,0 +1,44 @@ +# Time: O(n^2) +# Space: O(n^2) + +class UnionFind(object): + def __init__(self, n): + self.set = range(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: + return False + self.set[min(x_root, y_root)] = max(x_root, y_root) + return True + + +class Solution(object): + def swimInWater(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + n = len(grid) + positions = [None] * (n**2) + for i in xrange(n): + for j in xrange(n): + positions[grid[i][j]] = (i, j) + directions = ((-1, 0), (1, 0), (0, -1), (0, 1)) + + union_find = UnionFind(n**2) + for elevation in xrange(n**2): + i, j = positions[elevation] + for direction in directions: + x, y = i+direction[0], j+direction[1] + if 0 <= x < n and 0 <= y < n and grid[x][y] <= elevation: + union_find.union_set(i*n+j, x*n+y) + if union_find.find_set(0) == union_find.find_set(n**2-1): + return elevation + return n**2-1 + From 7657c3db3ce6ae2117bb68e3f369348439b18578 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Feb 2018 22:08:51 +0800 Subject: [PATCH 4400/4971] Update swap-adjacent-in-lr-string.py --- Python/swap-adjacent-in-lr-string.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Python/swap-adjacent-in-lr-string.py b/Python/swap-adjacent-in-lr-string.py index 1fb80cafd..1a2129283 100644 --- a/Python/swap-adjacent-in-lr-string.py +++ b/Python/swap-adjacent-in-lr-string.py @@ -1,6 +1,28 @@ # Time: O(n) # Space: O(1) +# In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", +# a move consists of either replacing one occurrence of "XL" with "LX", +# or replacing one occurrence of "RX" with "XR". +# Given the starting string start and the ending string end, +# return True if and only if there exists a sequence of moves to transform one string to the other. +# +# Example: +# Input: start = "RXXLRXRXL", end = "XRLXXRRLX" +# Output: True +# +# Explanation: +# We can transform start to end following these steps: +# RXXLRXRXL -> +# XRXLRXRXL -> +# XRLXRXRXL -> +# XRLXXRRXL -> +# XRLXXRRLX +# +# Note: +# - 1 <= len(start) = len(end) <= 10000. +# - Both start and end will only consist of characters in {'L', 'R', 'X'}. + class Solution(object): def canTransform(self, start, end): """ From fe66e5a570a98f344cf22c04dedd71e75aea57aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Feb 2018 22:11:17 +0800 Subject: [PATCH 4401/4971] Update swim-in-rising-water.py --- Python/swim-in-rising-water.py | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Python/swim-in-rising-water.py b/Python/swim-in-rising-water.py index 7a60846f0..0418afd34 100644 --- a/Python/swim-in-rising-water.py +++ b/Python/swim-in-rising-water.py @@ -1,6 +1,44 @@ # Time: O(n^2) # Space: O(n^2) +# On an N x N grid, each square grid[i][j] represents the elevation at that point (i,j). +# +# Now rain starts to fall. At time t, the depth of the water everywhere is t. +# You can swim from a square to another 4-directionally adjacent square +# if and only if the elevation of both squares individually are at most t. +# You can swim infinite distance in zero time. Of course, +# you must stay within the boundaries of the grid during your swim. +# +# You start at the top left square (0, 0). +# What is the least time until you can reach the bottom right square (N-1, N-1)? +# +# Example 1: +# Input: [[0,2],[1,3]] +# Output: 3 +# Explanation: +# At time 0, you are in grid location (0, 0). +# You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. +# +# You cannot reach point (1, 1) until time 3. +# When the depth of water is 3, we can swim anywhere inside the grid. +# Example 2: +# +# Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]] +# Output: 16 +# Explanation: +# 0 1 2 3 4 +# 24 23 22 21 5 +# 12 13 14 15 16 +# 11 17 18 19 20 +# 10 9 8 7 6 +# +# The final route is marked in bold. +# We need to wait until time 16 so that (0, 0) and (4, 4) are connected. +# +# Note: +# - 2 <= N <= 50. +# - grid[i][j] is a permutation of [0, ..., N*N - 1]. + class UnionFind(object): def __init__(self, n): self.set = range(n) From 1250a49b0a1ff30907332318daed2faaeeb45651 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Feb 2018 22:12:51 +0800 Subject: [PATCH 4402/4971] Update k-th-symbol-in-grammar.py --- Python/k-th-symbol-in-grammar.py | 33 +++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/Python/k-th-symbol-in-grammar.py b/Python/k-th-symbol-in-grammar.py index f26879ff8..e2eccc395 100644 --- a/Python/k-th-symbol-in-grammar.py +++ b/Python/k-th-symbol-in-grammar.py @@ -1,6 +1,37 @@ # Time: O(logn) # Space: O(1) - + +# On the first row, we write a 0. +# Now in every subsequent row, +# we look at the previous row and replace each occurrence of 0 with 01, +# and each occurrence of 1 with 10. +# +# Given row N and index K, return the K-th indexed symbol in row N. +# (The values of K are 1-indexed.) (1 indexed). +# +# Examples: +# Input: N = 1, K = 1 +# Output: 0 +# +# Input: N = 2, K = 1 +# Output: 0 +# +# Input: N = 2, K = 2 +# Output: 1 +# +# Input: N = 4, K = 5 +# Output: 1 +# +# Explanation: +# row 1: 0 +# row 2: 01 +# row 3: 0110 +# row 4: 01101001 +# +# Note: +# - N will be an integer in the range [1, 30]. +# - K will be an integer in the range [1, 2^(N-1)]. + class Solution(object): def kthGrammar(self, N, K): """ From 2aa4c7431d37769ad403edf87903785a0f5d7b46 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Feb 2018 22:19:59 +0800 Subject: [PATCH 4403/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 930e6249b..01463d9ed 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 766 | [Toeplitz Matrix](https://leetcode.com/problems/toeplitz-matrix/) | [C++](./C++/toeplitz-matrix.cpp) [Python](./Python/toeplitz-matrix.py) | _O(m * n)_ | _O(1)_ | Easy || 768 | [Max Chunks To Make Sorted II](https://leetcode.com/problems/max-chunks-to-make-sorted-ii/) | [C++](./C++/max-chunks-to-make-sorted-ii.cpp) [Python](./Python/max-chunks-to-make-sorted-ii.py) | _O(nlogn)_ | _O(n)_ | Hard || 769 | [Max Chunks To Make Sorted](https://leetcode.com/problems/max-chunks-to-make-sorted/) | [C++](./C++/max-chunks-to-make-sorted.cpp) [Python](./Python/max-chunks-to-make-sorted.py) | _O(n)_ | _O(1)_ | Medium || +778 | [Swim in Rising Water](https://leetcode.com/problems/swim-in-rising-water/) | [C++](./C++/swim-in-rising-water.cpp) [Python](./Python/swim-in-rising-water.py) | _O(n^2)_ | _O(n^2)_ | Hard || Union Find ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -425,6 +426,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 728 | [Self Dividing Numbers](https://leetcode.com/problems/self-dividing-numbers/) | [C++](./C++/self-dividing-numbers.cpp) [Python](./Python/self-dividing-numbers.py) | _O(n)_ | _O(1)_ | Medium ||| 754 | [Reach a Number](https://leetcode.com/problems/reach-a-number/) | [C++](./C++/reach-a-number.cpp) [Python](./Python/reach-a-number.py) | _O(logn)_ | _O(1)_ | Medium ||| 775 | [Global and Local Inversions](https://leetcode.com/problems/global-and-local-inversions/) | [C++](./C++/global-and-local-inversions.cpp) [Python](./Python/global-and-local-inversions.py) | _O(n)_ | _O(1)_ | Medium ||| +779 | [K-th Symbol in Grammar](https://leetcode.com/problems/k-th-symbol-in-grammar/) | [C++](./C++/k-th-symbol-in-grammar.cpp) [Python](./Python/k-th-symbol-in-grammar.py) | _O(1)_ | _O(1)_ | Medium || ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -468,6 +470,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 457| [Circular Array Loop](https://leetcode.com/problems/circular-array-loop/) | [C++](./C++/circular-array-loop.cpp) [Python](./Python/circular-array-loop.py) | _O(n)_ | _O(1)_ | Medium || 567| [Permutation in String](https://leetcode.com/problems/permutation-in-string/) | [C++](./C++/permutation-in-string.cpp) [Python](./Python/permutation-in-string.py) | _O(n)_ | _O(1)_ | Medium || 611| [Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/) | [C++](./C++/valid-triangle-number.cpp) [Python](./Python/valid-triangle-number.py) | _O(n^2)_ | _O(1)_ | Medium || +777| [Swap Adjacent in LR String](https://leetcode.com/problems/swap-adjacent-in-lr-string/) | [C++](./C++/swap-adjacent-in-lr-string.cpp) [Python](./Python/swap-adjacent-in-lr-string.py) | _O(n)_ | _O(1)_ | Medium || ## Recursion | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -545,6 +548,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/)| [C++](./C++/serialize-and-deserialize-bst.cpp) [Python](./Python/serialize-and-deserialize-bst.py)| _O(n)_ | _O(h)_ | Medium | | | 450|[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/)| [C++](./C++/delete-node-in-a-bst.cpp) [Python](./Python/delete-node-in-a-bst.py)| _O(h)_ | _O(h)_ | Medium | | | 530|[Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)| [C++](./C++/minimum-absolute-difference-in-bst.cpp) [Python](./Python/minimum-absolute-difference-in-bst.py)| _O(n)_ | _O(h)_ | Easy | | | +776|[Split BST](https://leetcode.com/problems/split-bst/)| [C++](./C++/split-bst.cpp) [Python](./Python/split-bst.py)| _O(n)_ | _O(h)_ | Medium | 📖 | | ## Breadth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 872bbcdad33ac6c8509541fb21b704c33716929c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Feb 2018 22:21:02 +0800 Subject: [PATCH 4404/4971] Update k-th-symbol-in-grammar.cpp --- C++/k-th-symbol-in-grammar.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/k-th-symbol-in-grammar.cpp b/C++/k-th-symbol-in-grammar.cpp index fce42bacd..b3cc69ee9 100644 --- a/C++/k-th-symbol-in-grammar.cpp +++ b/C++/k-th-symbol-in-grammar.cpp @@ -1,4 +1,4 @@ -// Time: O(logn) +// Time: O(logn) = O(1) because n is 32-bit integer // Space: O(1) class Solution { From affd1a18915a81379133183617e91fe6adb26dfd Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Feb 2018 22:21:41 +0800 Subject: [PATCH 4405/4971] Update k-th-symbol-in-grammar.py --- Python/k-th-symbol-in-grammar.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/k-th-symbol-in-grammar.py b/Python/k-th-symbol-in-grammar.py index e2eccc395..dbed8a5f6 100644 --- a/Python/k-th-symbol-in-grammar.py +++ b/Python/k-th-symbol-in-grammar.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(logn) = O(1) because n is 32-bit integer # Space: O(1) # On the first row, we write a 0. From 2179ed300d701d0f80d5278664195f4276c464af Mon Sep 17 00:00:00 2001 From: poweihuang17 Date: Sat, 10 Feb 2018 16:02:45 +0800 Subject: [PATCH 4406/4971] 122 is now an easy problem. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 01463d9ed..361f4d6e2 100644 --- a/README.md +++ b/README.md @@ -729,7 +729,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 044| [Wildcard Matching](https://leetcode.com/problems/wildcard-matching/) | [Python](./Python/wildcard-matching.py) | _O(m + n)_ | _O(1)_ | Hard || Tricky 045| [Jump Game II](https://leetcode.com/problems/jump-game-ii/) | [Python](./Python/jump-game-ii.py) | _O(n)_ | _O(1)_ | Hard || 055| [Jump Game](https://leetcode.com/problems/jump-game/) | [Python](./Python/jump-game.py) | _O(n)_ | _O(1)_ | Medium || -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 || +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)_ | Easy || 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/)| [C++](./C++/candy.cpp) [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)_| Hard || Ascending Stack | From e1c0e725d55ddf83ca0f6d82e8b7a6b5db3c0fab Mon Sep 17 00:00:00 2001 From: JXZGitHub <35183837+JXZGitHub@users.noreply.github.com> Date: Sat, 10 Feb 2018 23:13:17 -0500 Subject: [PATCH 4407/4971] Minor readability improvement --- Python/permutations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/permutations.py b/Python/permutations.py index 03d76be78..c615f05aa 100644 --- a/Python/permutations.py +++ b/Python/permutations.py @@ -20,7 +20,7 @@ def permute(self, num): def permuteRecu(self, result, used, cur, num): if len(cur) == len(num): - result.append(cur + []) + result.append(cur[:]) return for i in xrange(len(num)): if not used[i]: From bee61e321e4d9db598d4f7f5eae1fadcbfb3f173 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 19:41:40 +0800 Subject: [PATCH 4408/4971] Create transform-to-chessboard.cpp --- C++/transform-to-chessboard.cpp | 78 +++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 C++/transform-to-chessboard.cpp diff --git a/C++/transform-to-chessboard.cpp b/C++/transform-to-chessboard.cpp new file mode 100644 index 000000000..69f4b2311 --- /dev/null +++ b/C++/transform-to-chessboard.cpp @@ -0,0 +1,78 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + int movesToChessboard(vector>& board) { + const int N = board.size(); + unordered_map, int, Hash>> row_lookup, col_lookup; + for (int i = 0; i < N; ++i) { + const auto& row = board[i]; + ++row_lookup[row]; + if (row_lookup.size() > 2) { + return -1; + } + } + for (int j = 0; j < N; ++j) { + vector col; + for (int i = 0; i < N; ++i) { + col.emplace_back(board[i][j]); + } + ++col_lookup[col]; + if (col_lookup.size() > 2) { + return -1; + } + } + + int row_count = move(N, row_lookup); + if (row_count < 0) { + return -1; + } + int col_count = move(N, col_lookup); + if (col_count < 0) { + return -1; + } + return row_count + col_count; + } + +private: + template + struct Hash { + size_t operator()(const ContType& v) const { + size_t seed = 0; + for (const auto& i : v) { + seed ^= std::hash{}(i) + 0x9e3779b9 + (seed<<6) + (seed>>2); + } + return seed; + } + }; + + int move(int N, const unordered_map, int, Hash>>& lookup) { + if (lookup.size() != 2 || + min(lookup.begin()->second, next(lookup.begin())->second) != N / 2 || + max(lookup.begin()->second, next(lookup.begin())->second) != (N + 1) / 2) { + return -1; + } + const auto& seq1 = lookup.begin()->first; + const auto& seq2 = next(lookup.begin())->first; + for (int i = 0; i < N; ++i) { + if (seq1[i] == seq2[i]) { + return -1; + } + } + + vector begins = (N % 2) ? vector{static_cast(std::count(seq1.begin(), seq1.end(), 1) * 2 > N)} : + vector{0, 1}; + int result = numeric_limits::max(); + for (const auto& begin : begins) { + int i = begin; + int sum = 0; + for (const auto& v : seq1) { + sum += (i - v + 2) % 2; + ++i; + } + result = min(result, sum / 2); + } + return result; + } +}; From 86d9796661302c9d17e134e900706dc215c79ca6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 19:46:12 +0800 Subject: [PATCH 4409/4971] Create transform-to-chessboard.py --- Python/transform-to-chessboard.py | 63 +++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Python/transform-to-chessboard.py diff --git a/Python/transform-to-chessboard.py b/Python/transform-to-chessboard.py new file mode 100644 index 000000000..85ee0d2d6 --- /dev/null +++ b/Python/transform-to-chessboard.py @@ -0,0 +1,63 @@ +# Time: O(n^2) +# Space: O(n^2) + +# An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, +# or any 2 columns with each other. +# +# What is the minimum number of moves to transform the board into a "chessboard" - +# a board where no 0s and no 1s are 4-directionally adjacent? If the task is impossible, return -1. +# +# Examples: +# Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]] +# Output: 2 +# Explanation: +# One potential sequence of moves is shown below, from left to right: +# +# 0110 1010 1010 +# 0110 --> 1010 --> 0101 +# 1001 0101 1010 +# 1001 0101 0101 +# +# The first move swaps the first and second column. +# The second move swaps the second and third row. +# +# Input: board = [[0, 1], [1, 0]] +# Output: 0 +# Explanation: +# Also note that the board with 0 in the top left corner, +# 01 +# 10 +# +# is also a valid chessboard. +# +# Input: board = [[1, 0], [1, 0]] +# Output: -1 +# Explanation: +# No matter what sequence of moves you make, you cannot end with a valid chessboard. +# +# Note: +# - board will have the same number of rows and columns, a number in the range [2, 30]. +# - board[i][j] will be only 0s or 1s. + +class Solution(object): + def movesToChessboard(self, board): + """ + :type board: List[List[int]] + :rtype: int + """ + N = len(board) + result = 0 + for count in (collections.Counter(map(tuple, board)), \ + collections.Counter(itertools.izip(*board))): + if len(count) != 2 or \ + sorted(count.values()) != [N/2, (N+1)/2]: + return -1 + + seq1, seq2 = count + if any(x == y for x, y in itertools.izip(seq1, seq2)): + return -1 + begins = [int(seq1.count(1) * 2 > N)] if N%2 else [0, 1] + result += min(sum((i-v) % 2 for i, v in enumerate(seq1, begin)) \ + for begin in begins) / 2 + return result + From f535355e0f587aede0a10892af404001692cf0b1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 19:55:42 +0800 Subject: [PATCH 4410/4971] Update transform-to-chessboard.cpp --- C++/transform-to-chessboard.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/transform-to-chessboard.cpp b/C++/transform-to-chessboard.cpp index 69f4b2311..181036c7e 100644 --- a/C++/transform-to-chessboard.cpp +++ b/C++/transform-to-chessboard.cpp @@ -68,7 +68,7 @@ class Solution { int i = begin; int sum = 0; for (const auto& v : seq1) { - sum += (i - v + 2) % 2; + sum += static_cast((i % 2) != v); ++i; } result = min(result, sum / 2); From 5b55103d7107cadae96a577d2d2b2edd05c57b5b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 19:57:00 +0800 Subject: [PATCH 4411/4971] Update transform-to-chessboard.py --- Python/transform-to-chessboard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/transform-to-chessboard.py b/Python/transform-to-chessboard.py index 85ee0d2d6..9c03a9041 100644 --- a/Python/transform-to-chessboard.py +++ b/Python/transform-to-chessboard.py @@ -57,7 +57,7 @@ def movesToChessboard(self, board): if any(x == y for x, y in itertools.izip(seq1, seq2)): return -1 begins = [int(seq1.count(1) * 2 > N)] if N%2 else [0, 1] - result += min(sum((i-v) % 2 for i, v in enumerate(seq1, begin)) \ + result += min(sum(int(i%2 != v) for i, v in enumerate(seq1, begin)) \ for begin in begins) / 2 return result From dbaf36b504cdc1890d3321e481f3f618bb0f6a7c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 20:49:30 +0800 Subject: [PATCH 4412/4971] Create minimum-distance-between-bst-nodes.cpp --- C++/minimum-distance-between-bst-nodes.cpp | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/minimum-distance-between-bst-nodes.cpp diff --git a/C++/minimum-distance-between-bst-nodes.cpp b/C++/minimum-distance-between-bst-nodes.cpp new file mode 100644 index 000000000..c84359bd7 --- /dev/null +++ b/C++/minimum-distance-between-bst-nodes.cpp @@ -0,0 +1,34 @@ +// 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 minDiffInBST(TreeNode* root) { + int prev = numeric_limits::min(); + int result = numeric_limits::max(); + dfs(root, &prev, &result); + return result; + } + +private: + void dfs(TreeNode* node, int *prev, int *result) { + if (!node) { + return; + } + dfs(node->left, prev, result); + if (*prev != numeric_limits::min()) { + *result = min(*result, node->val - *prev); + } + *prev = node->val; + dfs(node->right, prev, result); + } +}; From eff883316f422262b4550ac021c2823455bc889b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 20:51:13 +0800 Subject: [PATCH 4413/4971] Create minimum-distance-between-bst-nodes.py --- Python/minimum-distance-between-bst-nodes.py | 54 ++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/minimum-distance-between-bst-nodes.py diff --git a/Python/minimum-distance-between-bst-nodes.py b/Python/minimum-distance-between-bst-nodes.py new file mode 100644 index 000000000..ca26974c7 --- /dev/null +++ b/Python/minimum-distance-between-bst-nodes.py @@ -0,0 +1,54 @@ +# Time: O(n) +# Space: O(h) + +# Given a Binary Search Tree (BST) with the root node root, +# return the minimum difference between the values of any two different nodes in the tree. +# +# Example : +# +# Input: root = [4,2,6,1,3,null,null] +# Output: 1 +# Explanation: +# Note that root is a TreeNode object, not an array. +# +# The given tree [4,2,6,1,3,null,null] is represented by the following diagram: +# +# 4 +# / \ +# 2 6 +# / \ +# 1 3 +# +# while the minimum difference in this tree is 1, +# it occurs between node 1 and node 2, also between node 3 and node 2. +# +# Note: +# - The size of the BST will be between 2 and 100. +# - The BST is always valid, each node's value is an integer, and each node's value is different. + +# 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 minDiffInBST(self, root): + """ + :type root: TreeNode + :rtype: int + """ + def dfs(node): + if not node: + return + dfs(node.left) + self.result = min(self.result, node.val-self.prev) + self.prev = node.val + dfs(node.right) + + self.prev = float('-inf') + self.result = float('inf') + dfs(root) + return self.result + From ea535c991b74a23d260a6025d73c0a330de776c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 21:15:34 +0800 Subject: [PATCH 4414/4971] Create rabbits-in-forest.cpp --- C++/rabbits-in-forest.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/rabbits-in-forest.cpp diff --git a/C++/rabbits-in-forest.cpp b/C++/rabbits-in-forest.cpp new file mode 100644 index 000000000..5e0740939 --- /dev/null +++ b/C++/rabbits-in-forest.cpp @@ -0,0 +1,17 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int numRabbits(vector& answers) { + unordered_map lookup; + for (const auto& answer : answers) { + ++lookup[answer]; + } + int result = 0; + for (const auto& kvp : lookup) { + result += ((kvp.first + 1) + kvp.second - 1) / (kvp.first + 1) * (kvp.first + 1); + } + return result; + } +}; From 7b73da577fae31b35d416c30bfd0a2baf2abd8ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 21:17:48 +0800 Subject: [PATCH 4415/4971] Create rabbits-in-forest.py --- Python/rabbits-in-forest.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/rabbits-in-forest.py diff --git a/Python/rabbits-in-forest.py b/Python/rabbits-in-forest.py new file mode 100644 index 000000000..0c3dad1d6 --- /dev/null +++ b/Python/rabbits-in-forest.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(n) + +# In a forest, each rabbit has some color. +# Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. +# Those answers are placed in an array. +# +# Return the minimum number of rabbits that could be in the forest. +# +# Examples: +# Input: answers = [1, 1, 2] +# Output: 5 +# Explanation: +# The two rabbits that answered "1" could both be the same color, say red. +# The rabbit than answered "2" can't be red or the answers would be inconsistent. +# Say the rabbit that answered "2" was blue. +# Then there should be 2 other blue rabbits in the forest that didn't answer into the array. +# The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't. +# +# Input: answers = [10, 10, 10] +# Output: 11 +# +# Input: answers = [] +# Output: 0 +# +# Note: +# - answers will have length at most 1000. +# - Each answers[i] will be an integer in the range [0, 999]. + +class Solution(object): + def numRabbits(self, answers): + """ + :type answers: List[int] + :rtype: int + """ + count = collections.Counter(answers) + return sum((((k+1)+v-1)//(k+1))*(k+1) for k, v in count.iteritems()) From 6e95065049c914a369de6854171d2ad028add907 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 21:35:02 +0800 Subject: [PATCH 4416/4971] Create reaching-points.cpp --- C++/reaching-points.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/reaching-points.cpp diff --git a/C++/reaching-points.cpp b/C++/reaching-points.cpp new file mode 100644 index 000000000..914752f4c --- /dev/null +++ b/C++/reaching-points.cpp @@ -0,0 +1,20 @@ +// Time: O(log(max(m, n))) +// Space: O(1) + +class Solution { +public: + bool reachingPoints(int sx, int sy, int tx, int ty) { + while (tx >= sx && ty >= sy) { + if (tx < ty) { + swap(sx, sy); + swap(tx, ty); + } + if (ty > sy) { + tx %= ty; + } else { + return (tx - sx) % ty == 0; + } + } + return false; + } +}; From eecc245851e3844f9710a6526d9b117da33ca151 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 21:36:38 +0800 Subject: [PATCH 4417/4971] Create reaching-points.py --- Python/reaching-points.py | 46 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/reaching-points.py diff --git a/Python/reaching-points.py b/Python/reaching-points.py new file mode 100644 index 000000000..cd8a18bba --- /dev/null +++ b/Python/reaching-points.py @@ -0,0 +1,46 @@ +# Time: O(log(max(m, n))) +# Space: O(1) + +# A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y). +# +# Given a starting point (sx, sy) and a target point (tx, ty), +# return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). +# Otherwise, return False. +# +# Examples: +# Input: sx = 1, sy = 1, tx = 3, ty = 5 +# Output: True +# Explanation: +# One series of moves that transforms the starting point to the target is: +# (1, 1) -> (1, 2) +# (1, 2) -> (3, 2) +# (3, 2) -> (3, 5) +# +# Input: sx = 1, sy = 1, tx = 2, ty = 2 +# Output: False +# +# Input: sx = 1, sy = 1, tx = 1, ty = 1 +# Output: True +# +# Note: +# - sx, sy, tx, ty will all be integers in the range [1, 10^9]. + +class Solution(object): + def reachingPoints(self, sx, sy, tx, ty): + """ + :type sx: int + :type sy: int + :type tx: int + :type ty: int + :rtype: bool + """ + while tx >= sx and ty >= sy: + if tx < ty: + sx, sy = sy, sx + tx, ty = ty, tx + if ty > sy: + tx %= ty + else: + return (tx - sx) % ty == 0 + + return False From 76228934533551b77939224b04def4dfdd2bcb97 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 21:55:23 +0800 Subject: [PATCH 4418/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 361f4d6e2..e74da9bfc 100644 --- a/README.md +++ b/README.md @@ -427,6 +427,9 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 754 | [Reach a Number](https://leetcode.com/problems/reach-a-number/) | [C++](./C++/reach-a-number.cpp) [Python](./Python/reach-a-number.py) | _O(logn)_ | _O(1)_ | Medium ||| 775 | [Global and Local Inversions](https://leetcode.com/problems/global-and-local-inversions/) | [C++](./C++/global-and-local-inversions.cpp) [Python](./Python/global-and-local-inversions.py) | _O(n)_ | _O(1)_ | Medium ||| 779 | [K-th Symbol in Grammar](https://leetcode.com/problems/k-th-symbol-in-grammar/) | [C++](./C++/k-th-symbol-in-grammar.cpp) [Python](./Python/k-th-symbol-in-grammar.py) | _O(1)_ | _O(1)_ | Medium || +780 | [Reaching Points](https://leetcode.com/problems/reaching-points/) | [C++](./C++/reaching-points.cpp) [Python](./Python/reaching-points.py) | _O(log(max(m, n)))_ | _O(1)_ | Hard || +781 | [Rabbits in Forest](https://leetcode.com/problems/rabbits-in-forest/) | [C++](./C++/rabbits-in-forest.cpp) [Python](./Python/rabbits-in-forest.py) | _O(n)_ | _O(n)_ | Medium || +782 | [Transform to Chessboard](https://leetcode.com/problems/transform-to-chessboard/) | [C++](./C++/transform-to-chessboard.cpp) [Python](./Python/transform-to-chessboard.py) | _O(n^2)_ | _O(n)_ | Hard || ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -549,6 +552,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 450|[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/)| [C++](./C++/delete-node-in-a-bst.cpp) [Python](./Python/delete-node-in-a-bst.py)| _O(h)_ | _O(h)_ | Medium | | | 530|[Minimum Absolute Difference in BST](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)| [C++](./C++/minimum-absolute-difference-in-bst.cpp) [Python](./Python/minimum-absolute-difference-in-bst.py)| _O(n)_ | _O(h)_ | Easy | | | 776|[Split BST](https://leetcode.com/problems/split-bst/)| [C++](./C++/split-bst.cpp) [Python](./Python/split-bst.py)| _O(n)_ | _O(h)_ | Medium | 📖 | | +783|[Minimum Distance Between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes/)| [C++](./C++/minimum-distance-between-bst-nodes.cpp) [Python](./Python/minimum-distance-between-bst-nodes.py)| _O(n)_ | _O(h)_ | Easy | | | ## Breadth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 0e365089d125a0cfe251f9863d90fa827a3dd177 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Feb 2018 21:56:53 +0800 Subject: [PATCH 4419/4971] Update transform-to-chessboard.py --- Python/transform-to-chessboard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/transform-to-chessboard.py b/Python/transform-to-chessboard.py index 9c03a9041..b6cdbfae5 100644 --- a/Python/transform-to-chessboard.py +++ b/Python/transform-to-chessboard.py @@ -1,5 +1,5 @@ # Time: O(n^2) -# Space: O(n^2) +# Space: O(n^2), used by Counter, this could be reduced to O(n) by skipping invalid input # An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, # or any 2 columns with each other. From a2716057ca953d00285e46f874952b0e2381b32b Mon Sep 17 00:00:00 2001 From: poweihuang17 Date: Mon, 12 Feb 2018 14:16:15 +0800 Subject: [PATCH 4420/4971] Add note for 646. It's similar to 435. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 361f4d6e2..2e0d0f3c7 100644 --- a/README.md +++ b/README.md @@ -744,7 +744,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/) | [C++](./C++/assign-cookies.cpp) [Python](./Python/assign-cookies.py) | _O(nlogn)_ | _O(1)_ | Easy | | 621 | [Task Scheduler](https://leetcode.com/problems/task-scheduler/) | [C++](./C++/task-scheduler.cpp) [Python](./Python/task-scheduler.py) | _O(n)_ | _O(1)_ | Medium | | 630 | [Course Schedule III](https://leetcode.com/problems/course-schedule-iii/) | [C++](./C++/course-schedule-iii.cpp) [Python](./Python/course-schedule-iii.py) | _O(nlogn)_ | _O(k)_ | Hard || -646 | [Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) | [C++](./C++/maximum-length-of-pair-chain.cpp) [Python](./Python/maximum-length-of-pair-chain.py) | _O(nlogn)_ | _O(1)_ | Medium || Scan Line +646 | [Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) | [C++](./C++/maximum-length-of-pair-chain.cpp) [Python](./Python/maximum-length-of-pair-chain.py) | _O(nlogn)_ | _O(1)_ | Medium || Scan Line. Similar to "435 Non-overlapping Intervals". 649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [C++](./C++/dota2-senate.cpp) [Python](./Python/dota2-senate.py) | _O(n)_ | _O(n)_ | Medium ||| 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | 738 | [Monotone Increasing Digits](https://leetcode.com/problems/monotone-increasing-digits/) | [C++](./C++/monotone-increasing-digits.cpp) [Python](./Python/monotone-increasing-digits.py) | _O(1)_ | _O(1)_ | Medium | | From 4d70d8f8da5493d754fe79108e39f64cff8de455 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Feb 2018 21:25:15 +0800 Subject: [PATCH 4421/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2e0d0f3c7..66f4c56dc 100644 --- a/README.md +++ b/README.md @@ -739,12 +739,12 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 392| [Is Subsequence](https://leetcode.com/problems/is-subsequence/)| [C++](./C++/is-subsequence.cpp) [Python](./Python/is-subsequence.py) | _O(n)_ | _O(1)_ | Medium || 397| [Integer Replacement](https://leetcode.com/problems/integer-replacement/)| [C++](./C++/integer-replacement.cpp) [Python](./Python/integer-replacement.py) | _O(n)_ | _O(1)_ | Medium || Math 402 | [Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./C++/remove-k-digits.cpp) [Python](./Python/remove-k-digits.py) | _O(n)_ | _O(n)_ | Medium | LintCode | -435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | +435 | [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | [C++](./C++/non-overlapping-intervals.cpp) [Python](./Python/non-overlapping-intervals.py) | _O(nlogn)_ | _O(1)_ | Medium | | Scan Line 452 | [Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | [C++](./C++/minimum-number-of-arrows-to-burst-balloons.cpp) [Python](./Python/minimum-number-of-arrows-to-burst-balloons.py) | _O(nlogn)_ | _O(1)_ | Medium | | 455 | [Assign Cookies](https://leetcode.com/problems/assign-cookies/) | [C++](./C++/assign-cookies.cpp) [Python](./Python/assign-cookies.py) | _O(nlogn)_ | _O(1)_ | Easy | | 621 | [Task Scheduler](https://leetcode.com/problems/task-scheduler/) | [C++](./C++/task-scheduler.cpp) [Python](./Python/task-scheduler.py) | _O(n)_ | _O(1)_ | Medium | | 630 | [Course Schedule III](https://leetcode.com/problems/course-schedule-iii/) | [C++](./C++/course-schedule-iii.cpp) [Python](./Python/course-schedule-iii.py) | _O(nlogn)_ | _O(k)_ | Hard || -646 | [Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) | [C++](./C++/maximum-length-of-pair-chain.cpp) [Python](./Python/maximum-length-of-pair-chain.py) | _O(nlogn)_ | _O(1)_ | Medium || Scan Line. Similar to "435 Non-overlapping Intervals". +646 | [Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) | [C++](./C++/maximum-length-of-pair-chain.cpp) [Python](./Python/maximum-length-of-pair-chain.py) | _O(nlogn)_ | _O(1)_ | Medium | similar to [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | Scan Line 649 | [Dota2 Senate](https://leetcode.com/problems/dota2-senate/) | [C++](./C++/dota2-senate.cpp) [Python](./Python/dota2-senate.py) | _O(n)_ | _O(n)_ | Medium ||| 659 | [Split Array into Consecutive Subsequences](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) | [C++](./C++/split-array-into-consecutive-subsequences.cpp) [Python](./Python/split-array-into-consecutive-subsequences.py) | _O(n)_ | _O(1)_ | Medium | | 738 | [Monotone Increasing Digits](https://leetcode.com/problems/monotone-increasing-digits/) | [C++](./C++/monotone-increasing-digits.cpp) [Python](./Python/monotone-increasing-digits.py) | _O(1)_ | _O(1)_ | Medium | | From 987f09ac0692a49cdb73d70f159c9226857c4b20 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Feb 2018 22:38:36 +0800 Subject: [PATCH 4422/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 73f38f370..69f27670c 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | +525| [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/) | [C++](./C++/longest-word-in-dictionary-through-deleting.cpp) [Python](./Python/longest-word-in-dictionary-through-deleting.py) | _O((d * l) * logd)_ | _O(1)_ | Medium | | Sort 527| [Word Abbreviation](https://leetcode.com/problems/word-abbreviation/) | [C++](./C++/word-abbreviation.cpp) [Python](./Python/word-abbreviation.py) | _O(n * l)_ ~ _O(n^2 * l^2)_ | _O(n * l)_ | Hard |📖| 539| [Minimum Time Difference](https://leetcode.com/problems/minimum-time-difference/) | [C++](./C++/minimum-time-difference.cpp) [Python](./Python/minimum-time-difference.py) | _O(nlogn)_ | _O(n)_ | Medium | | 541| [Reverse String II](https://leetcode.com/problems/reverse-string-ii/) | [C++](./C++/reverse-string-ii.cpp) [Python](./Python/reverse-string-ii.py) | _O(n)_ | _O(1)_ | Easy | | From 7dd5cf532696b0c10904b057eda04adf49fbab43 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Feb 2018 22:39:06 +0800 Subject: [PATCH 4423/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 69f27670c..cb5e8ee7e 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 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | -525| [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/) | [C++](./C++/longest-word-in-dictionary-through-deleting.cpp) [Python](./Python/longest-word-in-dictionary-through-deleting.py) | _O((d * l) * logd)_ | _O(1)_ | Medium | | Sort +524| [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/) | [C++](./C++/longest-word-in-dictionary-through-deleting.cpp) [Python](./Python/longest-word-in-dictionary-through-deleting.py) | _O((d * l) * logd)_ | _O(1)_ | Medium | | Sort 527| [Word Abbreviation](https://leetcode.com/problems/word-abbreviation/) | [C++](./C++/word-abbreviation.cpp) [Python](./Python/word-abbreviation.py) | _O(n * l)_ ~ _O(n^2 * l^2)_ | _O(n * l)_ | Hard |📖| 539| [Minimum Time Difference](https://leetcode.com/problems/minimum-time-difference/) | [C++](./C++/minimum-time-difference.cpp) [Python](./Python/minimum-time-difference.py) | _O(nlogn)_ | _O(n)_ | Medium | | 541| [Reverse String II](https://leetcode.com/problems/reverse-string-ii/) | [C++](./C++/reverse-string-ii.cpp) [Python](./Python/reverse-string-ii.py) | _O(n)_ | _O(1)_ | Easy | | From 3086051c26a90d4bf89ee2178853bb1f98757933 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Feb 2018 22:40:44 +0800 Subject: [PATCH 4424/4971] Update longest-word-in-dictionary-through-deleting.cpp --- C++/longest-word-in-dictionary-through-deleting.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/longest-word-in-dictionary-through-deleting.cpp b/C++/longest-word-in-dictionary-through-deleting.cpp index f2e3f438d..4be187803 100644 --- a/C++/longest-word-in-dictionary-through-deleting.cpp +++ b/C++/longest-word-in-dictionary-through-deleting.cpp @@ -1,4 +1,4 @@ -// Time: O(dlogd) +// Time: O((d * l) * logd), l is the average length of words // Space: O(1) class Solution { From 8b28dbbf9f3ae761b7078cc54ff9abafecc8de04 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Feb 2018 22:41:07 +0800 Subject: [PATCH 4425/4971] Update longest-word-in-dictionary-through-deleting.py --- Python/longest-word-in-dictionary-through-deleting.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/longest-word-in-dictionary-through-deleting.py b/Python/longest-word-in-dictionary-through-deleting.py index 7b69a39d0..7437ca338 100644 --- a/Python/longest-word-in-dictionary-through-deleting.py +++ b/Python/longest-word-in-dictionary-through-deleting.py @@ -1,4 +1,4 @@ -# Time: O(dlogd) +# Time: O((d * l) * logd), l is the average length of words # Space: O(1) # Given a string and a string dictionary, From 4649ea618a4f41f5a2f54eb73806d3e1b98e5e00 Mon Sep 17 00:00:00 2001 From: Artem Muterko Date: Wed, 14 Feb 2018 16:03:01 +0200 Subject: [PATCH 4426/4971] Add another solution for 'Number complement' problem --- Python/number-complement.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Python/number-complement.py b/Python/number-complement.py index 5e628b8e6..97d814779 100644 --- a/Python/number-complement.py +++ b/Python/number-complement.py @@ -32,3 +32,10 @@ def findComplement(self, num): while i <= num: i <<= 1 return (i - 1) ^ num + + +class Solution3(object): + def findComplement(self, num): + bits = '{0:b}'.format(num) + complement_bits = ''.join('1' if bit == '0' else '0' for bit in bits) + return int(complement_bits, 2) From 541d4080821692ed879bfee47eb0ce1a8b278dac Mon Sep 17 00:00:00 2001 From: Artem Muterko Date: Wed, 14 Feb 2018 18:39:24 +0200 Subject: [PATCH 4427/4971] Add alternative solution for 'Reverse words in string III' --- Python/reverse-words-in-a-string-iii.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Python/reverse-words-in-a-string-iii.py b/Python/reverse-words-in-a-string-iii.py index 31947e6ae..973b55d0b 100644 --- a/Python/reverse-words-in-a-string-iii.py +++ b/Python/reverse-words-in-a-string-iii.py @@ -26,3 +26,9 @@ def reverse(s, begin, end): reverse(s, i, j) i = j + 1 return "".join(s) + + +class Solution2(object): + def reverseWords(self, s): + reversed_words = [word[::-1] for word in s.split(' ')] + return ' '.join(reversed_words) From 19fae1fc2703aa24f9d26ad1426e1ac3c1acd232 Mon Sep 17 00:00:00 2001 From: Artem Muterko Date: Wed, 14 Feb 2018 18:58:14 +0200 Subject: [PATCH 4428/4971] Add alternative solution for 'Keyboard Row' problem --- Python/keyboard-row.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Python/keyboard-row.py b/Python/keyboard-row.py index 13314b621..9291dcf63 100644 --- a/Python/keyboard-row.py +++ b/Python/keyboard-row.py @@ -34,3 +34,18 @@ def findWords(self, words): else: result.append(word) return result + + +class Solution2(object): + def findWords(self, words): + """ + :type words: List[str] + :rtype: List[str] + """ + keyboard_rows = ['qwertyuiop', 'asdfghjkl', 'zxcvbnm'] + single_row_words = [] + for word in words: + for row in keyboard_rows: + if all(letter in row for letter in word.lower()): + single_row_words.append(word) + return single_row_words From 5a1c17751250cfce66c71810cc40a382c2620ad6 Mon Sep 17 00:00:00 2001 From: Artem Muterko Date: Fri, 16 Feb 2018 12:36:29 +0200 Subject: [PATCH 4429/4971] Add a bit more readable solution for 'Toeplitz matrix' problem --- Python/toeplitz-matrix.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Python/toeplitz-matrix.py b/Python/toeplitz-matrix.py index 605447981..fbabbb154 100644 --- a/Python/toeplitz-matrix.py +++ b/Python/toeplitz-matrix.py @@ -38,3 +38,18 @@ def isToeplitzMatrix(self, matrix): return all(i == 0 or j == 0 or matrix[i-1][j-1] == val for i, row in enumerate(matrix) for j, val in enumerate(row)) + + +class Solution2(object): + def isToeplitzMatrix(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: bool + """ + for row_index, row in enumerate(matrix): + for digit_index, digit in enumerate(row): + if not row_index or not digit_index: + continue + if matrix[row_index - 1][digit_index - 1] != digit: + return False + return True From 80db7fe0d12642b32dfa27cce74eb85f973121fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Feb 2018 22:35:11 +0800 Subject: [PATCH 4430/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index cb5e8ee7e..2ce8afbcd 100644 --- a/README.md +++ b/README.md @@ -354,6 +354,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 447| [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/) | [C++](./C++/number-of-boomerangs.cpp) [Python](./Python/number-of-boomerangs.py) | _O(n^2)_ | _O(n)_ | Easy || 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || +523| [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) |[C++](./C++/continuous-subarray-sum.cpp)  [Python](./Python/continuous-subarray-sum.py) | _O(n)_ | _O(k)_ | Medium         | | 532| [K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) |[C++](./C++/k-diff-pairs-in-an-array.cpp) [Python](./Python/k-diff-pairs-in-an-array.py) | _O(n)_ | _O(n)_ | Easy | | 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | 560| [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) |[C++](./C++/subarray-sum-equals-k.cpp) [Python](./Python/subarray-sum-equals-k.py) | _O(n)_ | _O(n)_ | Medium | | From fdc692f05dd93c27e9a891b42bdb0d2ccdc84b71 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Feb 2018 22:37:01 +0800 Subject: [PATCH 4431/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2ce8afbcd..7f96c5759 100644 --- a/README.md +++ b/README.md @@ -354,7 +354,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 447| [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/) | [C++](./C++/number-of-boomerangs.cpp) [Python](./Python/number-of-boomerangs.py) | _O(n^2)_ | _O(n)_ | Easy || 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || -523| [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) |[C++](./C++/continuous-subarray-sum.cpp)  [Python](./Python/continuous-subarray-sum.py) | _O(n)_ | _O(k)_ | Medium         | | +523| [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) | [C++](./C++/continuous-subarray-sum.cpp)  [Python](./Python/continuous-subarray-sum.py) | _O(n)_ | _O(k)_ | Medium || 532| [K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) |[C++](./C++/k-diff-pairs-in-an-array.cpp) [Python](./Python/k-diff-pairs-in-an-array.py) | _O(n)_ | _O(n)_ | Easy | | 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | 560| [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) |[C++](./C++/subarray-sum-equals-k.cpp) [Python](./Python/subarray-sum-equals-k.py) | _O(n)_ | _O(n)_ | Medium | | From 0ea57145a0f4c0bd4efe634b754b6c9a00377e75 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 17 Feb 2018 22:37:50 +0800 Subject: [PATCH 4432/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7f96c5759..663b4adcc 100644 --- a/README.md +++ b/README.md @@ -354,8 +354,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 447| [Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/) | [C++](./C++/number-of-boomerangs.cpp) [Python](./Python/number-of-boomerangs.py) | _O(n^2)_ | _O(n)_ | Easy || 454| [4Sum II](https://leetcode.com/problems/4sum-ii/) | [C++](./C++/4sum-ii.cpp) [Python](./Python/4sum-ii.py) | _O(n^2)_ | _O(n^2)_ | Medium || 473| [Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) | [C++](./C++/matchsticks-to-square.cpp) [Python](./Python/matchsticks-to-square.py) | _O(n * s * 2^n)_ | _O(n * (2^n + s))_ | Medium || -523| [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) | [C++](./C++/continuous-subarray-sum.cpp)  [Python](./Python/continuous-subarray-sum.py) | _O(n)_ | _O(k)_ | Medium || -532| [K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) |[C++](./C++/k-diff-pairs-in-an-array.cpp) [Python](./Python/k-diff-pairs-in-an-array.py) | _O(n)_ | _O(n)_ | Easy | | +523| [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) | [C++](./C++/continuous-subarray-sum.cpp) [Python](./Python/continuous-subarray-sum.py) | _O(n)_ | _O(k)_ | Medium || +532| [K-diff Pairs in an Array](https://leetcode.com/problems/k-diff-pairs-in-an-array/) |[C++](./C++/k-diff-pairs-in-an-array.cpp) [Python](./Python/k-diff-pairs-in-an-array.py) | _O(n)_ | _O(n)_ | Easy | | 554| [Brick Wall](https://leetcode.com/problems/brick-wall/) |[C++](./C++/brick-wall.cpp) [Python](./Python/brick-wall.py) | _O(n)_ | _O(m)_ | Medium | | 560| [Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) |[C++](./C++/subarray-sum-equals-k.cpp) [Python](./Python/subarray-sum-equals-k.py) | _O(n)_ | _O(n)_ | Medium | | 561| [Array Partition I](https://leetcode.com/problems/array-partition-i/) |[C++](./C++/array-partition-i.cpp) [Python](./Python/array-partition-i.py) | _O(r)_ | _O(r)_ | Easy | | From ce38e4789a0140f7713b233500220514cf0c5dd1 Mon Sep 17 00:00:00 2001 From: Artem Muterko Date: Sun, 18 Feb 2018 15:55:59 +0200 Subject: [PATCH 4433/4971] Add alternative solution for 'Array Partition' problem --- Python/array-partition-i.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Python/array-partition-i.py b/Python/array-partition-i.py index 65e190c22..8bc7fd47f 100644 --- a/Python/array-partition-i.py +++ b/Python/array-partition-i.py @@ -42,3 +42,13 @@ def arrayPairSum(self, nums): for i in xrange(0, len(nums), 2): result += nums[i] return result + + +class Solution3(object): + def arrayPairSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums = sorted(nums) + return sum([nums[i] for i in range(0, len(nums), 2)]) From 3b3fb2d7186d71e50e0f1b7e6fe74be17b932d7f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Feb 2018 23:10:10 +0800 Subject: [PATCH 4434/4971] Create k-th-smallest-prime-fraction.cpp --- C++/k-th-smallest-prime-fraction.cpp | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C++/k-th-smallest-prime-fraction.cpp diff --git a/C++/k-th-smallest-prime-fraction.cpp b/C++/k-th-smallest-prime-fraction.cpp new file mode 100644 index 000000000..5e1ba7f99 --- /dev/null +++ b/C++/k-th-smallest-prime-fraction.cpp @@ -0,0 +1,44 @@ +// Time: O(nlogr) +// Space: O(1) + +class Solution { +public: + vector kthSmallestPrimeFraction(vector& A, int K) { + vector result; + double left = 0.0, right = 1.0; + while (right - left > 1e-8) { + double mid = left + (right - left) / 2.0; + if (check(mid, A, K, &result)) { + right = mid; + } else { + left = mid; + } + if (!result.empty()) { + break; + } + } + return result; + } + +private: + bool check(double mid, const vector& A, int K, vector *result) { + vector tmp(2); + int count = 0; + for (int i = 0, j = 0; i < A.size(); ++i) { + for (; j < A.size(); ++j) { + if (i < j && A[i] < A[j] * mid) { + if (tmp[0] == 0 || tmp[0] * A[j] < tmp[1] * A[i]) { + tmp[0] = A[i]; + tmp[1] = A[j]; + } + break; + } + } + count += A.size() - j; + } + if (count == K) { + *result = move(tmp); + } + return count >= K; + } +}; From 82130e301e991626d46f969d9ad466046d2c6014 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Feb 2018 23:35:12 +0800 Subject: [PATCH 4435/4971] Create k-th-smallest-prime-fraction.py --- Python/k-th-smallest-prime-fraction.py | 61 ++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/k-th-smallest-prime-fraction.py diff --git a/Python/k-th-smallest-prime-fraction.py b/Python/k-th-smallest-prime-fraction.py new file mode 100644 index 000000000..9461523c4 --- /dev/null +++ b/Python/k-th-smallest-prime-fraction.py @@ -0,0 +1,61 @@ +# Time: O(logr * nlogn) +# Space: O(1) + +# A sorted list A contains 1, plus some number of primes. +# Then, for every p < q in the list, we consider the fraction p/q. +# +# What is the K-th smallest fraction considered? +# Return your answer as an array of ints, where answer[0] = p and answer[1] = q. +# +# Examples: +# Input: A = [1, 2, 3, 5], K = 3 +# Output: [2, 5] +# Explanation: +# The fractions to be considered in sorted order are: +# 1/5, 1/3, 2/5, 1/2, 3/5, 2/3. +# The third fraction is 2/5. +# +# Input: A = [1, 7], K = 1 +# Output: [1, 7] +# +# Note: +# - A will have length between 2 and 2000. +# - Each A[i] will be between 1 and 30000. +# - K will be between 1 and A.length * (A.length + 1) / 2. + +class Solution(object): + def kthSmallestPrimeFraction(self, A, K): + """ + :type A: List[int] + :type K: int + :rtype: List[int] + """ + def check(mid, A, K, result): + tmp = [0]*2 + count = 0 + j = 0 + for i in xrange(len(A)): + while j < len(A): + if i < j and A[i] < A[j]*mid: + if tmp[0] == 0 or \ + tmp[0]*A[j] < tmp[1]*A[i]: + tmp[0] = A[i] + tmp[1] = A[j] + break + j += 1 + count += len(A)-j + if count == K: + result[:] = tmp + return count >= K + + result = [] + left, right = 0.0, 1.0 + while right-left > 1e-8: + mid = left + (right-left) / 2.0 + if check(mid, A, K, result): + right = mid + else: + left = mid + if result: + break + return result From 99696f6fa26fe271ec0f7b178dd400ddabb7bd17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Feb 2018 23:36:54 +0800 Subject: [PATCH 4436/4971] Update k-th-smallest-prime-fraction.py --- Python/k-th-smallest-prime-fraction.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/k-th-smallest-prime-fraction.py b/Python/k-th-smallest-prime-fraction.py index 9461523c4..56899ccf2 100644 --- a/Python/k-th-smallest-prime-fraction.py +++ b/Python/k-th-smallest-prime-fraction.py @@ -1,4 +1,4 @@ -# Time: O(logr * nlogn) +# Time: O(nlogr) # Space: O(1) # A sorted list A contains 1, plus some number of primes. From 46296cf5b714fe6a140fcd75c48e110cf975b782 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Feb 2018 23:41:11 +0800 Subject: [PATCH 4437/4971] Update array-partition-i.py --- Python/array-partition-i.py | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/Python/array-partition-i.py b/Python/array-partition-i.py index 8bc7fd47f..78c7bbda0 100644 --- a/Python/array-partition-i.py +++ b/Python/array-partition-i.py @@ -29,6 +29,7 @@ def arrayPairSum(self, nums): r = (lookup[i-LEFT] + r) % 2 return result + # Time: O(nlogn) # Space: O(1) class Solution2(object): @@ -38,17 +39,4 @@ def arrayPairSum(self, nums): :rtype: int """ nums.sort() - result = 0 - for i in xrange(0, len(nums), 2): - result += nums[i] - return result - - -class Solution3(object): - def arrayPairSum(self, nums): - """ - :type nums: List[int] - :rtype: int - """ - nums = sorted(nums) - return sum([nums[i] for i in range(0, len(nums), 2)]) + return sum([nums[i] for i in xrange(0, len(nums), 2)]) From 387958e328ec108729ea352a2a6cd63e8d5ce314 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Feb 2018 23:45:28 +0800 Subject: [PATCH 4438/4971] Update array-partition-i.py --- Python/array-partition-i.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Python/array-partition-i.py b/Python/array-partition-i.py index 78c7bbda0..8c91e46f4 100644 --- a/Python/array-partition-i.py +++ b/Python/array-partition-i.py @@ -39,4 +39,19 @@ def arrayPairSum(self, nums): :rtype: int """ nums.sort() - return sum([nums[i] for i in xrange(0, len(nums), 2)]) + result = 0 + for i in xrange(0, len(nums), 2): + result += nums[i] + return result + + +# Time: O(nlogn) +# Space: O(n) +class Solution3(object): + def arrayPairSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums = sorted(nums) + return sum([nums[i] for i in range(0, len(nums), 2)]) From 791be4c1ed219a107c8ff3437380ab5191317eb5 Mon Sep 17 00:00:00 2001 From: Artem Muterko Date: Sun, 18 Feb 2018 17:54:55 +0200 Subject: [PATCH 4439/4971] Add alternative solution for 'Encode and decode tiny url' problem --- Python/encode-and-decode-tinyurl.py | 33 ++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/Python/encode-and-decode-tinyurl.py b/Python/encode-and-decode-tinyurl.py index b112e211f..5bfe41982 100644 --- a/Python/encode-and-decode-tinyurl.py +++ b/Python/encode-and-decode-tinyurl.py @@ -10,6 +10,7 @@ # You just need to ensure that a URL can be encoded to a tiny URL # and the tiny URL can be decoded to the original URL. + class Codec: def __init__(self): self.__random_length = 6 @@ -17,7 +18,6 @@ def __init__(self): self.__alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" self.__lookup = {} - def encode(self, longUrl): """Encodes a URL to a shortened URL. @@ -35,7 +35,6 @@ def getRand(): key = getRand() self.__lookup[key] = longUrl return self.__tiny_url + key - def decode(self, shortUrl): """Decodes a shortened URL to its original URL. @@ -44,7 +43,35 @@ def decode(self, shortUrl): :rtype: str """ return self.__lookup[shortUrl[len(self.__tiny_url):]] - + + +from hashlib import sha256 + + +class Codec2: + + def __init__(self): + self._cache = {} + self.url = 'http://tinyurl.com/' + + def encode(self, long_url): + """Encodes a URL to a shortened URL. + + :type long_url: str + :rtype: str + """ + key = sha256(long_url.encode()).hexdigest()[:6] + self._cache[key] = long_url + return self.url + key + + def decode(self, short_url): + """Decodes a shortened URL to its original URL. + + :type short_url: str + :rtype: str + """ + key = short_url.replace(self.url, '') + return self._cache[key] # Your Codec object will be instantiated and called as such: # codec = Codec() From 4cc3b6948c43c35b6b42c333c76dd0222de82efa Mon Sep 17 00:00:00 2001 From: Artem Muterko Date: Sun, 18 Feb 2018 20:26:34 +0200 Subject: [PATCH 4440/4971] Refactor 'Distribute candies' solution --- Python/distribute-candies.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/distribute-candies.py b/Python/distribute-candies.py index 922454a98..a04064883 100644 --- a/Python/distribute-candies.py +++ b/Python/distribute-candies.py @@ -25,13 +25,13 @@ # The length of the given array is in range [2, 10,000], and will be even. # The number in given array is in range [-100,000, 100,000]. + class Solution(object): + def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ - lookup = set() - for candy in candies: - lookup.add(candy) + lookup = set(candies) return min(len(lookup), len(candies)/2) From 634e206775b765d9f5218e2b5557d89aa6526a2e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 02:37:18 +0800 Subject: [PATCH 4441/4971] Create cheapest-flights-within-k-stops.cpp --- C++/cheapest-flights-within-k-stops.cpp | 34 +++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/cheapest-flights-within-k-stops.cpp diff --git a/C++/cheapest-flights-within-k-stops.cpp b/C++/cheapest-flights-within-k-stops.cpp new file mode 100644 index 000000000..7a8e22cda --- /dev/null +++ b/C++/cheapest-flights-within-k-stops.cpp @@ -0,0 +1,34 @@ +// Time: O(|E| + |V|log|V|) +// Space: O(|E| + |V|) + +class Solution { +public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int K) { + using P = pair; + unordered_map> adj; + for (const auto& flight : flights) { + int u, v, w; + tie(u, v, w) = make_tuple(flight[0], flight[1], flight[2]); + adj[u].emplace_back(v, w); + } + + using T = tuple; + priority_queue, greater> min_heap; + min_heap.emplace(0, src, K + 1); + while (!min_heap.empty()) { + int result, u, k; + tie(result, u, k) = min_heap.top(); min_heap.pop(); + if (u == dst) { + return result; + } + if (k > 0) { + for (const auto& kvp : adj[u]) { + int v, w; + tie(v, w) = kvp; + min_heap.emplace(result + w, v, k - 1); + } + } + } + return -1; + } +}; From 0edc9f974ea0c3f735ebcc9178b223e69b2372a9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 02:42:49 +0800 Subject: [PATCH 4442/4971] Create cheapest-flights-within-k-stops.py --- Python/cheapest-flights-within-k-stops.py | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/cheapest-flights-within-k-stops.py diff --git a/Python/cheapest-flights-within-k-stops.py b/Python/cheapest-flights-within-k-stops.py new file mode 100644 index 000000000..906bf1fd1 --- /dev/null +++ b/Python/cheapest-flights-within-k-stops.py @@ -0,0 +1,55 @@ +# Time: O(|E| + |V|log|V|) +# Space: O(|E| + |V|) + +# There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w. +# +# Now given all the cities and fights, together with starting city src and the destination dst, +# your task is to find the cheapest price from src to dst with up to k stops. +# If there is no such route, output -1. +# +# Example 1: +# Input: +# n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]] +# src = 0, dst = 2, k = 1 +# Output: 200 +# Explanation: +# The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture. +# +# Example 2: +# Input: +# n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]] +# src = 0, dst = 2, k = 0 +# Output: 500 +# +# Explanation: +# The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture. +# Note: +# - The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1. +# - The size of flights will be in range [0, n * (n - 1) / 2]. +# - The format of each flight will be (src, dst, price). +# - The price of each flight will be in the range [1, 10000]. +# - k is in the range of [0, n - 1]. +# - There will not be any duplicated flights or self cycles. + +class Solution(object): + def findCheapestPrice(self, n, flights, src, dst, K): + """ + :type n: int + :type flights: List[List[int]] + :type src: int + :type dst: int + :type K: int + :rtype: int + """ + adj = collections.defaultdict(list) + for u, v, w in flights: + adj[u].append((v, w)) + min_heap = [(0, src, K+1)] + while min_heap: + result, u, k = heapq.heappop(min_heap) + if u == dst: + return result + if k > 0: + for v, w in adj[u]: + heapq.heappush(min_heap, (result+w, v, k-1)) + return -1 From 4050de5db433c740017d131a9c3d4fa4f8768404 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 13:06:49 +0800 Subject: [PATCH 4443/4971] Update k-th-smallest-prime-fraction.py --- Python/k-th-smallest-prime-fraction.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/k-th-smallest-prime-fraction.py b/Python/k-th-smallest-prime-fraction.py index 56899ccf2..110ec687c 100644 --- a/Python/k-th-smallest-prime-fraction.py +++ b/Python/k-th-smallest-prime-fraction.py @@ -1,6 +1,9 @@ # Time: O(nlogr) # Space: O(1) +# Another cool O(n) solution by using quick select with median of median could be found here: +# https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/115545/O(n) + # A sorted list A contains 1, plus some number of primes. # Then, for every p < q in the list, we consider the fraction p/q. # From 49193f87cf63459add32fc83a5be34bce1e086d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 13:07:29 +0800 Subject: [PATCH 4444/4971] Update k-th-smallest-prime-fraction.cpp --- C++/k-th-smallest-prime-fraction.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/C++/k-th-smallest-prime-fraction.cpp b/C++/k-th-smallest-prime-fraction.cpp index 5e1ba7f99..9ed6dda15 100644 --- a/C++/k-th-smallest-prime-fraction.cpp +++ b/C++/k-th-smallest-prime-fraction.cpp @@ -1,6 +1,9 @@ // Time: O(nlogr) // Space: O(1) +// Another cool O(n) solution by using quick select with median of median could be found here: +// https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/115545/O(n) + class Solution { public: vector kthSmallestPrimeFraction(vector& A, int K) { From 0710a8db3748b3b9cc3d5507cb24da20d632759b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 13:43:08 +0800 Subject: [PATCH 4445/4971] Create is-graph-bipartite.cpp --- C++/is-graph-bipartite.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/is-graph-bipartite.cpp diff --git a/C++/is-graph-bipartite.cpp b/C++/is-graph-bipartite.cpp new file mode 100644 index 000000000..b6041c969 --- /dev/null +++ b/C++/is-graph-bipartite.cpp @@ -0,0 +1,28 @@ +// Time: O(|V| + |E|) +// Space: O(|V|) + +class Solution { +public: + bool isBipartite(vector>& graph) { + unordered_map color; + for (int node = 0; node < graph.size(); ++node) { + if (color.count(node)) { + continue; + } + vector stack{node}; + color[node] = 0; + while (!stack.empty()) { + int curr = stack.back(); stack.pop_back(); + for (const auto& neighbor : graph[curr]) { + if (!color.count(neighbor)) { + stack.emplace_back(neighbor); + color[neighbor] = color[curr] ^ 1; + } else if (color[neighbor] == color[curr]) { + return false; + } + } + } + } + return true; + } +}; From 6193786bb2307550ab9dfb9c218f6d8b3f407156 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 13:43:51 +0800 Subject: [PATCH 4446/4971] Create is-graph-bipartite.py --- Python/is-graph-bipartite.py | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Python/is-graph-bipartite.py diff --git a/Python/is-graph-bipartite.py b/Python/is-graph-bipartite.py new file mode 100644 index 000000000..213d8e372 --- /dev/null +++ b/Python/is-graph-bipartite.py @@ -0,0 +1,63 @@ +# Time: O(|V| + |E|) +# Space: O(|V|) + +# Given a graph, return true if and only if it is bipartite. +# +# Recall that a graph is bipartite if we can split it's set of nodes into +# two independent subsets A and B such that every edge in the graph has +# one node in A and another node in B. +# +# The graph is given in the following form: graph[i] is a list of indexes j +# for which the edge between nodes i and j exists. +# Each node is an integer between 0 and graph.length - 1. +# There are no self edges or parallel edges: graph[i] does not contain i, +# and it doesn't contain any element twice. +# +# Example 1: +# Input: [[1,3], [0,2], [1,3], [0,2]] +# Output: true +# Explanation: +# The graph looks like this: +# 0----1 +# | | +# | | +# 3----2 +# We can divide the vertices into two groups: {0, 2} and {1, 3}. +# +# Example 2: +# Input: [[1,2,3], [0,2], [0,1,3], [0,2]] +# Output: false +# Explanation: +# The graph looks like this: +# 0----1 +# | \ | +# | \ | +# 3----2 +# We cannot find a way to divide the set of nodes into two independent ubsets. +# +# Note: +# - graph will have length in range [1, 100]. +# - graph[i] will contain integers in range [0, graph.length - 1]. +# - graph[i] will not contain i or duplicate values. + +class Solution(object): + def isBipartite(self, graph): + """ + :type graph: List[List[int]] + :rtype: bool + """ + color = {} + for node in xrange(len(graph)): + if node in color: + continue + stack = [node] + color[node] = 0 + while stack: + curr = stack.pop() + for neighbor in graph[curr]: + if neighbor not in color: + stack.append(neighbor) + color[neighbor] = color[curr] ^ 1 + elif color[neighbor] == color[curr]: + return False + return True From 24581953cbeb34366b885541de19bd66942a5e96 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 13:58:56 +0800 Subject: [PATCH 4447/4971] Create letter-case-permutation.cpp --- C++/letter-case-permutation.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/letter-case-permutation.cpp diff --git a/C++/letter-case-permutation.cpp b/C++/letter-case-permutation.cpp new file mode 100644 index 000000000..06f1ddf2d --- /dev/null +++ b/C++/letter-case-permutation.cpp @@ -0,0 +1,24 @@ +// Time: O(n * 2^n) +// Space: O(1) + +class Solution { +public: + vector letterCasePermutation(string S) { + vector result{""}; + for (const auto& c : S) { + if (isalpha(c)) { + const auto& size = result.size(); + for (int i = 0; i < size; ++i) { + result.emplace_back(result[i]); + result.back() += toupper(c); + result[i] += tolower(c); + } + } else { + for (auto &s : result) { + s += c; + } + } + } + return result; + } +}; From 5cd212c9d4095e5bf2bc63788ab26fc306dde5e0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 14:08:03 +0800 Subject: [PATCH 4448/4971] Create letter-case-permutation.py --- Python/letter-case-permutation.py | 37 +++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/letter-case-permutation.py diff --git a/Python/letter-case-permutation.py b/Python/letter-case-permutation.py new file mode 100644 index 000000000..34ef2b4f9 --- /dev/null +++ b/Python/letter-case-permutation.py @@ -0,0 +1,37 @@ +# Time: O(n * 2^n) +# Space: O(1) + +# Given a string S, we can transform every letter individually to be lowercase +# or uppercase to create another string. Return a list of all possible strings we could create. +# +# Examples: +# Input: S = "a1b2" +# Output: ["a1b2", "a1B2", "A1b2", "A1B2"] +# +# Input: S = "3z4" +# Output: ["3z4", "3Z4"] +# +# Input: S = "12345" +# Output: ["12345"] +# +# Note: +# - S will be a string with length at most 12. +# - S will consist only of letters or digits. + +class Solution(object): + def letterCasePermutation(self, S): + """ + :type S: str + :rtype: List[str] + """ + result = [[]] + for c in S: + if c.isalpha(): + for i in xrange(len(result)): + result.append(result[i][:]) + result[-1].append(c.upper()) + result[i].append(c.lower()) + else: + for s in result: + s.append(c) + return map("".join, result) From afa5d1cef9513f258ec2f0c3c358df193d97b8c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 14:09:21 +0800 Subject: [PATCH 4449/4971] Update letter-case-permutation.py --- Python/letter-case-permutation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/letter-case-permutation.py b/Python/letter-case-permutation.py index 34ef2b4f9..93b33616a 100644 --- a/Python/letter-case-permutation.py +++ b/Python/letter-case-permutation.py @@ -1,5 +1,5 @@ # Time: O(n * 2^n) -# Space: O(1) +# Space: O(n * 2^n) # Given a string S, we can transform every letter individually to be lowercase # or uppercase to create another string. Return a list of all possible strings we could create. From 80889986cd4742d7c63be46447b0097eac5bd745 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 14:12:45 +0800 Subject: [PATCH 4450/4971] Update letter-case-permutation.py --- Python/letter-case-permutation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/letter-case-permutation.py b/Python/letter-case-permutation.py index 93b33616a..07fe2a9c0 100644 --- a/Python/letter-case-permutation.py +++ b/Python/letter-case-permutation.py @@ -29,8 +29,8 @@ def letterCasePermutation(self, S): if c.isalpha(): for i in xrange(len(result)): result.append(result[i][:]) - result[-1].append(c.upper()) result[i].append(c.lower()) + result[-1].append(c.upper()) else: for s in result: s.append(c) From d98ba1ba91afade4ecbfed1740bcb26b5b7fcc5e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Feb 2018 14:13:14 +0800 Subject: [PATCH 4451/4971] Update letter-case-permutation.cpp --- C++/letter-case-permutation.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/letter-case-permutation.cpp b/C++/letter-case-permutation.cpp index 06f1ddf2d..9214affd3 100644 --- a/C++/letter-case-permutation.cpp +++ b/C++/letter-case-permutation.cpp @@ -10,8 +10,8 @@ class Solution { const auto& size = result.size(); for (int i = 0; i < size; ++i) { result.emplace_back(result[i]); - result.back() += toupper(c); result[i] += tolower(c); + result.back() += toupper(c); } } else { for (auto &s : result) { From 95deadac52814613325e113d8dcf29b9ea167e23 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Feb 2018 22:05:30 +0800 Subject: [PATCH 4452/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 663b4adcc..0330b2b35 100644 --- a/README.md +++ b/README.md @@ -540,6 +540,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 719 | [Find K-th Smallest Pair Distance](https://leetcode.com/problems/find-k-th-smallest-pair-distance/) | [C++](./C++/find-k-th-smallest-pair-distance.cpp) [Python](./Python/find-k-th-smallest-pair-distance.py) | _O(nlogn + nlogw)_ | _O(1)_ | Hard | | 744 | [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/) | [C++](./C++/find-smallest-letter-greater-than-target.cpp) [Python](./Python/find-smallest-letter-greater-than-target.py) | _O(logn)_ | _O(1)_ | Easy | | 774 | [Minimize Max Distance to Gas Station](https://leetcode.com/problems/minimize-max-distance-to-gas-station/) | [C++](./C++/minimize-max-distance-to-gas-station.cpp) [Python](./Python/minimize-max-distance-to-gas-station.py) | _O(nlogr)_ | _O(1)_ | Hard | | +786 | [K-th Smallest Prime Fraction](https://leetcode.com/problems/k-th-smallest-prime-fraction/) | [C++](./C++/k-th-smallest-prime-fraction.cpp) [Python](./Python/k-th-smallest-prime-fraction.py) | _O(nlogr)_ | _O(1)_ | Hard | | ## Binary Search Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -582,6 +583,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O(\|E\| + \|V\|log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | 752|[Open the Lock](https://leetcode.com/problems/open-the-lock/)| [C++](./C++/open-the-lock.cpp) [Python](./Python/open-the-lock.py)| _O(k * n^k + d)_ | _O(k * n^k + d)_ | Medium | | | 773|[Sliding Puzzle](https://leetcode.com/problems/sliding-puzzle/)| [C++](./C++/sliding-puzzle.cpp) [Python](./Python/sliding-puzzle.py)| _O((m * n) * (m * n)!)_ | _O((m * n) * (m * n)!)_ | Hard | | `A* Search Algorithm` | +787|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| [C++](./C++/cheapest-flights-within-k-stops.cpp) [Python](./Python/cheapest-flights-within-k-stops.py)| _O(\|E\| + \|V\|log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -616,6 +618,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 749| [Contain Virus](https://leetcode.com/problems/contain-virus/) | [C++](./C++/contain-virus.cpp) [Python](./Python/contain-virus.py) | _O((m * n)^(4/3))_ | _O(m * n)_ | Hard || Simulation| 753| [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [C++](./C++/cracking-the-safe.cpp) [Python](./Python/cracking-the-safe.py) | _O(k^n)_ | _O(k^n)_ | Hard || `de Bruijn sequences`, `Lyndon word` | 756| [Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix/) | [C++](./C++/pyramid-transition-matrix.cpp) [Python](./Python/pyramid-transition-matrix.py) | _O(a^b)_ | _O(a^b)_ | Medium ||| +785| [Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/) | [C++](./C++/is-graph-bipartite.cpp) [Python](./Python/is-graph-bipartite.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium ||| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -650,6 +653,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 679| [24 Game](https://leetcode.com/problems/24-game/) | [C++](./C++/24-game.cpp) [Python](./Python/24-game.py) | _O(1)_ | _O(1)_ | Hard || DFS 698| [Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) | [C++](./C++/partition-to-k-equal-sum-subsets.cpp) [Python](./Python/partition-to-k-equal-sum-subsets.py) | _O(n * 2^n)_ | _O(2^n)_ | Medium || DFS, DP, Memoization 718 | [Maximum Length of Repeated Subarray](https://leetcode.com/problems/maximum-length-of-repeated-subarray/) | [C++](./C++/maximum-length-of-repeated-subarray.cpp) [Python](./Python/maximum-length-of-repeated-subarray.py) | _O(m * n)_ | _O(min(m, n))_ | Medium || DP, Hash, Binary Search +784| [Letter Case Permutation](https://leetcode.com/problems/letter-case-permutation/) | [C++](./C++/letter-case-permutation.cpp) [Python](./Python/letter-case-permutation.py) | _O(n * 2^n)_ | _O(1)_ | Easy || ## Dynamic Programming | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From c5cb8cbeb8d171bb91b10f154f79c17adfadce12 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 21 Feb 2018 23:24:17 +0800 Subject: [PATCH 4453/4971] Update two-sum.go --- Golang/two-sum.go | 41 ++++++++--------------------------------- 1 file changed, 8 insertions(+), 33 deletions(-) diff --git a/Golang/two-sum.go b/Golang/two-sum.go index bdf987986..32950b739 100644 --- a/Golang/two-sum.go +++ b/Golang/two-sum.go @@ -1,37 +1,12 @@ -package leetcode +package twoSum -import "sort" - -// Given an array of integers, return indices of the two numbers -// such that they add up to a specific target. -// You may assume that each input would have exactly one solution. -// -// Example: -// Given nums = [2, 7, 11, 15], target = 9, -// Because nums[0] + nums[1] = 2 + 7 = 9, -// return [0, 1]. -func TwoSum(nums []int, target int) []int { - - indexs := make([]int, 2) - hash := map[int]int{} - - for i := range nums { - hash[target-nums[i]] = i - } - - for i := range nums { - index, ok := hash[nums[i]] - if ok { - if i == index { - continue - } - indexs[0] = index - indexs[1] = i - sort.Ints(indexs) - break +func twoSum(nums []int, target int) []int { + lookup := make(map[int]int) + for i, num := range nums { + if j, ok := lookup[target-num]; ok { + return []int{j, i} } - continue + lookup[nums[i]] = i } - - return indexs + return nil } From dc2b68ff4022b9caa4674fd874a3fe4b2157e174 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Feb 2018 23:18:48 +0800 Subject: [PATCH 4454/4971] Update add-two-numbers.go --- Golang/add-two-numbers.go | 82 +++++++++++++-------------------------- 1 file changed, 28 insertions(+), 54 deletions(-) diff --git a/Golang/add-two-numbers.go b/Golang/add-two-numbers.go index a344cc633..105e54a81 100644 --- a/Golang/add-two-numbers.go +++ b/Golang/add-two-numbers.go @@ -1,62 +1,36 @@ -package leetcode - -// ListNode represents a non-negative number. -// You are given two linked lists representing two non-negative numbers. -// The digits are stored in reverse order and each of their nodes contain a single digit. -// Add the two numbers and return it as a linked list. -// -// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) -// Output: 7 -> 0 -> 8 -type ListNode struct { - Val int - Next *ListNode -} - +// Time: O(n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { - results := &ListNode{} - node := results - node1 := l1 - node2 := l2 - - overten := false - - for node1 != nil || node2 != nil { - - tmp := 0 - - if node1 != nil { - tmp = tmp + node1.Val - node1 = node1.Next + dummy := &ListNode{} + current, carry := dummy, 0 + + for l1 != nil || l2 != nil { + val := carry + if l1 != nil { + val += l1.Val + l1 = l1.Next } - - if node2 != nil { - tmp = tmp + node2.Val - node2 = node2.Next - } - if overten { - tmp++ - } - - if tmp >= 10 { - overten = true - tmp -= 10 - } else { - overten = false - } - - node.Val = tmp - - if node1 != nil || node2 != nil { - node.Next = &ListNode{} - node = node.Next + if l2 != nil { + val += l2.Val + l2 = l2.Next } + carry = val / 10 + val %= 10 + current.Next = &ListNode{Val: val} + current = current.Next } - if overten { - node.Next = &ListNode{} - node = node.Next - node.Val = 1 + if carry == 1 { + current.Next = &ListNode{Val: 1} } - return results + return dummy.Next } From ce90104552139885dc95322b65a378a8e7231976 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Feb 2018 23:19:18 +0800 Subject: [PATCH 4455/4971] Update two-sum.go --- Golang/two-sum.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Golang/two-sum.go b/Golang/two-sum.go index 32950b739..0cf7df1b2 100644 --- a/Golang/two-sum.go +++ b/Golang/two-sum.go @@ -1,4 +1,5 @@ -package twoSum +// Time: O(n) +// Space: O(n) func twoSum(nums []int, target int) []int { lookup := make(map[int]int) From 600ddbe0ca425b92e6d8c6012c355f010e156f68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 22 Feb 2018 23:20:58 +0800 Subject: [PATCH 4456/4971] Update add-two-numbers.go --- Golang/add-two-numbers.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Golang/add-two-numbers.go b/Golang/add-two-numbers.go index 105e54a81..a3f033323 100644 --- a/Golang/add-two-numbers.go +++ b/Golang/add-two-numbers.go @@ -22,8 +22,7 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { val += l2.Val l2 = l2.Next } - carry = val / 10 - val %= 10 + carry, val = val / 10, val % 10 current.Next = &ListNode{Val: val} current = current.Next } From 11111fcc954a59610fd18251d9e058ef90ebed67 Mon Sep 17 00:00:00 2001 From: Randy Chen Date: Fri, 23 Feb 2018 01:44:12 +0800 Subject: [PATCH 4457/4971] update power-of-three.py add another solution for 'Power of Three' based on The Change-of-Base Formula --- Python/power-of-three.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Python/power-of-three.py b/Python/power-of-three.py index 7398d4bf5..02f90144b 100644 --- a/Python/power-of-three.py +++ b/Python/power-of-three.py @@ -20,3 +20,8 @@ def isPowerOfThree(self, n): :rtype: bool """ return n > 0 and self.__max_pow3 % n == 0 + + +class Solution2(object): + def isPowerOfThree(self, n): + return n > 0 and (math.log10(n)/math.log10(3)).is_integer() From 4b382eb9238cb046387bc73a3291dcc3e92b24b8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 15:00:24 +0800 Subject: [PATCH 4458/4971] Create rotated-digits.cpp --- C++/rotated-digits.cpp | 65 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 C++/rotated-digits.cpp diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp new file mode 100644 index 000000000..a8b0fa2cf --- /dev/null +++ b/C++/rotated-digits.cpp @@ -0,0 +1,65 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int rotatedDigits(int N) { + vector dp(N + 1); + unordered_set same = {0, 1, 8}; + unordered_set diff = {2, 5, 6, 9}; + for (const auto& i : same) { + if (i <= N) { + dp[i] = 1; + } + } + for (const auto& i : diff) { + if (i <= N) { + dp[i] = 2; + } + } + for (int i = 0; i <= N; ++i) { + if (dp[i] > 0) { + for (const auto& j : same) { + if (i * 10 + j <= N) { + dp[i * 10 + j] = max(1, dp[i]); + } + } + for (const auto& j : diff) { + if (i * 10 + j <= N) { + dp[i * 10 + j] = 2; + } + } + } + } + return accumulate(dp.begin(), dp.end(), 0, + [](int a, int b) { + return a + static_cast(b == 2); + }); + } + +}; + +// Time: O(nlogn) = O(n), because O(logn) = O(32) by this input +// Space: O(logn) = O(1) +class Solution2 { +public: + int rotatedDigits(int N) { + int result = 0; + for (int i = 0; i <= N; ++i){ + string s(to_string(i)); + unordered_set lookup(s.begin(),s.end()); + if (lookup.count('3') || + lookup.count('4') || + lookup.count('7')) { + continue; + } + if (lookup.count('2') || + lookup.count('5') || + lookup.count('6') || + lookup.count('9')) { + ++result; + } + } + return result; + } +}; From ec4c48b18aef5b9ff67eaf619d4ad2d6a157de73 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 15:02:32 +0800 Subject: [PATCH 4459/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index a8b0fa2cf..dcd156ae1 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -17,7 +17,7 @@ class Solution { dp[i] = 2; } } - for (int i = 0; i <= N; ++i) { + for (int i = 0; 10 * i <= N; ++i) { if (dp[i] > 0) { for (const auto& j : same) { if (i * 10 + j <= N) { From 7a320dea7cfc9cc1008fa201323c3508513d8bd3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 15:08:48 +0800 Subject: [PATCH 4460/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index dcd156ae1..788a280d0 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -4,36 +4,37 @@ class Solution { public: int rotatedDigits(int N) { - vector dp(N + 1); + enum State { INVALID, SAME, DIFF }; + vector dp(N + 1); unordered_set same = {0, 1, 8}; unordered_set diff = {2, 5, 6, 9}; for (const auto& i : same) { if (i <= N) { - dp[i] = 1; + dp[i] = SAME; } } for (const auto& i : diff) { if (i <= N) { - dp[i] = 2; + dp[i] = DIFF; } } for (int i = 0; 10 * i <= N; ++i) { - if (dp[i] > 0) { + if (dp[i] != INVALID) { for (const auto& j : same) { if (i * 10 + j <= N) { - dp[i * 10 + j] = max(1, dp[i]); + dp[i * 10 + j] = max(SAME, dp[i]); } } for (const auto& j : diff) { if (i * 10 + j <= N) { - dp[i * 10 + j] = 2; + dp[i * 10 + j] = DIFF; } } } } return accumulate(dp.begin(), dp.end(), 0, [](int a, int b) { - return a + static_cast(b == 2); + return a + static_cast(b == DIFF); }); } From 807c92a9eb8cbdda7a35ad87bb0b8ccd94ec78ef Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 15:10:38 +0800 Subject: [PATCH 4461/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index 788a280d0..fd7e720ff 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -32,10 +32,7 @@ class Solution { } } } - return accumulate(dp.begin(), dp.end(), 0, - [](int a, int b) { - return a + static_cast(b == DIFF); - }); + return count(dp.cbegin(), dp.cend(), DIFF); } }; From 09a438a13eb2570a9afb0f6e3d0bc9234b52f988 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 15:16:00 +0800 Subject: [PATCH 4462/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index fd7e720ff..28a20e32b 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -8,18 +8,9 @@ class Solution { vector dp(N + 1); unordered_set same = {0, 1, 8}; unordered_set diff = {2, 5, 6, 9}; - for (const auto& i : same) { - if (i <= N) { - dp[i] = SAME; - } - } - for (const auto& i : diff) { - if (i <= N) { - dp[i] = DIFF; - } - } for (int i = 0; 10 * i <= N; ++i) { - if (dp[i] != INVALID) { + if (i == 0 || + dp[i] != INVALID) { for (const auto& j : same) { if (i * 10 + j <= N) { dp[i * 10 + j] = max(SAME, dp[i]); From 5b00b6b56ecd4b668ab528c44b5bb545be5d994d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 15:16:48 +0800 Subject: [PATCH 4463/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index 28a20e32b..b0edd63e5 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -8,9 +8,9 @@ class Solution { vector dp(N + 1); unordered_set same = {0, 1, 8}; unordered_set diff = {2, 5, 6, 9}; + dp[0] = SAME; for (int i = 0; 10 * i <= N; ++i) { - if (i == 0 || - dp[i] != INVALID) { + if (dp[i] != INVALID) { for (const auto& j : same) { if (i * 10 + j <= N) { dp[i * 10 + j] = max(SAME, dp[i]); From 50c9a6802aa825790bd92c8866dace2039b66f75 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 15:17:39 +0800 Subject: [PATCH 4464/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index b0edd63e5..8344da228 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -4,10 +4,10 @@ class Solution { public: int rotatedDigits(int N) { - enum State { INVALID, SAME, DIFF }; - vector dp(N + 1); + enum State {INVALID, SAME, DIFF}; unordered_set same = {0, 1, 8}; unordered_set diff = {2, 5, 6, 9}; + vector dp(N + 1); dp[0] = SAME; for (int i = 0; 10 * i <= N; ++i) { if (dp[i] != INVALID) { From 35a0cb1139df741bb9943e9d31ee52595a04f88a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 15:23:06 +0800 Subject: [PATCH 4465/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index 8344da228..0110b6f63 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -25,7 +25,6 @@ class Solution { } return count(dp.cbegin(), dp.cend(), DIFF); } - }; // Time: O(nlogn) = O(n), because O(logn) = O(32) by this input From d7fe32d66cb66c1f99ece64ea50b3e14077e5a6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 16:03:48 +0800 Subject: [PATCH 4466/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index 0110b6f63..daa8ab314 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -5,8 +5,8 @@ class Solution { public: int rotatedDigits(int N) { enum State {INVALID, SAME, DIFF}; - unordered_set same = {0, 1, 8}; - unordered_set diff = {2, 5, 6, 9}; + vector same = {0, 1, 8}; + vector diff = {2, 5, 6, 9}; vector dp(N + 1); dp[0] = SAME; for (int i = 0; 10 * i <= N; ++i) { From 6e9c31c27180caadc83700ba3e354bfcdfb3dd5d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 17:04:22 +0800 Subject: [PATCH 4467/4971] Create rotated-digits.py --- Python/rotated-digits.py | 60 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/rotated-digits.py diff --git a/Python/rotated-digits.py b/Python/rotated-digits.py new file mode 100644 index 000000000..58c40c7c0 --- /dev/null +++ b/Python/rotated-digits.py @@ -0,0 +1,60 @@ +# Time: O(n) +# Space: O(n) + +# X is a good number if after rotating each digit individually by 180 degrees, +# we get a valid number that is different from X. +# A number is valid if each digit remains a digit after rotation. +# 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; +# 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number. +# +# Now given a positive number N, how many numbers X from 1 to N are good? +# +# Example: +# Input: 10 +# Output: 4 +# Explanation: +# There are four good numbers in the range [1, 10] : 2, 5, 6, 9. +# Note that 1 and 10 are not good numbers, since they remain unchanged after rotating. +# +# Note: +# - N will be in range [1, 10000]. + +class Solution(object): + def rotatedDigits(self, N): + """ + :type N: int + :rtype: int + """ + INVALID, SAME, DIFF = 0, 1, 2 + same, diff = [0, 1, 8], [2, 5, 6, 9] + dp = [0] * (N+1) + dp[0] = SAME + for i in xrange(N//10+1): + if dp[i] != INVALID: + for j in same: + if i*10+j <= N: + dp[i*10+j] = max(SAME, dp[i]) + for j in diff: + if i*10+j <= N: + dp[i*10+j] = DIFF + return dp.count(DIFF) + + +# Time: O(nlogn) = O(n), because O(logn) = O(32) by this input +# Space: O(logn) = O(1) +class Solution2(object): + def rotatedDigits(self, N): + """ + :type N: int + :rtype: int + """ + result = 0 + invalid, diff = set(['3', '4', '7']), set(['2', '5', '6', '9']) + for i in xrange(N+1): + lookup = set(list(str(i))) + if invalid & lookup: + continue + if diff & lookup: + result += 1 + return result + From 1d5881aa447572f8a03be5380ab026434832b8ef Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 17:14:11 +0800 Subject: [PATCH 4468/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index daa8ab314..7df262aaf 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -33,21 +33,31 @@ class Solution2 { public: int rotatedDigits(int N) { int result = 0; + unordered_set invalid = {'3', '4', '7'}; + unordered_set diff = {'2', '5', '6', '9'}; + for (int i = 0; i <= N; ++i){ string s(to_string(i)); unordered_set lookup(s.begin(),s.end()); - if (lookup.count('3') || - lookup.count('4') || - lookup.count('7')) { + if (intersect(invalid, lookup)) { continue; } - if (lookup.count('2') || - lookup.count('5') || - lookup.count('6') || - lookup.count('9')) { + if (intersect(diff, lookup)) { ++result; } } return result; } + +private: + template + bool intersect(const unordered_set& a, const unordered_set& b) { + if (a.size() > b.size()) { + return intersect(b, a); + } + return any_of(a.cbegin(), a.cend(), + [&b](const T& e) { + return b.count(e); + }); + } }; From 565eef81f9f109b49c9a0b910a76087ab7ddb31a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 17:15:48 +0800 Subject: [PATCH 4469/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index 7df262aaf..ba2e414a7 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -5,8 +5,8 @@ class Solution { public: int rotatedDigits(int N) { enum State {INVALID, SAME, DIFF}; - vector same = {0, 1, 8}; - vector diff = {2, 5, 6, 9}; + const vector same = {0, 1, 8}; + const vector diff = {2, 5, 6, 9}; vector dp(N + 1); dp[0] = SAME; for (int i = 0; 10 * i <= N; ++i) { @@ -32,10 +32,9 @@ class Solution { class Solution2 { public: int rotatedDigits(int N) { + const unordered_set invalid = {'3', '4', '7'}; + const unordered_set diff = {'2', '5', '6', '9'}; int result = 0; - unordered_set invalid = {'3', '4', '7'}; - unordered_set diff = {'2', '5', '6', '9'}; - for (int i = 0; i <= N; ++i){ string s(to_string(i)); unordered_set lookup(s.begin(),s.end()); From 26fc4098c4092c4777e18d889160efcb7ab7501e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 17:16:34 +0800 Subject: [PATCH 4470/4971] Update rotated-digits.py --- Python/rotated-digits.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/rotated-digits.py b/Python/rotated-digits.py index 58c40c7c0..4c3d8d4c5 100644 --- a/Python/rotated-digits.py +++ b/Python/rotated-digits.py @@ -48,8 +48,8 @@ def rotatedDigits(self, N): :type N: int :rtype: int """ - result = 0 invalid, diff = set(['3', '4', '7']), set(['2', '5', '6', '9']) + result = 0 for i in xrange(N+1): lookup = set(list(str(i))) if invalid & lookup: From 3e155571f5a7d3461bc87e7c84a8d20d66cc476b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 17:29:18 +0800 Subject: [PATCH 4471/4971] Create escape-the-ghosts.cpp --- C++/escape-the-ghosts.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 C++/escape-the-ghosts.cpp diff --git a/C++/escape-the-ghosts.cpp b/C++/escape-the-ghosts.cpp new file mode 100644 index 000000000..cb8b72eb3 --- /dev/null +++ b/C++/escape-the-ghosts.cpp @@ -0,0 +1,13 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool escapeGhosts(vector>& ghosts, vector& target) { + const auto& total = abs(target[0]) + abs(target[1]); + return all_of(ghosts.cbegin(), ghosts.cend(), + [&target, &total](const vector& ghost) { + return total < abs(target[0] - ghost[0]) + abs(target[1] - ghost[1]); + }); + } +}; From 50203ff9218e2586c689cbd09083ca60e39620a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 17:31:38 +0800 Subject: [PATCH 4472/4971] Create escape-the-ghosts.py --- Python/escape-the-ghosts.py | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/escape-the-ghosts.py diff --git a/Python/escape-the-ghosts.py b/Python/escape-the-ghosts.py new file mode 100644 index 000000000..be1e5f43f --- /dev/null +++ b/Python/escape-the-ghosts.py @@ -0,0 +1,55 @@ +# Time: O(n) +# Space: O(1) + +# You are playing a simplified Pacman game. +# You start at the point (0, 0), and your destination is (target[0], target[1]). +# There are several ghosts on the map, the i-th ghost starts at (ghosts[i][0], ghosts[i][1]). +# +# Each turn, you and all ghosts simultaneously *may* move +# in one of 4 cardinal directions: north, east, west, or south, +# going from the previous point to a new point 1 unit of distance away. +# +# You escape if and only if you can reach the target before any ghost +# reaches you (for any given moves the ghosts may take.) +# If you reach any square (including the target) at the same time as a ghost, +# it doesn't count as an escape. +# +# Return True if and only if it is possible to escape. +# +# Example 1: +# Input: +# ghosts = [[1, 0], [0, 3]] +# target = [0, 1] +# Output: true +# Explanation: +# You can directly reach the destination (0, 1) at time 1, +# while the ghosts located at (1, 0) or (0, 3) have no way to catch up with you. +# +# Example 2: +# Input: +# ghosts = [[1, 0]] +# target = [2, 0] +# Output: false +# Explanation: +# You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination. +# Example 3: +# Input: +# ghosts = [[2, 0]] +# target = [1, 0] +# Output: false +# Explanation: +# The ghost can reach the target at the same time as you. +# +# Note: +# - All points have coordinates with absolute value <= 10000. +# - The number of ghosts will not exceed 100. + +class Solution(object): + def escapeGhosts(self, ghosts, target): + """ + :type ghosts: List[List[int]] + :type target: List[int] + :rtype: bool + """ + total = abs(target[0])+abs(target[1]) + return all(total < abs(target[0]-i)+abs(target[1]-j) for i, j in ghosts) From 1ef57c9d81c6d3469551955c7a9541aef234e20a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 17:44:33 +0800 Subject: [PATCH 4473/4971] Create domino-and-tromino-tiling.cpp --- C++/domino-and-tromino-tiling.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/domino-and-tromino-tiling.cpp diff --git a/C++/domino-and-tromino-tiling.cpp b/C++/domino-and-tromino-tiling.cpp new file mode 100644 index 000000000..8f42223b2 --- /dev/null +++ b/C++/domino-and-tromino-tiling.cpp @@ -0,0 +1,15 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int numTilings(int N) { + const int M = 1e9 + 7; + vector dp(3); + dp[1] = 1, dp[2] = 1; + for (int i = 3; i <= N + 1; ++i) { + dp[i % 3] = (2 * dp[(i - 1) % 3] % M + dp[(i - 3) % 3]) % M; + } + return dp[(N + 1) % 3]; + } +}; From 91805b9dbe1cfc763a96eae1d7175c47827242b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 18:18:52 +0800 Subject: [PATCH 4474/4971] Update domino-and-tromino-tiling.cpp --- C++/domino-and-tromino-tiling.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/C++/domino-and-tromino-tiling.cpp b/C++/domino-and-tromino-tiling.cpp index 8f42223b2..6a6a759bc 100644 --- a/C++/domino-and-tromino-tiling.cpp +++ b/C++/domino-and-tromino-tiling.cpp @@ -1,15 +1,22 @@ // Time: O(n) // Space: O(1) +// Prove: +// dp[n] = dp[n-1](|) + dp[n-2](=) + 2*(dp[n-3](「」) + ... + d[0](「 == 」)) +// = dp[n-1] + dp[n-2] + dp[n-3] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) +// = dp[n-1] + dp[n-3] + (dp[n-2] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) +// = dp[n-1] + dp[n-3] + dp[n-1] +// = 2*dp[n-1] + dp[n-3] + class Solution { public: int numTilings(int N) { const int M = 1e9 + 7; vector dp(3); - dp[1] = 1, dp[2] = 1; - for (int i = 3; i <= N + 1; ++i) { + dp[0] = 1, dp[1] = 1, dp[2] = 2; + for (int i = 3; i <= N; ++i) { dp[i % 3] = (2 * dp[(i - 1) % 3] % M + dp[(i - 3) % 3]) % M; } - return dp[(N + 1) % 3]; + return dp[N % 3]; } }; From d7bfbf005e99963dc92ea12f60ef408bfed8cbdf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 18:23:53 +0800 Subject: [PATCH 4475/4971] Update domino-and-tromino-tiling.cpp --- C++/domino-and-tromino-tiling.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/domino-and-tromino-tiling.cpp b/C++/domino-and-tromino-tiling.cpp index 6a6a759bc..8828fd1bf 100644 --- a/C++/domino-and-tromino-tiling.cpp +++ b/C++/domino-and-tromino-tiling.cpp @@ -2,7 +2,7 @@ // Space: O(1) // Prove: -// dp[n] = dp[n-1](|) + dp[n-2](=) + 2*(dp[n-3](「」) + ... + d[0](「 == 」)) +// dp[n] = dp[n-1](|) + dp[n-2](=) + 2*(dp[n-3](「」) + ... + d[0](「 = ... = 」)) // = dp[n-1] + dp[n-2] + dp[n-3] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) // = dp[n-1] + dp[n-3] + (dp[n-2] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) // = dp[n-1] + dp[n-3] + dp[n-1] From eb6cc9751aba2725f97b1b432e9296217cd1494c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 18:25:26 +0800 Subject: [PATCH 4476/4971] Create domino-and-tromino-tiling.py --- Python/domino-and-tromino-tiling.py | 46 +++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/domino-and-tromino-tiling.py diff --git a/Python/domino-and-tromino-tiling.py b/Python/domino-and-tromino-tiling.py new file mode 100644 index 000000000..a9f7b3c85 --- /dev/null +++ b/Python/domino-and-tromino-tiling.py @@ -0,0 +1,46 @@ +# Time: O(n) +# Space: O(1) + +# We have two types of tiles: a 2x1 domino shape, and an "L" tromino shape. +# These shapes may be rotated. +# +# XX <- domino +# +# XX <- "L" tromino +# X +# Given N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 7. +# +# (In a tiling, every square must be covered by a tile. +# Two tilings are different if and only if there are two 4-directionally adjacent cells on the board +# such that exactly one of the tilings has both squares occupied by a tile.) +# +# Example: +# Input: 3 +# Output: 5 +# Explanation: +# The five different ways are listed below, different letters indicates different tiles: +# XYZ XXZ XYY XXY XYY +# XYZ YYZ XZZ XYY XXY +# +# Note: +# - N will be in range [1, 1000]. + +# Prove: +# dp[n] = dp[n-1](|) + dp[n-2](=) + 2*(dp[n-3](「」) + ... + d[0](「 = ... = 」)) +# = dp[n-1] + dp[n-2] + dp[n-3] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) +# = dp[n-1] + dp[n-3] + (dp[n-2] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) +# = dp[n-1] + dp[n-3] + dp[n-1] +# = 2*dp[n-1] + dp[n-3] + +class Solution(object): + def numTilings(self, N): + """ + :type N: int + :rtype: int + """ + M = int(1e9+7) + dp = [1, 1, 2] + for i in xrange(3, N+1): + dp[i%3] = (2*dp[(i-1)%3]%M + dp[(i-3)%3])%M + return dp[N%3] + From 9edf8db573bd5f21891bf5b81f1cb03a4438ca3e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 18:45:37 +0800 Subject: [PATCH 4477/4971] Create custom-sort-string.cpp --- C++/custom-sort-string.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/custom-sort-string.cpp diff --git a/C++/custom-sort-string.cpp b/C++/custom-sort-string.cpp new file mode 100644 index 000000000..da155af38 --- /dev/null +++ b/C++/custom-sort-string.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string customSortString(string S, string T) { + unordered_set s(S.cbegin(), S.cend()); + unordered_map counter; + for (const auto& c : T) { + ++counter[c]; + } + string result; + for (const auto& c : S) { + result += string(counter[c], c); + } + for (const auto& kvp : counter) { + if (!s.count(kvp.first)) { + result += string(kvp.second, kvp.first); + } + } + return result; + } +}; From e8a149836241aa7a1305c513a711e747725d7f3a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 18:47:20 +0800 Subject: [PATCH 4478/4971] Create custom-sort-string.py --- Python/custom-sort-string.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/custom-sort-string.py diff --git a/Python/custom-sort-string.py b/Python/custom-sort-string.py new file mode 100644 index 000000000..6851fa07e --- /dev/null +++ b/Python/custom-sort-string.py @@ -0,0 +1,36 @@ +# Time: O(n) +# Space: O(1) + +# S and T are strings composed of lowercase letters. In S, no letter occurs more than once. +# +# S was sorted in some custom order previously. +# We want to permute the characters of T so that they match the order that S was sorted. +# More specifically, if x occurs before y in S, then x should occur before y in the returned string. +# +# Return any permutation of T (as a string) that satisfies this property. +# +# Example : +# Input: +# S = "cba" +# T = "abcd" +# Output: "cbad" +# Explanation: +# "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". +# Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs. +# +# Note: +# - S has length at most 26, and no character is repeated in S. +# - T has length at most 200. +# - S and T consist of lowercase letters only. + +class Solution(object): + def customSortString(self, S, T): + """ + :type S: str + :type T: str + :rtype: str + """ + counter, s = collections.Counter(T), set(S) + result = [c*counter[c] for c in S] + result.extend([c*counter for c, counter in counter.iteritems() if c not in s]) + return "".join(result) From 5763fbc0a96f579a8061e689e2674225477411b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Feb 2018 19:14:31 +0800 Subject: [PATCH 4479/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 0330b2b35..3af36f3aa 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 722| [Remove Comments](https://leetcode.com/problems/remove-comments/) | [C++](./C++/remove-comments.cpp) [Python](./Python/remove-comments.py) | _O(n)_ | _O(k)_ | Medium ||| 751| [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) | [C++](./C++/ip-to-cidr.cpp) [Python](./Python/ip-to-cidr.py) | _O(n)_ | _O(1)_ | Medium ||| 758| [Bold Words in String](https://leetcode.com/contest/weekly-contest-66/problems/bold-words-in-string/) | [C++](./C++/bold-words-in-string.cpp) [Python](./Python/bold-words-in-string.py) | _O(n * l)_ | _O(t)_ | Easy | 📖, variant of [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | +791| [Custom Sort String](https://leetcode.com/problems/custom-sort-string/) | [C++](./C++/custom-sort-string.cpp) [Python](./Python/custom-sort-string.py) | _O(n)_ | _O(1)_ | Medium ||| ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -432,6 +433,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 780 | [Reaching Points](https://leetcode.com/problems/reaching-points/) | [C++](./C++/reaching-points.cpp) [Python](./Python/reaching-points.py) | _O(log(max(m, n)))_ | _O(1)_ | Hard || 781 | [Rabbits in Forest](https://leetcode.com/problems/rabbits-in-forest/) | [C++](./C++/rabbits-in-forest.cpp) [Python](./Python/rabbits-in-forest.py) | _O(n)_ | _O(n)_ | Medium || 782 | [Transform to Chessboard](https://leetcode.com/problems/transform-to-chessboard/) | [C++](./C++/transform-to-chessboard.cpp) [Python](./Python/transform-to-chessboard.py) | _O(n^2)_ | _O(n)_ | Hard || +789 | [Escape The Ghosts](https://leetcode.com/problems/escape-the-ghosts/) | [C++](./C++/escape-the-ghosts.cpp) [Python](./Python/escape-the-ghosts.py) | _O(n)_ | _O(1)_ | Medium || ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -730,6 +732,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) | [C++](./C++/min-cost-climbing-stairs.cpp) [Python](./Python/min-cost-climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || 750 | [Number Of Corner Rectangles](https://leetcode.com/problems/number-of-corner-rectangles/) | [C++](./C++/number-of-corner-rectangles.cpp) [Python](./Python/number-of-corner-rectangles.py) | _O(n * m^2)_ | _O(n * m)_ | Medium || 764 | [Largest Plus Sign](https://leetcode.com/problems/largest-plus-sign/) | [C++](./C++/largest-plus-sign.cpp) [Python](./Python/largest-plus-sign.py) | _O(n^2)_ | _O(n^2)_ | Medium || +788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/) | [C++](./C++/rotated-digits.cpp) [Python](./Python/rotated-digits.py) | _O(n)_ | _O(n)_ | Easy || +790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/) | [C++](./C++/domino-and-tromino-tiling.cpp) [Python](./Python/domino-and-tromino-tiling.py) | _O(n)_ | _O(1)_ | Medium || ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 5a1c48403a912eedc4f5d87215fafdb05eb49ed5 Mon Sep 17 00:00:00 2001 From: Artem Muterko Date: Mon, 26 Feb 2018 15:22:42 +0200 Subject: [PATCH 4480/4971] Add alternative solution for 'Find all duplicates in an array' --- Python/find-all-duplicates-in-an-array.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Python/find-all-duplicates-in-an-array.py b/Python/find-all-duplicates-in-an-array.py index 79c8b174c..774e186ec 100644 --- a/Python/find-all-duplicates-in-an-array.py +++ b/Python/find-all-duplicates-in-an-array.py @@ -33,3 +33,15 @@ def findDuplicates(self, nums): if i != nums[i]-1: result.append(nums[i]) return result + + +from collections import Counter + + +class Solution2(object): + def findDuplicates(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + return [elem for elem, count in Counter(nums).items() if count == 2] From 98dd9e5153f32be270e9b8b0e4d81a5428fd2ec7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 21:41:47 +0800 Subject: [PATCH 4481/4971] Update find-all-duplicates-in-an-array.py --- Python/find-all-duplicates-in-an-array.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/find-all-duplicates-in-an-array.py b/Python/find-all-duplicates-in-an-array.py index 774e186ec..b9cf52b29 100644 --- a/Python/find-all-duplicates-in-an-array.py +++ b/Python/find-all-duplicates-in-an-array.py @@ -35,9 +35,9 @@ def findDuplicates(self, nums): return result +# Time: O(n) +# Space: O(n), this doesn't satisfy the question from collections import Counter - - class Solution2(object): def findDuplicates(self, nums): """ From 24d151da97aa1cac6236dc698382e1a9504baa60 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 21:44:08 +0800 Subject: [PATCH 4482/4971] Update find-all-duplicates-in-an-array.py --- Python/find-all-duplicates-in-an-array.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Python/find-all-duplicates-in-an-array.py b/Python/find-all-duplicates-in-an-array.py index b9cf52b29..5c062ca8d 100644 --- a/Python/find-all-duplicates-in-an-array.py +++ b/Python/find-all-duplicates-in-an-array.py @@ -16,6 +16,23 @@ # [2,3] class Solution(object): + def findDuplicates(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + result = [] + for i in nums: + if nums[abs(i)-1] < 0: + result.append(abs(i)) + else: + nums[abs(i)-1] *= -1 + return result + + +# Time: O(n) +# Space: O(1) +class Solution2(object): def findDuplicates(self, nums): """ :type nums: List[int] From 973d26e8306c4168f62a78a248efbc5ce5bcabcd Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 21:44:19 +0800 Subject: [PATCH 4483/4971] Update find-all-duplicates-in-an-array.py --- Python/find-all-duplicates-in-an-array.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/find-all-duplicates-in-an-array.py b/Python/find-all-duplicates-in-an-array.py index 5c062ca8d..a9f4f054d 100644 --- a/Python/find-all-duplicates-in-an-array.py +++ b/Python/find-all-duplicates-in-an-array.py @@ -55,7 +55,7 @@ def findDuplicates(self, nums): # Time: O(n) # Space: O(n), this doesn't satisfy the question from collections import Counter -class Solution2(object): +class Solution3(object): def findDuplicates(self, nums): """ :type nums: List[int] From 669b6f10256358e745fbf82994aee039535e8e92 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 21:47:14 +0800 Subject: [PATCH 4484/4971] Update find-all-duplicates-in-an-array.cpp --- C++/find-all-duplicates-in-an-array.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/C++/find-all-duplicates-in-an-array.cpp b/C++/find-all-duplicates-in-an-array.cpp index 5cc2e8b93..8d6c78400 100644 --- a/C++/find-all-duplicates-in-an-array.cpp +++ b/C++/find-all-duplicates-in-an-array.cpp @@ -2,6 +2,21 @@ // Space: O(1) class Solution { +public: + vector findDuplicates(vector& nums) { + vector result; + for (const auto& i : nums) { + if (nums[abs(i) - 1] < 0) { + result.emplace_back(abs(i)); + } else { + nums[abs(i) - 1] *= -1; + } + } + return result; + } +}; + +class Solution2 { public: vector findDuplicates(vector& nums) { vector result; From 5167de4c1df177e87de6f23fd6a0bc9d02576eb4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 22:25:29 +0800 Subject: [PATCH 4485/4971] Update rotated-digits.py --- Python/rotated-digits.py | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/Python/rotated-digits.py b/Python/rotated-digits.py index 4c3d8d4c5..4a0f1baf4 100644 --- a/Python/rotated-digits.py +++ b/Python/rotated-digits.py @@ -1,5 +1,5 @@ -# Time: O(n) -# Space: O(n) +# Time: O(logn) +# Space: O(logn) # X is a good number if after rotating each digit individually by 180 degrees, # we get a valid number that is different from X. @@ -19,7 +19,35 @@ # Note: # - N will be in range [1, 10000]. +# memoization (top-down dp) class Solution(object): + def rotatedDigits(self, N): + """ + :type N: int + :rtype: int + """ + A = map(int, str(N)) + invalid, diff = set([3, 4, 7]), set([2, 5, 6, 9]) + def dp(A, i, is_prefix_equal, is_good, lookup): + if i == len(A): return int(is_good) + if (i, is_prefix_equal, is_good) not in lookup: + result = 0 + for d in xrange(A[i]+1 if is_prefix_equal else 10): + if d in invalid: continue + result += dp(A, i+1, + is_prefix_equal and d == A[i], + is_good or d in diff, + lookup) + lookup[i, is_prefix_equal, is_good] = result + return lookup[i, is_prefix_equal, is_good] + + lookup = {} + return dp(A, 0, True, False, lookup) + + +# Time: O(n) +# Space: O(n) +class Solution2(object): def rotatedDigits(self, N): """ :type N: int @@ -42,7 +70,7 @@ def rotatedDigits(self, N): # Time: O(nlogn) = O(n), because O(logn) = O(32) by this input # Space: O(logn) = O(1) -class Solution2(object): +class Solution3(object): def rotatedDigits(self, N): """ :type N: int From 8078807f73f90dce9868b0143be65cba1781afd9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 23:05:04 +0800 Subject: [PATCH 4486/4971] Update rotated-digits.cpp --- C++/rotated-digits.cpp | 60 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 3 deletions(-) diff --git a/C++/rotated-digits.cpp b/C++/rotated-digits.cpp index ba2e414a7..a13ecf5bb 100644 --- a/C++/rotated-digits.cpp +++ b/C++/rotated-digits.cpp @@ -1,7 +1,61 @@ -// Time: O(n) -// Space: O(n) +// Time: O(logn) +// Space: O(logn) +// memoization (top-down dp) class Solution { +private: + template + struct TupleHash { + size_t operator()(const tuple& p) const { + size_t seed = 0; + A a; B b; C c; + tie(a, b, c) = p; + seed ^= std::hash{}(a) + 0x9e3779b9 + (seed<<6) + (seed>>2); + seed ^= std::hash{}(b) + 0x9e3779b9 + (seed<<6) + (seed>>2); + seed ^= std::hash{}(c) + 0x9e3779b9 + (seed<<6) + (seed>>2); + return seed; + } + }; + +public: + int rotatedDigits(int N) { + vector A; + for (; N; N /= 10) { + A.emplace_back(N % 10); + } + reverse(A.begin(), A.end()); + unordered_map, int, TupleHash> lookup; + return dp(A, 0, true, false, &lookup); + } + +private: + int dp(const vector& A, int i, bool is_prefix_equal, bool is_good, + unordered_map, int, TupleHash> *lookup) { + if (i == A.size()) { + return static_cast(is_good); + } + if (!lookup->count(make_tuple(i, is_prefix_equal, is_good))) { + const auto& ceil = is_prefix_equal ? A[i] + 1 : 10; + int result = 0; + for (int d = 0; d < ceil; ++d) { + if (invalid.count(d)) continue; + result += dp(A, i + 1, + is_prefix_equal && d == A[i], + is_good || diff.count(d), + lookup); + } + (*lookup)[make_tuple(i, is_prefix_equal, is_good)] = result; + } + return (*lookup)[make_tuple(i, is_prefix_equal, is_good)]; + } + + const unordered_set invalid = {3, 4, 7}; + const unordered_set diff = {2, 5, 6, 9}; +}; + +// Time: O(n) +// Space: O(n) +class Solution2 { public: int rotatedDigits(int N) { enum State {INVALID, SAME, DIFF}; @@ -29,7 +83,7 @@ class Solution { // Time: O(nlogn) = O(n), because O(logn) = O(32) by this input // Space: O(logn) = O(1) -class Solution2 { +class Solution3 { public: int rotatedDigits(int N) { const unordered_set invalid = {'3', '4', '7'}; From eecd9ad5656211442dce7d2b725d0dcda5598d8f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 23:49:37 +0800 Subject: [PATCH 4487/4971] Update domino-and-tromino-tiling.cpp --- C++/domino-and-tromino-tiling.cpp | 64 ++++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 9 deletions(-) diff --git a/C++/domino-and-tromino-tiling.cpp b/C++/domino-and-tromino-tiling.cpp index 8828fd1bf..13cec13b7 100644 --- a/C++/domino-and-tromino-tiling.cpp +++ b/C++/domino-and-tromino-tiling.cpp @@ -1,16 +1,62 @@ -// Time: O(n) -// Space: O(1) - -// Prove: -// dp[n] = dp[n-1](|) + dp[n-2](=) + 2*(dp[n-3](「」) + ... + d[0](「 = ... = 」)) -// = dp[n-1] + dp[n-2] + dp[n-3] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) -// = dp[n-1] + dp[n-3] + (dp[n-2] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) -// = dp[n-1] + dp[n-3] + dp[n-1] -// = 2*dp[n-1] + dp[n-3] +// Time: O(logn) +// Space: O(logn) class Solution { public: int numTilings(int N) { + vector> T{{1, 0, 0, 1}, // #(|) = #(|) + #(=) + {1, 0, 1, 0}, // #(「) = #(|) + #(L) + {1, 1, 0, 0}, // #(L) = #(|) + #(「) + {1, 1, 1, 0}}; // #(=) = #(|) + #(「) + #(L) + return matrixExpo(T, N)[0][0]; // [1, 0, 0, 0] * T^N + } + +private: + vector> matrixExpo(const vector>& A, int pow) { + if (pow == 0) { + vector> I(A.size(), vector(A.size())); + for (int i = 0; i < A.size(); ++i) { + I[i][i] = 1; + } + return I; + } + if (pow == 1) { + return A; + } + if (pow % 2 == 1) { + return matrixMult(matrixExpo(A, pow - 1), A); + } + const auto& B = matrixExpo(A, pow / 2); + return matrixMult(B, B); + } + + vector> matrixMult(const vector>& A, const vector>& B) { + vector> result(A.size(), vector(A.size())); + for (int i = 0; i < A.size(); ++i) { + for (int j = 0; j < B[0].size(); ++j) { + int64_t entry = 0; + for (int k = 0; k < B.size(); ++k) { + entry = (static_cast(A[i][k]) * B[k][j] % M + entry) % M; + } + result[i][j] = static_cast(entry); + } + } + return result; + } + const int M = 1e9 + 7; +}; + +// Time: O(n) +// Space: O(1) +class Solution2 { +public: + int numTilings(int N) { + // Prove: + // dp[n] = dp[n-1](|) + dp[n-2](=) + 2*(dp[n-3](「」) + ... + d[0](「 = ... = 」)) + // = dp[n-1] + dp[n-2] + dp[n-3] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) + // = dp[n-1] + dp[n-3] + (dp[n-2] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) + // = dp[n-1] + dp[n-3] + dp[n-1] + // = 2*dp[n-1] + dp[n-3] const int M = 1e9 + 7; vector dp(3); dp[0] = 1, dp[1] = 1, dp[2] = 2; From 76dadc07793ee338bab6d3219f9ab2714a347dfd Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 23:51:51 +0800 Subject: [PATCH 4488/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3af36f3aa..16622bd4d 100644 --- a/README.md +++ b/README.md @@ -732,8 +732,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) | [C++](./C++/min-cost-climbing-stairs.cpp) [Python](./Python/min-cost-climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || 750 | [Number Of Corner Rectangles](https://leetcode.com/problems/number-of-corner-rectangles/) | [C++](./C++/number-of-corner-rectangles.cpp) [Python](./Python/number-of-corner-rectangles.py) | _O(n * m^2)_ | _O(n * m)_ | Medium || 764 | [Largest Plus Sign](https://leetcode.com/problems/largest-plus-sign/) | [C++](./C++/largest-plus-sign.cpp) [Python](./Python/largest-plus-sign.py) | _O(n^2)_ | _O(n^2)_ | Medium || -788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/) | [C++](./C++/rotated-digits.cpp) [Python](./Python/rotated-digits.py) | _O(n)_ | _O(n)_ | Easy || -790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/) | [C++](./C++/domino-and-tromino-tiling.cpp) [Python](./Python/domino-and-tromino-tiling.py) | _O(n)_ | _O(1)_ | Medium || +788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/) | [C++](./C++/rotated-digits.cpp) [Python](./Python/rotated-digits.py) | _O(logn)_ | _O(logn)_ | Easy || +790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/) | [C++](./C++/domino-and-tromino-tiling.cpp) [Python](./Python/domino-and-tromino-tiling.py) | _O(logn)_ | _O(logn)_ | Medium || ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 47fd34bf9c30aba7799ada16da050e47bc877d3c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 23:53:19 +0800 Subject: [PATCH 4489/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 16622bd4d..33bc6e42d 100644 --- a/README.md +++ b/README.md @@ -732,8 +732,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) | [C++](./C++/min-cost-climbing-stairs.cpp) [Python](./Python/min-cost-climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || 750 | [Number Of Corner Rectangles](https://leetcode.com/problems/number-of-corner-rectangles/) | [C++](./C++/number-of-corner-rectangles.cpp) [Python](./Python/number-of-corner-rectangles.py) | _O(n * m^2)_ | _O(n * m)_ | Medium || 764 | [Largest Plus Sign](https://leetcode.com/problems/largest-plus-sign/) | [C++](./C++/largest-plus-sign.cpp) [Python](./Python/largest-plus-sign.py) | _O(n^2)_ | _O(n^2)_ | Medium || -788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/) | [C++](./C++/rotated-digits.cpp) [Python](./Python/rotated-digits.py) | _O(logn)_ | _O(logn)_ | Easy || -790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/) | [C++](./C++/domino-and-tromino-tiling.cpp) [Python](./Python/domino-and-tromino-tiling.py) | _O(logn)_ | _O(logn)_ | Medium || +788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/) | [C++](./C++/rotated-digits.cpp) [Python](./Python/rotated-digits.py) | _O(logn)_ | _O(logn)_ | Easy | Memoization | +790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/) | [C++](./C++/domino-and-tromino-tiling.cpp) [Python](./Python/domino-and-tromino-tiling.py) | _O(logn)_ | _O(logn)_ | Medium | Matrix Exponentiation | ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From e5092a29bd44d96b1c86d73298ffbefbd6504a35 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 23:54:51 +0800 Subject: [PATCH 4490/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 33bc6e42d..8934762d4 100644 --- a/README.md +++ b/README.md @@ -732,8 +732,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 746 | [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) | [C++](./C++/min-cost-climbing-stairs.cpp) [Python](./Python/min-cost-climbing-stairs.py) | _O(n)_ | _O(1)_ | Easy || 750 | [Number Of Corner Rectangles](https://leetcode.com/problems/number-of-corner-rectangles/) | [C++](./C++/number-of-corner-rectangles.cpp) [Python](./Python/number-of-corner-rectangles.py) | _O(n * m^2)_ | _O(n * m)_ | Medium || 764 | [Largest Plus Sign](https://leetcode.com/problems/largest-plus-sign/) | [C++](./C++/largest-plus-sign.cpp) [Python](./Python/largest-plus-sign.py) | _O(n^2)_ | _O(n^2)_ | Medium || -788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/) | [C++](./C++/rotated-digits.cpp) [Python](./Python/rotated-digits.py) | _O(logn)_ | _O(logn)_ | Easy | Memoization | -790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/) | [C++](./C++/domino-and-tromino-tiling.cpp) [Python](./Python/domino-and-tromino-tiling.py) | _O(logn)_ | _O(logn)_ | Medium | Matrix Exponentiation | +788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/) | [C++](./C++/rotated-digits.cpp) [Python](./Python/rotated-digits.py) | _O(logn)_ | _O(logn)_ | Easy || Memoization | +790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/) | [C++](./C++/domino-and-tromino-tiling.cpp) [Python](./Python/domino-and-tromino-tiling.py) | _O(logn)_ | _O(logn)_ | Medium || Matrix Exponentiation | ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From b90f4d132eba3ce877dc21c8dfdd27e5d9028dcc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Feb 2018 23:58:41 +0800 Subject: [PATCH 4491/4971] Update domino-and-tromino-tiling.cpp --- C++/domino-and-tromino-tiling.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/domino-and-tromino-tiling.cpp b/C++/domino-and-tromino-tiling.cpp index 13cec13b7..cc3a53f9a 100644 --- a/C++/domino-and-tromino-tiling.cpp +++ b/C++/domino-and-tromino-tiling.cpp @@ -7,7 +7,7 @@ class Solution { vector> T{{1, 0, 0, 1}, // #(|) = #(|) + #(=) {1, 0, 1, 0}, // #(「) = #(|) + #(L) {1, 1, 0, 0}, // #(L) = #(|) + #(「) - {1, 1, 1, 0}}; // #(=) = #(|) + #(「) + #(L) + {1, 1, 1, 0}}; // #(=) = #(|) + #(「) + #(L) return matrixExpo(T, N)[0][0]; // [1, 0, 0, 0] * T^N } From 1182e021cd39a02f7c69c19f7e67dbf78d58e349 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Feb 2018 00:00:22 +0800 Subject: [PATCH 4492/4971] Update domino-and-tromino-tiling.py --- Python/domino-and-tromino-tiling.py | 51 ++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 9 deletions(-) diff --git a/Python/domino-and-tromino-tiling.py b/Python/domino-and-tromino-tiling.py index a9f7b3c85..66f213f8d 100644 --- a/Python/domino-and-tromino-tiling.py +++ b/Python/domino-and-tromino-tiling.py @@ -1,5 +1,5 @@ -# Time: O(n) -# Space: O(1) +# Time: O(logn) +# Space: O(logn) # We have two types of tiles: a 2x1 domino shape, and an "L" tromino shape. # These shapes may be rotated. @@ -25,13 +25,6 @@ # Note: # - N will be in range [1, 1000]. -# Prove: -# dp[n] = dp[n-1](|) + dp[n-2](=) + 2*(dp[n-3](「」) + ... + d[0](「 = ... = 」)) -# = dp[n-1] + dp[n-2] + dp[n-3] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) -# = dp[n-1] + dp[n-3] + (dp[n-2] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) -# = dp[n-1] + dp[n-3] + dp[n-1] -# = 2*dp[n-1] + dp[n-3] - class Solution(object): def numTilings(self, N): """ @@ -39,6 +32,46 @@ def numTilings(self, N): :rtype: int """ M = int(1e9+7) + + def matrix_expo(A, K): + if K == 0: + return [[int(i==j) for j in xrange(len(A))] \ + for i in xrange(len(A))] + if K == 1: + return A + if K % 2: + return matrix_mult(matrix_expo(A, K-1), A) + B = matrix_expo(A, K//2) + return matrix_mult(B, B) + + def matrix_mult(A, B): + ZB = zip(*B) + return [[sum(a*b for a, b in itertools.izip(row, col)) % M \ + for col in ZB] for row in A] + + T = [[1, 0, 0, 1], # #(|) = #(|) + #(=) + [1, 0, 1, 0], # #(「) = #(|) + #(L) + [1, 1, 0, 0], # #(L) = #(|) + #(「) + [1, 1, 1, 0]] # #(=) = #(|) + #(「) + #(L) + + return matrix_expo(T, N)[0][0] # [1, 0, 0, 0] * T^N + + +# Time: O(n) +# Space: O(1) +class Solution2(object): + def numTilings(self, N): + """ + :type N: int + :rtype: int + """ + # Prove: + # dp[n] = dp[n-1](|) + dp[n-2](=) + 2*(dp[n-3](「」) + ... + d[0](「 = ... = 」)) + # = dp[n-1] + dp[n-2] + dp[n-3] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) + # = dp[n-1] + dp[n-3] + (dp[n-2] + dp[n-3] + 2*(dp[n-4] + ... + d[0]) + # = dp[n-1] + dp[n-3] + dp[n-1] + # = 2*dp[n-1] + dp[n-3] + M = int(1e9+7) dp = [1, 1, 2] for i in xrange(3, N+1): dp[i%3] = (2*dp[(i-1)%3]%M + dp[(i-3)%3])%M From 674625191e89306a847dbe1506fc27ab48f743db Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Feb 2018 00:40:00 +0800 Subject: [PATCH 4493/4971] Update domino-and-tromino-tiling.py --- Python/domino-and-tromino-tiling.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/domino-and-tromino-tiling.py b/Python/domino-and-tromino-tiling.py index 66f213f8d..a7919a81b 100644 --- a/Python/domino-and-tromino-tiling.py +++ b/Python/domino-and-tromino-tiling.py @@ -54,7 +54,7 @@ def matrix_mult(A, B): [1, 1, 0, 0], # #(L) = #(|) + #(「) [1, 1, 1, 0]] # #(=) = #(|) + #(「) + #(L) - return matrix_expo(T, N)[0][0] # [1, 0, 0, 0] * T^N + return matrix_expo(T, N)[0][0] # T^N * [1, 0, 0, 0] # Time: O(n) From 57a4a3fddb80f73f2715954a4ed155ea3f2e2052 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Feb 2018 00:43:03 +0800 Subject: [PATCH 4494/4971] Update domino-and-tromino-tiling.cpp --- C++/domino-and-tromino-tiling.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/domino-and-tromino-tiling.cpp b/C++/domino-and-tromino-tiling.cpp index cc3a53f9a..73337cdeb 100644 --- a/C++/domino-and-tromino-tiling.cpp +++ b/C++/domino-and-tromino-tiling.cpp @@ -8,7 +8,7 @@ class Solution { {1, 0, 1, 0}, // #(「) = #(|) + #(L) {1, 1, 0, 0}, // #(L) = #(|) + #(「) {1, 1, 1, 0}}; // #(=) = #(|) + #(「) + #(L) - return matrixExpo(T, N)[0][0]; // [1, 0, 0, 0] * T^N + return matrixExpo(T, N)[0][0]; // T^N * [1, 0, 0, 0] } private: From c4287eeff1d3d474d16166f7ec41983dbd2a5bde Mon Sep 17 00:00:00 2001 From: oshapeman Date: Tue, 27 Feb 2018 23:02:26 +0800 Subject: [PATCH 4495/4971] Update combinations.py --- Python/combinations.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/combinations.py b/Python/combinations.py index 1f206daad..90ab8e36f 100644 --- a/Python/combinations.py +++ b/Python/combinations.py @@ -26,6 +26,7 @@ def combine(self, n, k): def combineRecu(self, n, result, start, intermediate, k): if k == 0: result.append(intermediate[:]) + return for i in xrange(start, n): intermediate.append(i + 1) self.combineRecu(n, result, i + 1, intermediate, k - 1) From 4b12d272a226287e1a14d663e4d3514af90d82c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Feb 2018 02:02:11 +0800 Subject: [PATCH 4496/4971] Update combinations.py --- Python/combinations.py | 59 ++++++++++++++++++++++++++++++------------ 1 file changed, 43 insertions(+), 16 deletions(-) diff --git a/Python/combinations.py b/Python/combinations.py index 90ab8e36f..d77ce0e4f 100644 --- a/Python/combinations.py +++ b/Python/combinations.py @@ -1,6 +1,6 @@ -# Time: O(n!) -# Space: O(n) -# +# Time: O(k * C(n, k)) +# Space: O(k) + # Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. # # For example, @@ -14,23 +14,50 @@ # [1,3], # [1,4], # ] -# -class Solution: - # @return a list of lists of integers +class Solution(object): def combine(self, n, k): - result = [] - self.combineRecu(n, result, 0, [], k) + """ + :type n: int + :type k: int + :rtype: List[List[int]] + """ + result, combination = [], [] + i = 1 + while True: + if len(combination) == k: + result.append(combination[:]) + if len(combination) == k or \ + len(combination)+(n-i+1) < k: + if not combination: + return result + i = combination.pop()+1 + else: + combination.append(i) + i += 1 return result - def combineRecu(self, n, result, start, intermediate, k): - if k == 0: - result.append(intermediate[:]) - return - for i in xrange(start, n): - intermediate.append(i + 1) - self.combineRecu(n, result, i + 1, intermediate, k - 1) - intermediate.pop() + +class Solution2(object): + def combine(self, n, k): + """ + :type n: int + :type k: int + :rtype: List[List[int]] + """ + def combineDFS(n, start, intermediate, k, result): + if k == 0: + result.append(intermediate[:]) + return + for i in xrange(start, n): + intermediate.append(i+1) + combineDFS(n, i+1, intermediate, k-1, result) + intermediate.pop() + + result = [] + combineDFS(n, 0, [], k, result) + return result + if __name__ == "__main__": result = Solution().combine(4, 2) From a68ea9afd1da401ab2d9dd9ad60f4be93caadc27 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Feb 2018 02:03:23 +0800 Subject: [PATCH 4497/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8934762d4..d3a3e6d51 100644 --- a/README.md +++ b/README.md @@ -635,7 +635,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 051| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || 052| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || 077| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || -079| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || +079| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(O(k * C(n, k)))_ | _O(k)_ | Medium || 093| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(1)_ | _O(1)_ | Medium || 078| [Subsets](https://leetcode.com/problems/subsets/) | [C++](./C++/subsets.cpp) [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || 090| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [C++](./C++/subsets-ii.cpp) [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || From 9c4b72493185e94f078669f045a0c52e316bde60 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Feb 2018 02:04:30 +0800 Subject: [PATCH 4498/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d3a3e6d51..53738a76f 100644 --- a/README.md +++ b/README.md @@ -634,8 +634,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 047| [Permutations II](https://leetcode.com/problems/permutations-ii/)| [Python](./Python/permutations-ii.py) | _O(n * n!)_ | _O(n)_ | Medium || 051| [N-Queens](https://leetcode.com/problems/n-queens/) | [Python](./Python/n-queens.py) | _O(n!)_ | _O(n)_ | Hard || 052| [N-Queens-II](https://leetcode.com/problems/n-queens-ii/) | [Python](./Python/n-queens-ii.py) | _O(n!)_ | _O(n)_ | Hard || -077| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(n!)_ | _O(n)_ | Medium || -079| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(O(k * C(n, k)))_ | _O(k)_ | Medium || +077| [Combinations](https://leetcode.com/problems/combinations/) | [Python](./Python/combinations.py) | _O(O(k * C(n, k)))_ | _O(k)_ | Medium || +079| [Word Search](https://leetcode.com/problems/word-search/) | [Python](./Python/word-search.py) | _O(m * n * l)_ | _O(l)_ | Medium || 093| [Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) | [Python](./Python/restore-ip-addresses.py) | _O(1)_ | _O(1)_ | Medium || 078| [Subsets](https://leetcode.com/problems/subsets/) | [C++](./C++/subsets.cpp) [Python](./Python/subsets.py) | _O(n * 2^n)_ | _O(1)_ | Medium || 090| [Subsets II](https://leetcode.com/problems/subsets-ii/) | [C++](./C++/subsets-ii.cpp) [Python](./Python/subsets-ii.py) | _O(n * 2^n)_ | _O(1)_ | Medium || From 5506ac9b69d1ef1ce8ad22dc5621cd34ed94a332 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Feb 2018 02:14:15 +0800 Subject: [PATCH 4499/4971] Update combinations.py --- Python/combinations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/combinations.py b/Python/combinations.py index d77ce0e4f..7a4ba2a5f 100644 --- a/Python/combinations.py +++ b/Python/combinations.py @@ -30,7 +30,7 @@ def combine(self, n, k): if len(combination) == k or \ len(combination)+(n-i+1) < k: if not combination: - return result + break i = combination.pop()+1 else: combination.append(i) From f1f044a1b24a0cb63755b45593cd568136b3e6e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 15:01:55 +0800 Subject: [PATCH 4500/4971] Create preimage-size-of-factorial-zeroes-function.py --- ...image-size-of-factorial-zeroes-function.py | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/preimage-size-of-factorial-zeroes-function.py diff --git a/Python/preimage-size-of-factorial-zeroes-function.py b/Python/preimage-size-of-factorial-zeroes-function.py new file mode 100644 index 000000000..6fce5e9b4 --- /dev/null +++ b/Python/preimage-size-of-factorial-zeroes-function.py @@ -0,0 +1,46 @@ +# Time: O((logn)^2) +# Space: O(1) + +# Let f(x) be the number of zeroes at the end of x!. +# (Recall that x! = 1 * 2 * 3 * ... * x, and by convention, 0! = 1.) +# +# For example, f(3) = 0 because 3! = 6 has no zeroes at the end, +# while f(11) = 2 because 11! = 39916800 has 2 zeroes at the end. +# Given K, find how many non-negative integers x have the property that f(x) = K. +# +# Example 1: +# Input: K = 0 +# Output: 5 +# Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes. +# +# Example 2: +# Input: K = 5 +# Output: 0 +# Explanation: There is no x such that x! ends in K = 5 zeroes. +# Note: +# - K will be an integer in the range [0, 10^9]. + +class Solution(object): + def preimageSizeFZF(self, K): + """ + :type K: int + :rtype: int + """ + def count_of_factorial_primes(n, p): + cnt = 0 + while n > 0: + cnt += n//p + n /= p + return cnt + + p = 5 + left, right = 0, p*K + while left <= right: + mid = left + (right-left)//2 + if count_of_factorial_primes(mid, p) >= K: + right = mid-1 + else: + left = mid+1 + if count_of_factorial_primes(left, p) != K: + return 0 + return (left//p+1)*p - left From bde1b300a0b343edf65f5bf9ed5c7c441e324467 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 15:04:40 +0800 Subject: [PATCH 4501/4971] Update preimage-size-of-factorial-zeroes-function.py --- Python/preimage-size-of-factorial-zeroes-function.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/preimage-size-of-factorial-zeroes-function.py b/Python/preimage-size-of-factorial-zeroes-function.py index 6fce5e9b4..7b86429f0 100644 --- a/Python/preimage-size-of-factorial-zeroes-function.py +++ b/Python/preimage-size-of-factorial-zeroes-function.py @@ -30,7 +30,7 @@ def count_of_factorial_primes(n, p): cnt = 0 while n > 0: cnt += n//p - n /= p + n //= p return cnt p = 5 From 9cd5d25a081f13bc9d18b192beb69c3c73090d2b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 15:07:47 +0800 Subject: [PATCH 4502/4971] Create preimage-size-of-factorial-zeroes-function.cpp --- ...mage-size-of-factorial-zeroes-function.cpp | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/preimage-size-of-factorial-zeroes-function.cpp diff --git a/C++/preimage-size-of-factorial-zeroes-function.cpp b/C++/preimage-size-of-factorial-zeroes-function.cpp new file mode 100644 index 000000000..79dd93055 --- /dev/null +++ b/C++/preimage-size-of-factorial-zeroes-function.cpp @@ -0,0 +1,31 @@ +// Time: O((logn)^2) +// Space: O(1) + +class Solution { +public: + int preimageSizeFZF(int K) { + const int p = 5; + int left = 0, right = p * K; + while (left <= right) { + const int mid = left + (right - left) / 2; + if (countOfFactorialPrimes(mid, p) >= K) { + right = mid - 1; + } else { + left = mid + 1; + } + } + if (countOfFactorialPrimes(left, p) != K) { + return 0; + } + return (left / p + 1) * p - left; + } + +private: + int countOfFactorialPrimes(int n, int p) { + int cnt = 0; + for (; n > 0; n /= p) { + cnt += n / p; + } + return cnt; + } +}; From b6322c6fe385ca0f490378abe391da77fb592d25 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 15:13:25 +0800 Subject: [PATCH 4503/4971] Update preimage-size-of-factorial-zeroes-function.cpp --- C++/preimage-size-of-factorial-zeroes-function.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/C++/preimage-size-of-factorial-zeroes-function.cpp b/C++/preimage-size-of-factorial-zeroes-function.cpp index 79dd93055..bd1066a39 100644 --- a/C++/preimage-size-of-factorial-zeroes-function.cpp +++ b/C++/preimage-size-of-factorial-zeroes-function.cpp @@ -14,10 +14,8 @@ class Solution { left = mid + 1; } } - if (countOfFactorialPrimes(left, p) != K) { - return 0; - } - return (left / p + 1) * p - left; + return countOfFactorialPrimes(left, p) == K ? + (left / p + 1) * p - left : 0; } private: From 6cbfda8009369640b83819ac6af48ff470f855a2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 15:15:23 +0800 Subject: [PATCH 4504/4971] Update preimage-size-of-factorial-zeroes-function.py --- Python/preimage-size-of-factorial-zeroes-function.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/preimage-size-of-factorial-zeroes-function.py b/Python/preimage-size-of-factorial-zeroes-function.py index 7b86429f0..2dc116253 100644 --- a/Python/preimage-size-of-factorial-zeroes-function.py +++ b/Python/preimage-size-of-factorial-zeroes-function.py @@ -41,6 +41,6 @@ def count_of_factorial_primes(n, p): right = mid-1 else: left = mid+1 - if count_of_factorial_primes(left, p) != K: - return 0 - return (left//p+1)*p - left + return (left//p+1)*p - left \ + if count_of_factorial_primes(left, p) == K \ + else 0 From 7fe396a7ada06e1bf7996cad12693b37c96fc157 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 15:19:23 +0800 Subject: [PATCH 4505/4971] Update preimage-size-of-factorial-zeroes-function.cpp --- C++/preimage-size-of-factorial-zeroes-function.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/preimage-size-of-factorial-zeroes-function.cpp b/C++/preimage-size-of-factorial-zeroes-function.cpp index bd1066a39..3f02ab71f 100644 --- a/C++/preimage-size-of-factorial-zeroes-function.cpp +++ b/C++/preimage-size-of-factorial-zeroes-function.cpp @@ -14,8 +14,7 @@ class Solution { left = mid + 1; } } - return countOfFactorialPrimes(left, p) == K ? - (left / p + 1) * p - left : 0; + return countOfFactorialPrimes(left, p) == K ? p : 0; } private: From 94e2e87512e94c3429cdc1075f90ab41f01998e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 15:19:52 +0800 Subject: [PATCH 4506/4971] Update preimage-size-of-factorial-zeroes-function.py --- Python/preimage-size-of-factorial-zeroes-function.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/preimage-size-of-factorial-zeroes-function.py b/Python/preimage-size-of-factorial-zeroes-function.py index 2dc116253..1bb7c4e2c 100644 --- a/Python/preimage-size-of-factorial-zeroes-function.py +++ b/Python/preimage-size-of-factorial-zeroes-function.py @@ -41,6 +41,5 @@ def count_of_factorial_primes(n, p): right = mid-1 else: left = mid+1 - return (left//p+1)*p - left \ - if count_of_factorial_primes(left, p) == K \ + return p if count_of_factorial_primes(left, p) == K \ else 0 From 6959cd93a37535f0eb113dc9439d62227cb45ad1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 15:20:35 +0800 Subject: [PATCH 4507/4971] Update preimage-size-of-factorial-zeroes-function.py --- Python/preimage-size-of-factorial-zeroes-function.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/preimage-size-of-factorial-zeroes-function.py b/Python/preimage-size-of-factorial-zeroes-function.py index 1bb7c4e2c..2d9849e88 100644 --- a/Python/preimage-size-of-factorial-zeroes-function.py +++ b/Python/preimage-size-of-factorial-zeroes-function.py @@ -41,5 +41,4 @@ def count_of_factorial_primes(n, p): right = mid-1 else: left = mid+1 - return p if count_of_factorial_primes(left, p) == K \ - else 0 + return p if count_of_factorial_primes(left, p) == K else 0 From 62b60a347370f9b0697d1ed012558bfd9fa076c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 16:04:56 +0800 Subject: [PATCH 4508/4971] Create valid-tic-tac-toe-state.cpp --- C++/valid-tic-tac-toe-state.cpp | 54 +++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 C++/valid-tic-tac-toe-state.cpp diff --git a/C++/valid-tic-tac-toe-state.cpp b/C++/valid-tic-tac-toe-state.cpp new file mode 100644 index 000000000..cd61f04ad --- /dev/null +++ b/C++/valid-tic-tac-toe-state.cpp @@ -0,0 +1,54 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + bool validTicTacToe(vector& board) { + const auto FIRST = 'X', SECOND = 'O'; + const auto x_count = + accumulate(board.cbegin(), board.cend(), 0, + [&FIRST](int accu, const string& s) { + return accu + count(s.cbegin(), s.cend(), FIRST); + }); + const auto o_count = + accumulate(board.cbegin(), board.cend(), 0, + [&SECOND](int accu, const string& s) { + return accu + count(s.cbegin(), s.cend(), SECOND); + }); + if (o_count != x_count - 1 && o_count != x_count) { + return false; + } + if (isWin(board, FIRST) && o_count != x_count - 1) { + return false; + } + if (isWin(board, SECOND) && o_count != x_count) { + return false; + } + return true; + } + +private: + bool isWin(const vector& board, char player) { + for (int i = 0; i < board.size(); ++i) { + if (all_of(board[i].cbegin(), board[i].cend(), + [&player](const char& c) { + return c == player; + })) { + return true; + } + if (all_of(board.cbegin(), board.cend(), + [&i, &player](const string& row) { + return row[i] == player; + })) { + return true; + } + } + + return (player == board[1][1] && + board[1][1] == board[0][0] && + board[0][0] == board[2][2]) || + (player == board[1][1] && + board[1][1] == board[0][2] && + board[0][2] == board[2][0]); + } +}; From f60123ea933cba6b57214ad335b244b48cc65fdf Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 16:06:56 +0800 Subject: [PATCH 4509/4971] Create valid-tic-tac-toe-state.py --- Python/valid-tic-tac-toe-state.py | 64 +++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Python/valid-tic-tac-toe-state.py diff --git a/Python/valid-tic-tac-toe-state.py b/Python/valid-tic-tac-toe-state.py new file mode 100644 index 000000000..a8df880cb --- /dev/null +++ b/Python/valid-tic-tac-toe-state.py @@ -0,0 +1,64 @@ +# Time: O(1) +# Space: O(1) + +# A Tic-Tac-Toe board is given as a string array board. Return True +# if and only if it is possible to reach this board position +# during the course of a valid tic-tac-toe game. +# +# The board is a 3 x 3 array, and consists of characters " ", "X", +# and "O". The " " character represents an empty square. +# +# Here are the rules of Tic-Tac-Toe: +# - Players take turns placing characters into empty squares (" "). +# - The first player always places "X" characters, while the second player always places "O" characters. +# - "X" and "O" characters are always placed into empty squares, never filled ones. +# - The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal. +# - The game also ends if all squares are non-empty. +# - No more moves can be played if the game is over. +# +# Example 1: +# Input: board = ["O ", " ", " "] +# Output: false +# Explanation: The first player always plays "X". +# +# Example 2: +# Input: board = ["XOX", " X ", " "] +# Output: false +# Explanation: Players take turns making moves. +# +# Example 3: +# Input: board = ["XXX", " ", "OOO"] +# Output: false +# +# Example 4: +# Input: board = ["XOX", "O O", "XOX"] +# Output: true +# +# Note: +# - board is a length-3 array of strings, where each string board[i] has length 3. +# - Each board[i][j] is a character in the set {" ", "X", "O"}. + +class Solution(object): + def validTicTacToe(self, board): + """ + :type board: List[str] + :rtype: bool + """ + def win(board, player): + for i in xrange(3): + if all(board[i][j] == player for j in xrange(3)): + return True + if all(board[j][i] == player for j in xrange(3)): + return True + + return (player == board[1][1] == board[0][0] == board[2][2] or \ + player == board[1][1] == board[0][2] == board[2][0]) + + FIRST, SECOND = ('X', 'O') + x_count = sum(row.count(FIRST) for row in board) + o_count = sum(row.count(SECOND) for row in board) + if o_count not in {x_count-1, x_count}: return False + if win(board, FIRST) and x_count-1 != o_count: return False + if win(board, SECOND) and x_count != o_count: return False + + return True From b9b6b82b85041b5377ce5c8031ff5bf260e3bae2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 16:31:13 +0800 Subject: [PATCH 4510/4971] Create number-of-matching-subsequences.cpp --- C++/number-of-matching-subsequences.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/number-of-matching-subsequences.cpp diff --git a/C++/number-of-matching-subsequences.cpp b/C++/number-of-matching-subsequences.cpp new file mode 100644 index 000000000..b1965ef9b --- /dev/null +++ b/C++/number-of-matching-subsequences.cpp @@ -0,0 +1,22 @@ +// Time: O(n + w), n is the size of S, w is the size of words +// Space: O(1) + +class Solution { +public: + int numMatchingSubseq(string S, vector& words) { + unordered_map>> waiting; + for (int i = 0; i < words.size(); ++i) { + waiting[words[i][0]].emplace_back(i, 1); + } + for (const auto& c : S) { + auto advance = move(waiting[c]); + waiting.erase(c); + for (const auto& kvp : advance) { + int i = kvp.first, j = kvp.second; + int next = (j != words[i].length()) ? words[i][j] : 0; + waiting[next].emplace_back(i, j + 1); + } + } + return waiting[0].size(); + } +}; From 43916bdadc013f3df5cf2f6664facb19e98c1d90 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 16:44:46 +0800 Subject: [PATCH 4511/4971] Create number-of-matching-subsequences.py --- Python/number-of-matching-subsequences.py | 32 +++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/number-of-matching-subsequences.py diff --git a/Python/number-of-matching-subsequences.py b/Python/number-of-matching-subsequences.py new file mode 100644 index 000000000..86b8af903 --- /dev/null +++ b/Python/number-of-matching-subsequences.py @@ -0,0 +1,32 @@ +# Time: O(n + w), n is the size of S, w is the size of words +# Space: O(1) + +# Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. +# +# Example : +# Input: +# S = "abcde" +# words = ["a", "bb", "acd", "ace"] +# Output: 3 +# Explanation: There are three words in words that are a subsequence of S: "a", "acd", "ace". +# +# Note: +# - All words in words and S will only consists of lowercase letters. +# - The length of S will be in the range of [1, 50000]. +# - The length of words will be in the range of [1, 5000]. +# - The length of words[i] will be in the range of [1, 50]. + +class Solution(object): + def numMatchingSubseq(self, S, words): + """ + :type S: str + :type words: List[str] + :rtype: int + """ + waiting = collections.defaultdict(list) + for word in words: + waiting[word[0]].append(iter(word[1:])) + for c in S: + for it in waiting.pop(c, ()): + waiting[next(it, None)].append(it) + return len(waiting[None]) From c53105647b10259ee0abb61741bbb5ebbb6cbd97 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 16:56:57 +0800 Subject: [PATCH 4512/4971] Create number-of-subarrays-with-bounded-maximum.cpp --- ...mber-of-subarrays-with-bounded-maximum.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/number-of-subarrays-with-bounded-maximum.cpp diff --git a/C++/number-of-subarrays-with-bounded-maximum.cpp b/C++/number-of-subarrays-with-bounded-maximum.cpp new file mode 100644 index 000000000..203e69560 --- /dev/null +++ b/C++/number-of-subarrays-with-bounded-maximum.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int numSubarrayBoundedMax(vector& A, int L, int R) { + return count(A, R) - count(A, L - 1); + } + +private: + int count(const vector& A, int bound) const { + int result = 0, curr = 0; + for (const auto& i : A) { + curr = (i <= bound) ? curr + 1 : 0; + result += curr; + } + return result; + } +}; From f5c3b5b7cd01c3ca20cc339d196ca0df669c4702 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 16:57:36 +0800 Subject: [PATCH 4513/4971] Create number-of-subarrays-with-bounded-maximum.py --- ...umber-of-subarrays-with-bounded-maximum.py | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Python/number-of-subarrays-with-bounded-maximum.py diff --git a/Python/number-of-subarrays-with-bounded-maximum.py b/Python/number-of-subarrays-with-bounded-maximum.py new file mode 100644 index 000000000..56aaaaffc --- /dev/null +++ b/Python/number-of-subarrays-with-bounded-maximum.py @@ -0,0 +1,37 @@ +# Time: O(n) +# Space: O(1) + +# We are given an array A of positive integers, +# and two positive integers L and R (L <= R). +# +# Return the number of (contiguous, non-empty) subarrays +# such that the value of the maximum array element in that subarray is at least L and at most R. +# +# Example : +# Input: +# A = [2, 1, 4, 3] +# L = 2 +# R = 3 +# Output: 3 +# Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3]. +# +# Note: +# - L, R and A[i] will be an integer in the range [0, 10^9]. +# - The length of A will be in the range of [1, 50000]. + +class Solution(object): + def numSubarrayBoundedMax(self, A, L, R): + """ + :type A: List[int] + :type L: int + :type R: int + :rtype: int + """ + def count(A, bound): + result, curr = 0, 0 + for i in A : + curr = curr + 1 if i <= bound else 0 + result += curr + return result + + return count(A, R) - count(A, L-1) From 6e9eb33023c4f32e10de2aecf7ac706df66d0ca4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 17:03:11 +0800 Subject: [PATCH 4514/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 53738a76f..1623e039f 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,9 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 768 | [Max Chunks To Make Sorted II](https://leetcode.com/problems/max-chunks-to-make-sorted-ii/) | [C++](./C++/max-chunks-to-make-sorted-ii.cpp) [Python](./Python/max-chunks-to-make-sorted-ii.py) | _O(nlogn)_ | _O(n)_ | Hard || 769 | [Max Chunks To Make Sorted](https://leetcode.com/problems/max-chunks-to-make-sorted/) | [C++](./C++/max-chunks-to-make-sorted.cpp) [Python](./Python/max-chunks-to-make-sorted.py) | _O(n)_ | _O(1)_ | Medium || 778 | [Swim in Rising Water](https://leetcode.com/problems/swim-in-rising-water/) | [C++](./C++/swim-in-rising-water.cpp) [Python](./Python/swim-in-rising-water.py) | _O(n^2)_ | _O(n^2)_ | Hard || Union Find +792 | [Number of Matching Subsequences](https://leetcode.com/problems/number-of-matching-subsequences/) | [C++](./C++/number-of-matching-subsequences.cpp) [Python](./Python/number-of-matching-subsequences.py) | _O(n + w)_ | _O(1)_ | Medium || +794 | [Valid Tic-Tac-Toe State](https://leetcode.com/problems/valid-tic-tac-toe-state/) | [C++](./C++/valid-tic-tac-toe-state.cpp) [Python](./Python/valid-tic-tac-toe-state.py) | _O(1)_ | _O(1)_ | Medium || +795 | [Number of Subarrays with Bounded Maximum](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/) | [C++](./C++/number-of-subarrays-with-bounded-maximum.cpp) [Python](./Python/number-of-subarrays-with-bounded-maximum.py) | _O(1)_ | _O(1)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -543,6 +546,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 744 | [Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/) | [C++](./C++/find-smallest-letter-greater-than-target.cpp) [Python](./Python/find-smallest-letter-greater-than-target.py) | _O(logn)_ | _O(1)_ | Easy | | 774 | [Minimize Max Distance to Gas Station](https://leetcode.com/problems/minimize-max-distance-to-gas-station/) | [C++](./C++/minimize-max-distance-to-gas-station.cpp) [Python](./Python/minimize-max-distance-to-gas-station.py) | _O(nlogr)_ | _O(1)_ | Hard | | 786 | [K-th Smallest Prime Fraction](https://leetcode.com/problems/k-th-smallest-prime-fraction/) | [C++](./C++/k-th-smallest-prime-fraction.cpp) [Python](./Python/k-th-smallest-prime-fraction.py) | _O(nlogr)_ | _O(1)_ | Hard | | +793 | [Preimage Size of Factorial Zeroes Function](https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/) | [C++](./C++/preimage-size-of-factorial-zeroes-function.cpp) [Python](./Python/preimage-size-of-factorial-zeroes-function.py) | _O((logn)^2)_ | _O(1)_ | Hard | | ## Binary Search Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 6ca669f8ba84c02536f967d2f695bcdcf967ec79 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 4 Mar 2018 17:05:14 +0800 Subject: [PATCH 4515/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1623e039f..e3b94f04b 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 778 | [Swim in Rising Water](https://leetcode.com/problems/swim-in-rising-water/) | [C++](./C++/swim-in-rising-water.cpp) [Python](./Python/swim-in-rising-water.py) | _O(n^2)_ | _O(n^2)_ | Hard || Union Find 792 | [Number of Matching Subsequences](https://leetcode.com/problems/number-of-matching-subsequences/) | [C++](./C++/number-of-matching-subsequences.cpp) [Python](./Python/number-of-matching-subsequences.py) | _O(n + w)_ | _O(1)_ | Medium || 794 | [Valid Tic-Tac-Toe State](https://leetcode.com/problems/valid-tic-tac-toe-state/) | [C++](./C++/valid-tic-tac-toe-state.cpp) [Python](./Python/valid-tic-tac-toe-state.py) | _O(1)_ | _O(1)_ | Medium || -795 | [Number of Subarrays with Bounded Maximum](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/) | [C++](./C++/number-of-subarrays-with-bounded-maximum.cpp) [Python](./Python/number-of-subarrays-with-bounded-maximum.py) | _O(1)_ | _O(1)_ | Medium || +795 | [Number of Subarrays with Bounded Maximum](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/) | [C++](./C++/number-of-subarrays-with-bounded-maximum.cpp) [Python](./Python/number-of-subarrays-with-bounded-maximum.py) | _O(n)_ | _O(1)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 498e85a6e734df538745535609a96ccd5523289e Mon Sep 17 00:00:00 2001 From: Harish Date: Tue, 6 Mar 2018 22:51:58 -0500 Subject: [PATCH 4516/4971] fix - type error because of float --- 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 596fffaaf..70c5daf04 100644 --- a/Python/longest-increasing-subsequence.py +++ b/Python/longest-increasing-subsequence.py @@ -27,7 +27,7 @@ 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; + mid = int(left + (right - left) / 2) if LIS[mid] >= target: right = mid - 1 else: From 212534396d53237d60c5babe4366f2b7e1e10f84 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 7 Mar 2018 22:15:33 +0800 Subject: [PATCH 4517/4971] 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 70c5daf04..ac477873b 100644 --- a/Python/longest-increasing-subsequence.py +++ b/Python/longest-increasing-subsequence.py @@ -27,7 +27,7 @@ def insert(target): left, right = 0, len(LIS) - 1 # Find the first index "left" which satisfies LIS[left] >= target while left <= right: - mid = int(left + (right - left) / 2) + mid = left + (right - left) // 2 if LIS[mid] >= target: right = mid - 1 else: From a9858cc3679d748fcbd51fffce0926ad55eaecfe Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Mar 2018 23:55:26 +0800 Subject: [PATCH 4518/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index e3b94f04b..cef511d60 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | +522| [Longest Uncommon Subsequence II](https://leetcode.com/problems/longest-uncommon-subsequence-ii/) | [C++](./C++/longest-uncommon-subsequence-ii.cpp) [Python](./Python/longest-uncommon-subsequence-ii.py) | _O(l * n^2)_ | _O(1)_ | Medium | | 524| [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/) | [C++](./C++/longest-word-in-dictionary-through-deleting.cpp) [Python](./Python/longest-word-in-dictionary-through-deleting.py) | _O((d * l) * logd)_ | _O(1)_ | Medium | | Sort 527| [Word Abbreviation](https://leetcode.com/problems/word-abbreviation/) | [C++](./C++/word-abbreviation.cpp) [Python](./Python/word-abbreviation.py) | _O(n * l)_ ~ _O(n^2 * l^2)_ | _O(n * l)_ | Hard |📖| 539| [Minimum Time Difference](https://leetcode.com/problems/minimum-time-difference/) | [C++](./C++/minimum-time-difference.cpp) [Python](./Python/minimum-time-difference.py) | _O(nlogn)_ | _O(n)_ | Medium | | From 3621cc89634dde6643bc1857780c2f70afe630d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 8 Mar 2018 23:56:14 +0800 Subject: [PATCH 4519/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cef511d60..8cc7fe4a6 100644 --- a/README.md +++ b/README.md @@ -181,7 +181,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | -522| [Longest Uncommon Subsequence II](https://leetcode.com/problems/longest-uncommon-subsequence-ii/) | [C++](./C++/longest-uncommon-subsequence-ii.cpp) [Python](./Python/longest-uncommon-subsequence-ii.py) | _O(l * n^2)_ | _O(1)_ | Medium | | +522| [Longest Uncommon Subsequence II](https://leetcode.com/problems/longest-uncommon-subsequence-ii/) | [C++](./C++/longest-uncommon-subsequence-ii.cpp) [Python](./Python/longest-uncommon-subsequence-ii.py) | _O(l * n^2)_ | _O(1)_ | Medium | | Sort 524| [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/) | [C++](./C++/longest-word-in-dictionary-through-deleting.cpp) [Python](./Python/longest-word-in-dictionary-through-deleting.py) | _O((d * l) * logd)_ | _O(1)_ | Medium | | Sort 527| [Word Abbreviation](https://leetcode.com/problems/word-abbreviation/) | [C++](./C++/word-abbreviation.cpp) [Python](./Python/word-abbreviation.py) | _O(n * l)_ ~ _O(n^2 * l^2)_ | _O(n * l)_ | Hard |📖| 539| [Minimum Time Difference](https://leetcode.com/problems/minimum-time-difference/) | [C++](./C++/minimum-time-difference.cpp) [Python](./Python/minimum-time-difference.py) | _O(nlogn)_ | _O(n)_ | Medium | | From 389531f9282a8c5c5994d1f85334610a7e04f559 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Mar 2018 00:15:06 +0800 Subject: [PATCH 4520/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 8cc7fe4a6..20e50e2e2 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | +521| [Longest Uncommon Subsequence I](https://leetcode.com/problems/longest-uncommon-subsequence-i/) | [C++](./C++/longest-uncommon-subsequence-i.cpp) [Python](./Python/longest-uncommon-subsequence-i.py) | _O(min(a, b))_ | _O(1)_ | Easy | | Sort 522| [Longest Uncommon Subsequence II](https://leetcode.com/problems/longest-uncommon-subsequence-ii/) | [C++](./C++/longest-uncommon-subsequence-ii.cpp) [Python](./Python/longest-uncommon-subsequence-ii.py) | _O(l * n^2)_ | _O(1)_ | Medium | | Sort 524| [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/) | [C++](./C++/longest-word-in-dictionary-through-deleting.cpp) [Python](./Python/longest-word-in-dictionary-through-deleting.py) | _O((d * l) * logd)_ | _O(1)_ | Medium | | Sort 527| [Word Abbreviation](https://leetcode.com/problems/word-abbreviation/) | [C++](./C++/word-abbreviation.cpp) [Python](./Python/word-abbreviation.py) | _O(n * l)_ ~ _O(n^2 * l^2)_ | _O(n * l)_ | Hard |📖| From da52248b52b848dfb8db7eaa4ad665aadb1c05fc Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 9 Mar 2018 00:15:38 +0800 Subject: [PATCH 4521/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 20e50e2e2..5bc3ccb63 100644 --- a/README.md +++ b/README.md @@ -181,7 +181,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | -521| [Longest Uncommon Subsequence I](https://leetcode.com/problems/longest-uncommon-subsequence-i/) | [C++](./C++/longest-uncommon-subsequence-i.cpp) [Python](./Python/longest-uncommon-subsequence-i.py) | _O(min(a, b))_ | _O(1)_ | Easy | | Sort +521| [Longest Uncommon Subsequence I](https://leetcode.com/problems/longest-uncommon-subsequence-i/) | [C++](./C++/longest-uncommon-subsequence-i.cpp) [Python](./Python/longest-uncommon-subsequence-i.py) | _O(min(a, b))_ | _O(1)_ | Easy | | 522| [Longest Uncommon Subsequence II](https://leetcode.com/problems/longest-uncommon-subsequence-ii/) | [C++](./C++/longest-uncommon-subsequence-ii.cpp) [Python](./Python/longest-uncommon-subsequence-ii.py) | _O(l * n^2)_ | _O(1)_ | Medium | | Sort 524| [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/) | [C++](./C++/longest-word-in-dictionary-through-deleting.cpp) [Python](./Python/longest-word-in-dictionary-through-deleting.py) | _O((d * l) * logd)_ | _O(1)_ | Medium | | Sort 527| [Word Abbreviation](https://leetcode.com/problems/word-abbreviation/) | [C++](./C++/word-abbreviation.cpp) [Python](./Python/word-abbreviation.py) | _O(n * l)_ ~ _O(n^2 * l^2)_ | _O(n * l)_ | Hard |📖| From 6e18fba96fe9eefeb2e05b0609c5a41266db490e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 10 Mar 2018 19:27:26 +0800 Subject: [PATCH 4522/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5bc3ccb63..67c28d96c 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 443| [String Compression](https://leetcode.com/problems/string-compression/) | [C++](./C++/string-compression.cpp) [Python](./Python/string-compression.py) | _O(n)_ | _O(1)_ | Easy | | 459| [Repeated Substring Pattern](https://leetcode.com/problems/repeated-substring-pattern/) | [C++](./C++/repeated-substring-pattern.cpp) [Python](./Python/repeated-substring-pattern.py) | _O(n)_ | _O(n)_ | Easy || `KMP Algorithm` | 468| [Validate IP Address](https://leetcode.com/problems/validate-ip-address/) | [C++](./C++/validate-ip-address.cpp) [Python](./Python/validate-ip-address.py) | _O(1)_ | _O(1)_ | Medium | | +520| [Detect Capital](https://leetcode.com/problems/detect-capital/) | [C++](./C++/detect-capital.cpp) [Python](./Python/detect-capital.py) | _O(l)_ | _O(1)_ | Easy | | 521| [Longest Uncommon Subsequence I](https://leetcode.com/problems/longest-uncommon-subsequence-i/) | [C++](./C++/longest-uncommon-subsequence-i.cpp) [Python](./Python/longest-uncommon-subsequence-i.py) | _O(min(a, b))_ | _O(1)_ | Easy | | 522| [Longest Uncommon Subsequence II](https://leetcode.com/problems/longest-uncommon-subsequence-ii/) | [C++](./C++/longest-uncommon-subsequence-ii.cpp) [Python](./Python/longest-uncommon-subsequence-ii.py) | _O(l * n^2)_ | _O(1)_ | Medium | | Sort 524| [Longest Word in Dictionary through Deleting](https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/) | [C++](./C++/longest-word-in-dictionary-through-deleting.cpp) [Python](./Python/longest-word-in-dictionary-through-deleting.py) | _O((d * l) * logd)_ | _O(1)_ | Medium | | Sort From 1eca0a30b5f787445acc286e798d10facaa31e07 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 11 Mar 2018 23:59:29 +0800 Subject: [PATCH 4523/4971] Create smallest-rotation-with-highest-score.cpp --- C++/smallest-rotation-with-highest-score.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/smallest-rotation-with-highest-score.cpp diff --git a/C++/smallest-rotation-with-highest-score.cpp b/C++/smallest-rotation-with-highest-score.cpp new file mode 100644 index 000000000..089f143e5 --- /dev/null +++ b/C++/smallest-rotation-with-highest-score.cpp @@ -0,0 +1,17 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int bestRotation(vector& A) { + const int N = A.size(); + vector change(N); + for (int i = 0; i < N; ++i) { + --change[(i - A[i] + 1 + N) % N]; + } + for (int i = 1; i < N; ++i) { + change[i] += change[i - 1] + 1; + } + return distance(change.begin(), max_element(change.begin(), change.begin() + N)); + } +}; From 46d4570d8dc8d70b56c439ab3ceedcf335768e8d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 00:23:03 +0800 Subject: [PATCH 4524/4971] Create smallest-rotation-with-highest-score.py --- .../smallest-rotation-with-highest-score.py | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/smallest-rotation-with-highest-score.py diff --git a/Python/smallest-rotation-with-highest-score.py b/Python/smallest-rotation-with-highest-score.py new file mode 100644 index 000000000..c46d7421d --- /dev/null +++ b/Python/smallest-rotation-with-highest-score.py @@ -0,0 +1,52 @@ +# Time: O(n) +# Space: O(n) + +# Given an array A, we may rotate it by a non-negative integer K +# so that the array becomes A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1]. +# Afterward, any entries that are less than or equal to their index are worth 1 point. +# +# For example, if we have [2, 4, 1, 3, 0], and we rotate by K = 2, +# it becomes [1, 3, 0, 2, 4]. +# This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], +# 0 <= 2 [one point], 2 <= 3 [one point], 4 <= 4 [one point]. +# +# Over all possible rotations, +# return the rotation index K that corresponds to the highest score we could receive. +# If there are multiple answers, return the smallest such index K. +# +# Example 1: +# Input: [2, 3, 1, 4, 0] +# Output: 3 +# Explanation: +# Scores for each K are listed below: +# K = 0, A = [2,3,1,4,0], score 2 +# K = 1, A = [3,1,4,0,2], score 3 +# K = 2, A = [1,4,0,2,3], score 3 +# K = 3, A = [4,0,2,3,1], score 4 +# K = 4, A = [0,2,3,1,4], score 3 +# So we should choose K = 3, which has the highest score. +# +# Example 2: +# Input: [1, 3, 0, 2, 4] +# Output: 0 +# Explanation: A will always have 3 points no matter how it shifts. +# So we will choose the smallest K, which is 0. +# +# Note: +# - A will have length at most 20000. +# - A[i] will be in the range [0, A.length]. + +class Solution(object): + def bestRotation(self, A): + """ + :type A: List[int] + :rtype: int + """ + N = len(A) + change = [1] * N + for i in xrange(N): + change[(i-A[i]+1)%N] -= 1 + for i in xrange(1, N): + change[i] += change[i-1] + return change.index(max(change)) + From 0cd9bc85f40fdf8d8054103fa0c946184c65be84 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 00:50:59 +0800 Subject: [PATCH 4525/4971] Create champagne-tower.cpp --- C++/champagne-tower.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/champagne-tower.cpp diff --git a/C++/champagne-tower.cpp b/C++/champagne-tower.cpp new file mode 100644 index 000000000..ce79eade8 --- /dev/null +++ b/C++/champagne-tower.cpp @@ -0,0 +1,17 @@ +// Time: O(n^2) = O(1), since n is at most 99 +// Space: O(n) = O(1) + +class Solution { +public: + double champagneTower(int poured, int query_row, int query_glass) { + vector result(query_row + 2); + result[0] = poured; + for (int i = 1; i <= query_row; ++i) { + for(int j = i; j >= 0; --j) { + result[j] = max(0.0, (result[j] - 1) / 2); + result[j + 1] += result[j]; + } + } + return min(1.0, result[query_glass]); + } +}; From ea12b7c379b14639379947f9cda197620f076f0a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 01:01:18 +0800 Subject: [PATCH 4526/4971] Update champagne-tower.cpp --- C++/champagne-tower.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/champagne-tower.cpp b/C++/champagne-tower.cpp index ce79eade8..14cd8b371 100644 --- a/C++/champagne-tower.cpp +++ b/C++/champagne-tower.cpp @@ -4,14 +4,14 @@ class Solution { public: double champagneTower(int poured, int query_row, int query_glass) { - vector result(query_row + 2); + vector result(1 + query_row); result[0] = poured; for (int i = 1; i <= query_row; ++i) { for(int j = i; j >= 0; --j) { - result[j] = max(0.0, (result[j] - 1) / 2); - result[j + 1] += result[j]; + result[j] = max((result[j] - 1), 0.0) / 2 + + max((result[j - 1] - 1), 0.0) / 2; } } - return min(1.0, result[query_glass]); + return min(result[query_glass], 1.0); } }; From 3d6079d7f1b2de58b6f8ae960dc807d84d993f79 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 01:04:28 +0800 Subject: [PATCH 4527/4971] Create champagne-tower.py --- Python/champagne-tower.py | 55 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/champagne-tower.py diff --git a/Python/champagne-tower.py b/Python/champagne-tower.py new file mode 100644 index 000000000..ae3bac153 --- /dev/null +++ b/Python/champagne-tower.py @@ -0,0 +1,55 @@ +# Time: O(n^2) = O(1), since n is at most 99 +# Space: O(n) = O(1) + +# We stack glasses in a pyramid, where the first row has 1 glass, +# the second row has 2 glasses, and so on until the 100th row. +# Each glass holds one cup (250ml) of champagne. +# +# Then, some champagne is poured in the first glass at the top. +# When the top most glass is full, any excess liquid poured will fall +# equally to the glass immediately to the left and right of it. +# When those glasses become full, any excess champagne will fall +# equally to the left and right of those glasses, and so on. +# (A glass at the bottom row has it's excess champagne fall on the floor.) +# +# For example, after one cup of champagne is poured, the top most glass is full. +# After two cups of champagne are poured, the two glasses on the second row are half full. +# After three cups of champagne are poured, those two cups become full - +# there are 3 full glasses total now. After four cups of champagne are poured, +# the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below. +# +# Now after pouring some non-negative integer cups of champagne, +# return how full the j-th glass in the i-th row is (both i and j are 0 indexed.) +# +# Example 1: +# Input: poured = 1, query_glass = 1, query_row = 1 +# Output: 0.0 +# Explanation: We poured 1 cup of champange to the top glass of the tower +# (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty. +# +# Example 2: +# Input: poured = 2, query_glass = 1, query_row = 1 +# Output: 0.5 +# Explanation: We poured 2 cups of champange to the top glass of the tower +# (which is indexed as (0, 0)). There is one cup of excess liquid. +# The glass indexed as (1, 0) and the glass indexed as (1, 1) will share +# the excess liquid equally, and each will get half cup of champange. +# +# Note: +# - poured will be in the range of [0, 10 ^ 9]. +# - query_glass and query_row will be in the range of [0, 99]. + +class Solution(object): + def champagneTower(self, poured, query_row, query_glass): + """ + :type poured: int + :type query_row: int + :type query_glass: int + :rtype: float + """ + result = [poured] + [0] * query_row + for i in xrange(1, query_row+1): + for j in reversed(xrange(i+1)): + result[j] = max(result[j]-1, 0)/2.0 + \ + max(result[j-1]-1, 0)/2.0 + return min(result[query_glass], 1) From c71f90691ff79b4c85fe80a2db4ac0311e916e4c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 01:26:11 +0800 Subject: [PATCH 4528/4971] Create all-paths-from-source-to-target.cpp --- C++/all-paths-from-source-to-target.cpp | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/all-paths-from-source-to-target.cpp diff --git a/C++/all-paths-from-source-to-target.cpp b/C++/all-paths-from-source-to-target.cpp new file mode 100644 index 000000000..ec4e12698 --- /dev/null +++ b/C++/all-paths-from-source-to-target.cpp @@ -0,0 +1,28 @@ +// Time: O(p + r * n), p is the count of all the possible paths in graph, +// r is the count of the result. +// Space: O(n) + +class Solution { +public: + vector> allPathsSourceTarget(vector>& graph) { + vector> result; + vector path{0}; + dfs(graph, 0, &path, &result); + return result; + } + +private: + void dfs(const vector>& graph, + int curr, vector *path, + vector> *result) { + if (curr == graph.size() - 1) { + result->emplace_back(*path); + return; + } + for (const auto& node: graph[curr]) { + path->emplace_back(node); + dfs(graph, node, path, result); + path->pop_back(); + } + } +}; From 88f2b41db9c7a8012d1c3930d2197d1eac0de0e7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 01:30:27 +0800 Subject: [PATCH 4529/4971] Create all-paths-from-source-to-target.py --- Python/all-paths-from-source-to-target.py | 42 +++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/all-paths-from-source-to-target.py diff --git a/Python/all-paths-from-source-to-target.py b/Python/all-paths-from-source-to-target.py new file mode 100644 index 000000000..cb8feb53f --- /dev/null +++ b/Python/all-paths-from-source-to-target.py @@ -0,0 +1,42 @@ +# Time: O(p + r * n), p is the count of all the possible paths in graph, +# r is the count of the result. +# Space: O(n) + +# Given a directed, acyclic graph of N nodes. +# Find all possible paths from node 0 to node N-1, and return them in any order. +# +# The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. +# graph[i] is a list of all nodes j for which the edge (i, j) exists. +# +# Example: +# Input: [[1,2], [3], [3], []] +# Output: [[0,1,3],[0,2,3]] +# Explanation: The graph looks like this: +# 0--->1 +# | | +# v v +# 2--->3 +# There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. +# +# Note: +# - The number of nodes in the graph will be in the range [2, 15]. +# - You can print different paths in any order, but you should keep the order of nodes inside one path. + +class Solution(object): + def allPathsSourceTarget(self, graph): + """ + :type graph: List[List[int]] + :rtype: List[List[int]] + """ + def dfs(graph, curr, path, result): + if curr == len(graph)-1: + result.append(path[:]) + return + for node in graph[curr]: + path.append(node) + dfs(graph, node, path, result) + path.pop() + + result = [] + dfs(graph, 0, [0], result) + return result From 46e544efecd856b6bdb00b2d966a85abde6f3c5e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 01:38:25 +0800 Subject: [PATCH 4530/4971] Create rotate-string.cpp --- C++/rotate-string.cpp | 75 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 C++/rotate-string.cpp diff --git a/C++/rotate-string.cpp b/C++/rotate-string.cpp new file mode 100644 index 000000000..c225ebc7d --- /dev/null +++ b/C++/rotate-string.cpp @@ -0,0 +1,75 @@ +// Time: O(n + m) +// Space: O(1) + +// Rabin-Karp Algorithm (rolling hash) +class Solution { +public: + bool rotateString(string A, string B) { + static const uint64_t M = 1000000007; + static const uint64_t p = 113; + static const uint64_t p_inv = pow(p, M - 2, M); + + const auto q = (B.length() + A.length() - 1) / A.length(); + + uint64_t b_hash = 0, power = 1; + for (int i = 0; i < B.length(); ++i) { + b_hash += power * B[i]; + b_hash %= M; + power = (power * p) % M; + } + + uint64_t a_hash = 0; power = 1; + for (int i = 0; i < B.length(); ++i) { + a_hash += power * A[i % A.length()]; + a_hash %= M; + power = (power * p) % M; + } + if (a_hash == b_hash && check(0, A, B)) { + return true; + } + + power = (power * p_inv) % M; + for (int i = B.length(); i < (q + 1) * A.length(); ++i) { + a_hash -= A[(i - B.length()) % A.length()]; + a_hash *= p_inv; + a_hash += power * A[i % A.length()]; + a_hash %= M; + if (a_hash == b_hash && check(i - B.length() + 1, A, B)) { + return true; + } + } + return false; + } + +private: + bool check(int index, const string& A, const string& B) { + for (int i = 0; i < B.length(); ++i) { + if (A[(i + index) % A.length()] != B[i]) { + return false; + } + } + return true; + } + + uint64_t pow(uint64_t a,uint64_t b, uint64_t m) { + a %= m; + uint64_t result = 1; + while (b) { + if (b & 1) { + result = (result * a) % m; + } + a = (a * a) % m; + b >>= 1; + } + return result; + } +}; + +// Time: O(n * m) +// Space: O(n) +class Solution2 { +public: + bool rotateString(string A, string B) { + return A.size() == B.size() && (A + A).find(B) != string::npos; + } +}; From 1d7f2a842408c0585566f14a10952cc6874f5963 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 01:51:34 +0800 Subject: [PATCH 4531/4971] Create rotate-string.py --- Python/rotate-string.py | 71 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Python/rotate-string.py diff --git a/Python/rotate-string.py b/Python/rotate-string.py new file mode 100644 index 000000000..b71c693dc --- /dev/null +++ b/Python/rotate-string.py @@ -0,0 +1,71 @@ +# Time: O(n + m) +# Space: O(1) + +# We are given two strings, A and B. +# +# A shift on A consists of taking string A and moving the leftmost character to the rightmost position. +# For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True +# if and only if A can become B after some number of shifts on A. +# +# Example 1: +# Input: A = 'abcde', B = 'cdeab' +# Output: true +# +# Example 2: +# Input: A = 'abcde', B = 'abced' +# Output: false +# +# Note: +# - A and B will have length at most 100. + +# Rabin-Karp Algorithm (rolling hash) +class Solution(object): + def rotateString(self, A, B): + """ + :type A: str + :type B: str + :rtype: bool + """ + def check(index): + return all(A[(i+index) % len(A)] == c + for i, c in enumerate(B)) + + M, p = 10**9+7, 113 + p_inv = pow(p, M-2, M) + q = (len(B)+len(A)-1) // len(A) + + b_hash, power = 0, 1 + for c in B: + b_hash += power * ord(c) + b_hash %= M + power = (power*p) % M + + a_hash, power = 0, 1 + for i in xrange(len(B)): + a_hash += power * ord(A[i%len(A)]) + a_hash %= M + power = (power*p) % M + + if a_hash == b_hash and check(0): return True + + power = (power*p_inv) % M + for i in xrange(len(B), (q+1)*len(A)): + a_hash = (a_hash-ord(A[(i-len(B))%len(A)])) * p_inv + a_hash += power * ord(A[i%len(A)]) + a_hash %= M + if a_hash == b_hash and check(i-len(B)+1): + return True + + return False + + +# Time: O(n * m) +# Space: O(n) +class Solution2(object): + def rotateString(self, A, B): + """ + :type A: str + :type B: str + :rtype: bool + """ + return len(A) == len(B) and B in A + A From f36df6a6436ac9def9206e393ed8eed9c40fe88b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 01:57:54 +0800 Subject: [PATCH 4532/4971] Update rotate-string.cpp --- C++/rotate-string.cpp | 65 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/C++/rotate-string.cpp b/C++/rotate-string.cpp index c225ebc7d..3fe18b381 100644 --- a/C++/rotate-string.cpp +++ b/C++/rotate-string.cpp @@ -1,15 +1,16 @@ -// Time: O(n + m) +// Time: O(n ) // Space: O(1) // Rabin-Karp Algorithm (rolling hash) class Solution { public: bool rotateString(string A, string B) { + if (A.length() != B.length()) { + return false; + } static const uint64_t M = 1000000007; static const uint64_t p = 113; static const uint64_t p_inv = pow(p, M - 2, M); - - const auto q = (B.length() + A.length() - 1) / A.length(); uint64_t b_hash = 0, power = 1; for (int i = 0; i < B.length(); ++i) { @@ -29,7 +30,7 @@ class Solution { } power = (power * p_inv) % M; - for (int i = B.length(); i < (q + 1) * A.length(); ++i) { + for (int i = B.length(); i < 2 * A.length(); ++i) { a_hash -= A[(i - B.length()) % A.length()]; a_hash *= p_inv; a_hash += power * A[i % A.length()]; @@ -65,9 +66,63 @@ class Solution { } }; -// Time: O(n * m) +// Time: O(n) // Space: O(n) +// KMP algorithm class Solution2 { +public: + bool rotateString(string A, string B) { + if (A.length() != B.length()) { + return false; + } + return strStr(A + A, B) != -1; + } + +private: + 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^2) +// Space: O(n) +class Solution3 { public: bool rotateString(string A, string B) { return A.size() == B.size() && (A + A).find(B) != string::npos; From 341f747203522a1706f05a761389003d8059d0ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 01:58:09 +0800 Subject: [PATCH 4533/4971] Update rotate-string.cpp --- C++/rotate-string.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/rotate-string.cpp b/C++/rotate-string.cpp index 3fe18b381..0ae259746 100644 --- a/C++/rotate-string.cpp +++ b/C++/rotate-string.cpp @@ -1,4 +1,4 @@ -// Time: O(n ) +// Time: O(n) // Space: O(1) // Rabin-Karp Algorithm (rolling hash) From ea0c1389739962fcd3f57e265cce29835ded0bef Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 02:01:44 +0800 Subject: [PATCH 4534/4971] Update implement-strstr.py --- Python/implement-strstr.py | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index 6af9a5ec2..a592a3654 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -44,16 +44,6 @@ def getPrefix(self, pattern): prefix[i] = j return prefix - def strStr2(self, haystack, needle): - """ - :type haystack: str - :type needle: str - :rtype: int - """ - try: - return haystack.index(needle) - except: - return -1 # Time: O(n * k) # Space: O(k) @@ -68,7 +58,8 @@ def strStr(self, haystack, needle): if haystack[i : i + len(needle)] == needle: return i return -1 - + + if __name__ == "__main__": print Solution().strStr("a", "") print Solution().strStr("abababcdab", "ababcdx") From 3b80375cb5ea7765d12711b2b1cd72c7899355ca Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 02:06:21 +0800 Subject: [PATCH 4535/4971] Update rotate-string.py --- Python/rotate-string.py | 55 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 5 deletions(-) diff --git a/Python/rotate-string.py b/Python/rotate-string.py index b71c693dc..4fb92f055 100644 --- a/Python/rotate-string.py +++ b/Python/rotate-string.py @@ -1,4 +1,4 @@ -# Time: O(n + m) +# Time: O(n) # Space: O(1) # We are given two strings, A and B. @@ -30,9 +30,11 @@ def check(index): return all(A[(i+index) % len(A)] == c for i, c in enumerate(B)) + if len(A) != len(B): + return False + M, p = 10**9+7, 113 p_inv = pow(p, M-2, M) - q = (len(B)+len(A)-1) // len(A) b_hash, power = 0, 1 for c in B: @@ -49,7 +51,7 @@ def check(index): if a_hash == b_hash and check(0): return True power = (power*p_inv) % M - for i in xrange(len(B), (q+1)*len(A)): + for i in xrange(len(B), 2*len(A)): a_hash = (a_hash-ord(A[(i-len(B))%len(A)])) * p_inv a_hash += power * ord(A[i%len(A)]) a_hash %= M @@ -58,10 +60,53 @@ def check(index): return False - -# Time: O(n * m) + +# Time: O(n) # Space: O(n) +# KMP algorithm class Solution2(object): + def rotateString(self, A, B): + """ + :type A: str + :type B: str + :rtype: bool + """ + def strStr(haystack, needle): + def KMP(text, pattern): + prefix = getPrefix(pattern) + j = -1 + for i in xrange(len(text)): + while j > -1 and pattern[j + 1] != text[i]: + j = prefix[j] + if pattern[j + 1] == text[i]: + j += 1 + if j == len(pattern) - 1: + return i - j + return -1 + + 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 needle: + return 0 + return KMP(haystack, needle) + + if len(A) != len(B): + return False + return strStr(A * 2, B) != -1 + + +# Time: O(n^2) +# Space: O(n) +class Solution3(object): def rotateString(self, A, B): """ :type A: str From d4261cdee60f7129cd304c3c4b8e68ae5bcf6566 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 02:07:10 +0800 Subject: [PATCH 4536/4971] Update rotate-string.py --- Python/rotate-string.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/rotate-string.py b/Python/rotate-string.py index 4fb92f055..b988e3bf4 100644 --- a/Python/rotate-string.py +++ b/Python/rotate-string.py @@ -101,7 +101,7 @@ def getPrefix(pattern): if len(A) != len(B): return False - return strStr(A * 2, B) != -1 + return strStr(A*2, B) != -1 # Time: O(n^2) @@ -113,4 +113,4 @@ def rotateString(self, A, B): :type B: str :rtype: bool """ - return len(A) == len(B) and B in A + A + return len(A) == len(B) and B in A*2 From fa274fbc2936d597f7ec39e19c71ac52f1fcf06b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 02:15:18 +0800 Subject: [PATCH 4537/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 67c28d96c..dbca31c9c 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 751| [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) | [C++](./C++/ip-to-cidr.cpp) [Python](./Python/ip-to-cidr.py) | _O(n)_ | _O(1)_ | Medium ||| 758| [Bold Words in String](https://leetcode.com/contest/weekly-contest-66/problems/bold-words-in-string/) | [C++](./C++/bold-words-in-string.cpp) [Python](./Python/bold-words-in-string.py) | _O(n * l)_ | _O(t)_ | Easy | 📖, variant of [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | 791| [Custom Sort String](https://leetcode.com/problems/custom-sort-string/) | [C++](./C++/custom-sort-string.cpp) [Python](./Python/custom-sort-string.py) | _O(n)_ | _O(1)_ | Medium ||| +796| [Rotate String](https://leetcode.com/problems/rotate-string/) | [C++](./C++/rotate-string.cpp) [Python](./Python/rotate-string.py) | _O(n)_ | _O(1)_ | Easy || `KMP Algorithm` Rolling Hash | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -628,6 +629,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 753| [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/) | [C++](./C++/cracking-the-safe.cpp) [Python](./Python/cracking-the-safe.py) | _O(k^n)_ | _O(k^n)_ | Hard || `de Bruijn sequences`, `Lyndon word` | 756| [Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix/) | [C++](./C++/pyramid-transition-matrix.cpp) [Python](./Python/pyramid-transition-matrix.py) | _O(a^b)_ | _O(a^b)_ | Medium ||| 785| [Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/) | [C++](./C++/is-graph-bipartite.cpp) [Python](./Python/is-graph-bipartite.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium ||| +797| [All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target/) | [C++](./C++/all-paths-from-source-to-target.cpp) [Python](./Python/all-paths-from-source-to-target.py) | _O(p + r * n)_ | _O(n)_ | Medium ||| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -741,6 +743,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 764 | [Largest Plus Sign](https://leetcode.com/problems/largest-plus-sign/) | [C++](./C++/largest-plus-sign.cpp) [Python](./Python/largest-plus-sign.py) | _O(n^2)_ | _O(n^2)_ | Medium || 788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/) | [C++](./C++/rotated-digits.cpp) [Python](./Python/rotated-digits.py) | _O(logn)_ | _O(logn)_ | Easy || Memoization | 790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/) | [C++](./C++/domino-and-tromino-tiling.cpp) [Python](./Python/domino-and-tromino-tiling.py) | _O(logn)_ | _O(logn)_ | Medium || Matrix Exponentiation | +799 | [Champagne Tower](https://leetcode.com/problems/champagne-tower/) | [C++](./C++/champagne-tower.cpp) [Python](./Python/champagne-tower.py) | _O(n^2)_ | _O(n)_ | Medium ||| ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -773,6 +776,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 759 | [Employee Free Time](https://leetcode.com/problems/employee-free-time/) | [C++](./C++/employee-free-time.cpp) [Python](./Python/employee-free-time.py) | _O(m * logn)_ | _O(n)_ | Hard | | 763 | [Partition Labels](https://leetcode.com/problems/partition-labels/) | [C++](./C++/partition-labels.cpp) [Python](./Python/partition-labels.py) | _O(n)_ | _O(n)_ | Medium | | 767 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | [C++](./C++/reorganize-string.cpp) [Python](./Python/reorganize-string.py) | _O(n)_ | _O(1)_ | Medium | | +798 | [Smallest Rotation with Highest Score](https://leetcode.com/problems/smallest-rotation-with-highest-score/) | [C++](./C++/smallest-rotation-with-highest-score.cpp) [Python](./Python/smallest-rotation-with-highest-score.py) | _O(n)_ | _O(1)_ | Hard | | ## Graph | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From d2a61ddeeeda81f329ce7c55b9b56fd581616368 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 12 Mar 2018 02:17:07 +0800 Subject: [PATCH 4538/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dbca31c9c..7a0f0c8ce 100644 --- a/README.md +++ b/README.md @@ -207,7 +207,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 751| [IP to CIDR](https://leetcode.com/problems/ip-to-cidr/) | [C++](./C++/ip-to-cidr.cpp) [Python](./Python/ip-to-cidr.py) | _O(n)_ | _O(1)_ | Medium ||| 758| [Bold Words in String](https://leetcode.com/contest/weekly-contest-66/problems/bold-words-in-string/) | [C++](./C++/bold-words-in-string.cpp) [Python](./Python/bold-words-in-string.py) | _O(n * l)_ | _O(t)_ | Easy | 📖, variant of [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | 791| [Custom Sort String](https://leetcode.com/problems/custom-sort-string/) | [C++](./C++/custom-sort-string.cpp) [Python](./Python/custom-sort-string.py) | _O(n)_ | _O(1)_ | Medium ||| -796| [Rotate String](https://leetcode.com/problems/rotate-string/) | [C++](./C++/rotate-string.cpp) [Python](./Python/rotate-string.py) | _O(n)_ | _O(1)_ | Easy || `KMP Algorithm` Rolling Hash | +796| [Rotate String](https://leetcode.com/problems/rotate-string/) | [C++](./C++/rotate-string.cpp) [Python](./Python/rotate-string.py) | _O(n)_ | _O(1)_ | Easy || `KMP Algorithm` `Rabin-Karp Algorithm` | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 6145dde77792f5421a52562747eaa5a4c3e973db Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 13 Mar 2018 23:29:53 +0800 Subject: [PATCH 4539/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7a0f0c8ce..e21ee4324 100644 --- a/README.md +++ b/README.md @@ -419,6 +419,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 453 | [Minimum Moves to Equal Array Elements](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/) | [C++](./C++/minimum-moves-to-equal-array-elements.cpp) [Python](./Python/minimum-moves-to-equal-array-elements.py) | _O(n)_ | _O(1)_ | Easy ||| 458 | [Poor Pigs](https://leetcode.com/problems/poor-pigs/) | [C++](./C++/poor-pigs.cpp) [Python](./Python/poor-pigs.py) | _O(n)_ | _O(1)_ | Easy ||| 469 | [Convex Polygon](https://leetcode.com/problems/convex-polygon/) | [C++](./C++/convex-polygon.cpp) [Python](./Python/convex-polygon.py) | _O(n)_ | _O(1)_ | Medium |📖|| +517 | [Super Washing Machines](https://leetcode.com/problems/super-washing-machines/) | [C++](./C++/super-washing-machines.cpp) [Python](./Python/super-washing-machines.py) | _O(n)_ | _O(1)_ | Hard ||| 537 | [Complex Number Multiplication](https://leetcode.com/problems/complex-number-multiplication/) | [C++](./C++/complex-number-multiplication.cpp) [Python](./Python/complex-number-multiplication.py) | _O(1)_ | _O(1)_ | Medium ||| 553 | [Optimal Division](https://leetcode.com/problems/optimal-division/) | [C++](./C++/optimal-division.cpp) [Python](./Python/optimal-division.py) | _O(n)_ | _O(1)_ | Medium ||| 573 | [Squirrel Simulation](https://leetcode.com/problems/squirrel-simulation/) | [C++](./C++/squirrel-simulation.cpp) [Python](./Python/squirrel-simulation.py) | _O(n)_ | _O(1)_ | Medium |📖|| From 1d29043251cda79937eafdc0b9077b50c16c0fa4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 14 Mar 2018 23:57:09 +0800 Subject: [PATCH 4540/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index e21ee4324..25db379b8 100644 --- a/README.md +++ b/README.md @@ -717,6 +717,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +516 | [Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/) | [C++](./C++/longest-palindromic-subsequence.cpp) [Python](./Python/longest-palindromic-subsequence.py) | _O(n^2)_ | _O(n)_ | Medium ||| 546 | [Remove Boxes](https://leetcode.com/problems/remove-boxes/) | [C++](./C++/remove-boxes.cpp) [Python](./Python/remove-boxes.py) | _O(n^3)_ ~ _O(n^4)_ | _O(n^3)_ | Hard ||| 552 | [Student Attendance Record II](https://leetcode.com/problems/student-attendance-record-ii/) | [C++](./C++/student-attendance-record-ii.cpp) [Python](./Python/student-attendance-record-ii.py) | _O(n)_ | _O(1)_ | Hard ||| 562 | [Longest Line of Consecutive One in Matrix](https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/) | [C++](./C++/longest-line-of-consecutive-one-in-matrix.cpp) [Python](./Python/longest-line-of-consecutive-one-in-matrix.py) | _O(m * n)_ | _O(n)_ | Medium |📖|| From 6eb6885defd5cf3fd72d0c87821883caf4c27b47 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Mar 2018 12:47:12 +0800 Subject: [PATCH 4541/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 25db379b8..87be01f19 100644 --- a/README.md +++ b/README.md @@ -618,6 +618,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || 440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn)_ | _O(logn)_ | Hard || 464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || +517| [Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/) | [C++](./C++/find-largest-value-in-each-tree-row.cpp) [Python](./Python/find-largest-value-in-each-tree-row.py) | _O(n)_ | _O(h)_ | Medium ||| 547| [Friend Circles](https://leetcode.com/problems/friend-circles/) | [C++](./C++/friend-circles.cpp) [Python](./Python/friend-circles.py) | _O(n^2)_ | _O(n)_ | Medium || Union Find | 582| [Kill Process](https://leetcode.com/problems/kill-process/) | [C++](./C++/kill-process.cpp) [Python](./Python/kill-process.py) | _O(n)_ | _O(n)_ | Medium |📖| DFS, BFS | 638| [Shopping Offers](https://leetcode.com/problems/shopping-offers/) | [C++](./C++/shopping-offers.cpp) [Python](./Python/shopping-offers.py) | _O(n * 2^n)_ | _O(n)_ | Medium || From b33f9886b6eb00e9251f498f724b01aac0a3006e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 15 Mar 2018 12:48:34 +0800 Subject: [PATCH 4542/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 87be01f19..5985dbea3 100644 --- a/README.md +++ b/README.md @@ -618,7 +618,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 417 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | [C++](./C++/pacific-atlantic-water-flow.cpp) [Python](./Python/pacific-atlantic-water-flow.py) | _O(m * n)_ | _O(m * n)_ | Medium || 440| [K-th Smallest in Lexicographical Order](https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/) | [C++](./C++/k-th-smallest-in-lexicographical-order.cpp) [Python](./Python/k-th-smallest-in-lexicographical-order.py) | _O(logn)_ | _O(logn)_ | Hard || 464| [Can I Win](https://leetcode.com/problems/can-i-win/) | [C++](./C++/can-i-win.cpp) [Python](./Python/can-i-win.py) | _O(n!)_ | _O(n)_ | Medium || -517| [Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/) | [C++](./C++/find-largest-value-in-each-tree-row.cpp) [Python](./Python/find-largest-value-in-each-tree-row.py) | _O(n)_ | _O(h)_ | Medium ||| +515| [Find Largest Value in Each Tree Row](https://leetcode.com/problems/find-largest-value-in-each-tree-row/) | [C++](./C++/find-largest-value-in-each-tree-row.cpp) [Python](./Python/find-largest-value-in-each-tree-row.py) | _O(n)_ | _O(h)_ | Medium ||| 547| [Friend Circles](https://leetcode.com/problems/friend-circles/) | [C++](./C++/friend-circles.cpp) [Python](./Python/friend-circles.py) | _O(n^2)_ | _O(n)_ | Medium || Union Find | 582| [Kill Process](https://leetcode.com/problems/kill-process/) | [C++](./C++/kill-process.cpp) [Python](./Python/kill-process.py) | _O(n)_ | _O(n)_ | Medium |📖| DFS, BFS | 638| [Shopping Offers](https://leetcode.com/problems/shopping-offers/) | [C++](./C++/shopping-offers.cpp) [Python](./Python/shopping-offers.py) | _O(n * 2^n)_ | _O(n)_ | Medium || From 4e9856b212e3f5df203c2a216e57ae7230ed3f80 Mon Sep 17 00:00:00 2001 From: april12925 <35503506+april12925@users.noreply.github.com> Date: Thu, 15 Mar 2018 21:38:04 +0100 Subject: [PATCH 4543/4971] Added variable "self" to perfect_tree_pivot() --- 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 ca9e1314d..4602c6d75 100644 --- a/Python/convert-sorted-array-to-binary-search-tree.py +++ b/Python/convert-sorted-array-to-binary-search-tree.py @@ -18,7 +18,7 @@ def sortedArrayToBST(self, num): return self.sortedArrayToBSTRecu(num, 0, len(num)) @staticmethod - def perfect_tree_pivot(n): + def perfect_tree_pivot(self, n): """ Find the point to partition n keys for a perfect binary search tree """ From a37a61983364d6eff8d4cbe3111980d7dbcd6c72 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Mar 2018 13:21:58 +0800 Subject: [PATCH 4544/4971] Update convert-sorted-array-to-binary-search-tree.py --- ...vert-sorted-array-to-binary-search-tree.py | 31 ++++++++++--------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/Python/convert-sorted-array-to-binary-search-tree.py b/Python/convert-sorted-array-to-binary-search-tree.py index 4602c6d75..4f5858c07 100644 --- a/Python/convert-sorted-array-to-binary-search-tree.py +++ b/Python/convert-sorted-array-to-binary-search-tree.py @@ -11,13 +11,24 @@ def __init__(self, x): self.left = None self.right = None -class Solution: - # @param num, a list of integers - # @return a tree node - def sortedArrayToBST(self, num): - return self.sortedArrayToBSTRecu(num, 0, len(num)) + +class Solution(object): + def sortedArrayToBST(self, nums): + """ + :type nums: List[int] + :rtype: TreeNode + """ + return self.sortedArrayToBSTRecu(nums, 0, len(nums)) + + def sortedArrayToBSTRecu(self, nums, start, end): + if start == end: + return None + mid = start + self.perfect_tree_pivot(end - start) + node = TreeNode(nums[mid]) + node.left = self.sortedArrayToBSTRecu(nums, start, mid) + node.right = self.sortedArrayToBSTRecu(nums, mid + 1, end) + return node - @staticmethod def perfect_tree_pivot(self, n): """ Find the point to partition n keys for a perfect binary search tree @@ -34,14 +45,6 @@ def perfect_tree_pivot(self, n): return n - x // 2 # case 2 == n - (x//2 - 1) - 1 : the left subtree of the root # has more nodes and the right subtree is perfect. - def sortedArrayToBSTRecu(self, num, start, end): - if start == end: - return None - mid = start + self.perfect_tree_pivot(end - start) - node = TreeNode(num[mid]) - node.left = self.sortedArrayToBSTRecu(num, start, mid) - node.right = self.sortedArrayToBSTRecu(num, mid + 1, end) - return node if __name__ == "__main__": num = [1, 2, 3] From a01ab93470deb435e473215c03e391576ae9ebf0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Mar 2018 21:37:32 +0800 Subject: [PATCH 4545/4971] Create similar-rgb-color.cpp --- C++/similar-rgb-color.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/similar-rgb-color.cpp diff --git a/C++/similar-rgb-color.cpp b/C++/similar-rgb-color.cpp new file mode 100644 index 000000000..39a7c8809 --- /dev/null +++ b/C++/similar-rgb-color.cpp @@ -0,0 +1,24 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + string similarRGB(string color) { + string result = "#"; + result += round(color.substr(1, 2)); + result += round(color.substr(3, 2)); + result += round(color.substr(5, 2)); + return result; + } + +private: + string round(const string& color) { + std::stringstream in(color); + int decimal = 0; + in >> std::hex >> decimal; + decimal = decimal / 17 + (decimal % 17 > 8 ? 1 : 0); + std::stringstream out; + out << std::setfill('0') << std::setw(2) << std::hex << 17 * q; + return out.str(); + } +}; From 47a4fc43b6bb4e55897c52828df119df8a5e4aa6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Mar 2018 21:41:36 +0800 Subject: [PATCH 4546/4971] Create similar-rgb-color.py --- Python/similar-rgb-color.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Python/similar-rgb-color.py diff --git a/Python/similar-rgb-color.py b/Python/similar-rgb-color.py new file mode 100644 index 000000000..caefa472b --- /dev/null +++ b/Python/similar-rgb-color.py @@ -0,0 +1,18 @@ +# Time: O(1) +# Space: O(1) + +class Solution(object): + def similarRGB(self, color): + """ + :type color: str + :rtype: str + """ + def rounding(color): + q, r = divmod(int(color, 16), 17) + if r > 8: q += 1 + return '{:02x}'.format(17*q) + + return '#' + \ + rounding(color[1:3]) + \ + rounding(color[3:5]) + \ + rounding(color[5:7]) From 0d1d9cab36ea55de766d81238c41a937e5a67ec2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Mar 2018 21:58:58 +0800 Subject: [PATCH 4547/4971] Create minimum-swaps-to-make-sequences-increasing.cpp --- ...mum-swaps-to-make-sequences-increasing.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/minimum-swaps-to-make-sequences-increasing.cpp diff --git a/C++/minimum-swaps-to-make-sequences-increasing.cpp b/C++/minimum-swaps-to-make-sequences-increasing.cpp new file mode 100644 index 000000000..73f7bc7d3 --- /dev/null +++ b/C++/minimum-swaps-to-make-sequences-increasing.cpp @@ -0,0 +1,21 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int minSwap(vector& A, vector& B) { + vector dp_no_swap(2), dp_swap(2, 1); + for (int i = 1; i < A.size(); ++i) { + dp_no_swap[i % 2] = dp_swap[i % 2] = numeric_limits::max(); + if (A[i - 1] < A[i] && B[i -1] < B[i]) { + dp_no_swap[i % 2] = min(dp_no_swap[i % 2], dp_no_swap[(i - 1) % 2]); + dp_swap[i % 2] = min(dp_swap[i % 2], dp_swap[(i - 1) % 2] + 1); + } + if (A[i - 1] < B[i] && B[i - 1] < A[i]) { + dp_no_swap[i % 2] = min(dp_no_swap[i % 2], dp_swap[(i - 1) % 2]); + dp_swap[i % 2] = min(dp_swap[i % 2], dp_no_swap[(i - 1) % 2] + 1); + } + } + return min(dp_no_swap[(A.size() - 1) % 2], dp_swap[(A.size() - 1) % 2]); + } +}; From a80248e62bacf8e437da61fc81d51dc456d4c189 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Mar 2018 22:00:01 +0800 Subject: [PATCH 4548/4971] Create minimum-swaps-to-make-sequences-increasing.py --- ...imum-swaps-to-make-sequences-increasing.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Python/minimum-swaps-to-make-sequences-increasing.py diff --git a/Python/minimum-swaps-to-make-sequences-increasing.py b/Python/minimum-swaps-to-make-sequences-increasing.py new file mode 100644 index 000000000..f04e3f388 --- /dev/null +++ b/Python/minimum-swaps-to-make-sequences-increasing.py @@ -0,0 +1,20 @@ +# Time: O(n) +# Space: O(1) + +class Solution(object): + def minSwap(self, A, B): + """ + :type A: List[int] + :type B: List[int] + :rtype: int + """ + dp_no_swap, dp_swap = [0]*2, [1]*2 + for i in xrange(1, len(A)): + dp_no_swap[i%2], dp_swap[i%2] = float("inf"), float("inf") + if A[i-1] < A[i] and B[i-1] < B[i]: + dp_no_swap[i%2] = min(dp_no_swap[i%2], dp_no_swap[(i-1)%2]) + dp_swap[i%2] = min(dp_swap[i%2], dp_swap[(i-1)%2]+1) + if A[i-1] < B[i] and B[i-1] < A[i]: + dp_no_swap[i%2] = min(dp_no_swap[i%2], dp_swap[(i-1)%2]) + dp_swap[i%2] = min(dp_swap[i%2], dp_no_swap[(i-1)%2]+1) + return min(dp_no_swap[(len(A)-1)%2], dp_swap[(len(A)-1)%2]) From f2b16ff801b00f866e7e182aedffb73405d3e7c5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Mar 2018 23:21:28 +0800 Subject: [PATCH 4549/4971] Create find-eventual-safe-states.cpp --- C++/find-eventual-safe-states.cpp | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 C++/find-eventual-safe-states.cpp diff --git a/C++/find-eventual-safe-states.cpp b/C++/find-eventual-safe-states.cpp new file mode 100644 index 000000000..0880c4b09 --- /dev/null +++ b/C++/find-eventual-safe-states.cpp @@ -0,0 +1,38 @@ +// Time: O(|V| + |E|) +// Space: O(|V|) + +class Solution { +public: + enum Color { WHITE, GRAY, BLACK }; + + vector eventualSafeNodes(vector>& graph) { + vector result; + unordered_map lookup; + for (int i = 0; i < graph.size(); ++i) { + if (dfs(graph, i, &lookup)) { + result.emplace_back(i); + } + } + return result; + } + +private: + bool dfs(const vector>& graph, int node, + unordered_map *lookup) { + if ((*lookup)[node] != WHITE) { + return (*lookup)[node] == BLACK; + } + (*lookup)[node] = GRAY; + for (const auto& child : graph[node]) { + if ((*lookup)[child] == BLACK) { + continue; + } + if ((*lookup)[child] == GRAY || + !dfs(graph, child, lookup)) { + return false; + } + } + (*lookup)[node] = BLACK; + return true; + } +}; From f60907223e055bb48b47dad37b0e8a62d6e7d635 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Mar 2018 23:22:43 +0800 Subject: [PATCH 4550/4971] Create find-eventual-safe-states.py --- Python/find-eventual-safe-states.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Python/find-eventual-safe-states.py diff --git a/Python/find-eventual-safe-states.py b/Python/find-eventual-safe-states.py new file mode 100644 index 000000000..eb6cd8b05 --- /dev/null +++ b/Python/find-eventual-safe-states.py @@ -0,0 +1,26 @@ +# Time: O(|V| + |E|) +# Space: O(|V|) + +class Solution(object): + def eventualSafeNodes(self, graph): + """ + :type graph: List[List[int]] + :rtype: List[int] + """ + WHITE, GRAY, BLACK = 0, 1, 2 + + def dfs(graph, node, lookup): + if lookup[node] != WHITE: + return lookup[node] == BLACK + lookup[node] = GRAY + for child in graph[node]: + if lookup[child] == BLACK: + continue + if lookup[child] == GRAY or \ + not dfs(graph, child, lookup): + return False + lookup[node] = BLACK + return True + + lookup = collections.defaultdict(int) + return filter(lambda node: dfs(graph, node, lookup), xrange(len(graph))) From b39d1575a0959b509745637ff862f141157ab7fb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Mar 2018 01:01:43 +0800 Subject: [PATCH 4551/4971] Create bricks-falling-when-hit.cpp --- C++/bricks-falling-when-hit.cpp | 95 +++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 C++/bricks-falling-when-hit.cpp diff --git a/C++/bricks-falling-when-hit.cpp b/C++/bricks-falling-when-hit.cpp new file mode 100644 index 000000000..34a9387d4 --- /dev/null +++ b/C++/bricks-falling-when-hit.cpp @@ -0,0 +1,95 @@ +// Time: O(r * c) +// Space: O(r * c) + +class Solution { +public: + vector hitBricks(vector>& grid, vector>& hits) { + static const vector> directions{{-1, 0}, { 1, 0}, + { 0, 1}, { 0, -1}}; + const int R = grid.size(); + const int C = grid[0].size(); + const auto index = [&C](int r, int c) { return r * C + c; }; + + vector> hit_grid(grid); + for (const auto& hit : hits) { + hit_grid[hit[0]][hit[1]] = 0; + } + + UnionFind union_find(R * C); + for (int r = 0; r < hit_grid.size(); ++r) { + for (int c = 0; c < hit_grid[r].size(); ++c) { + if (!hit_grid[r][c]) { + continue; + } + if (r == 0) { + union_find.union_set(index(r, c), R * C); + } + if (r && hit_grid[r - 1][c]) { + union_find.union_set(index(r, c), index(r - 1, c)); + } + if (c && hit_grid[r][c - 1]) { + union_find.union_set(index(r, c), index(r, c - 1)); + } + } + } + + vector result; + for (int i = hits.size() - 1; i >= 0; --i) { + int r = hits[i][0], c = hits[i][1]; + const auto prev_roof = union_find.top(); + if (grid[r][c] == 0) { + result.emplace_back(0); + continue; + } + for (const auto& d : directions) { + int nr = r + d.first, nc = c + d.second; + if (0 <= nr && nr < R && + 0 <= nc && nc < C && + hit_grid[nr][nc]) { + union_find.union_set(index(r, c), index(nr, nc)); + } + } + if (r == 0) { + union_find.union_set(index(r, c), R * C); + } + hit_grid[r][c] = 1; + result.emplace_back(max(0, union_find.top() - prev_roof - 1)); + } + reverse(result.begin(), result.end()); + return result; + } + +private: + class UnionFind { + public: + UnionFind(const int n) : set_(n + 1), size_(n + 1, 1) { + iota(set_.begin(), set_.end(), 0); + size_.back() = 0; + } + + int find_set(const int x) { + if (set_[x] != x) { + set_[x] = find_set(set_[x]); // Path compression. + } + return set_[x]; + } + + bool union_set(const int x, const int y) { + int x_root = find_set(x), y_root = find_set(y); + if (x_root == y_root) { + return false; + } + set_[min(x_root, y_root)] = max(x_root, y_root); + size_[max(x_root, y_root)] += size_[min(x_root, y_root)]; + return true; + } + + int top() { + return size_[find_set(size_.size() - 1)]; + } + + private: + vector set_; + vector size_; + }; +}; From 27aa0f11a2ede0f0ef30a78213df898a4a31b091 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Mar 2018 01:01:57 +0800 Subject: [PATCH 4552/4971] Create bricks-falling-when-hit.py --- Python/bricks-falling-when-hit.py | 69 +++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Python/bricks-falling-when-hit.py diff --git a/Python/bricks-falling-when-hit.py b/Python/bricks-falling-when-hit.py new file mode 100644 index 000000000..a799a3ac8 --- /dev/null +++ b/Python/bricks-falling-when-hit.py @@ -0,0 +1,69 @@ +# Time: O(r * c) +# Space: O(r * c) + +class UnionFind: + def __init__(self, n): + self.set = range(n+1) + self.size = [1]*(n+1) + self.size[-1] = 0 + + 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: + return False + self.set[min(x_root, y_root)] = max(x_root, y_root) + self.size[max(x_root, y_root)] += self.size[min(x_root, y_root)] + return True + + def top(self): + return self.size[self.find_set(len(self.size)-1)] + + +class Solution(object): + def hitBricks(self, grid, hits): + """ + :type grid: List[List[int]] + :type hits: List[List[int]] + :rtype: List[int] + """ + def index(C, r, c): + return r*C+c + + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + R, C = len(grid), len(grid[0]) + + hit_grid = [row[:] for row in grid] + for i, j in hits: + hit_grid[i][j] = 0 + + union_find = UnionFind(R*C) + for r, row in enumerate(hit_grid): + for c, val in enumerate(row): + if not val: continue + if r == 0: + union_find.union_set(index(C, r, c), R*C) + if r and hit_grid[r-1][c]: + union_find.union_set(index(C, r, c), index(C, r-1, c)) + if c and hit_grid[r][c-1]: + union_find.union_set(index(C, r, c), index(C, r, c-1)) + + result = [] + for r, c in reversed(hits): + prev_roof = union_find.top() + if grid[r][c] == 0: + result.append(0) + continue + for d in directions: + nr, nc = (r+d[0], c+d[1]) + if 0 <= nr < R and 0 <= nc < C and hit_grid[nr][nc]: + union_find.union_set(index(C, r, c), index(C, nr, nc)) + if r == 0: + union_find.union_set(index(C, r, c), R*C) + hit_grid[r][c] = 1 + result.append(max(0, union_find.top()-prev_roof-1)) + return result[::-1] From c042f3dbb41e60e9290e3360efb7112e528d6db6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Mar 2018 01:03:49 +0800 Subject: [PATCH 4553/4971] Update bricks-falling-when-hit.cpp --- C++/bricks-falling-when-hit.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/bricks-falling-when-hit.cpp b/C++/bricks-falling-when-hit.cpp index 34a9387d4..5fb3931a6 100644 --- a/C++/bricks-falling-when-hit.cpp +++ b/C++/bricks-falling-when-hit.cpp @@ -35,14 +35,14 @@ class Solution { vector result; for (int i = hits.size() - 1; i >= 0; --i) { - int r = hits[i][0], c = hits[i][1]; + const auto r = hits[i][0], c = hits[i][1]; const auto prev_roof = union_find.top(); if (grid[r][c] == 0) { result.emplace_back(0); continue; } for (const auto& d : directions) { - int nr = r + d.first, nc = c + d.second; + const auto nr = r + d.first, nc = c + d.second; if (0 <= nr && nr < R && 0 <= nc && nc < C && hit_grid[nr][nc]) { From 9a380f6a277569946c23c015ba53ff5630bfa17a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Mar 2018 20:47:24 +0800 Subject: [PATCH 4554/4971] Update graph-valid-tree.py --- Python/graph-valid-tree.py | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 54408e956..50c5ababc 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -2,47 +2,38 @@ # Space: O(|V| + |E|) # BFS solution. Same complexity but faster version. -class Solution: +class Solution(object): # @param {integer} n # @param {integer[][]} edges # @return {boolean} def validTree(self, n, edges): if len(edges) != n - 1: # Check number of edges. return False - elif n == 1: - return True - # A structure to track each node's [visited_from, neighbors] - visited_from = [-1] * n + # init node's neighbors in dict neighbors = collections.defaultdict(list) for u, v in edges: neighbors[u].append(v) neighbors[v].append(u) - - if len(neighbors) != n: # Check number of nodes. - return False # BFS to check whether the graph is valid tree. visited = {} q = collections.deque([0]) while q: - i = q.popleft() - visited[i] = True - for node in neighbors[i]: - if node != visited_from[i]: - if node in visited: - return False - else: - visited[node] = True - visited_from[node] = i - q.append(node) + curr = q.popleft() + visited[curr] = True + for node in neighbors[curr]: + if node not in visited: + visited[node] = True + q.append(node) + return len(visited) == n # Time: O(|V| + |E|) # Space: O(|V| + |E|) # BFS solution. -class Solution2: +class Solution2(object): # @param {integer} n # @param {integer[][]} edges # @return {boolean} From 561428045e8e5a2849048e851070b7e6156341ba Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Mar 2018 20:55:57 +0800 Subject: [PATCH 4555/4971] Update graph-valid-tree.cpp --- C++/graph-valid-tree.cpp | 30 +++++++----------------------- 1 file changed, 7 insertions(+), 23 deletions(-) diff --git a/C++/graph-valid-tree.cpp b/C++/graph-valid-tree.cpp index 983f6ecfa..ded8ab274 100644 --- a/C++/graph-valid-tree.cpp +++ b/C++/graph-valid-tree.cpp @@ -4,26 +4,15 @@ // Same complexity, but faster version. class Solution { public: - struct node { - int parent = -1; - vectorneighbors; - }; - bool validTree(int n, vector>& edges) { if (edges.size() != n - 1) { return false; - } else if (n == 1) { - return true; } - unordered_map nodes; + unordered_map> neighbors; for (const auto& edge : edges) { - nodes[edge.first].neighbors.emplace_back(edge.second); - nodes[edge.second].neighbors.emplace_back(edge.first); - } - - if (nodes.size() != n) { - return false; + neighbors[edge.first].emplace_back(edge.second); + neighbors[edge.second].emplace_back(edge.first); } unordered_set visited; @@ -33,15 +22,10 @@ class Solution { 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); - } + for (const auto& node : neighbors[i]) { + if (!visited.count(node)) { + visited.emplace(node); + q.emplace(node); } } } From fe00ea33784991cde55511f4c0df97f1f46b3994 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 19 Mar 2018 21:03:57 +0800 Subject: [PATCH 4556/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 5985dbea3..31fe238a2 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 792 | [Number of Matching Subsequences](https://leetcode.com/problems/number-of-matching-subsequences/) | [C++](./C++/number-of-matching-subsequences.cpp) [Python](./Python/number-of-matching-subsequences.py) | _O(n + w)_ | _O(1)_ | Medium || 794 | [Valid Tic-Tac-Toe State](https://leetcode.com/problems/valid-tic-tac-toe-state/) | [C++](./C++/valid-tic-tac-toe-state.cpp) [Python](./Python/valid-tic-tac-toe-state.py) | _O(1)_ | _O(1)_ | Medium || 795 | [Number of Subarrays with Bounded Maximum](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/) | [C++](./C++/number-of-subarrays-with-bounded-maximum.cpp) [Python](./Python/number-of-subarrays-with-bounded-maximum.py) | _O(n)_ | _O(1)_ | Medium || +803 | [Bricks Falling When Hit](https://leetcode.com/problems/bricks-falling-when-hit/) | [C++](./C++/bricks-falling-when-hit.cpp) [Python](./Python/bricks-falling-when-hit.py) | _O(r * c)_ | _O(r * c)_ | Hard || Union Find ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -442,6 +443,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 781 | [Rabbits in Forest](https://leetcode.com/problems/rabbits-in-forest/) | [C++](./C++/rabbits-in-forest.cpp) [Python](./Python/rabbits-in-forest.py) | _O(n)_ | _O(n)_ | Medium || 782 | [Transform to Chessboard](https://leetcode.com/problems/transform-to-chessboard/) | [C++](./C++/transform-to-chessboard.cpp) [Python](./Python/transform-to-chessboard.py) | _O(n^2)_ | _O(n)_ | Hard || 789 | [Escape The Ghosts](https://leetcode.com/problems/escape-the-ghosts/) | [C++](./C++/escape-the-ghosts.cpp) [Python](./Python/escape-the-ghosts.py) | _O(n)_ | _O(1)_ | Medium || +800 | [Similar RGB Color](https://leetcode.com/problems/similar-rgb-color/) | [C++](./C++/similar-rgb-color.cpp) [Python](./Python/similar-rgb-color.py) | _O(1)_ | _O(1)_ | Easy |📖|| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -632,6 +634,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 756| [Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix/) | [C++](./C++/pyramid-transition-matrix.cpp) [Python](./Python/pyramid-transition-matrix.py) | _O(a^b)_ | _O(a^b)_ | Medium ||| 785| [Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/) | [C++](./C++/is-graph-bipartite.cpp) [Python](./Python/is-graph-bipartite.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium ||| 797| [All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target/) | [C++](./C++/all-paths-from-source-to-target.cpp) [Python](./Python/all-paths-from-source-to-target.py) | _O(p + r * n)_ | _O(n)_ | Medium ||| +802| [Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) | [C++](./C++/find-eventual-safe-states.cpp) [Python](./Python/find-eventual-safe-states.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium ||| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -747,6 +750,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 788 | [Rotated Digits](https://leetcode.com/problems/rotated-digits/) | [C++](./C++/rotated-digits.cpp) [Python](./Python/rotated-digits.py) | _O(logn)_ | _O(logn)_ | Easy || Memoization | 790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/) | [C++](./C++/domino-and-tromino-tiling.cpp) [Python](./Python/domino-and-tromino-tiling.py) | _O(logn)_ | _O(logn)_ | Medium || Matrix Exponentiation | 799 | [Champagne Tower](https://leetcode.com/problems/champagne-tower/) | [C++](./C++/champagne-tower.cpp) [Python](./Python/champagne-tower.py) | _O(n^2)_ | _O(n)_ | Medium ||| +801 | [Minimum Swaps To Make Sequences Increasing](https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/) | [C++](./C++/minimum-swaps-to-make-sequences-increasing.cpp) [Python](./Python/minimum-swaps-to-make-sequences-increasing.py) | _O(n)_ | _O(1)_ | Medium ||| ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From ee6d70c2f3712c0836fff6cc1ad69c70a138c9c4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Mar 2018 21:11:38 +0800 Subject: [PATCH 4557/4971] Update minimum-swaps-to-make-sequences-increasing.py --- ...imum-swaps-to-make-sequences-increasing.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Python/minimum-swaps-to-make-sequences-increasing.py b/Python/minimum-swaps-to-make-sequences-increasing.py index f04e3f388..d3806d0d9 100644 --- a/Python/minimum-swaps-to-make-sequences-increasing.py +++ b/Python/minimum-swaps-to-make-sequences-increasing.py @@ -1,6 +1,29 @@ # Time: O(n) # Space: O(1) +# We have two integer sequences A and B of the same non-zero length. +# +# We are allowed to swap elements A[i] and B[i]. +# Note that both elements are in the same index position in their respective sequences. +# +# At the end of some number of swaps, A and B are both strictly increasing. +# (A sequence is strictly increasing if and only if A[0] < A[1] < A[2] < ... < A[A.length - 1].) +# +# Given A and B, return the minimum number of swaps to make both sequences strictly increasing. +# It is guaranteed that the given input always makes it possible. +# +# Example: +# Input: A = [1,3,5,4], B = [1,2,3,7] +# Output: 1 +# Explanation: +# Swap A[3] and B[3]. Then the sequences are: +# A = [1, 3, 5, 7] and B = [1, 2, 3, 4] +# which are both strictly increasing. +# +# Note: +# - A, B are arrays with the same length, and that length will be in the range [1, 1000]. +# - A[i], B[i] are integer values in the range [0, 2000]. + class Solution(object): def minSwap(self, A, B): """ From fb834f7db148e9abfb4df95ee07536543861124e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Mar 2018 21:13:16 +0800 Subject: [PATCH 4558/4971] Update find-eventual-safe-states.py --- Python/find-eventual-safe-states.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Python/find-eventual-safe-states.py b/Python/find-eventual-safe-states.py index eb6cd8b05..3edc7cb32 100644 --- a/Python/find-eventual-safe-states.py +++ b/Python/find-eventual-safe-states.py @@ -1,6 +1,28 @@ # Time: O(|V| + |E|) # Space: O(|V|) +# In a directed graph, we start at some node and every turn, walk along a directed edge of the graph. +# If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop. +# +# Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node. +# More specifically, there exists a natural number K so that for any choice of where to walk, +# we must have stopped at a terminal node in less than K steps. +# +# Which nodes are eventually safe? Return them as an array in sorted order. +# +# The directed graph has N nodes with labels 0, 1, ..., N-1, where N is the length of graph. +# The graph is given in the following form: graph[i] is a list of labels j +# such that (i, j) is a directed edge of the graph. +# +# Example: +# Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] +# Output: [2,4,5,6] +# +# Note: +# - graph will have length at most 10000. +# - The number of edges in the graph will not exceed 32000. +# - Each graph[i] will be a sorted list of different integers, chosen within the range [0, graph.length - 1]. + class Solution(object): def eventualSafeNodes(self, graph): """ From 8de51358e24ee1a680dbad1fedff8b9fec09ad5b Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 20 Mar 2018 21:15:07 +0800 Subject: [PATCH 4559/4971] Update bricks-falling-when-hit.py --- Python/bricks-falling-when-hit.py | 34 +++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Python/bricks-falling-when-hit.py b/Python/bricks-falling-when-hit.py index a799a3ac8..3a94f4bd5 100644 --- a/Python/bricks-falling-when-hit.py +++ b/Python/bricks-falling-when-hit.py @@ -1,6 +1,40 @@ # Time: O(r * c) # Space: O(r * c) +# We have a grid of 1s and 0s; the 1s in a cell represent bricks. +# A brick will not drop if and only if it is directly connected to the top of the grid, +# or at least one of its (4-way) adjacent bricks will not drop. +# +# We will do some erasures sequentially. Each time we want to do the erasure at the location (i, j), +# the brick (if it exists) on that location will disappear, +# and then some other bricks may drop because of that erasure. +# +# Return an array representing the number of bricks that will drop after each erasure in sequence. +# +# Example 1: +# Input: +# grid = [[1,0,0,0],[1,1,1,0]] +# hits = [[1,0]] +# Output: [2] +# Explanation: +# If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. So we should return 2. +# +# Example 2: +# Input: +# grid = [[1,0,0,0],[1,1,0,0]] +# hits = [[1,1],[1,0]] +# Output: [0,0] +# Explanation: +# When we erase the brick at (1, 0), the brick at (1, 1) has already disappeared due to the last move. +# So each erasure will cause no bricks dropping. +# Note that the erased brick (1, 0) will not be counted as a dropped brick. +# +# Note: +# - The number of rows and columns in the grid will be in the range [1, 200]. +# - The number of erasures will not exceed the area of the grid. +# - It is guaranteed that each erasure will be different from any other erasure, and located inside the grid. +# - An erasure may refer to a location with no brick - if it does, no bricks drop. + class UnionFind: def __init__(self, n): self.set = range(n+1) From 8f973e97dd3bfa76e01c48beaced1c37f92364f9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 23 Mar 2018 22:24:26 +0800 Subject: [PATCH 4560/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 31fe238a2..2b8ec42b8 100644 --- a/README.md +++ b/README.md @@ -721,6 +721,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 471 | [Encode String with Shortest Length](https://leetcode.com/problems/encode-string-with-shortest-length/) | [C++](./C++/encode-string-with-shortest-length.cpp) [Python](./Python/encode-string-with-shortest-length.py) | _O(n^3)_ on average | _O(n^2)_ | Medium |📖| 472 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | [C++](./C++/concatenated-words.cpp) [Python](./Python/concatenated-words.py) | _O(n * l^2)_ | _O(n * l)_ | Medium || 474 | [Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) | [C++](./C++/ones-and-zeroes.cpp) [Python](./Python/ones-and-zeroes.py) | _O(s * m * n)_ | _O(m * n)_ | Medium || +514 | [Freedom Trail](https://leetcode.com/problems/freedom-trail/) | [C++](./C++/freedom-trail.cpp) [Python](./Python/freedom-trail.py) | _O(k)_ ~ _O(k * r^2)_ | _O(r)_ | Hard ||| 516 | [Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/) | [C++](./C++/longest-palindromic-subsequence.cpp) [Python](./Python/longest-palindromic-subsequence.py) | _O(n^2)_ | _O(n)_ | Medium ||| 546 | [Remove Boxes](https://leetcode.com/problems/remove-boxes/) | [C++](./C++/remove-boxes.cpp) [Python](./Python/remove-boxes.py) | _O(n^3)_ ~ _O(n^4)_ | _O(n^3)_ | Hard ||| 552 | [Student Attendance Record II](https://leetcode.com/problems/student-attendance-record-ii/) | [C++](./C++/student-attendance-record-ii.cpp) [Python](./Python/student-attendance-record-ii.py) | _O(n)_ | _O(1)_ | Hard ||| From 45d75c381d9934eeff6ff5f1096210c730ceada6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Mar 2018 22:34:50 +0800 Subject: [PATCH 4561/4971] Create unique-morse-code-words.cpp --- C++/unique-morse-code-words.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/unique-morse-code-words.cpp diff --git a/C++/unique-morse-code-words.cpp b/C++/unique-morse-code-words.cpp new file mode 100644 index 000000000..26c72b140 --- /dev/null +++ b/C++/unique-morse-code-words.cpp @@ -0,0 +1,23 @@ +// Time: O(n), n is the sume of all word lengths +// Space: O(n) + +class Solution { +public: + int uniqueMorseRepresentations(vector& words) { + static const vector MORSE = + { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", + "....", "..", ".---", "-.-", ".-..", "--", "-.", + "---", ".--.", "--.-", ".-.", "...", "-", "..-", + "...-", ".--", "-..-", "-.--", "--.."}; + + unordered_set lookup; + for (const auto& word : words) { + string code; + for (const auto& c : word) { + code += MORSE[c - 'a']; + } + lookup.emplace(move(code)); + } + return lookup.size(); + } +}; From 1aba9628749e535b3b95a90c16f6e6def232a561 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 25 Mar 2018 22:39:48 +0800 Subject: [PATCH 4562/4971] Create unique-morse-code-words.py --- Python/unique-morse-code-words.py | 51 +++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/unique-morse-code-words.py diff --git a/Python/unique-morse-code-words.py b/Python/unique-morse-code-words.py new file mode 100644 index 000000000..3b43a876b --- /dev/null +++ b/Python/unique-morse-code-words.py @@ -0,0 +1,51 @@ +# Time: O(n), n is the sume of all word lengths +# Space: O(n) + +# International Morse Code defines a standard encoding where each letter +# is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps +# to "-...", "c" maps to "-.-.", and so on. +# +# For convenience, the full table for the 26 letters of the English alphabet is given below: +# +# [".-","-...","-.-.","-..",".","..-.","--.", +# "....","..",".---","-.-",".-..","--","-.", +# "---",".--.","--.-",".-.","...","-","..-", +# "...-",".--","-..-","-.--","--.."] +# Now, given a list of words, each word can be written as a concatenation of +# the Morse code of each letter. For example, "cab" can be written as "-.-.-....-", +# (which is the concatenation "-.-." + "-..." + ".-"). +# We'll call such a concatenation, the transformation of a word. +# +# Return the number of different transformations among all words we have. +# +# Example: +# Input: words = ["gin", "zen", "gig", "msg"] +# Output: 2 +# Explanation: +# The transformation of each word is: +# "gin" -> "--...-." +# "zen" -> "--...-." +# "gig" -> "--...--." +# "msg" -> "--...--." +# +# There are 2 different transformations, "--...-." and "--...--.". +# +# Note: +# - The length of words will be at most 100. +# - Each words[i] will have length in range [1, 12]. +# - words[i] will only consist of lowercase letters. + +class Solution(object): + def uniqueMorseRepresentations(self, words): + """ + :type words: List[str] + :rtype: int + """ + MORSE = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", + "....", "..", ".---", "-.-", ".-..", "--", "-.", + "---", ".--.", "--.-", ".-.", "...", "-", "..-", + "...-", ".--", "-..-", "-.--", "--.."] + + lookup = {"".join(MORSE[ord(c) - ord('a')] for c in word) \ + for word in words} + return len(lookup) From f7e061d449becab323f04785ea16cc483e8de228 Mon Sep 17 00:00:00 2001 From: oshapeman Date: Mon, 26 Mar 2018 18:23:11 +0800 Subject: [PATCH 4563/4971] Update average-of-levels-in-binary-tree.py --- Python/average-of-levels-in-binary-tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/average-of-levels-in-binary-tree.py b/Python/average-of-levels-in-binary-tree.py index 572699d3c..f6b0887f3 100644 --- a/Python/average-of-levels-in-binary-tree.py +++ b/Python/average-of-levels-in-binary-tree.py @@ -45,6 +45,6 @@ def averageOfLevels(self, root): next_q.append(n.left) if n.right: next_q.append(n.right) - q, next_q = next_q, q + q = next_q result.append(float(total) / count) return result From 5719e944221c1eb14b1deca09de134e8f3af950a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Mar 2018 22:04:35 +0800 Subject: [PATCH 4564/4971] Create split-array-with-same-average.cpp --- C++/split-array-with-same-average.cpp | 40 +++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/split-array-with-same-average.cpp diff --git a/C++/split-array-with-same-average.cpp b/C++/split-array-with-same-average.cpp new file mode 100644 index 000000000..2c32605e5 --- /dev/null +++ b/C++/split-array-with-same-average.cpp @@ -0,0 +1,40 @@ +// Time: O(n^4) +// Space: O(n^3) + +class Solution { +public: + bool splitArraySameAverage(vector& A) { + const int n = A.size(); + const int sum = accumulate(A.cbegin(), A.cend(), 0); + if (!possible(n, sum)) { + return false; + } + + vector> sums(n / 2 + 1); + sums[0].emplace(0); + for (const auto& num: A) { // O(n) times + for (int i = n / 2; i >= 1; --i) { // O(n) times + for (const auto& prev : sums[i - 1]) { // O(1) + O(2) + ... O(n/2) = O(n^2) times + sums[i].emplace(prev + num); + } + } + } + for (int i = 1; i <= n / 2; ++i) { + if (sum * i % n == 0 && + sums[i].count(sum * i / n)) { + return true; + } + } + return false; + } + +private: + bool possible(int n, int sum) { + for (int i = 1; i <= n / 2; ++i) { + if (sum * i % n == 0) { + return true; + } + } + return false; + } +}; From 5f3e014371ba4feda3e1703804fc95332d4233f4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Mar 2018 22:05:37 +0800 Subject: [PATCH 4565/4971] Create split-array-with-same-average.py --- Python/split-array-with-same-average.py | 44 +++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/split-array-with-same-average.py diff --git a/Python/split-array-with-same-average.py b/Python/split-array-with-same-average.py new file mode 100644 index 000000000..aaca0d8bf --- /dev/null +++ b/Python/split-array-with-same-average.py @@ -0,0 +1,44 @@ +# Time: O(n^4) +# Space: O(n^3) + +# In a given integer array A, we must move every element of A to +# either list B or list C. (B and C initially start empty.) +# +# Return true if and only if after such a move, it is possible that +# the average value of B is equal to the average value of C, and B and C are both non-empty. +# +# Example : +# Input: +# [1,2,3,4,5,6,7,8] +# Output: true +# Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5. +# +# Note: +# - The length of A will be in the range [1, 30]. +# - A[i] will be in the range of [0, 10000]. + +class Solution(object): + def splitArraySameAverage(self, A): + """ + :type A: List[int] + :rtype: bool + """ + def possible(total, n): + for i in xrange(1, n//2+1): + if total*i%n == 0: + return True + return False + n, s = len(A), sum(A) + if not possible(n, s): + return False + + sums = [set() for _ in xrange(n//2+1)]; + sums[0].add(0) + for num in A: # O(n) times + for i in reversed(xrange(1, n//2+1)): # O(n) times + for prev in sums[i-1]: # O(1) + O(2) + ... O(n/2) = O(n^2) times + sums[i].add(prev+num) + for i in xrange(1, n//2+1): + if s*i%n == 0 and s*i//n in sums[i]: + return True + return False From 7a100c8cf66c2be8bb67d01ba8de9d5f2aca4ae9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Mar 2018 22:12:12 +0800 Subject: [PATCH 4566/4971] Create number-of-lines-to-write-string.py --- Python/number-of-lines-to-write-string.py | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/number-of-lines-to-write-string.py diff --git a/Python/number-of-lines-to-write-string.py b/Python/number-of-lines-to-write-string.py new file mode 100644 index 000000000..886f139c3 --- /dev/null +++ b/Python/number-of-lines-to-write-string.py @@ -0,0 +1,55 @@ +# Time: O(n) +# Space: O(1) + +# We are to write the letters of a given string S, from left to right into lines. +# Each line has maximum width 100 units, and if writing a letter would cause the width +# of the line to exceed 100 units, it is written on the next line. +# We are given an array widths, an array where widths[0] is the width of 'a', widths[1] +# is the width of 'b', ..., and widths[25] is the width of 'z'. +# +# Now answer two questions: how many lines have at least one character from S, +# and what is the width used by the last such line? Return your answer as an integer list of length 2. +# +# Example : +# Input: +# widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] +# S = "abcdefghijklmnopqrstuvwxyz" +# Output: [3, 60] +# +# Explanation: +# All letters have the same length of 10. To write all 26 letters, +# we need two full lines and one line with 60 units. +# Example : +# Input: +# widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] +# S = "bbbcccdddaaa" +# Output: [2, 4] +# +# Explanation: +# All letters except 'a' have the same length of 10, and +# "bbbcccdddaa" will cover 9 * 10 + 2 * 4 = 98 units. +# For the last 'a', it is written on the second line because +# there is only 2 units left in the first line. +# So the answer is 2 lines, plus 4 units in the second line. +# +# Note: +# - The length of S will be in the range [1, 1000]. +# - S will only contain lowercase letters. +# - widths is an array of length 26. +# - widths[i] will be in the range of [2, 10]. + +class Solution(object): + def numberOfLines(self, widths, S): + """ + :type widths: List[int] + :type S: str + :rtype: List[int] + """ + result = [1, 0] + for c in S: + w = widths[ord(c)-ord('a')] + result[1] += w + if result[1] > 100: + result[0] += 1 + result[1] = w + return result From e19df009481565e6261c070f4127fd5b0ec6298d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Mar 2018 22:12:50 +0800 Subject: [PATCH 4567/4971] Create number-of-lines-to-write-string.cpp --- C++/number-of-lines-to-write-string.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/number-of-lines-to-write-string.cpp diff --git a/C++/number-of-lines-to-write-string.cpp b/C++/number-of-lines-to-write-string.cpp new file mode 100644 index 000000000..8bbb14e08 --- /dev/null +++ b/C++/number-of-lines-to-write-string.cpp @@ -0,0 +1,19 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector numberOfLines(vector& widths, string S) { + vector result(2); + result.front() = 1; + for (const auto& c : S) { + const auto& w = widths[c - 'a']; + result.back() += w; + if (result.back() > 100) { + ++result.front(); + result.back() = w; + } + } + return result; + } +}; From 3f173f03c710cab1f3975ccbc987919ef826f153 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Mar 2018 22:27:14 +0800 Subject: [PATCH 4568/4971] Create max-increase-to-keep-city-skyline.cpp --- C++/max-increase-to-keep-city-skyline.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/max-increase-to-keep-city-skyline.cpp diff --git a/C++/max-increase-to-keep-city-skyline.cpp b/C++/max-increase-to-keep-city-skyline.cpp new file mode 100644 index 000000000..b94d2a94d --- /dev/null +++ b/C++/max-increase-to-keep-city-skyline.cpp @@ -0,0 +1,23 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + int maxIncreaseKeepingSkyline(vector>& grid) { + vector row_maxes(grid.size()); + vector col_maxes(grid[0].size()); + for (int r = 0; r < grid.size(); ++r) { + for (int c = 0; c < grid[r].size(); ++c) { + row_maxes[r] = max(row_maxes[r], grid[r][c]); + col_maxes[c] = max(col_maxes[c], grid[r][c]); + } + } + int result = 0; + for (int r = 0; r < grid.size(); ++r) { + for (int c = 0; c < grid[r].size(); ++c) { + result += min(row_maxes[r], col_maxes[c]) - grid[r][c]; + } + } + return result; + } +}; From 82ea895f63a6b25f1e412b5cc8ba8d8578e3dc6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Mar 2018 22:27:58 +0800 Subject: [PATCH 4569/4971] Create max-increase-to-keep-city-skyline.py --- Python/max-increase-to-keep-city-skyline.py | 53 +++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/max-increase-to-keep-city-skyline.py diff --git a/Python/max-increase-to-keep-city-skyline.py b/Python/max-increase-to-keep-city-skyline.py new file mode 100644 index 000000000..ce46816ad --- /dev/null +++ b/Python/max-increase-to-keep-city-skyline.py @@ -0,0 +1,53 @@ +# Time: O(n^2) +# Space: O(n) + +# In a 2 dimensional array grid, each value grid[i][j] represents the height of +# a building located there. We are allowed to increase the height of any number of buildings, +# by any amount (the amounts can be different for different buildings). +# Height 0 is considered to be a building as well. +# +# At the end, the "skyline" when viewed from all four directions of the grid, +# i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. +# A city's skyline is the outer contour of the rectangles formed by +# all the buildings when viewed from a distance. See the following example. +# +# What is the maximum total sum that the height of the buildings can be increased? +# +# Example: +# Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]] +# Output: 35 +# Explanation: +# The grid is: +# [ [3, 0, 8, 4], +# [2, 4, 5, 7], +# [9, 2, 6, 3], +# [0, 3, 1, 0] ] +# +# The skyline viewed from top or bottom is: [9, 4, 8, 7] +# The skyline viewed from left or right is: [8, 7, 9, 3] +# +# The grid after increasing the height of buildings without affecting skylines is: +# +# gridNew = [ [8, 4, 8, 7], +# [7, 4, 7, 7], +# [9, 4, 8, 7], +# [3, 3, 3, 3] ] +# +# Notes: +# - 1 < grid.length = grid[0].length <= 50. +# - All heights grid[i][j] are in the range [0, 100]. +# - All buildings in grid[i][j] occupy the entire grid cell: +# that is, they are a 1 x 1 x grid[i][j] rectangular prism. + +class Solution(object): + def maxIncreaseKeepingSkyline(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + row_maxes = [max(row) for row in grid] + col_maxes = [max(col) for col in itertools.izip(*grid)] + + return sum(min(row_maxes[r], col_maxes[c])-val \ + for r, row in enumerate(grid) \ + for c, val in enumerate(row)) From 1df7a5f5763bf3e33b0092d5b60f055c134f3c13 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 26 Mar 2018 22:35:37 +0800 Subject: [PATCH 4570/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 2b8ec42b8..ab6480ec1 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 794 | [Valid Tic-Tac-Toe State](https://leetcode.com/problems/valid-tic-tac-toe-state/) | [C++](./C++/valid-tic-tac-toe-state.cpp) [Python](./Python/valid-tic-tac-toe-state.py) | _O(1)_ | _O(1)_ | Medium || 795 | [Number of Subarrays with Bounded Maximum](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/) | [C++](./C++/number-of-subarrays-with-bounded-maximum.cpp) [Python](./Python/number-of-subarrays-with-bounded-maximum.py) | _O(n)_ | _O(1)_ | Medium || 803 | [Bricks Falling When Hit](https://leetcode.com/problems/bricks-falling-when-hit/) | [C++](./C++/bricks-falling-when-hit.cpp) [Python](./Python/bricks-falling-when-hit.py) | _O(r * c)_ | _O(r * c)_ | Hard || Union Find +807 | [Max Increase to Keep City Skyline](https://leetcode.com/problems/max-increase-to-keep-city-skyline/) | [C++](./C++/max-increase-to-keep-city-skyline.cpp) [Python](./Python/max-increase-to-keep-city-skyline.py) | _O(n^2)_ | _O(n)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -209,6 +210,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 758| [Bold Words in String](https://leetcode.com/contest/weekly-contest-66/problems/bold-words-in-string/) | [C++](./C++/bold-words-in-string.cpp) [Python](./Python/bold-words-in-string.py) | _O(n * l)_ | _O(t)_ | Easy | 📖, variant of [Add Bold Tag in String](https://leetcode.com/problems/add-bold-tag-in-string/) | 791| [Custom Sort String](https://leetcode.com/problems/custom-sort-string/) | [C++](./C++/custom-sort-string.cpp) [Python](./Python/custom-sort-string.py) | _O(n)_ | _O(1)_ | Medium ||| 796| [Rotate String](https://leetcode.com/problems/rotate-string/) | [C++](./C++/rotate-string.cpp) [Python](./Python/rotate-string.py) | _O(n)_ | _O(1)_ | Easy || `KMP Algorithm` `Rabin-Karp Algorithm` | +804| [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/) | [C++](./C++/unique-morse-code-words.cpp) [Python](./Python/unique-morse-code-words.py) | _O(n)_ | _O(n)_ | Easy ||| +806| [Number of Lines To Write String](https://leetcode.com/problems/number-of-lines-to-write-string/) | [C++](./C++/number-of-lines-to-write-string.cpp) [Python](./Python/number-of-lines-to-write-string.py) | _O(n)_ | _O(1)_ | Easy ||| ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -752,6 +755,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 790 | [Domino and Tromino Tiling](https://leetcode.com/problems/domino-and-tromino-tiling/) | [C++](./C++/domino-and-tromino-tiling.cpp) [Python](./Python/domino-and-tromino-tiling.py) | _O(logn)_ | _O(logn)_ | Medium || Matrix Exponentiation | 799 | [Champagne Tower](https://leetcode.com/problems/champagne-tower/) | [C++](./C++/champagne-tower.cpp) [Python](./Python/champagne-tower.py) | _O(n^2)_ | _O(n)_ | Medium ||| 801 | [Minimum Swaps To Make Sequences Increasing](https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/) | [C++](./C++/minimum-swaps-to-make-sequences-increasing.cpp) [Python](./Python/minimum-swaps-to-make-sequences-increasing.py) | _O(n)_ | _O(1)_ | Medium ||| +805 | [Split Array With Same Average](https://leetcode.com/problems/split-array-with-same-average/) | [C++](./C++/split-array-with-same-average.cpp) [Python](./Python/split-array-with-same-average.py) | _O(n^4)_ | _O(n^3)_ | Hard ||| ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 7252c768ba496f461af2d88ce262a5ffae6eb8ce Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Mar 2018 21:10:09 +0800 Subject: [PATCH 4571/4971] Update average-of-levels-in-binary-tree.py --- Python/average-of-levels-in-binary-tree.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Python/average-of-levels-in-binary-tree.py b/Python/average-of-levels-in-binary-tree.py index f6b0887f3..db9e5d1fb 100644 --- a/Python/average-of-levels-in-binary-tree.py +++ b/Python/average-of-levels-in-binary-tree.py @@ -33,10 +33,9 @@ def averageOfLevels(self, root): :rtype: List[float] """ result = [] - q = collections.deque([root]) + q, next_q = collections.deque([root]), collections.deque([]) while q: total, count = 0, 0 - next_q = collections.deque([]) while q: n = q.popleft() total += n.val; @@ -45,6 +44,6 @@ def averageOfLevels(self, root): next_q.append(n.left) if n.right: next_q.append(n.right) - q = next_q + q, next_q = next_q, q result.append(float(total) / count) return result From 5840831fd123c5ff01944130d1c82879dcbc0bbc Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 27 Mar 2018 21:11:08 +0800 Subject: [PATCH 4572/4971] Update average-of-levels-in-binary-tree.cpp --- C++/average-of-levels-in-binary-tree.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/C++/average-of-levels-in-binary-tree.cpp b/C++/average-of-levels-in-binary-tree.cpp index 731edd9ee..20011b31c 100644 --- a/C++/average-of-levels-in-binary-tree.cpp +++ b/C++/average-of-levels-in-binary-tree.cpp @@ -14,11 +14,10 @@ class Solution { public: vector averageOfLevels(TreeNode* root) { vector result; - queue q; + queue q, next; q.emplace(root); while (!q.empty()) { long long sum = 0, count = 0; - queue next; while (!q.empty()) { auto n = q.front(); q.pop(); From 0a66477bfc936aa1695c7960ed0d9516358c236c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Mar 2018 00:53:17 +0800 Subject: [PATCH 4573/4971] Update average-of-levels-in-binary-tree.cpp --- C++/average-of-levels-in-binary-tree.cpp | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/C++/average-of-levels-in-binary-tree.cpp b/C++/average-of-levels-in-binary-tree.cpp index 20011b31c..3edb91479 100644 --- a/C++/average-of-levels-in-binary-tree.cpp +++ b/C++/average-of-levels-in-binary-tree.cpp @@ -14,23 +14,21 @@ class Solution { public: vector averageOfLevels(TreeNode* root) { vector result; - queue q, next; - q.emplace(root); + vector q, next_q; + q.emplace_back(root); while (!q.empty()) { long long sum = 0, count = 0; - while (!q.empty()) { - auto n = q.front(); - q.pop(); + for (const auto& n : q) { sum += n->val; ++count; if (n->left) { - next.emplace(n->left); + next_q.emplace_back(n->left); } if (n->right) { - next.emplace(n->right); + next_q.emplace_back(n->right); } } - swap(q, next); + q = move(next_q); result.emplace_back(sum * 1.0 / count); } return result; From 901e72a1cb928c3bd1a4ee1afd619ad9103fef8a Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Mar 2018 00:55:29 +0800 Subject: [PATCH 4574/4971] Update average-of-levels-in-binary-tree.py --- Python/average-of-levels-in-binary-tree.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/average-of-levels-in-binary-tree.py b/Python/average-of-levels-in-binary-tree.py index db9e5d1fb..40bfe2fe0 100644 --- a/Python/average-of-levels-in-binary-tree.py +++ b/Python/average-of-levels-in-binary-tree.py @@ -33,17 +33,17 @@ def averageOfLevels(self, root): :rtype: List[float] """ result = [] - q, next_q = collections.deque([root]), collections.deque([]) + q = [root] while q: total, count = 0, 0 - while q: - n = q.popleft() + next_q = [] + for n in q: total += n.val; count += 1 if n.left: next_q.append(n.left) if n.right: next_q.append(n.right) - q, next_q = next_q, q + q = next_q result.append(float(total) / count) return result From 5cd5fbfc7e3dc7b5aaf1f49e70256e45a64d6507 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Mar 2018 00:59:05 +0800 Subject: [PATCH 4575/4971] Update average-of-levels-in-binary-tree.cpp --- C++/average-of-levels-in-binary-tree.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/C++/average-of-levels-in-binary-tree.cpp b/C++/average-of-levels-in-binary-tree.cpp index 3edb91479..4a9e68d8f 100644 --- a/C++/average-of-levels-in-binary-tree.cpp +++ b/C++/average-of-levels-in-binary-tree.cpp @@ -14,10 +14,11 @@ class Solution { public: vector averageOfLevels(TreeNode* root) { vector result; - vector q, next_q; + vector q; q.emplace_back(root); while (!q.empty()) { long long sum = 0, count = 0; + vector next_q; for (const auto& n : q) { sum += n->val; ++count; @@ -28,7 +29,7 @@ class Solution { next_q.emplace_back(n->right); } } - q = move(next_q); + swap(q, next_q); result.emplace_back(sum * 1.0 / count); } return result; From ca4eef6b4558f25a88621e8bd54143c96182848e Mon Sep 17 00:00:00 2001 From: Keqi Huang Date: Tue, 27 Mar 2018 17:29:45 -0500 Subject: [PATCH 4576/4971] Update jump-game-ii.py --- Python/jump-game-ii.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/Python/jump-game-ii.py b/Python/jump-game-ii.py index 61223b114..ef3887ea8 100644 --- a/Python/jump-game-ii.py +++ b/Python/jump-game-ii.py @@ -48,7 +48,7 @@ def jump(self, A): # when you on an index of nums, move to next index which can move farthest in range of this index reachable # Time: O(log(n)) -# Space: O(1) +# Space: O(n) class Solution3(object): def jump(self, nums): """ @@ -71,6 +71,33 @@ def find_max_index(index): break return steps + +# greedy solution, the current jump is ```[i, cur_end]```, and the cur_farthest is the farthest point +# that all of point in [i, cur_end] can reach, whenever cur_farthest is larger than the last point' index, +# return current jump+1; whenever i reaches cur_end, update cur_end to current cur_farthest. +# Time: O(log(n)) +# Space: O(1) +class Solution4(object): + def jump(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + # Note You can assume that you can always reach the last index. + cur_end, cur_farthest, step, n = 0, 0, 0, len(nums) + for i in range(n-1): + cur_farthest = max(cur_farthest, i + nums[i]) + if cur_farthest >= n - 1: + step += 1 + break + if i == cur_end: + cur_end = cur_farthest + step += 1 + return step + + + + if __name__ == "__main__": print Solution().jump([2,3,1,1,4]) print Solution().jump([3,2,1,0,4]) From 95bfeb97f6a1b9f173c4d3a4299249eab6a6e9da Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 28 Mar 2018 09:24:46 +0800 Subject: [PATCH 4577/4971] Update jump-game-ii.py --- Python/jump-game-ii.py | 69 +----------------------------------------- 1 file changed, 1 insertion(+), 68 deletions(-) diff --git a/Python/jump-game-ii.py b/Python/jump-game-ii.py index ef3887ea8..571c405d4 100644 --- a/Python/jump-game-ii.py +++ b/Python/jump-game-ii.py @@ -14,7 +14,7 @@ # # not pass on leetcode because of time limit -class Solution: +class Solution(object): # @param A, a list of integers # @return an integer def jump(self, A): @@ -29,73 +29,6 @@ def jump(self, A): 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): - result, prev_reachable, reachable = 0, -1, 0 - while reachable > prev_reachable: - if reachable >= len(A) - 1: - return result - result += 1 - prev_reachable = reachable - for i, length in enumerate(A[:reachable + 1]): - reachable = max(reachable, i + length) - return -1 - -# when you on an index of nums, move to next index which can move farthest in range of this index reachable -# Time: O(log(n)) -# Space: O(n) -class Solution3(object): - def jump(self, nums): - """ - :type nums: List[int] - :rtype: int - """ - nums[-1] = 2 ** 31 - nums2, l = [i + j for i, j in enumerate(nums)], len(nums) - 1 - - def find_max_index(index): - tmp = nums2[index:index + nums[index] + 1] - return index + tmp.index(max(tmp)) - - index, steps = 0, 0 - while True: - index = find_max_index(index) - if index: - steps += 1 - if index == l: - break - return steps - - -# greedy solution, the current jump is ```[i, cur_end]```, and the cur_farthest is the farthest point -# that all of point in [i, cur_end] can reach, whenever cur_farthest is larger than the last point' index, -# return current jump+1; whenever i reaches cur_end, update cur_end to current cur_farthest. -# Time: O(log(n)) -# Space: O(1) -class Solution4(object): - def jump(self, nums): - """ - :type nums: List[int] - :rtype: int - """ - # Note You can assume that you can always reach the last index. - cur_end, cur_farthest, step, n = 0, 0, 0, len(nums) - for i in range(n-1): - cur_farthest = max(cur_farthest, i + nums[i]) - if cur_farthest >= n - 1: - step += 1 - break - if i == cur_end: - cur_end = cur_farthest - step += 1 - return step - - if __name__ == "__main__": From 395c2ad73c6e9324c4badbb35c12192bf6ef3de7 Mon Sep 17 00:00:00 2001 From: Keqi Huang Date: Wed, 28 Mar 2018 22:00:59 -0500 Subject: [PATCH 4578/4971] Update n-queens.py --- Python/n-queens.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Python/n-queens.py b/Python/n-queens.py index 30612250a..5bf2c7441 100644 --- a/Python/n-queens.py +++ b/Python/n-queens.py @@ -62,5 +62,35 @@ def solveNQueensRecu(self, solution, row, n): if i not in solution and reduce(lambda acc, j: abs(row - j) != abs(i - solution[j]) and acc, xrange(len(solution)), True): self.solveNQueensRecu(solution + [i], row + 1, n) + + +# For any point (x,y), if we want the new point (p,q) don't share the same row, column, or diagonal. +# then there must have ```p+q != x+y``` and ```p-q!= x-y``` +# the former focus on eliminate 'left bottom right top' diagonal; +# the latter focus on eliminate 'left top right bottom' diagonal + +# - col_per_row: the list of column index per row +# - cur_row:current row we are seraching for valid column +# - xy_diff:the list of x-y +# - xy_sum:the list of x+y +class Solution3(object): + def solveNQueens(self, n): + """ + :type n: int + :rtype: List[List[str]] + """ + def dfs(col_per_row, xy_diff, xy_sum): + cur_row = len(col_per_row) + if cur_row == n: + ress.append(col_per_row) + for col in range(n): + if col not in col_per_row and cur_row-col not in xy_diff and cur_row+col not in xy_sum: + dfs(col_per_row+[col], xy_diff+[cur_row-col], xy_sum+[cur_row+col]) + ress = [] + dfs([], [], []) + return [['.'*i + 'Q' + '.'*(n-i-1) for i in res] for res in ress] + + + if __name__ == "__main__": print Solution().solveNQueens(8) From fcf65410243dc5db7ad2b75c3a5012ecc26b72ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 29 Mar 2018 13:56:30 +0800 Subject: [PATCH 4579/4971] Update super-ugly-number.cpp --- C++/super-ugly-number.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/super-ugly-number.cpp b/C++/super-ugly-number.cpp index 3e786e2b0..67097c6fb 100644 --- a/C++/super-ugly-number.cpp +++ b/C++/super-ugly-number.cpp @@ -1,4 +1,4 @@ -// Time: O(n * logk) ~ O(n * k) +// Time: O(n * k) // Space: O(n + k) // Heap solution. (308ms) @@ -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); // worst time: O(k) + while (ugly_by_last_prime[++idx[k]] > k); // average time: O(k) heap.emplace(uglies[idx[k]] * primes[k], k); } return uglies[n - 1]; From 77dda1c8348c2ad4e90da88919369281bb58de43 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 29 Mar 2018 13:56:53 +0800 Subject: [PATCH 4580/4971] 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 993afd326..3775efbb3 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -1,4 +1,4 @@ -# Time: O(n * logk) ~ O(n * k) +# Time: O(n * k) # Space: O(n + k) # Write a program to find the nth super ugly number. From 9fb215d93bb43adb3c45b7dad3bbc81bcc6390a5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 30 Mar 2018 23:09:42 +0800 Subject: [PATCH 4581/4971] Update n-queens.py --- Python/n-queens.py | 65 ++++++++++++++++++---------------------------- 1 file changed, 25 insertions(+), 40 deletions(-) diff --git a/Python/n-queens.py b/Python/n-queens.py index 5bf2c7441..9ca999b96 100644 --- a/Python/n-queens.py +++ b/Python/n-queens.py @@ -1,6 +1,6 @@ # Time: O(n!) # Space: O(n) -# + # The n-queens puzzle is the problem of placing n queens on # an nxn chess board such that no two queens attack each other. # @@ -24,46 +24,32 @@ # ".Q.."] # ] -# quick solution for checking if it is diagonally legal -class Solution: - # @return an integer - def solveNQueens(self, n): - self.cols = [False] * n - self.main_diag = [False] * (2 * n) - self.anti_diag = [False] * (2 * n) - self.solutions = [] - self.solveNQueensRecu([], 0, n) - return self.solutions - - - def solveNQueensRecu(self, solution, row, n): - if row == n: - self.solutions.append(map(lambda x: '.' * x + "Q" + '.' * (n - x - 1), solution)) - else: - for i in xrange(n): - if not self.cols[i] and not self.main_diag[row + i] and not self.anti_diag[row - i + n]: - self.cols[i] = self.main_diag[row + i] = self.anti_diag[row - i + n] = True - self.solveNQueensRecu(solution + [i], row + 1, n) - self.cols[i] = self.main_diag[row + i] = self.anti_diag[row - i + n] = False - -# slower solution -class Solution2: - # @return an integer +class Solution(object): def solveNQueens(self, n): - self.solutions = [] - self.solveNQueensRecu([], 0, n) - return self.solutions - - def solveNQueensRecu(self, solution, row, n): - if row == n: - self.solutions.append(map(lambda x: '.' * x + "Q" + '.' * (n - x - 1), solution)) - else: + """ + :type n: int + :rtype: List[List[str]] + """ + def dfs(curr, cols, main_diag, anti_diag, result): + row, n = len(curr), len(cols) + if row == n: + result.append(map(lambda x: '.'*x + "Q" + '.'*(n-x-1), curr)) + return for i in xrange(n): - if i not in solution and reduce(lambda acc, j: abs(row - j) != abs(i - solution[j]) and acc, xrange(len(solution)), True): - self.solveNQueensRecu(solution + [i], row + 1, n) + if cols[i] or main_diag[row+i] or anti_diag[row-i+n]: + continue + cols[i] = main_diag[row+i] = anti_diag[row-i+n] = True + curr.append(i) + dfs(curr, cols, main_diag, anti_diag, result) + curr.pop() + cols[i] = main_diag[row+i] = anti_diag[row-i+n] = False + + result = [] + cols, main_diag, anti_diag = [False]*n, [False]*(2*n), [False]*(2*n) + dfs([], cols, main_diag, anti_diag, result) + return result - # For any point (x,y), if we want the new point (p,q) don't share the same row, column, or diagonal. # then there must have ```p+q != x+y``` and ```p-q!= x-y``` # the former focus on eliminate 'left bottom right top' diagonal; @@ -73,7 +59,7 @@ def solveNQueensRecu(self, solution, row, n): # - cur_row:current row we are seraching for valid column # - xy_diff:the list of x-y # - xy_sum:the list of x+y -class Solution3(object): +class Solution2(object): def solveNQueens(self, n): """ :type n: int @@ -89,8 +75,7 @@ def dfs(col_per_row, xy_diff, xy_sum): ress = [] dfs([], [], []) return [['.'*i + 'Q' + '.'*(n-i-1) for i in res] for res in ress] - - + if __name__ == "__main__": print Solution().solveNQueens(8) From 8b0dccd07f2eefc73a30ce284c6fbfd38b0f9b62 Mon Sep 17 00:00:00 2001 From: cclauss Date: Sat, 31 Mar 2018 10:28:57 +0200 Subject: [PATCH 4582/4971] Add Travis CI to do automated testing on all PRs [Travis CI](https://travis-ci.org) is a framework for running tests which is free for open source projects like this one. The owner of the this repo would need to go to https://travis-ci.org/profile and flip the repository switch __on__ to enable free automated testing of each pull request. [Flake8](http://flake8.pycqa.org) is a linter that can help to find Python syntax errors, undefined names, and other code quality issues. Other linters could be run for the other languages. --- .travis.yml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..a4fc1b08e --- /dev/null +++ b/.travis.yml @@ -0,0 +1,28 @@ +group: travis_latest +language: python +cache: pip +python: + - 2.7 + - 3.6 + #- nightly + #- pypy + #- pypy3 +matrix: + allow_failures: + - python: 3.6 + - python: nightly + - python: pypy + - python: pypy3 +install: + #- pip install -r requirements.txt + - pip install flake8 # pytest # add another testing frameworks later +before_script: + # stop the build if there are Python syntax errors or undefined names + - flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics +script: + - true # pytest --capture=sys # add other tests here +notifications: + on_success: change + on_failure: change # `always` will be the setting once code changes slow down From 65b3ea4e9aaf5362f09f1d666a8fe8c39d10fcab Mon Sep 17 00:00:00 2001 From: cclauss Date: Sun, 1 Apr 2018 07:13:23 +0200 Subject: [PATCH 4583/4971] Fix flake8 related issues --- Python/01-matrix.py | 9 ++-- Python/4sum-ii.py | 3 ++ Python/4sum.py | 9 ++-- Python/accounts-merge.py | 11 +++-- Python/add-bold-tag-in-string.py | 5 +- Python/alien-dictionary.py | 45 ++++++++++------- Python/arithmetic-slices-ii-subsequence.py | 3 ++ Python/arranging-coins.py | 3 ++ Python/basic-calculator-iv.py | 24 +++++---- .../binary-tree-vertical-order-traversal.py | 3 ++ Python/bold-words-in-string.py | 3 ++ Python/brick-wall.py | 5 +- Python/bulb-switcher.py | 21 ++++---- Python/bulls-and-cows.py | 22 +++++---- Python/cheapest-flights-within-k-stops.py | 12 +++-- Python/closest-leaf-in-a-binary-tree.py | 5 +- Python/construct-the-rectangle.py | 5 +- Python/contains-duplicate-iii.py | 16 +++--- Python/course-schedule-ii.py | 49 ++++++++++--------- Python/course-schedule-iii.py | 10 ++-- Python/custom-sort-string.py | 9 ++-- Python/cut-off-trees-for-golf-event.py | 15 ++++-- Python/degree-of-an-array.py | 6 ++- Python/design-compressed-string-iterator.py | 7 ++- Python/design-excel-sum-formula.py | 9 ++-- Python/design-search-autocomplete-system.py | 9 ++-- Python/design-snake-game.py | 14 +++--- Python/design-tic-tac-toe.py | 15 ++++-- Python/design-twitter.py | 4 ++ Python/different-ways-to-add-parentheses.py | 16 +++--- Python/domino-and-tromino-tiling.py | 8 +-- Python/dota2-senate.py | 19 ++++--- Python/employee-free-time.py | 3 ++ Python/employee-importance.py | 3 ++ Python/encode-and-decode-tinyurl.py | 8 +-- Python/equal-tree-partition.py | 3 ++ Python/erect-the-fence.py | 5 +- Python/evaluate-division.py | 9 ++-- Python/falling-squares.py | 17 ++++--- Python/find-anagram-mappings.py | 3 ++ Python/find-duplicate-file-in-system.py | 11 +++-- Python/find-duplicate-subtrees.py | 7 ++- Python/find-eventual-safe-states.py | 5 +- Python/find-k-closest-elements.py | 3 ++ Python/find-right-interval.py | 3 ++ ...ind-smallest-letter-greater-than-target.py | 3 ++ Python/flip-game-ii.py | 4 ++ Python/fraction-addition-and-subtraction.py | 3 ++ Python/freedom-trail.py | 9 ++-- Python/graph-valid-tree.py | 3 ++ Python/group-anagrams.py | 3 ++ Python/group-shifted-strings.py | 5 +- Python/heaters.py | 4 +- Python/implement-magic-dictionary.py | 17 ++++--- Python/implement-stack-using-queues.py | 14 +++--- Python/increasing-triplet-subsequence.py | 8 +-- Python/invert-binary-tree.py | 26 +++++----- Python/ipo.py | 3 ++ Python/kill-process.py | 3 ++ Python/lfu-cache.py | 15 +++--- Python/line-reflection.py | 3 ++ Python/logger-rate-limiter.py | 3 ++ Python/lonely-pixel-ii.py | 3 ++ Python/longest-harmonious-subsequence.py | 7 ++- Python/longest-word-in-dictionary.py | 11 +++-- Python/magical-string.py | 4 ++ Python/map-sum-pairs.py | 7 ++- Python/max-increase-to-keep-city-skyline.py | 11 +++-- Python/max-points-on-a-line.py | 11 +++-- Python/max-stack.py | 19 ++++--- Python/maximum-length-of-repeated-subarray.py | 12 +++-- Python/minesweeper.py | 20 ++++---- Python/minimum-height-trees.py | 19 ++++--- Python/missing-number.py | 5 +- Python/most-frequent-subtree-sum.py | 3 ++ Python/my-calendar-iii.py | 17 ++++--- Python/network-delay-time.py | 6 ++- Python/next-greater-element-iii.py | 14 ++++-- Python/number-of-atoms.py | 16 +++--- Python/number-of-matching-subsequences.py | 5 +- Python/optimal-account-balancing.py | 5 +- Python/palindrome-pairs.py | 9 ++-- Python/palindrome-permutation-ii.py | 8 ++- Python/palindrome-permutation.py | 5 +- Python/path-sum-iii.py | 7 ++- Python/path-sum-iv.py | 5 +- Python/permutation-in-string.py | 3 ++ Python/poor-pigs.py | 3 ++ Python/prefix-and-suffix-search.py | 17 ++++--- Python/rabbits-in-forest.py | 3 ++ Python/range-module.py | 5 +- Python/reach-a-number.py | 6 ++- Python/reconstruct-itinerary.py | 7 ++- Python/remove-duplicate-letters.py | 3 ++ Python/reorganize-string.py | 6 ++- Python/replace-words.py | 3 ++ .../second-minimum-node-in-a-binary-tree.py | 9 ++-- Python/sentence-similarity-ii.py | 3 ++ Python/sentence-similarity.py | 3 ++ Python/sequence-reconstruction.py | 4 +- Python/serialize-and-deserialize-bst.py | 7 ++- Python/shortest-completing-word.py | 3 ++ Python/shortest-word-distance-ii.py | 4 +- Python/shuffle-an-array.py | 7 ++- Python/sliding-puzzle.py | 16 +++--- Python/smallest-good-base.py | 5 +- Python/smallest-range.py | 9 ++-- ...allest-rectangle-enclosing-black-pixels.py | 4 ++ Python/solve-the-equation.py | 3 ++ Python/sort-characters-by-frequency.py | 9 ++-- Python/stickers-to-spell-word.py | 10 ++-- Python/subarray-sum-equals-k.py | 3 ++ ...bstring-with-concatenation-of-all-words.py | 14 ++++-- Python/sum-of-square-numbers.py | 5 +- Python/summary-ranges.py | 6 +++ Python/super-ugly-number.py | 9 ++-- Python/surrounded-regions.py | 17 ++++--- Python/target-sum.py | 7 ++- Python/task-scheduler.py | 5 +- Python/the-maze-ii.py | 7 ++- Python/the-maze-iii.py | 9 ++-- Python/the-maze.py | 7 ++- Python/top-k-frequent-elements.py | 21 +++++--- Python/top-k-frequent-words.py | 23 ++++++--- Python/transform-to-chessboard.py | 5 +- Python/unique-word-abbreviation.py | 7 ++- Python/valid-anagram.py | 10 ++-- Python/validate-ip-address.py | 7 ++- Python/word-abbreviation.py | 5 +- Python/zigzag-iterator.py | 3 ++ Python/zuma-game.py | 15 +++--- 131 files changed, 792 insertions(+), 374 deletions(-) diff --git a/Python/01-matrix.py b/Python/01-matrix.py index a4ff877ba..46351da5a 100644 --- a/Python/01-matrix.py +++ b/Python/01-matrix.py @@ -4,7 +4,7 @@ # Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. # The distance between two adjacent cells is 1. # -# Example 1: +# Example 1: # # Input: # 0 0 0 @@ -16,7 +16,7 @@ # 0 1 0 # 0 0 0 # -# Example 2: +# Example 2: # # Input: # 0 0 0 @@ -33,6 +33,9 @@ # There are at least one 0 in the given matrix. # The cells are adjacent in only four directions: up, down, left and right. +import collections + + class Solution(object): def updateMatrix(self, matrix): """ @@ -57,7 +60,7 @@ def updateMatrix(self, matrix): continue queue.append((i, j)) matrix[i][j] = matrix[cell[0]][cell[1]]+1 - + return matrix diff --git a/Python/4sum-ii.py b/Python/4sum-ii.py index 016952602..a11bede5a 100644 --- a/Python/4sum-ii.py +++ b/Python/4sum-ii.py @@ -24,6 +24,9 @@ # 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 # 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 +import collections + + class Solution(object): def fourSumCount(self, A, B, C, D): """ diff --git a/Python/4sum.py b/Python/4sum.py index d65759bdc..6f137b1ef 100644 --- a/Python/4sum.py +++ b/Python/4sum.py @@ -1,7 +1,7 @@ # Time: O(n^3) # Space: O(1) -# Given an array S of n integers, +# Given an array S of n integers, # are there elements a, b, c, and d in S such that a + b + c + d = target? # Find all unique quadruplets in the array which gives the sum of target. # @@ -16,6 +16,9 @@ # (-2, 0, 0, 2) # +import collections + + # Two pointer solution. (1356ms) class Solution(object): def fourSum(self, nums, target): @@ -62,7 +65,7 @@ def fourSum(self, nums, target): """ nums, result, lookup = sorted(nums), [], collections.defaultdict(list) for i in xrange(0, len(nums) - 1): - for j in xrange(i + 1, len(nums)): + for j in xrange(i + 1, len(nums)): is_duplicated = False for [x, y] in lookup[nums[i] + nums[j]]: if nums[x] == nums[i]: @@ -95,7 +98,7 @@ def fourSum(self, nums, target): """ nums, result, lookup = sorted(nums), [], collections.defaultdict(list) for i in xrange(0, len(nums) - 1): - for j in xrange(i + 1, len(nums)): + for j in xrange(i + 1, len(nums)): lookup[nums[i] + nums[j]].append([i, j]) for i in lookup.keys(): diff --git a/Python/accounts-merge.py b/Python/accounts-merge.py index 3f3a57b40..2eac67d94 100644 --- a/Python/accounts-merge.py +++ b/Python/accounts-merge.py @@ -16,7 +16,7 @@ # The accounts themselves can be returned in any order. # # Example 1: -# Input: +# Input: # accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], # ["John", "johnnybravo@mail.com"], # ["John", "johnsmith@mail.com", "john_newyork@mail.com"], @@ -24,12 +24,12 @@ # Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], # ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]] # -# Explanation: +# Explanation: # The first and third John's are the same person as they have the common email "johnsmith@mail.com". # The second John and Mary are different people as none of their email addresses are used by other accounts. # We could return these lists in any order, # for example the answer [['Mary', 'mary@mail.com'], -# ['John', 'johnnybravo@mail.com'], +# ['John', 'johnnybravo@mail.com'], # ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] # would still be accepted. # @@ -39,6 +39,9 @@ # The length of accounts[i] will be in the range [1, 10]. # The length of accounts[i][j] will be in the range [1, 30]. +import collections + + class UnionFind(object): def __init__(self): self.set = [] @@ -46,7 +49,7 @@ def __init__(self): def get_id(self): self.set.append(len(self.set)) return len(self.set)-1 - + def find_set(self, x): if self.set[x] != x: self.set[x] = self.find_set(self.set[x]) # path compression. diff --git a/Python/add-bold-tag-in-string.py b/Python/add-bold-tag-in-string.py index def3394f3..984d640aa 100644 --- a/Python/add-bold-tag-in-string.py +++ b/Python/add-bold-tag-in-string.py @@ -1,6 +1,9 @@ # Time: O(n * d * l), l is the average string length # Space: O(n) +import collections + + # 59ms class Solution(object): def addBoldTag(self, s, dict): @@ -25,7 +28,7 @@ def addBoldTag(self, s, dict): result.append(""); return "".join(result) - + # Time: O(n * l), l is the average string length # Space: O(t) , t is the size of trie # trie solution, 439ms diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index b9eccb43b..2274736ad 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -1,6 +1,14 @@ # Time: O(n) # Space: O(|V|+|E|) = O(26 + 26^2) = O(1) +import collections + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + # BFS solution. class Solution(object): def alienOrder(self, words): @@ -8,34 +16,35 @@ def alienOrder(self, words): :type words: List[str] :rtype: str """ - result, zero_in_degree_queue, in_degree, out_degree = [], collections.deque(), {}, {} - nodes = sets.Set() + result, in_degree, out_degree = [], {}, {} + zero_in_degree_queue = collections.deque() + nodes = set() for word in words: for c in word: nodes.add(c) - + for i in xrange(1, len(words)): - if len(words[i-1]) > len(words[i]) and \ - words[i-1][:len(words[i])] == words[i]: - return "" + if (len(words[i-1]) > len(words[i]) and + words[i-1][:len(words[i])] == words[i]): + return "" 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.popleft() result.append(precedence) - + if precedence in out_degree: 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] - + if out_degree: return "" @@ -48,9 +57,9 @@ def findEdges(self, word1, word2, in_degree, out_degree): for i in xrange(str_len): if word1[i] != word2[i]: if word2[i] not in in_degree: - in_degree[word2[i]] = sets.Set() + in_degree[word2[i]] = set() if word1[i] not in out_degree: - out_degree[word1[i]] = sets.Set() + out_degree[word1[i]] = set() in_degree[word2[i]].add(word1[i]) out_degree[word1[i]].add(word2[i]) break @@ -64,16 +73,16 @@ def alienOrder(self, words): :rtype: str """ # Find ancestors of each node by DFS. - nodes, ancestors = sets.Set(), {} + nodes, ancestors = set(), {} 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)): - if len(words[i-1]) > len(words[i]) and \ - words[i-1][:len(words[i])] == words[i]: - return "" + if (len(words[i-1]) > len(words[i]) and + words[i-1][:len(words[i])] == words[i]): + return "" self.findEdges(words[i - 1], words[i], ancestors) # Output topological order by DFS. @@ -82,7 +91,7 @@ def alienOrder(self, words): for node in nodes: if self.topSortDFS(node, node, ancestors, visited, result): return "" - + return "".join(result) diff --git a/Python/arithmetic-slices-ii-subsequence.py b/Python/arithmetic-slices-ii-subsequence.py index 30418e704..adf5e643e 100644 --- a/Python/arithmetic-slices-ii-subsequence.py +++ b/Python/arithmetic-slices-ii-subsequence.py @@ -42,6 +42,9 @@ # [2,4,6,8,10] # [2,6,10] +import collections + + class Solution(object): def numberOfArithmeticSlices(self, A): """ diff --git a/Python/arranging-coins.py b/Python/arranging-coins.py index f4e3de1df..85d0c868d 100644 --- a/Python/arranging-coins.py +++ b/Python/arranging-coins.py @@ -30,6 +30,9 @@ # # Because the 4th row is incomplete, we return 3. +import math + + class Solution(object): def arrangeCoins(self, n): """ diff --git a/Python/basic-calculator-iv.py b/Python/basic-calculator-iv.py index cdf693a0b..ddb15ab7c 100644 --- a/Python/basic-calculator-iv.py +++ b/Python/basic-calculator-iv.py @@ -15,7 +15,7 @@ # have a leading coefficient or unary operator like "2x" or "-x". # # Expressions are evaluated in the usual order: -# brackets first, then multiplication, then addition and subtraction. +# brackets first, then multiplication, then addition and subtraction. # For example, expression = "1 + 2 * 3" has an answer of ["7"]. # # The format of the output is as follows: @@ -26,9 +26,9 @@ # counting multiplicity. (For example, "a*a*b*c" has degree 4.) # We write the largest degree terms of our answer first, # breaking ties by lexicographic order ignoring the leading coefficient of the term. -# - The leading coefficient of the term is placed directly to the left with an asterisk separating it +# - The leading coefficient of the term is placed directly to the left with an asterisk separating it # from the variables (if they exist.) A leading coefficient of 1 is still printed. -# - An example of a well formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] +# - An example of a well formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] # - Terms (including constant terms) with coefficient 0 are not included. # For example, an expression of "0" has an output of []. # @@ -52,7 +52,7 @@ # # Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))", # evalvars = [], evalints = [] -# Output: +# Output: # ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c", # "1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b", # "2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"] @@ -61,6 +61,10 @@ # - expression will have length in range [1, 1000]. # - evalvars, evalints will have equal lengths in range [0, 1000]. +import collections +import itertools + + class Poly(collections.Counter): def __init__(self, expr=None): if expr is None: @@ -94,9 +98,9 @@ def merge(k1, k2): i += 1 else: result.append(k2[j]) - j += 1 + j += 1 return result - + result = Poly() for k1, v1 in self.items(): for k2, v2 in other.items(): @@ -119,8 +123,8 @@ def to_list(self): return ["*".join((str(v),) + k) \ for k, v in sorted(self.items(), key=lambda(k, _): (-len(k), k)) \ if v] - - + + class Solution(object): def basicCalculatorIV(self, expression, evalvars, evalints): """ @@ -138,7 +142,7 @@ def compute(operands, operators): operands.append(left - right) elif op == '*': operands.append(left * right) - + def parse(s): if not s: return Poly() @@ -163,6 +167,6 @@ def parse(s): while operators: compute(operands, operators) return operands[-1] - + lookup = dict(itertools.izip(evalvars, evalints)) return parse(expression).eval(lookup).to_list() diff --git a/Python/binary-tree-vertical-order-traversal.py b/Python/binary-tree-vertical-order-traversal.py index 69e483787..6790d59fd 100644 --- a/Python/binary-tree-vertical-order-traversal.py +++ b/Python/binary-tree-vertical-order-traversal.py @@ -8,6 +8,9 @@ # self.left = None # self.right = None +import collections + + # BFS + hash solution. class Solution(object): def verticalOrder(self, root): diff --git a/Python/bold-words-in-string.py b/Python/bold-words-in-string.py index 455e3717f..0f794f228 100644 --- a/Python/bold-words-in-string.py +++ b/Python/bold-words-in-string.py @@ -1,6 +1,9 @@ # Time: O(n * l), n is the length of S, l is the average length of words # Space: O(t) , t is the size of trie +import collections + + class Solution(object): def boldWords(self, words, S): """ diff --git a/Python/brick-wall.py b/Python/brick-wall.py index 47ea1c230..767290085 100644 --- a/Python/brick-wall.py +++ b/Python/brick-wall.py @@ -15,7 +15,7 @@ # in which case the line will obviously cross no bricks. # # Example: -# Input: +# Input: # [[1,2,2,1], # [3,1,2], # [1,3,2], @@ -30,6 +30,9 @@ # The height of wall is in range [1,10,000]. # Total number of bricks of the wall won't exceed 20,000. +import collections + + class Solution(object): def leastBricks(self, wall): """ diff --git a/Python/bulb-switcher.py b/Python/bulb-switcher.py index a63b6c39e..f2dd883dd 100644 --- a/Python/bulb-switcher.py +++ b/Python/bulb-switcher.py @@ -1,27 +1,30 @@ # 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 +# 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 +# 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. +# 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]. +# After third round, the three bulbs are [on, off, off]. # -# So you should return 1, because there is +# So you should return 1, because there is # only one bulb is on. +import math + + class Solution(object): def bulbSwitch(self, n): """ diff --git a/Python/bulls-and-cows.py b/Python/bulls-and-cows.py index b0c8849f4..ead89679c 100644 --- a/Python/bulls-and-cows.py +++ b/Python/bulls-and-cows.py @@ -3,9 +3,9 @@ # 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 +# 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. # @@ -15,13 +15,13 @@ # 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 +# 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 +# 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. # @@ -29,6 +29,9 @@ # digits, and their lengths are always equal. # +import operator + + # One pass solution. from collections import defaultdict from itertools import izip @@ -56,7 +59,7 @@ def getHint(self, secret, guess): B += 1 else: s_lookup[s] += 1 - + return "%dA%dB" % (A, B) @@ -74,4 +77,3 @@ def getHint(self, secret, guess): A = sum(imap(operator.eq, secret, guess)) B = sum((Counter(secret) & Counter(guess)).values()) - A return "%dA%dB" % (A, B) - diff --git a/Python/cheapest-flights-within-k-stops.py b/Python/cheapest-flights-within-k-stops.py index 906bf1fd1..f104bea2c 100644 --- a/Python/cheapest-flights-within-k-stops.py +++ b/Python/cheapest-flights-within-k-stops.py @@ -8,20 +8,20 @@ # If there is no such route, output -1. # # Example 1: -# Input: +# Input: # n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]] # src = 0, dst = 2, k = 1 # Output: 200 -# Explanation: +# Explanation: # The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture. # # Example 2: -# Input: +# Input: # n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]] # src = 0, dst = 2, k = 0 # Output: 500 # -# Explanation: +# Explanation: # The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture. # Note: # - The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1. @@ -31,6 +31,10 @@ # - k is in the range of [0, n - 1]. # - There will not be any duplicated flights or self cycles. +import collections +import heapq + + class Solution(object): def findCheapestPrice(self, n, flights, src, dst, K): """ diff --git a/Python/closest-leaf-in-a-binary-tree.py b/Python/closest-leaf-in-a-binary-tree.py index 839133c9f..1b5c789d7 100644 --- a/Python/closest-leaf-in-a-binary-tree.py +++ b/Python/closest-leaf-in-a-binary-tree.py @@ -58,6 +58,9 @@ # self.left = None # self.right = None +import collections + + class Solution(object): def findClosestLeaf(self, root, k): """ @@ -79,7 +82,7 @@ def traverse(node, neighbors, leaves): neighbors[node.val].append(node.right.val) neighbors[node.right.val].append(node.val) traverse(node.right, neighbors, leaves) - + neighbors, leaves = collections.defaultdict(list), set() traverse(root, neighbors, leaves) q, lookup = [k], set([k]) diff --git a/Python/construct-the-rectangle.py b/Python/construct-the-rectangle.py index 54a412741..400d5f08c 100644 --- a/Python/construct-the-rectangle.py +++ b/Python/construct-the-rectangle.py @@ -15,13 +15,16 @@ # Example: # Input: 4 # Output: [2, 2] -# Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. +# Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. # But according to requirement 2, [1,4] is illegal; according to requirement 3, # [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2. # Note: # The given area won't exceed 10,000,000 and is a positive integer # The web page's width and length you designed must be positive integers. +import math + + class Solution(object): def constructRectangle(self, area): """ diff --git a/Python/contains-duplicate-iii.py b/Python/contains-duplicate-iii.py index 42841b948..778be9eb5 100644 --- a/Python/contains-duplicate-iii.py +++ b/Python/contains-duplicate-iii.py @@ -1,16 +1,20 @@ # 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 +# 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 +# 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. + +import collections + + class Solution: # @param {integer[]} nums # @param {integer} k @@ -24,7 +28,7 @@ def containsNearbyAlmostDuplicate(self, nums, k, t): # 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)): diff --git a/Python/course-schedule-ii.py b/Python/course-schedule-ii.py index c7e9c290b..7b9f4d3cf 100644 --- a/Python/course-schedule-ii.py +++ b/Python/course-schedule-ii.py @@ -2,38 +2,41 @@ # 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, +# +# 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 +# +# 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 +# +# 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]. +# 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. +# 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. +# 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 +# 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. -# +# + +import collections + class Solution(object): def findOrder(self, numCourses, prerequisites): @@ -43,7 +46,7 @@ def findOrder(self, numCourses, prerequisites): :rtype: List[int] """ res, zero_in_degree_queue, in_degree, out_degree = [], collections.deque(), {}, {} - + for i, j in prerequisites: if i not in in_degree: in_degree[i] = set() @@ -51,24 +54,24 @@ def findOrder(self, numCourses, prerequisites): out_degree[j] = set() in_degree[i].add(j) out_degree[j].add(i) - + 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.popleft() res.append(prerequisite) - + if prerequisite in out_degree: for course in out_degree[prerequisite]: in_degree[course].discard(prerequisite) if not in_degree[course]: zero_in_degree_queue.append(course) - + del out_degree[prerequisite] - + if out_degree: return [] - + return res diff --git a/Python/course-schedule-iii.py b/Python/course-schedule-iii.py index af874fc69..605f9cc19 100644 --- a/Python/course-schedule-iii.py +++ b/Python/course-schedule-iii.py @@ -11,13 +11,13 @@ # Example: # Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]] # Output: 3 -# Explanation: +# Explanation: # There're totally 4 courses, but you can take 3 courses at most: # First, take the 1st course, it costs 100 days so you will finish it on the 100th day, # and ready to take the next course on the 101st day. # Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, -# and ready to take the next course on the 1101st day. -# Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. +# and ready to take the next course on the 1101st day. +# Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. # The 4th course cannot be taken now, since you will finish it on the 3300th day, # which exceeds the closed date. # @@ -25,6 +25,10 @@ # The integer 1 <= d, t, n <= 10,000. # You can't take two courses simultaneously. +import collections +import heapq + + class Solution(object): def scheduleCourse(self, courses): """ diff --git a/Python/custom-sort-string.py b/Python/custom-sort-string.py index 6851fa07e..950760368 100644 --- a/Python/custom-sort-string.py +++ b/Python/custom-sort-string.py @@ -10,12 +10,12 @@ # Return any permutation of T (as a string) that satisfies this property. # # Example : -# Input: +# Input: # S = "cba" # T = "abcd" # Output: "cbad" -# Explanation: -# "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". +# Explanation: +# "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". # Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs. # # Note: @@ -23,6 +23,9 @@ # - T has length at most 200. # - S and T consist of lowercase letters only. +import collections + + class Solution(object): def customSortString(self, S, T): """ diff --git a/Python/cut-off-trees-for-golf-event.py b/Python/cut-off-trees-for-golf-event.py index b71b21091..e41eaad67 100644 --- a/Python/cut-off-trees-for-golf-event.py +++ b/Python/cut-off-trees-for-golf-event.py @@ -20,7 +20,7 @@ # You are guaranteed that no two trees have the same height and there is at least one tree needs to be cut off. # # Example 1: -# Input: +# Input: # [ # [1,2,3], # [0,0,4], @@ -28,7 +28,7 @@ # ] # Output: 6 # Example 2: -# Input: +# Input: # [ # [1,2,3], # [0,0,0], @@ -36,7 +36,7 @@ # ] # Output: -1 # Example 3: -# Input: +# Input: # [ # [2,3,4], # [0,0,5], @@ -47,11 +47,16 @@ # in (0,0) directly without walking. # Hint: size of the given matrix will not exceed 50x50. -# Solution Reference: +# Solution Reference: # 1. https://discuss.leetcode.com/topic/103532/my-python-solution-inspired-by-a-algorithm/2 # 2. https://discuss.leetcode.com/topic/103562/python-solution-based-on-wufangjie-s-hadlock-s-algorithm # 3. https://en.wikipedia.org/wiki/A*_search_algorithm # 4. https://cg2010studio.files.wordpress.com/2011/12/dijkstra-vs-a-star.png + +import collections +import heapq + + class Solution(object): def cutOffTree(self, forest): """ @@ -127,7 +132,7 @@ def minStep(p1, p2): lookup.add((i, j)) min_steps += 1 return -1 - + m, n = len(forest), len(forest[0]) min_heap = [] for i in xrange(m): diff --git a/Python/degree-of-an-array.py b/Python/degree-of-an-array.py index 567caa282..239c27095 100644 --- a/Python/degree-of-an-array.py +++ b/Python/degree-of-an-array.py @@ -10,7 +10,7 @@ # Example 1: # Input: [1, 2, 2, 3, 1] # Output: 2 -# Explanation: +# Explanation: # The input array has a degree of 2 because both elements 1 and 2 appear twice. # Of the subarrays that have the same degree: # [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] @@ -24,6 +24,9 @@ # nums.length will be between 1 and 50,000. # nums[i] will be an integer between 0 and 49,999. +import collections + + class Solution(object): def findShortestSubArray(self, nums): """ @@ -39,4 +42,3 @@ def findShortestSubArray(self, nums): return min(right[num]-left[num]+1 \ for num in counts.keys() \ if counts[num] == degree) - diff --git a/Python/design-compressed-string-iterator.py b/Python/design-compressed-string-iterator.py index 162840d79..e23233aa9 100644 --- a/Python/design-compressed-string-iterator.py +++ b/Python/design-compressed-string-iterator.py @@ -1,6 +1,9 @@ # Time: O(1) # Space: O(1) +import re + + class StringIterator(object): def __init__(self, compressedString): @@ -22,14 +25,14 @@ def next(self): self.__index += 1 self.__num -= 1 return self.__ch - + def hasNext(self): """ :rtype: bool """ return self.__index != len(self.__result) or self.__num != 0 - + # Your StringIterator object will be instantiated and called as such: diff --git a/Python/design-excel-sum-formula.py b/Python/design-excel-sum-formula.py index 24a1b47ca..edd5df557 100644 --- a/Python/design-excel-sum-formula.py +++ b/Python/design-excel-sum-formula.py @@ -3,6 +3,9 @@ # sum: O((r * c)^2) # Space: O(r * c) +import collections + + class Excel(object): def __init__(self, H, W): @@ -14,7 +17,7 @@ def __init__(self, H, W): for _ in xrange(H+1)] self.__fward = collections.defaultdict(lambda : collections.defaultdict(int)) self.__bward = collections.defaultdict(set) - + def set(self, r, c, v): """ @@ -25,7 +28,7 @@ def set(self, r, c, v): """ self.__reset_dependency(r, c); self.__update_others(r, c, v); - + def get(self, r, c): """ @@ -34,7 +37,7 @@ def get(self, r, c): :rtype: int """ return self.__exl[r][ord(c) - ord('A')] - + def sum(self, r, c, strs): """ diff --git a/Python/design-search-autocomplete-system.py b/Python/design-search-autocomplete-system.py index f7a4d04b7..cc540a426 100644 --- a/Python/design-search-autocomplete-system.py +++ b/Python/design-search-autocomplete-system.py @@ -1,7 +1,10 @@ # Time: O(p^2), p is the length of the prefix # Space: O(p * t + s), t is the number of nodes of trie # , s is the size of the sentences - + +import collections + + class TrieNode(object): def __init__(self): @@ -19,7 +22,7 @@ def insert(self, s, times): cur = cur.leaves[c] cur.add_info(s, times) - + def add_info(self, s, times): for p in self.infos: if p[1] == s: @@ -68,7 +71,7 @@ def input(self, c): self.__cur_node = self.__cur_node.leaves[c] result = [p[1] for p in self.__cur_node.infos] return result - + # Your AutocompleteSystem object will be instantiated and called as such: # obj = AutocompleteSystem(sentences, times) diff --git a/Python/design-snake-game.py b/Python/design-snake-game.py index 134dbcae3..f0792ac15 100644 --- a/Python/design-snake-game.py +++ b/Python/design-snake-game.py @@ -1,7 +1,7 @@ # Time: O(1) per move # Space: O(s), s is the current length of the snake. -from collections import deque +from collections import defaultdict, deque class SnakeGame(object): @@ -9,7 +9,7 @@ def __init__(self, width,height,food): """ Initialize your data structure here. @param width - screen width - @param height - screen height + @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int @@ -21,15 +21,15 @@ def __init__(self, width,height,food): self.__score = 0 self.__food = deque(food) self.__snake = deque([(0, 0)]) - self.__direction = {"U":(-1, 0), "L":(0, -1), "R":(0, 1), "D":(1, 0)}; - self.__lookup = collections.defaultdict(int) + self.__direction = {"U": (-1, 0), "L": (0, -1), "R": (0, 1), "D": (1, 0)} + self.__lookup = defaultdict(int) self.__lookup[(0, 0)] += 1 - + def move(self, direction): """ Moves the snake. - @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down - @return The game's score after the move. Return -1 if game over. + @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down + @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. :type direction: str :rtype: int diff --git a/Python/design-tic-tac-toe.py b/Python/design-tic-tac-toe.py index cf4b1384f..b5f6d0aac 100644 --- a/Python/design-tic-tac-toe.py +++ b/Python/design-tic-tac-toe.py @@ -1,6 +1,12 @@ # Time: O(1), per move. # Space: O(n^2) +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class TicTacToe(object): def __init__(self, n): @@ -13,7 +19,6 @@ def __init__(self, n): self.__cols = [[0, 0] for _ in xrange(n)] self.__diagonal = [0, 0] self.__anti_diagonal = [0, 0] - def move(self, row, col, player): """ @@ -37,10 +42,10 @@ def move(self, row, col, player): self.__diagonal[i] += 1 if col == len(self.__rows) - row - 1: self.__anti_diagonal[i] += 1 - if any([self.__rows[row][i] == self.__size), \ - self.__cols[col][i] == self.__size, \ - self.__diagonal[i] == self.__size, \ - self.__anti_diagonal[i] == self.__size]): + if any(self.__rows[row][i] == self.__size, + self.__cols[col][i] == self.__size, + self.__diagonal[i] == self.__size, + self.__anti_diagonal[i] == self.__size): return player return 0 diff --git a/Python/design-twitter.py b/Python/design-twitter.py index 8fe5ee95a..ed03792da 100644 --- a/Python/design-twitter.py +++ b/Python/design-twitter.py @@ -40,6 +40,10 @@ # // since user 1 is no longer following user 2. # twitter.getNewsFeed(1); +import collections +import heapq + + class Twitter(object): def __init__(self): diff --git a/Python/different-ways-to-add-parentheses.py b/Python/different-ways-to-add-parentheses.py index b83604fbf..c88602a20 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(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 the time complexity is at most n * Catalan numbers. @@ -28,6 +28,10 @@ # Output: [-34, -14, -10, -10, 10] # +import operator +import re + + class Solution: # @param {string} input # @return {integer[]} @@ -36,7 +40,7 @@ def diffWaysToCompute(self, 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]] @@ -47,7 +51,7 @@ def diffWaysToComputeRecu(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) class Solution2: @@ -66,10 +70,10 @@ def diffWaysToComputeRecu(left, right): 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 + lookup[left][right] = result return lookup[left][right] - + return diffWaysToComputeRecu(0, len(input)) diff --git a/Python/domino-and-tromino-tiling.py b/Python/domino-and-tromino-tiling.py index a7919a81b..401104ef0 100644 --- a/Python/domino-and-tromino-tiling.py +++ b/Python/domino-and-tromino-tiling.py @@ -17,7 +17,7 @@ # Example: # Input: 3 # Output: 5 -# Explanation: +# Explanation: # The five different ways are listed below, different letters indicates different tiles: # XYZ XXZ XYY XXY XYY # XYZ YYZ XZZ XYY XXY @@ -25,6 +25,9 @@ # Note: # - N will be in range [1, 1000]. +import itertools + + class Solution(object): def numTilings(self, N): """ @@ -43,7 +46,7 @@ def matrix_expo(A, K): return matrix_mult(matrix_expo(A, K-1), A) B = matrix_expo(A, K//2) return matrix_mult(B, B) - + def matrix_mult(A, B): ZB = zip(*B) return [[sum(a*b for a, b in itertools.izip(row, col)) % M \ @@ -76,4 +79,3 @@ def numTilings(self, N): for i in xrange(3, N+1): dp[i%3] = (2*dp[(i-1)%3]%M + dp[(i-3)%3])%M return dp[N%3] - diff --git a/Python/dota2-senate.py b/Python/dota2-senate.py index bbed007e5..38d55d6bc 100644 --- a/Python/dota2-senate.py +++ b/Python/dota2-senate.py @@ -8,9 +8,9 @@ # The voting for this change is a round-based procedure. # In each round, each senator can exercise one of the two rights: # -# Ban one senator's right: +# Ban one senator's right: # A senator can make another senator lose all his rights in this and all the following rounds. -# Announce the victory: +# Announce the victory: # If this senator found the senators who still have rights to vote are all from the same party, # he can announce the victory and make the decision about the change in the game. # @@ -29,20 +29,23 @@ # Example 1: # Input: "RD" # Output: "Radiant" -# Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. -# And the second senator can't exercise any rights any more since his right has been banned. +# Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1. +# And the second senator can't exercise any rights any more since his right has been banned. # And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. # Example 2: # Input: "RDD" # Output: "Dire" -# Explanation: -# The first senator comes from Radiant and he can just ban the next senator's right in the round 1. -# And the second senator can't exercise any rights anymore since his right has been banned. -# And the third senator comes from Dire and he can ban the first senator's right in the round 1. +# Explanation: +# The first senator comes from Radiant and he can just ban the next senator's right in the round 1. +# And the second senator can't exercise any rights anymore since his right has been banned. +# And the third senator comes from Dire and he can ban the first senator's right in the round 1. # And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. # Note: # The length of the given string will in the range [1, 10,000]. +import collections + + class Solution(object): def predictPartyVictory(self, senate): """ diff --git a/Python/employee-free-time.py b/Python/employee-free-time.py index e2f0779a1..6fe120844 100644 --- a/Python/employee-free-time.py +++ b/Python/employee-free-time.py @@ -33,6 +33,9 @@ # self.start = s # self.end = e +import heapq + + class Solution(object): def employeeFreeTime(self, schedule): """ diff --git a/Python/employee-importance.py b/Python/employee-importance.py index 92bab697b..06cf9d5da 100644 --- a/Python/employee-importance.py +++ b/Python/employee-importance.py @@ -26,6 +26,9 @@ # One employee has at most one direct leader and may have several subordinates. # The maximum number of employees won't exceed 2000. +import collections + + """ # Employee info class Employee(object): diff --git a/Python/encode-and-decode-tinyurl.py b/Python/encode-and-decode-tinyurl.py index 5bfe41982..8217902e4 100644 --- a/Python/encode-and-decode-tinyurl.py +++ b/Python/encode-and-decode-tinyurl.py @@ -10,6 +10,8 @@ # You just need to ensure that a URL can be encoded to a tiny URL # and the tiny URL can be decoded to the original URL. +import random + class Codec: def __init__(self): @@ -20,7 +22,7 @@ def __init__(self): def encode(self, longUrl): """Encodes a URL to a shortened URL. - + :type longUrl: str :rtype: str """ @@ -29,7 +31,7 @@ def getRand(): for _ in xrange(self.__random_length): rand += self.__alphabet[random.randint(0, len(self.__alphabet)-1)] return "".join(rand) - + key = getRand() while key in self.__lookup: key = getRand() @@ -38,7 +40,7 @@ def getRand(): def decode(self, shortUrl): """Decodes a shortened URL to its original URL. - + :type shortUrl: str :rtype: str """ diff --git a/Python/equal-tree-partition.py b/Python/equal-tree-partition.py index 7f77d97a4..52476fa96 100644 --- a/Python/equal-tree-partition.py +++ b/Python/equal-tree-partition.py @@ -8,6 +8,9 @@ # self.left = None # self.right = None +import collections + + class Solution(object): def checkEqualTree(self, root): """ diff --git a/Python/erect-the-fence.py b/Python/erect-the-fence.py index c1ffe423d..47dde4d13 100644 --- a/Python/erect-the-fence.py +++ b/Python/erect-the-fence.py @@ -15,7 +15,7 @@ # Input: [[1,2],[2,2],[4,2]] # Output: [[1,2],[2,2],[4,2]] # -# Even you only have trees in a line, you need to use rope to enclose them. +# Even you only have trees in a line, you need to use rope to enclose them. # Note: # # All trees should be enclosed together. @@ -31,6 +31,9 @@ # self.x = a # self.y = b +import itertools + + # Monotone Chain Algorithm class Solution(object): def outerTrees(self, points): diff --git a/Python/evaluate-division.py b/Python/evaluate-division.py index bf1399601..0a46fadd4 100644 --- a/Python/evaluate-division.py +++ b/Python/evaluate-division.py @@ -8,21 +8,24 @@ # If the answer does not exist, return -1.0. # # Example: -# Given a / b = 2.0, b / c = 3.0. -# queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? . +# Given a / b = 2.0, b / c = 3.0. +# queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? . # return [6.0, 0.5, -1.0, 1.0, -1.0 ]. # # The input is: # vector> euqations, vector& values, vector> query . # # where equations.size() == values.size(),the values are positive. -# this represents the equations.return vector. . +# this represents the equations.return vector. . # The example above: equations = [ ["a", "b"], ["b", "c"] ]. # values = [2.0, 3.0]. queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. # # The input is always valid. You may assume that # evaluating the queries will result in no division by zero and there is no contradiction. +import collections + + class Solution(object): def calcEquation(self, equations, values, query): """ diff --git a/Python/falling-squares.py b/Python/falling-squares.py index 13bb1c82b..d834723fd 100644 --- a/Python/falling-squares.py +++ b/Python/falling-squares.py @@ -3,7 +3,7 @@ # On an infinite number line (x-axis), we drop given squares in the order they are given. # -# The i-th square dropped (positions[i] = (left, side_length)) is a square +# The i-th square dropped (positions[i] = (left, side_length)) is a square # with the left-most point being positions[i][0] and sidelength positions[i][1]. # # The square is dropped with the bottom edge parallel to the number line, @@ -22,14 +22,14 @@ # Output: [2, 5, 5] # Explanation: # -# After the first drop of +# After the first drop of # positions[0] = [1, 2]: # _aa # _aa # ------- # The maximum height of any square is 2. # -# After the second drop of +# After the second drop of # positions[1] = [2, 3]: # __aaa # __aaa @@ -37,11 +37,11 @@ # _aa__ # _aa__ # -------------- -# The maximum height of any square is 5. +# The maximum height of any square is 5. # The larger square stays on top of the smaller square despite where its center # of gravity is, because squares are infinitely sticky on their bottom edge. # -# After the third drop of +# After the third drop of # positions[1] = [6, 1]: # __aaa # __aaa @@ -51,7 +51,7 @@ # -------------- # The maximum height of any square is still 5. # -# Thus, we return an answer of +# Thus, we return an answer of # [2, 5, 5] # . # @@ -65,6 +65,9 @@ # 1 <= positions[0] <= 10^8. # 1 <= positions[1] <= 10^6. +import bisect + + class SegmentTree(object): def __init__(self, N, update_fn, query_fn): self.N = N @@ -187,7 +190,7 @@ def update(heights, left, right, B, blocks, blocks_read, h): heights = [0] * W blocks = [0] * (B+2) blocks_read = [0] * (B+2) - + max_height = 0 result = [] for left, size in positions: diff --git a/Python/find-anagram-mappings.py b/Python/find-anagram-mappings.py index c113d42a0..69a2bf25d 100644 --- a/Python/find-anagram-mappings.py +++ b/Python/find-anagram-mappings.py @@ -22,6 +22,9 @@ # - A, B have equal lengths in range [1, 100]. # - A[i], B[i] are integers in range [0, 10^5]. +import collections + + class Solution(object): def anagramMappings(self, A, B): """ diff --git a/Python/find-duplicate-file-in-system.py b/Python/find-duplicate-file-in-system.py index 34e36011e..d0b2fb0dd 100644 --- a/Python/find-duplicate-file-in-system.py +++ b/Python/find-duplicate-file-in-system.py @@ -12,12 +12,12 @@ # # "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)" # -# It means there are n files (f1.txt, f2.txt ... fn.txt +# It means there are n files (f1.txt, f2.txt ... fn.txt # with content f1_content, f2_content ... fn_content, respectively) in # directory root/d1/d2/.../dm. Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory. # -# The output is a list of group of duplicate file paths. For each group, -# it contains all the file paths of the files that have the same content. +# The output is a list of group of duplicate file paths. For each group, +# it contains all the file paths of the files that have the same content. # A file path is a string that has the following format: # # "directory_path/file_name.txt" @@ -25,7 +25,7 @@ # Example 1: # Input: # ["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"] -# Output: +# Output: # [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] # Note: # No order is required for the final output. @@ -45,6 +45,9 @@ # What is the most time-consuming part and memory consuming part of it? How to optimize? # 5. How to make sure the duplicated files you find are not false positive? +import collections + + class Solution(object): def findDuplicate(self, paths): """ diff --git a/Python/find-duplicate-subtrees.py b/Python/find-duplicate-subtrees.py index 2ec2552c2..8c75ca059 100644 --- a/Python/find-duplicate-subtrees.py +++ b/Python/find-duplicate-subtrees.py @@ -6,7 +6,7 @@ # # Two trees are duplicate if they have the same structure with same node values. # -# Example 1: +# Example 1: # 1 # / \ # 2 3 @@ -29,6 +29,9 @@ # self.left = None # self.right = None +import collections + + class Solution(object): def findDuplicateSubtrees(self, root): """ @@ -68,7 +71,7 @@ def postOrderTraversal(node, lookup, result): result.append(node) lookup[s] += 1 return s - + lookup = collections.defaultdict(int) result = [] postOrderTraversal(root, lookup, result) diff --git a/Python/find-eventual-safe-states.py b/Python/find-eventual-safe-states.py index 3edc7cb32..48455c8a4 100644 --- a/Python/find-eventual-safe-states.py +++ b/Python/find-eventual-safe-states.py @@ -23,6 +23,9 @@ # - The number of edges in the graph will not exceed 32000. # - Each graph[i] will be a sorted list of different integers, chosen within the range [0, graph.length - 1]. +import collections + + class Solution(object): def eventualSafeNodes(self, graph): """ @@ -30,7 +33,7 @@ def eventualSafeNodes(self, graph): :rtype: List[int] """ WHITE, GRAY, BLACK = 0, 1, 2 - + def dfs(graph, node, lookup): if lookup[node] != WHITE: return lookup[node] == BLACK diff --git a/Python/find-k-closest-elements.py b/Python/find-k-closest-elements.py index d983de952..232df2879 100644 --- a/Python/find-k-closest-elements.py +++ b/Python/find-k-closest-elements.py @@ -16,6 +16,9 @@ # Length of the given array is positive and will not exceed 10^4 # Absolute value of elements in the array and x will not exceed 10^4 +import bisect + + class Solution(object): def findClosestElements(self, arr, k, x): """ diff --git a/Python/find-right-interval.py b/Python/find-right-interval.py index 8c1a9a9a2..4e00fb8d0 100644 --- a/Python/find-right-interval.py +++ b/Python/find-right-interval.py @@ -41,6 +41,9 @@ # self.start = s # self.end = e +import bisect + + class Solution(object): def findRightInterval(self, intervals): """ diff --git a/Python/find-smallest-letter-greater-than-target.py b/Python/find-smallest-letter-greater-than-target.py index 0f8fc0c37..2e20c9ad1 100644 --- a/Python/find-smallest-letter-greater-than-target.py +++ b/Python/find-smallest-letter-greater-than-target.py @@ -41,6 +41,9 @@ # - letters consists of lowercase letters, and contains at least 2 unique letters. # - target is a lowercase letter. +import bisect + + class Solution(object): def nextGreatestLetter(self, letters, target): """ diff --git a/Python/flip-game-ii.py b/Python/flip-game-ii.py index 79cc4b979..4135d1b7e 100644 --- a/Python/flip-game-ii.py +++ b/Python/flip-game-ii.py @@ -1,6 +1,10 @@ # Time: O(n + c^2) # Space: O(c) +import itertools +import re + + # 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): diff --git a/Python/fraction-addition-and-subtraction.py b/Python/fraction-addition-and-subtraction.py index cd51acb8e..f2ac5ecb0 100644 --- a/Python/fraction-addition-and-subtraction.py +++ b/Python/fraction-addition-and-subtraction.py @@ -30,6 +30,9 @@ # The number of given fractions will be in the range [1,10]. # The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int. +import re + + class Solution(object): def fractionAddition(self, expression): """ diff --git a/Python/freedom-trail.py b/Python/freedom-trail.py index 227b48c74..c7d1a9bb2 100644 --- a/Python/freedom-trail.py +++ b/Python/freedom-trail.py @@ -12,7 +12,7 @@ # Initially, the first character of the ring is aligned at 12:00 direction. # You need to spell all the characters in the string key one by one # by rotating the ring clockwise or anticlockwise to make each character of -# the string key aligned at 12:00 direction and then by pressing the center button. +# the string key aligned at 12:00 direction and then by pressing the center button. # At the stage of rotating the ring to spell the key character key[i]: # You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. # The final purpose of the rotation is to align one of the string ring's @@ -26,7 +26,7 @@ # Input: ring = "godding", key = "gd" # Output: 4 # Explanation: -# For the first key character 'g', since it is already in place, we just need 1 step to spell this character. +# For the first key character 'g', since it is already in place, we just need 1 step to spell this character. # For the second key character 'd', # we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo". # Also, we need 1 more step for spelling. @@ -36,6 +36,9 @@ # There are only lowercase letters in both strings and might be some duplcate characters in both strings. # It's guaranteed that string key could always be spelled by rotating the string ring. +import collections + + class Solution(object): def findRotateSteps(self, ring, key): """ @@ -46,7 +49,7 @@ def findRotateSteps(self, ring, key): lookup = collections.defaultdict(list) for i in xrange(len(ring)): lookup[ring[i]].append(i) - + dp = [[0] * len(ring) for _ in xrange(2)] prev = [0] for i in xrange(1, len(key)+1): diff --git a/Python/graph-valid-tree.py b/Python/graph-valid-tree.py index 50c5ababc..7e0be8344 100644 --- a/Python/graph-valid-tree.py +++ b/Python/graph-valid-tree.py @@ -1,6 +1,9 @@ # Time: O(|V| + |E|) # Space: O(|V| + |E|) +import collections + + # BFS solution. Same complexity but faster version. class Solution(object): # @param {integer} n diff --git a/Python/group-anagrams.py b/Python/group-anagrams.py index 7b4ff9628..f1a51e789 100644 --- a/Python/group-anagrams.py +++ b/Python/group-anagrams.py @@ -6,6 +6,9 @@ # Note: All inputs will be in lower-case. # +import collections + + class Solution(object): def groupAnagrams(self, strs): """ diff --git a/Python/group-shifted-strings.py b/Python/group-shifted-strings.py index 53259c496..9f58ee361 100644 --- a/Python/group-shifted-strings.py +++ b/Python/group-shifted-strings.py @@ -1,6 +1,9 @@ # Time: O(nlogn) # Space: O(n) +import collections + + class Solution: # @param {string[]} strings # @return {string[][]} @@ -12,7 +15,7 @@ def groupStrings(self, strings): result = [] for key, val in groups.iteritems(): result.append(sorted(val)) - + return result def hashStr(self, s): diff --git a/Python/heaters.py b/Python/heaters.py index 65de830f7..c2f8cdecd 100644 --- a/Python/heaters.py +++ b/Python/heaters.py @@ -26,6 +26,9 @@ # Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, # then all the houses can be warmed. +import bisect + + class Solution(object): def findRadius(self, houses, heaters): """ @@ -45,4 +48,3 @@ def findRadius(self, houses, heaters): curr_radius = min(curr_radius, house - heaters[smaller]) min_radius = max(min_radius, curr_radius) return min_radius - diff --git a/Python/implement-magic-dictionary.py b/Python/implement-magic-dictionary.py index d7785e595..7dd43640c 100644 --- a/Python/implement-magic-dictionary.py +++ b/Python/implement-magic-dictionary.py @@ -22,6 +22,9 @@ # Please remember to RESET your class variables declared in class MagicDictionary, # as static/class variables are persisted across multiple test cases. Please see here for more details. +import collections + + class MagicDictionary(object): def __init__(self): @@ -48,22 +51,22 @@ def search(self, word): :type word: str :rtype: bool """ - def find(word, curr, i, mistakeAllowed): + def find(word, curr, i, mistakeAllowed): if i == len(word): return "_end" in curr and not mistakeAllowed - if word[i] not in curr: + if word[i] not in curr: return any(find(word, curr[c], i+1, False) for c in curr if c != "_end") \ - if mistakeAllowed else False - - if mistakeAllowed: + if mistakeAllowed else False + + if mistakeAllowed: return find(word, curr[word[i]], i+1, True) or \ any(find(word, curr[c], i+1, False) \ for c in curr if c not in ("_end", word[i])) return find(word, curr[word[i]], i+1, False) - return find(word, self.trie, 0, True) - + return find(word, self.trie, 0, True) + # Your MagicDictionary object will be instantiated and called as such: diff --git a/Python/implement-stack-using-queues.py b/Python/implement-stack-using-queues.py index 05ec228d6..8713e606f 100644 --- a/Python/implement-stack-using-queues.py +++ b/Python/implement-stack-using-queues.py @@ -16,24 +16,26 @@ # 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). -# + +import collections + 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 diff --git a/Python/increasing-triplet-subsequence.py b/Python/increasing-triplet-subsequence.py index da1e27ccb..e5a940433 100644 --- a/Python/increasing-triplet-subsequence.py +++ b/Python/increasing-triplet-subsequence.py @@ -1,12 +1,12 @@ # Time: O(n) # Space: O(1) -# Given an unsorted array return whether an increasing +# 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] +# 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. @@ -17,6 +17,8 @@ # Given [5, 4, 3, 2, 1], # return false. +import bisect + class Solution(object): def increasingTriplet(self, nums): diff --git a/Python/invert-binary-tree.py b/Python/invert-binary-tree.py index 5c62fd73f..18b38c497 100644 --- a/Python/invert-binary-tree.py +++ b/Python/invert-binary-tree.py @@ -18,26 +18,30 @@ # Time: O(n) # Space: O(w), w is the max number of the nodes of the levels. + +import collections + + # 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): @@ -59,9 +63,9 @@ def invertTree(self, root): nodes.push(node.left) if node.right is not None: nodes.push(node.right) - + return root - + # Time: O(n) # Space: O(h) # Stack solution. @@ -79,9 +83,9 @@ def invertTree(self, root): 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. @@ -92,5 +96,5 @@ def invertTree(self, root): if root is not None: root.left, root.right = self.invertTree(root.right), \ self.invertTree(root.left) - + return root diff --git a/Python/ipo.py b/Python/ipo.py index ef1b99102..dffd3caf4 100644 --- a/Python/ipo.py +++ b/Python/ipo.py @@ -28,6 +28,9 @@ # The length of Profits array and Capital array will not exceed 50,000. # The answer is guaranteed to fit in a 32-bit signed integer. +import heapq + + class Solution(object): def findMaximizedCapital(self, k, W, Profits, Capital): """ diff --git a/Python/kill-process.py b/Python/kill-process.py index 88b0e0867..4eb4695ce 100644 --- a/Python/kill-process.py +++ b/Python/kill-process.py @@ -1,6 +1,9 @@ # Time: O(n) # Space: O(n) +import collections + + # DFS solution. class Solution(object): def killProcess(self, pid, ppid, kill): diff --git a/Python/lfu-cache.py b/Python/lfu-cache.py index 97a153540..8812da57b 100644 --- a/Python/lfu-cache.py +++ b/Python/lfu-cache.py @@ -4,7 +4,7 @@ # Design and implement a data structure for Least Frequently Used (LFU) cache. # It should support the following operations: get and put. # -# get(key) - Get the value (will always be positive) of the key +# get(key) - Get the value (will always be positive) of the key # if the key exists in the cache, otherwise return -1. # put(key, value) - Set or insert the value if the key is not already present. # When the cache reaches its capacity, @@ -31,6 +31,9 @@ # cache.get(3); // returns 3 # cache.get(4); // returns 4 +import collections + + class ListNode(object): def __init__(self, key, value, freq): self.key = key @@ -44,7 +47,7 @@ class LinkedList(object): def __init__(self): self.head = None self.tail = None - + def append(self, node): node.next, node.prev = None, None # avoid dirty node if self.head is None: @@ -53,7 +56,7 @@ def append(self, node): self.tail.next = node node.prev = self.tail self.tail = node - + def delete(self, node): if node.prev: node.prev.next = node.next @@ -99,7 +102,7 @@ def get(self, key): self.__freq_to_nodes[self.__key_to_node[key].freq].append(self.__key_to_node[key]) return self.__key_to_node[key].val - + def put(self, key, value): """ @@ -113,14 +116,14 @@ def put(self, key, value): if self.get(key) != -1: self.__key_to_node[key].val = value return - + if self.__size == self.__capa: del self.__key_to_node[self.__freq_to_nodes[self.__min_freq].head.key] self.__freq_to_nodes[self.__min_freq].delete(self.__freq_to_nodes[self.__min_freq].head) if not self.__freq_to_nodes[self.__min_freq].head: del self.__freq_to_nodes[self.__min_freq] self.__size -= 1 - + self.__min_freq = 1 self.__key_to_node[key] = ListNode(key, value, self.__min_freq) self.__freq_to_nodes[self.__key_to_node[key].freq].append(self.__key_to_node[key]) diff --git a/Python/line-reflection.py b/Python/line-reflection.py index 2d508e2e4..9929b8371 100644 --- a/Python/line-reflection.py +++ b/Python/line-reflection.py @@ -1,6 +1,9 @@ # Time: O(n) # Space: O(n) +import collections + + # Hash solution. class Solution(object): def isReflected(self, points): diff --git a/Python/logger-rate-limiter.py b/Python/logger-rate-limiter.py index 0e4006813..7fe8abc07 100644 --- a/Python/logger-rate-limiter.py +++ b/Python/logger-rate-limiter.py @@ -1,6 +1,9 @@ # Time: O(1), amortized # Space: O(k), k is the max number of printed messages in last 10 seconds +import collections + + class Logger(object): def __init__(self): diff --git a/Python/lonely-pixel-ii.py b/Python/lonely-pixel-ii.py index 25bb4c408..e4046be81 100644 --- a/Python/lonely-pixel-ii.py +++ b/Python/lonely-pixel-ii.py @@ -1,6 +1,9 @@ # Time: O(m * n) # Space: O(m * n) +import collections + + class Solution(object): def findBlackPixel(self, picture, N): """ diff --git a/Python/longest-harmonious-subsequence.py b/Python/longest-harmonious-subsequence.py index 585179747..7f394cf97 100644 --- a/Python/longest-harmonious-subsequence.py +++ b/Python/longest-harmonious-subsequence.py @@ -1,10 +1,10 @@ # Time: O(n) # Space: O(n) -# We define a harmonious array is an array where the difference +# We define a harmonious array is an array where the difference # between its maximum value and its minimum value is exactly 1. # -# Now, given an integer array, you need to find the length of its +# Now, given an integer array, you need to find the length of its # longest harmonious subsequence among all its possible subsequences. # # Example 1: @@ -13,6 +13,9 @@ # Explanation: The longest harmonious subsequence is [3,2,2,2,3]. # Note: The length of the input array will not exceed 20,000. +import collections + + class Solution(object): def findLHS(self, nums): """ diff --git a/Python/longest-word-in-dictionary.py b/Python/longest-word-in-dictionary.py index b6f900c14..c437f244a 100644 --- a/Python/longest-word-in-dictionary.py +++ b/Python/longest-word-in-dictionary.py @@ -7,17 +7,17 @@ # # If there is no answer, return the empty string. # Example 1: -# Input: +# Input: # words = ["w","wo","wor","worl", "world"] # Output: "world" -# Explanation: +# Explanation: # The word "world" can be built one character at a time by "w", "wo", "wor", and "worl". # # Example 2: -# Input: +# Input: # words = ["a", "banana", "app", "appl", "ap", "apply", "apple"] # Output: "apple" -# Explanation: +# Explanation: # Both "apply" and "apple" can be built from other words in the dictionary. # However, "apple" is lexicographically smaller than "apply". # @@ -26,6 +26,9 @@ # - The length of words will be in the range [1, 1000]. # - The length of words[i] will be in the range [1, 30]. +import collections + + class Solution(object): def longestWord(self, words): """ diff --git a/Python/magical-string.py b/Python/magical-string.py index 299d6b842..4954f9c1d 100644 --- a/Python/magical-string.py +++ b/Python/magical-string.py @@ -28,6 +28,10 @@ # Explanation: The first 6 elements of magical string S is "12211" and it contains three 1's, so return 3. # the solution comes from https://discuss.leetcode.com/topic/75242/o-log-n-space-using-recursive-generators + +import itertools + + class Solution(object): def magicalString(self, n): """ diff --git a/Python/map-sum-pairs.py b/Python/map-sum-pairs.py index 391bff1c1..1bc72f6cc 100644 --- a/Python/map-sum-pairs.py +++ b/Python/map-sum-pairs.py @@ -16,6 +16,9 @@ # Input: insert("app", 2), Output: Null # Input: sum("ap"), Output: 5 +import collections + + class MapSum(object): def __init__(self): @@ -25,7 +28,7 @@ def __init__(self): _trie = lambda: collections.defaultdict(_trie) self.__root = _trie() - + def insert(self, key, val): """ :type key: str @@ -39,7 +42,7 @@ def insert(self, key, val): delta = val if "_end" in curr: delta -= curr["_end"] - + curr = self.__root for c in key: curr = curr[c] diff --git a/Python/max-increase-to-keep-city-skyline.py b/Python/max-increase-to-keep-city-skyline.py index ce46816ad..902b54825 100644 --- a/Python/max-increase-to-keep-city-skyline.py +++ b/Python/max-increase-to-keep-city-skyline.py @@ -4,7 +4,7 @@ # In a 2 dimensional array grid, each value grid[i][j] represents the height of # a building located there. We are allowed to increase the height of any number of buildings, # by any amount (the amounts can be different for different buildings). -# Height 0 is considered to be a building as well. +# Height 0 is considered to be a building as well. # # At the end, the "skyline" when viewed from all four directions of the grid, # i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. @@ -16,9 +16,9 @@ # Example: # Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]] # Output: 35 -# Explanation: +# Explanation: # The grid is: -# [ [3, 0, 8, 4], +# [ [3, 0, 8, 4], # [2, 4, 5, 7], # [9, 2, 6, 3], # [0, 3, 1, 0] ] @@ -38,7 +38,10 @@ # - All heights grid[i][j] are in the range [0, 100]. # - All buildings in grid[i][j] occupy the entire grid cell: # that is, they are a 1 x 1 x grid[i][j] rectangular prism. - + +import itertools + + class Solution(object): def maxIncreaseKeepingSkyline(self, grid): """ diff --git a/Python/max-points-on-a-line.py b/Python/max-points-on-a-line.py index 67b31f245..79467c9a3 100644 --- a/Python/max-points-on-a-line.py +++ b/Python/max-points-on-a-line.py @@ -4,6 +4,9 @@ # Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. # +import collections + + # Definition for a point class Point: def __init__(self, a=0, b=0): @@ -28,13 +31,13 @@ def maxPoints(self, points): if start.x - end.x != 0: slope = (start.y - end.y) * 1.0 / (start.x - end.x) slope_count[slope] += 1 - - current_max = same + + current_max = same for slope in slope_count: current_max = max(current_max, slope_count[slope] + same) - + max_points = max(max_points, current_max) - + return max_points if __name__ == "__main__": diff --git a/Python/max-stack.py b/Python/max-stack.py index ee10bd1d8..7bf4ec185 100644 --- a/Python/max-stack.py +++ b/Python/max-stack.py @@ -4,7 +4,10 @@ # top: O(1) # peekMax: O(1) # Space: O(n), n is the number of values in the current stack - + +import collections + + class MaxStack(object): def __init__(self): @@ -15,7 +18,7 @@ def __init__(self): self.__val_to_idxs = collections.defaultdict(list) self.__top = None self.__max = None - + def push(self, x): """ @@ -36,7 +39,7 @@ def pop(self): val = self.__top self.__remove(val) return val - + def top(self): """ @@ -44,14 +47,14 @@ def top(self): """ return self.__top - + def peekMax(self): """ :rtype: int """ return self.__max - + def popMax(self): """ :rtype: int @@ -59,8 +62,8 @@ def popMax(self): val = self.__max self.__remove(val) return val - - + + def __remove(self, val): idx = self.__val_to_idxs[val][-1] self.__val_to_idxs[val].pop(); @@ -71,7 +74,7 @@ def __remove(self, val): self.__top = self.__idx_to_val[max(self.__idx_to_val.keys())] if self.__idx_to_val else None if val == self.__max: self.__max = max(self.__val_to_idxs.keys()) if self.__val_to_idxs else None - + # Your MaxStack object will be instantiated and called as such: # obj = MaxStack() diff --git a/Python/maximum-length-of-repeated-subarray.py b/Python/maximum-length-of-repeated-subarray.py index be588aa9c..e633ed608 100644 --- a/Python/maximum-length-of-repeated-subarray.py +++ b/Python/maximum-length-of-repeated-subarray.py @@ -9,13 +9,17 @@ # A: [1,2,3,2,1] # B: [3,2,1,4,7] # Output: 3 -# Explanation: +# Explanation: # The repeated subarray with maximum length is [3, 2, 1]. # Note: # 1 <= len(A), len(B) <= 1000 # 0 <= A[i], B[i] < 100 # dp solution (3752 ms) + +import collections + + class Solution(object): def findLength(self, A, B): """ @@ -35,9 +39,9 @@ def findLength(self, A, B): result = max(result, max(dp[(i+1)%2])) return result - + # Time: O(m * n * log(min(m, n))) -# Space: O(min(m, n)) +# Space: O(min(m, n)) # Binary search + rolling hash solution (226 ms) class Solution2(object): def findLength(self, A, B): @@ -93,7 +97,7 @@ def findLength(self, A, B): :rtype: int """ if len(A) > len(B): return findLength(B, A) - + def check(length): lookup = set(A[i:i+length] \ for i in xrange(len(A)-length+1)) diff --git a/Python/minesweeper.py b/Python/minesweeper.py index a3a9fe712..e5ee0b93d 100644 --- a/Python/minesweeper.py +++ b/Python/minesweeper.py @@ -14,32 +14,32 @@ # If a mine ('M') is revealed, then the game is over - change it to 'X'. # If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') # and all of its adjacent unrevealed squares should be revealed recursively. -# If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') +# If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') # representing the number of adjacent mines. # Return the board when no more squares will be revealed. # # Example 1: -# Input: +# Input: # [['E', 'E', 'E', 'E', 'E'], # ['E', 'E', 'M', 'E', 'E'], # ['E', 'E', 'E', 'E', 'E'], # ['E', 'E', 'E', 'E', 'E']] # Click : [3,0] -# Output: +# Output: # [['B', '1', 'E', '1', 'B'], # ['B', '1', 'M', '1', 'B'], # ['B', '1', '1', '1', 'B'], # ['B', 'B', 'B', 'B', 'B']] # # Example 2: -# Input: +# Input: # [['B', '1', 'E', '1', 'B'], # ['B', '1', 'M', '1', 'B'], # ['B', '1', '1', '1', 'B'], # ['B', 'B', 'B', 'B', 'B']] # # Click : [1,2] -# Output: +# Output: # [['B', '1', 'E', '1', 'B'], # ['B', '1', 'X', '1', 'B'], # ['B', '1', '1', '1', 'B'], @@ -50,10 +50,13 @@ # The click position will only be an unrevealed square ('M' or 'E'), # which also means the input board contains at least one clickable square. # The input board won't be a stage when game is over (some mines have been revealed). -# For simplicity, not mentioned rules should be ignored in this problem. +# For simplicity, not mentioned rules should be ignored in this problem. # For example, you don't need to reveal all the unrevealed mines when the game is over, # consider any cases that you will win the game or flag any squares. +import collections + + class Solution(object): def updateBoard(self, board, click): """ @@ -77,7 +80,7 @@ def updateBoard(self, board, click): continue if board[r][c] == 'M' or board[r][c] == 'X': count += 1 - + if count: board[row][col] = chr(count + ord('0')) else: @@ -119,7 +122,7 @@ def updateBoard(self, board, click): continue if board[r][c] == 'M' or board[r][c] == 'X': count += 1 - + if count: board[row][col] = chr(count + ord('0')) else: @@ -135,4 +138,3 @@ def updateBoard(self, board, click): self.updateBoard(board, (r, c)) return board - diff --git a/Python/minimum-height-trees.py b/Python/minimum-height-trees.py index dbd7df905..41ba4bc8c 100644 --- a/Python/minimum-height-trees.py +++ b/Python/minimum-height-trees.py @@ -5,7 +5,7 @@ # 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 +# Given such a graph, write a function to find all the # MHTs and return a list of their root labels. # # Format @@ -46,14 +46,17 @@ # 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, +# (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 +# (2) The height of a rooted tree is the number of edges on the # longest downward path between the root and a leaf. +import collections + + class Solution(object): def findMinHeightTrees(self, n, edges): """ @@ -76,17 +79,17 @@ def findMinHeightTrees(self, n, edges): unvisited.add(i) # A graph can have 2 MHTs at most. - # BFS from the leaves until the number + # BFS from the leaves until the number # of the unvisited nodes is less than 3. while len(unvisited) > 2: cur_level = [] for u in pre_level: unvisited.remove(u) for v in neighbors[u]: - if v in unvisited: + if v in unvisited: neighbors[v].remove(u) if len(neighbors[v]) == 1: cur_level.append(v) pre_level = cur_level - + return list(unvisited) diff --git a/Python/missing-number.py b/Python/missing-number.py index 39aae053a..b2b3426f0 100644 --- a/Python/missing-number.py +++ b/Python/missing-number.py @@ -8,10 +8,13 @@ # Given nums = [0, 1, 3] return 2. # # Note: -# Your algorithm should run in linear runtime complexity. +# Your algorithm should run in linear runtime complexity. # Could you implement it using only constant extra space complexity? # +import operator + + class Solution(object): def missingNumber(self, nums): """ diff --git a/Python/most-frequent-subtree-sum.py b/Python/most-frequent-subtree-sum.py index ca261a1b5..202eb6baa 100644 --- a/Python/most-frequent-subtree-sum.py +++ b/Python/most-frequent-subtree-sum.py @@ -30,6 +30,9 @@ # self.left = None # self.right = None +import collections + + class Solution(object): def findFrequentTreeSum(self, root): """ diff --git a/Python/my-calendar-iii.py b/Python/my-calendar-iii.py index 985a001a6..eacc90de9 100644 --- a/Python/my-calendar-iii.py +++ b/Python/my-calendar-iii.py @@ -23,7 +23,7 @@ # MyCalendarThree.book(5, 15); // returns 3 # MyCalendarThree.book(5, 10); // returns 3 # MyCalendarThree.book(25, 55); // returns 3 -# Explanation: +# Explanation: # The first two events can be booked and are disjoint, so the maximum K-booking is a 1-booking. # The third event [10, 40) intersects the first event, and the maximum K-booking is a 2-booking. # The remaining events cause the maximum K-booking to be only a 3-booking. @@ -32,12 +32,15 @@ # Note: # - The number of calls to MyCalendarThree.book per test case will be at most 400. # - In calls to MyCalendarThree.book(start, end), start and end are integers in the range [0, 10^9]. - + +import bisect + + class MyCalendarThree(object): def __init__(self): self.__books = [] - + def book(self, start, end): """ @@ -50,19 +53,19 @@ def book(self, start, end): self.__books[i] = (self.__books[i][0], self.__books[i][1]+1) else: self.__books.insert(i, (start, 1)) - + j = bisect.bisect_left(self.__books, (end, 1)) if j < len(self.__books) and self.__books[j][0] == end: self.__books[j] = (self.__books[j][0], self.__books[j][1]-1) else: self.__books.insert(j, (end, -1)) - + result, cnt = 0, 0 for book in self.__books: cnt += book[1] - result = max(result, cnt) + result = max(result, cnt) return result - + # Your MyCalendarThree object will be instantiated and called as such: # obj = MyCalendarThree() diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index b8f2a237f..f4251b59a 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -16,6 +16,9 @@ # - The length of times will be in the range [1, 6000]. # - All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100. +import heapq + + # Dijkstra's algorithm class Solution(object): def networkDelayTime(self, times, N, K): @@ -28,7 +31,7 @@ def networkDelayTime(self, times, N, K): adj = [[] for _ in xrange(N)] for u, v, w in times: adj[u-1].append((v-1, w)) - + result = 0 lookup = set() min_heap = [(0, K-1)] @@ -39,4 +42,3 @@ def networkDelayTime(self, times, N, K): if v in lookup: continue heapq.heappush(min_heap, (result+w, v)) return result if len(lookup) == N else -1 - diff --git a/Python/next-greater-element-iii.py b/Python/next-greater-element-iii.py index 9a4f344ea..2f0752522 100644 --- a/Python/next-greater-element-iii.py +++ b/Python/next-greater-element-iii.py @@ -4,7 +4,7 @@ # Given a positive 32-bit integer n, you need to find the smallest 32-bit integer # which has exactly the same digits existing in the integer n and is greater in value than n. # If no such positive 32-bit integer exists, you need to return -1. -@ +# # Example 1: # Input: 12 # Output: 21 @@ -12,6 +12,12 @@ # Input: 21 # Output: -1 +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def nextGreaterElement(self, n): """ @@ -23,15 +29,15 @@ def nextGreaterElement(self, n): for i in xrange(len(digits) - 1): if digits[i] < digits[i + 1]: k = i - + if k == -1: digits.reverse() return -1 - + for i in xrange(k + 1, len(digits)): if digits[i] > digits[k]: l = i - + digits[k], digits[l] = digits[l], digits[k] digits[k + 1:] = digits[:k:-1] result = int("".join(map(str, digits))) diff --git a/Python/number-of-atoms.py b/Python/number-of-atoms.py index ca0bb7fab..ac37e2251 100644 --- a/Python/number-of-atoms.py +++ b/Python/number-of-atoms.py @@ -20,24 +20,24 @@ # followed by its count (if that count is more than 1), and so on. # # Example 1: -# Input: +# Input: # formula = "H2O" # Output: "H2O" -# Explanation: +# Explanation: # The count of elements are {'H': 2, 'O': 1}. # # Example 2: -# Input: +# Input: # formula = "Mg(OH)2" # Output: "H2MgO2" -# Explanation: +# Explanation: # The count of elements are {'H': 2, 'Mg': 1, 'O': 2}. # # Example 3: -# Input: +# Input: # formula = "K4(ON(SO3)2)2" # Output: "K4N2O14S4" -# Explanation: +# Explanation: # The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}. # Note: # @@ -46,6 +46,10 @@ # formula will only consist of letters, digits, and round parentheses, # and is a valid formula as defined in the problem. +import collections +import re + + class Solution(object): def countOfAtoms(self, formula): """ diff --git a/Python/number-of-matching-subsequences.py b/Python/number-of-matching-subsequences.py index 86b8af903..f6d3602a2 100644 --- a/Python/number-of-matching-subsequences.py +++ b/Python/number-of-matching-subsequences.py @@ -4,7 +4,7 @@ # Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. # # Example : -# Input: +# Input: # S = "abcde" # words = ["a", "bb", "acd", "ace"] # Output: 3 @@ -16,6 +16,9 @@ # - The length of words will be in the range of [1, 5000]. # - The length of words[i] will be in the range of [1, 50]. +import collections + + class Solution(object): def numMatchingSubseq(self, S, words): """ diff --git a/Python/optimal-account-balancing.py b/Python/optimal-account-balancing.py index 4d409c853..32ffe34e4 100644 --- a/Python/optimal-account-balancing.py +++ b/Python/optimal-account-balancing.py @@ -1,6 +1,9 @@ # Time: O(n * 2^n), n is the size of the debt. # Space: O(n * 2^n) +import collections + + class Solution(object): def minTransfers(self, transactions): """ @@ -16,7 +19,7 @@ def minTransfers(self, transactions): for v in account.values(): if v: debt.append(v) - + if not debt: return 0 diff --git a/Python/palindrome-pairs.py b/Python/palindrome-pairs.py index bf823ce55..eb9283bae 100644 --- a/Python/palindrome-pairs.py +++ b/Python/palindrome-pairs.py @@ -2,7 +2,7 @@ # 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, +# in the given list, so that the concatenation of the two words, # i.e. words[i] + words[j] is a palindrome. # # Example 1: @@ -14,13 +14,16 @@ # Return [[0, 1], [1, 0], [3, 2], [2, 4]] # The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"] +import collections + + class Solution(object): def palindromePairs(self, words): """ :type words: List[str] :rtype: List[List[int]] """ - res = [] + res = [] lookup = {} for i, word in enumerate(words): lookup[word] = i @@ -55,7 +58,7 @@ def preProcess(s): T += ["#", c] T += ['#', '$'] return T - + T = preProcess(s) center, right = 0, 0 for i in xrange(1, len(T) - 1): diff --git a/Python/palindrome-permutation-ii.py b/Python/palindrome-permutation-ii.py index 097f0956a..c74444ba0 100644 --- a/Python/palindrome-permutation-ii.py +++ b/Python/palindrome-permutation-ii.py @@ -1,6 +1,10 @@ # Time: O(n * n!) # Space: O(n) +import collections +import itertools + + class Solution(object): def generatePalindromes(self, s): """ @@ -11,13 +15,13 @@ def generatePalindromes(self, 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 self.permuteUnique(mid, chars) if len(mid) < 2 else [] - + def permuteUnique(self, mid, nums): result = [] used = [False] * len(nums) self.permuteUniqueRecu(mid, result, used, [], nums) return result - + def permuteUniqueRecu(self, mid, result, used, cur, nums): if len(cur) == len(nums): half_palindrome = ''.join(cur) diff --git a/Python/palindrome-permutation.py b/Python/palindrome-permutation.py index 21df60552..1932a00ee 100644 --- a/Python/palindrome-permutation.py +++ b/Python/palindrome-permutation.py @@ -1,10 +1,13 @@ # Time: O(n) # Space: O(1) +import collections + + class Solution(object): def canPermutePalindrome(self, s): """ :type s: str :rtype: bool """ - return sum(v % 2 for v in collections.Counter(s).values()) < 2 + return sum(v % 2 for v in collections.Counter(s).values()) < 2 diff --git a/Python/path-sum-iii.py b/Python/path-sum-iii.py index ed24dde54..a3b8f6cc2 100644 --- a/Python/path-sum-iii.py +++ b/Python/path-sum-iii.py @@ -5,7 +5,7 @@ # # Find the number of paths that sum to a given value. # -# The path does not need to start or end at the root or a leaf, +# The path does not need to start or end at the root or a leaf, # but it must go downwards (traveling only from parent nodes to child nodes). # # The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. @@ -35,6 +35,9 @@ # self.left = None # self.right = None +import collections + + class Solution(object): def pathSum(self, root, sum): """ @@ -54,7 +57,7 @@ def pathSumHelper(root, curr, sum, lookup): if lookup[curr] == 0: del lookup[curr] return result - + lookup = collections.defaultdict(int) lookup[0] = 1 return pathSumHelper(root, 0, sum, lookup) diff --git a/Python/path-sum-iv.py b/Python/path-sum-iv.py index ead4b0735..6ee097bfa 100644 --- a/Python/path-sum-iv.py +++ b/Python/path-sum-iv.py @@ -1,6 +1,9 @@ # Time: O(n) # Space: O(p), p is the number of paths +import collections + + class Solution(object): def pathSum(self, nums): """ @@ -13,7 +16,7 @@ def __init__(self, num): self.i = (num%100)/10 - 1 self.val = num%10 self.leaf = True - + def isParent(self, other): return self.level == other.level-1 and \ self.i == other.i/2 diff --git a/Python/permutation-in-string.py b/Python/permutation-in-string.py index 171502725..338244159 100644 --- a/Python/permutation-in-string.py +++ b/Python/permutation-in-string.py @@ -16,6 +16,9 @@ # The input strings only contain lower case letters. # The length of both given strings is in range [1, 10,000]. +import collections + + class Solution(object): def checkInclusion(self, s1, s2): """ diff --git a/Python/poor-pigs.py b/Python/poor-pigs.py index c5263a9d3..5c33be03a 100644 --- a/Python/poor-pigs.py +++ b/Python/poor-pigs.py @@ -15,6 +15,9 @@ # how many pigs (x) you need to figure out the "poison" bucket within p minutes? # There is exact one bucket with poison. +import math + + class Solution(object): def poorPigs(self, buckets, minutesToDie, minutesToTest): """ diff --git a/Python/prefix-and-suffix-search.py b/Python/prefix-and-suffix-search.py index caecf336c..8c2eb8b23 100644 --- a/Python/prefix-and-suffix-search.py +++ b/Python/prefix-and-suffix-search.py @@ -21,12 +21,15 @@ # prefix, suffix have lengths in range [0, 10]. # words[i] and prefix, suffix queries consist of lowercase letters only. +import collections + + class WordFilter(object): def __init__(self, words): """ :type words: List[str] - """ + """ _trie = lambda: collections.defaultdict(_trie) self.__trie = _trie() @@ -38,7 +41,7 @@ def __init__(self, words): for j in xrange(i, 2*len(word)-1): cur = cur[word[j%len(word)]] cur["_weight"] = weight - + def f(self, prefix, suffix): """ :type prefix: str @@ -58,7 +61,7 @@ def f(self, prefix, suffix): # m is the number of the prefix match, n is the number of the suffix match # Space: O(w * l) class Trie(object): - + def __init__(self): _trie = lambda: collections.defaultdict(_trie) self.__trie = _trie() @@ -89,7 +92,7 @@ class WordFilter2(object): def __init__(self, words): """ :type words: List[str] - """ + """ self.__prefix_trie = Trie() self.__suffix_trie = Trie() for i in reversed(xrange(len(words))): @@ -101,7 +104,7 @@ def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int - """ + """ prefix_match = self.__prefix_trie.find(prefix) suffix_match = self.__suffix_trie.find(suffix[::-1]) i, j = 0, 0 @@ -113,8 +116,8 @@ def f(self, prefix, suffix): else: j += 1 return -1 - - + + # Your WordFilter object will be instantiated and called as such: # obj = WordFilter(words) # param_1 = obj.f(prefix,suffix) diff --git a/Python/rabbits-in-forest.py b/Python/rabbits-in-forest.py index 0c3dad1d6..bd92a73b9 100644 --- a/Python/rabbits-in-forest.py +++ b/Python/rabbits-in-forest.py @@ -27,6 +27,9 @@ # - answers will have length at most 1000. # - Each answers[i] will be an integer in the range [0, 999]. +import collections + + class Solution(object): def numRabbits(self, answers): """ diff --git a/Python/range-module.py b/Python/range-module.py index 612011f0e..f5a2adbb0 100644 --- a/Python/range-module.py +++ b/Python/range-module.py @@ -27,7 +27,10 @@ # - The total number of calls to addRange in a single test case is at most 1000. # - The total number of calls to queryRange in a single test case is at most 5000. # - The total number of calls to removeRange in a single test case is at most 1000. - + +import bisect + + class RangeModule(object): def __init__(self): diff --git a/Python/reach-a-number.py b/Python/reach-a-number.py index 138054d34..ff4344ee7 100644 --- a/Python/reach-a-number.py +++ b/Python/reach-a-number.py @@ -26,6 +26,9 @@ # Note: # - target will be a non-zero integer in the range [-10^9, 10^9]. +import math + + class Solution(object): def reachNumber(self, target): """ @@ -36,7 +39,7 @@ def reachNumber(self, target): k = int(math.ceil((-1+math.sqrt(1+8*target))/2)) target -= k*(k+1)/2 return k if target%2 == 0 else k+1+k%2 - + # Time: O(sqrt(n)) # Space: O(1) @@ -52,4 +55,3 @@ def reachNumber(self, target): k += 1 target -= k return k if target%2 == 0 else k+1+k%2 - diff --git a/Python/reconstruct-itinerary.py b/Python/reconstruct-itinerary.py index 2305889b4..b1864972f 100644 --- a/Python/reconstruct-itinerary.py +++ b/Python/reconstruct-itinerary.py @@ -1,4 +1,4 @@ -# Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, +# Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets, # ni is the number of the ticket which from is city i, # k is the total number of cities. # Space: O(t) @@ -10,7 +10,7 @@ # # Note: # If there are multiple valid itineraries, you should return the itinerary -# that has the smallest lexical order when read as a single string. +# 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). @@ -24,6 +24,9 @@ # Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. # But it is larger in lexical order. +import collections + + class Solution(object): def findItinerary(self, tickets): """ diff --git a/Python/remove-duplicate-letters.py b/Python/remove-duplicate-letters.py index 552643870..665537749 100644 --- a/Python/remove-duplicate-letters.py +++ b/Python/remove-duplicate-letters.py @@ -14,6 +14,9 @@ # Given "cbacdcbc" # Return "acdb" +import collections + + class Solution(object): def removeDuplicateLetters(self, s): """ diff --git a/Python/reorganize-string.py b/Python/reorganize-string.py index aa2dca926..719c1aeac 100644 --- a/Python/reorganize-string.py +++ b/Python/reorganize-string.py @@ -18,6 +18,10 @@ # Note: # - S will consist of lowercase letters and have length in range [1, 500]. +import collections +import heapq + + class Solution(object): def reorganizeString(self, S): """ @@ -27,7 +31,7 @@ def reorganizeString(self, S): counts = collections.Counter(S) if any(v > (len(S)+1)/2 for k, v in counts.iteritems()): return "" - + result = [] max_heap = [] for k, v in counts.iteritems(): diff --git a/Python/replace-words.py b/Python/replace-words.py index 8ed8c2513..662f8ec0f 100644 --- a/Python/replace-words.py +++ b/Python/replace-words.py @@ -22,6 +22,9 @@ # 1 <= root length <= 100 # 1 <= sentence words length <= 1000 +import collections + + class Solution(object): def replaceWords(self, dictionary, sentence): """ diff --git a/Python/second-minimum-node-in-a-binary-tree.py b/Python/second-minimum-node-in-a-binary-tree.py index ac2b21761..e300f12e5 100644 --- a/Python/second-minimum-node-in-a-binary-tree.py +++ b/Python/second-minimum-node-in-a-binary-tree.py @@ -11,7 +11,7 @@ # If no such second minimum value exists, output -1 instead. # # Example 1: -# Input: +# Input: # 2 # / \ # 2 5 @@ -21,14 +21,14 @@ # Output: 5 # Explanation: The smallest value is 2, the second smallest value is 5. # Example 2: -# Input: +# Input: # 2 # / \ # 2 2 # # Output: -1 # Explanation: The smallest value is 2, but there isn't any second smallest value. - + # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): @@ -36,6 +36,9 @@ # self.left = None # self.right = None +import heapq + + class Solution(object): def findSecondMinimumValue(self, root): """ diff --git a/Python/sentence-similarity-ii.py b/Python/sentence-similarity-ii.py index 3e0d8895a..312e04df2 100644 --- a/Python/sentence-similarity-ii.py +++ b/Python/sentence-similarity-ii.py @@ -29,6 +29,9 @@ # - The length of each pairs[i] will be 2. # - The length of each words[i] and pairs[i][j] will be in the range [1, 20]. +import itertools + + class UnionFind(object): def __init__(self, n): self.set = range(n) diff --git a/Python/sentence-similarity.py b/Python/sentence-similarity.py index 02ee74720..2cad00bba 100644 --- a/Python/sentence-similarity.py +++ b/Python/sentence-similarity.py @@ -27,6 +27,9 @@ # - The length of each pairs[i] will be 2. # - The length of each words[i] and pairs[i][j] will be in the range [1, 20]. +import itertools + + class Solution(object): def areSentencesSimilar(self, words1, words2, pairs): """ diff --git a/Python/sequence-reconstruction.py b/Python/sequence-reconstruction.py index 8b492df2a..5de09aed0 100644 --- a/Python/sequence-reconstruction.py +++ b/Python/sequence-reconstruction.py @@ -1,6 +1,9 @@ # Time: O(n * s), n is the size of org, s is the size of seqs # Space: O(n) +import collections + + class Solution(object): def sequenceReconstruction(self, org, seqs): """ @@ -79,4 +82,3 @@ def sequenceReconstruction(self, org, seqs): return False q.append(j) return res == org and len(org) == len(integer_set) - diff --git a/Python/serialize-and-deserialize-bst.py b/Python/serialize-and-deserialize-bst.py index 811fa44c2..7ab9837df 100644 --- a/Python/serialize-and-deserialize-bst.py +++ b/Python/serialize-and-deserialize-bst.py @@ -23,11 +23,14 @@ # self.left = None # self.right = None +import collections + + class Codec: def serialize(self, root): """Encodes a tree to a single string. - + :type root: TreeNode :rtype: str """ @@ -45,7 +48,7 @@ def serializeHelper(node, vals): def deserialize(self, data): """Decodes your encoded data to tree. - + :type data: str :rtype: TreeNode """ diff --git a/Python/shortest-completing-word.py b/Python/shortest-completing-word.py index 49c50fe11..46890b5c3 100644 --- a/Python/shortest-completing-word.py +++ b/Python/shortest-completing-word.py @@ -32,6 +32,9 @@ # - words will have a length in the range [10, 1000]. # - Every words[i] will consist of lowercase letters, and have length in range [1, 15]. +import collections + + class Solution(object): def shortestCompletingWord(self, licensePlate, words): """ diff --git a/Python/shortest-word-distance-ii.py b/Python/shortest-word-distance-ii.py index fb76a188c..21807b273 100644 --- a/Python/shortest-word-distance-ii.py +++ b/Python/shortest-word-distance-ii.py @@ -1,6 +1,9 @@ # Time: init: O(n), lookup: O(a + b), a, b is occurences of word1, word2 # Space: O(n) +import collections + + class WordDistance: # initialize your data structure here. # @param {string[]} words @@ -26,4 +29,3 @@ def shortest(self, word1, word2): j += 1 return dist - diff --git a/Python/shuffle-an-array.py b/Python/shuffle-an-array.py index 0d373852a..0bafe4e79 100644 --- a/Python/shuffle-an-array.py +++ b/Python/shuffle-an-array.py @@ -19,11 +19,14 @@ # // Returns the random shuffling of array [1,2,3]. # solution.shuffle(); +import random + + class Solution(object): def __init__(self, nums): """ - + :type nums: List[int] :type size: int """ @@ -36,7 +39,7 @@ def reset(self): :rtype: List[int] """ return self.__nums - + def shuffle(self): """ diff --git a/Python/sliding-puzzle.py b/Python/sliding-puzzle.py index 25ba2b692..04d104fed 100644 --- a/Python/sliding-puzzle.py +++ b/Python/sliding-puzzle.py @@ -9,7 +9,7 @@ # The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. # # Given a puzzle board, return the least number of moves required -# so that the state of the board is solved. If it is impossible +# so that the state of the board is solved. If it is impossible # for the state of the board to be solved, return -1. # # Examples: @@ -37,6 +37,10 @@ # - board will be a 2 x 3 array as described above. # - board[i][j] will be a permutation of [0, 1, 2, 3, 4, 5]. +import heapq +import itertools + + # A* Search Algorithm class Solution(object): def slidingPuzzle(self, board): @@ -46,7 +50,7 @@ def slidingPuzzle(self, board): """ def dot(p1, p2): return p1[0]*p2[0]+p1[1]*p2[1] - + def heuristic_estimate(board, R, C, expected): result = 0 for i in xrange(R): @@ -56,13 +60,13 @@ def heuristic_estimate(board, R, C, expected): r, c = expected[val] result += abs(r-i) + abs(c-j) return result - + R, C = len(board), len(board[0]) begin = tuple(itertools.chain(*board)) end = tuple(range(1, R*C) + [0]) expected = {(C*i+j+1) % (R*C) : (i, j) for i in xrange(R) for j in xrange(C)} - + min_steps = heuristic_estimate(begin, R, C, expected) closer, detour = [(begin.index(0), begin)], [] lookup = set() @@ -111,14 +115,14 @@ def heuristic_estimate(board, R, C, expected): r, c = expected[val] result += abs(r-i) + abs(c-j) return result - + R, C = len(board), len(board[0]) begin = tuple(itertools.chain(*board)) end = tuple(range(1, R*C) + [0]) end_wrong = tuple(range(1, R*C-2) + [R*C-1, R*C-2, 0]) expected = {(C*i+j+1) % (R*C) : (i, j) for i in xrange(R) for j in xrange(C)} - + min_heap = [(0, 0, begin.index(0), begin)] lookup = {begin: 0} while min_heap: diff --git a/Python/smallest-good-base.py b/Python/smallest-good-base.py index c63d418b6..ca093562b 100644 --- a/Python/smallest-good-base.py +++ b/Python/smallest-good-base.py @@ -3,7 +3,7 @@ # For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1. # -# Now given a string representing n, you should return the smallest good base of n in string format. +# Now given a string representing n, you should return the smallest good base of n in string format. # # Example 1: # Input: "13" @@ -21,6 +21,9 @@ # The range of n is [3, 10^18]. # The string representing n is always valid and will not have leading zeros. +import math + + class Solution(object): def smallestGoodBase(self, n): """ diff --git a/Python/smallest-range.py b/Python/smallest-range.py index 280dd05cf..8b5e76c90 100644 --- a/Python/smallest-range.py +++ b/Python/smallest-range.py @@ -9,7 +9,7 @@ # Example 1: # Input:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] # Output: [20,24] -# Explanation: +# Explanation: # List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. # List 2: [0, 9, 12, 20], 20 is in range [20,24]. # List 3: [5, 18, 22, 30], 22 is in range [20,24]. @@ -20,6 +20,9 @@ # For Java users, please note that the input type has been changed to List>. # And after you reset the code template, you'll see this point. +import heapq + + class Solution(object): def smallestRange(self, nums): """ @@ -33,10 +36,10 @@ def smallestRange(self, nums): right = max(right, row[0]) it = iter(row) heapq.heappush(min_heap, (next(it, None), it)) - + result = (left, right) while min_heap: - (val, it) = heapq.heappop(min_heap) + (val, it) = heapq.heappop(min_heap) val = next(it, None) if val is None: break diff --git a/Python/smallest-rectangle-enclosing-black-pixels.py b/Python/smallest-rectangle-enclosing-black-pixels.py index a410c374f..5e54d555d 100644 --- a/Python/smallest-rectangle-enclosing-black-pixels.py +++ b/Python/smallest-rectangle-enclosing-black-pixels.py @@ -1,6 +1,10 @@ # Time: O(nlogn) # Space: O(1) +import bisect +import itertools + + class Solution(object): def minArea(self, image, x, y): """ diff --git a/Python/solve-the-equation.py b/Python/solve-the-equation.py index a5ccdb1bb..21ce493de 100644 --- a/Python/solve-the-equation.py +++ b/Python/solve-the-equation.py @@ -26,6 +26,9 @@ # Input: "x=x+2" # Output: "No solution" +import re + + class Solution(object): def solveEquation(self, equation): """ diff --git a/Python/sort-characters-by-frequency.py b/Python/sort-characters-by-frequency.py index 72712cf14..3bfbde6d7 100644 --- a/Python/sort-characters-by-frequency.py +++ b/Python/sort-characters-by-frequency.py @@ -33,6 +33,9 @@ # "bbaA" is also a valid answer, but "Aabb" is incorrect. # Note that 'A' and 'a' are treated as two different characters. +import collections + + class Solution(object): def frequencySort(self, s): """ @@ -42,14 +45,14 @@ def frequencySort(self, s): freq = collections.defaultdict(int) for c in s: freq[c] += 1 - + counts = [""] * (len(s)+1) for c in freq: counts[freq[c]] += c - + result = "" for count in reversed(xrange(len(counts)-1)): for c in counts[count]: result += c * count - + return result diff --git a/Python/stickers-to-spell-word.py b/Python/stickers-to-spell-word.py index 6309f76ef..180f9889b 100644 --- a/Python/stickers-to-spell-word.py +++ b/Python/stickers-to-spell-word.py @@ -44,6 +44,9 @@ # - The time limit may be more challenging than usual. # It is expected that a 50 sticker test case can be solved within 35ms on average. +import collections + + class Solution(object): def minStickers(self, stickers, target): """ @@ -65,12 +68,11 @@ def minStickersHelper(sticker_counts, target, dp): new_target += [k]*(target_count[k] - sticker_count[k]) if len(new_target) != len(target): num = minStickersHelper(sticker_counts, new_target, dp) - if num != -1: - result = min(result, 1+num) + if num != -1: + result = min(result, 1+num) dp["".join(target)] = -1 if result == float("inf") else result return dp["".join(target)] - + sticker_counts = map(collections.Counter, stickers) dp = { "":0 } return minStickersHelper(sticker_counts, target, dp) - diff --git a/Python/subarray-sum-equals-k.py b/Python/subarray-sum-equals-k.py index 98e7d8ae0..96a14da77 100644 --- a/Python/subarray-sum-equals-k.py +++ b/Python/subarray-sum-equals-k.py @@ -12,6 +12,9 @@ # The length of the array is in range [1, 20,000]. # The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. +import collections + + class Solution(object): def subarraySum(self, nums, k): """ diff --git a/Python/substring-with-concatenation-of-all-words.py b/Python/substring-with-concatenation-of-all-words.py index f1127a886..f56813378 100644 --- a/Python/substring-with-concatenation-of-all-words.py +++ b/Python/substring-with-concatenation-of-all-words.py @@ -14,6 +14,10 @@ # (order does not matter). # Sliding window solution + +import collections + + class Solution(object): def findSubstring(self, s, words): """ @@ -24,7 +28,7 @@ def findSubstring(self, s, words): result, m, n, k = [], len(s), len(words), len(words[0]) if m < n*k: return result - + lookup = collections.defaultdict(int) for i in words: lookup[i] += 1 # Space: O(n * k) @@ -36,7 +40,7 @@ def findSubstring(self, s, words): s1 = s[j:j+k]; # Time: O(k) if s1 in lookup: tmp[s1] += 1 - if tmp[s1] <= lookup[s1]: + if tmp[s1] <= lookup[s1]: count += 1 else: while tmp[s1] > lookup[s1]: @@ -69,7 +73,7 @@ def findSubstring(self, s, words): result, m, n, k = [], len(s), len(words), len(words[0]) if m < n*k: return result - + lookup = collections.defaultdict(int) for i in words: lookup[i] += 1 # Space: O(n * k) @@ -78,7 +82,7 @@ def findSubstring(self, s, words): cur, j = collections.defaultdict(int), 0 while j < n: # Time: O(n) word = s[i+j*k:i+j*k+k] # Time: O(k) - if word not in lookup: + if word not in lookup: break cur[word] += 1 if cur[word] > lookup[word]: @@ -86,7 +90,7 @@ def findSubstring(self, s, words): j += 1 if j == n: result.append(i) - + return result diff --git a/Python/sum-of-square-numbers.py b/Python/sum-of-square-numbers.py index bf1a22f24..2688be8d1 100644 --- a/Python/sum-of-square-numbers.py +++ b/Python/sum-of-square-numbers.py @@ -11,7 +11,10 @@ # Example 2: # Input: 3 # Output: False - + +import math + + class Solution(object): def judgeSquareSum(self, c): """ diff --git a/Python/summary-ranges.py b/Python/summary-ranges.py index f602a5282..6bdddb9f2 100644 --- a/Python/summary-ranges.py +++ b/Python/summary-ranges.py @@ -8,6 +8,12 @@ # return ["0->2","4->5","7"]. # +import bisect +import collections +import itertools +import re + + class Solution: # @param {integer[]} nums # @return {string[]} diff --git a/Python/super-ugly-number.py b/Python/super-ugly-number.py index 3775efbb3..4ac12281d 100644 --- a/Python/super-ugly-number.py +++ b/Python/super-ugly-number.py @@ -3,10 +3,10 @@ # Write a program to find the nth super ugly number. # -# Super ugly numbers are positive numbers whose all +# 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 +# is the sequence of the first 12 super ugly numbers given # primes = [2, 7, 13, 19] of size 4. # # Note: @@ -14,6 +14,9 @@ # (2) The given numbers in primes are in ascending order. # (3) 0 < k <= 100, 0 < n <= 106, 0 < primes[i] < 1000. +import heapq + + # Heap solution. (620ms) class Solution(object): def nthSuperUglyNumber(self, n, primes): @@ -109,7 +112,7 @@ def nthSuperUglyNumber(self, n, primes): if uglies[i] == 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) diff --git a/Python/surrounded-regions.py b/Python/surrounded-regions.py index 98e7a65ad..e586a1acc 100644 --- a/Python/surrounded-regions.py +++ b/Python/surrounded-regions.py @@ -2,22 +2,25 @@ # Space: O(m + n) # # Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. -# +# # A region is captured by flipping all 'O's into 'X's in that surrounded region. -# +# # For example, # X X X X # X O O X # X X O X # X O X X # After running your function, the board should be: -# +# # X X X X # X X X X # X X X X # X O X X # +import collections + + class Solution: # @param board, a 2D array # Capture all regions by modifying the input board in-place. @@ -26,15 +29,15 @@ def solve(self, board): if not board: return q = collections.deque([]) - + for i in xrange(len(board)): q.append((i, 0)) q.append((i, len(board[0]) - 1)) - + for j in xrange(len(board[0])): q.append((0, j)) q.append((len(board) - 1, j)) - + while q: i, j = q.popleft() if board[i][j] in ['O', 'V']: @@ -44,7 +47,7 @@ def solve(self, board): board[x][y] == 'O': board[x][y] = 'V' q.append((x, y)) - + for i in xrange(len(board)): for j in xrange(len(board[0])): if board[i][j] != 'V': diff --git a/Python/target-sum.py b/Python/target-sum.py index 602767865..cb01825df 100644 --- a/Python/target-sum.py +++ b/Python/target-sum.py @@ -8,9 +8,9 @@ # Find out how many ways to assign symbols to make sum of integers equal to target S. # # Example 1: -# Input: nums is [1, 1, 1, 1, 1], S is 3. +# Input: nums is [1, 1, 1, 1, 1], S is 3. # Output: 5 -# Explanation: +# Explanation: # # -1+1+1+1+1 = 3 # +1-1+1+1+1 = 3 @@ -24,6 +24,9 @@ # The sum of elements in the given array will not exceed 1000. # Your output answer is guaranteed to be fitted in a 32-bit integer. +import collections + + class Solution(object): def findTargetSumWays(self, nums, S): """ diff --git a/Python/task-scheduler.py b/Python/task-scheduler.py index 4ee3eacc2..1e2bb7813 100644 --- a/Python/task-scheduler.py +++ b/Python/task-scheduler.py @@ -22,6 +22,9 @@ # The number of tasks is in the range [1, 10000]. # The integer n is in the range [0, 100]. +import collections + + class Solution(object): def leastInterval(self, tasks, n): """ @@ -34,7 +37,7 @@ def leastInterval(self, tasks, n): for task in tasks: count[task] += 1 max_count = max(max_count, count[task]) - + result = (max_count-1) * (n+1) for count in count.values(): if count == max_count: diff --git a/Python/the-maze-ii.py b/Python/the-maze-ii.py index 534ad0925..e651891d9 100644 --- a/Python/the-maze-ii.py +++ b/Python/the-maze-ii.py @@ -1,6 +1,9 @@ # Time: O(max(r, c) * wlogw) # Space: O(w) +import heapq + + class Solution(object): def shortestDistance(self, maze, start, destination): """ @@ -10,7 +13,7 @@ def shortestDistance(self, maze, start, destination): :rtype: int """ start, destination = tuple(start), tuple(destination) - + def neighbors(maze, node): for dir in [(-1, 0), (0, 1), (0, -1), (1, 0)]: cur_node, dist = list(node), 0 @@ -32,5 +35,5 @@ def neighbors(maze, node): visited.add(node) for neighbor_dist, neighbor in neighbors(maze, node): heapq.heappush(heap, (dist+neighbor_dist, neighbor)) - + return -1 diff --git a/Python/the-maze-iii.py b/Python/the-maze-iii.py index 02be0681a..ddcc087fe 100644 --- a/Python/the-maze-iii.py +++ b/Python/the-maze-iii.py @@ -1,6 +1,9 @@ # Time: O(max(r, c) * wlogw) # Space: O(w^2) +import heapq + + class Solution(object): def findShortestWay(self, maze, ball, hole): """ @@ -11,7 +14,7 @@ def findShortestWay(self, maze, ball, hole): """ ball, hole = tuple(ball), tuple(hole) dirs = {'u' : (-1, 0), 'r' : (0, 1), 'l' : (0, -1), 'd': (1, 0)} - + def neighbors(maze, node): for dir, vec in dirs.iteritems(): cur_node, dist = list(node), 0 @@ -24,7 +27,7 @@ def neighbors(maze, node): if tuple(cur_node) == hole: break yield tuple(cur_node), dir, dist - + heap = [(0, '', ball)] visited = set() while heap: @@ -34,5 +37,5 @@ def neighbors(maze, node): visited.add(node) for neighbor, dir, neighbor_dist in neighbors(maze, node): heapq.heappush(heap, (dist+neighbor_dist, path+dir, neighbor)) - + return "impossible" diff --git a/Python/the-maze.py b/Python/the-maze.py index 573eeebd4..0016d08c0 100644 --- a/Python/the-maze.py +++ b/Python/the-maze.py @@ -1,6 +1,9 @@ # Time: O(max(r, c) * w) # Space: O(w) +import collections + + class Solution(object): def hasPath(self, maze, start, destination): """ @@ -10,7 +13,7 @@ def hasPath(self, maze, start, destination): :rtype: bool """ start, destination = tuple(start), tuple(destination) - + def neighbors(maze, node): for dir in [(-1, 0), (0, 1), (0, -1), (1, 0)]: cur_node, dist = list(node), 0 @@ -32,5 +35,5 @@ def neighbors(maze, node): visited.add(node) for neighbor_dist, neighbor in neighbors(maze, node): queue.append((dist+neighbor_dist, neighbor)) - + return False diff --git a/Python/top-k-frequent-elements.py b/Python/top-k-frequent-elements.py index dd08c34ff..386c7dc11 100644 --- a/Python/top-k-frequent-elements.py +++ b/Python/top-k-frequent-elements.py @@ -7,13 +7,22 @@ # For example, # Given [1,1,1,2,2,3] and k = 2, return [1,2]. # -# Note: +# Note: # You may assume k is always valid, # 1 <= k <= number of unique elements. # Your algorithm's time complexity must be better # than O(n log n), where n is the array's size. # Bucket Sort Solution + +import collections + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def topKFrequent(self, nums, k): """ @@ -25,7 +34,7 @@ def topKFrequent(self, nums, k): buckets = [[] for _ in xrange(len(nums)+1)] for i, count in counts.iteritems(): buckets[count].append(i) - + result = [] for i in reversed(xrange(len(buckets))): for j in xrange(len(buckets[i])): @@ -50,14 +59,13 @@ def topKFrequent(self, nums, k): p = [] for key, val in counts.iteritems(): p.append((-val, key)) - self.kthElement(p, k); + self.kthElement(p, k) result = [] for i in xrange(k): result.append(p[i][1]) return result - def kthElement(self, nums, k): def PartitionAroundPivot(left, right, pivot_idx, nums): pivot_value = nums[pivot_idx] @@ -67,7 +75,7 @@ def PartitionAroundPivot(left, right, pivot_idx, nums): 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 @@ -81,7 +89,7 @@ def PartitionAroundPivot(left, right, pivot_idx, nums): right = new_pivot_idx - 1 else: # new_pivot_idx < k - 1. left = new_pivot_idx + 1 - + # Time: O(nlogk) # Space: O(n) @@ -93,4 +101,3 @@ def topKFrequent(self, nums, k): :rtype: List[int] """ return [key for key, _ in collections.Counter(nums).most_common(k)] - diff --git a/Python/top-k-frequent-words.py b/Python/top-k-frequent-words.py index d88d416bd..cf1ea8b3d 100644 --- a/Python/top-k-frequent-words.py +++ b/Python/top-k-frequent-words.py @@ -25,7 +25,12 @@ # Can you solve it in O(n) time with only O(k) extra space? # Quick Select Solution + +import collections +import heapq from random import randint + + class Solution(object): def topKFrequent(self, words, k): """ @@ -37,15 +42,14 @@ def topKFrequent(self, words, k): p = [] for key, val in counts.iteritems(): p.append((-val, key)) - self.kthElement(p, k); - + self.kthElement(p, k) + result = [] sorted_p = sorted(p[:k]) for i in xrange(k): result.append(sorted_p[i][1]) return result - def kthElement(self, nums, k): # O(n) on average def PartitionAroundPivot(left, right, pivot_idx, nums): pivot_value = nums[pivot_idx] @@ -55,7 +59,7 @@ def PartitionAroundPivot(left, right, pivot_idx, nums): 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 @@ -70,7 +74,7 @@ def PartitionAroundPivot(left, right, pivot_idx, nums): else: # new_pivot_idx < k - 1. left = new_pivot_idx + 1 - + # Time: O(nlogk) # Space: O(n) # Heap Solution @@ -82,12 +86,15 @@ def topKFrequent(self, words, k): :rtype: List[str] """ class MinHeapObj(object): - def __init__(self,val): self.val = val + def __init__(self,val): + self.val = val def __lt__(self,other): return self.val[1] > other.val[1] if self.val[0] == other.val[0] else \ self.val < other.val - def __eq__(self,other): return self.val == other.val - def __str__(self): return str(self.val) + def __eq__(self,other): + return self.val == other.val + def __str__(self): + return str(self.val) counts = collections.Counter(words) min_heap = [] diff --git a/Python/transform-to-chessboard.py b/Python/transform-to-chessboard.py index b6cdbfae5..236bbe106 100644 --- a/Python/transform-to-chessboard.py +++ b/Python/transform-to-chessboard.py @@ -39,6 +39,10 @@ # - board will have the same number of rows and columns, a number in the range [2, 30]. # - board[i][j] will be only 0s or 1s. +import collections +import itertools + + class Solution(object): def movesToChessboard(self, board): """ @@ -60,4 +64,3 @@ def movesToChessboard(self, board): result += min(sum(int(i%2 != v) for i, v in enumerate(seq1, begin)) \ for begin in begins) / 2 return result - diff --git a/Python/unique-word-abbreviation.py b/Python/unique-word-abbreviation.py index f734f40c8..6d90c05df 100644 --- a/Python/unique-word-abbreviation.py +++ b/Python/unique-word-abbreviation.py @@ -1,7 +1,10 @@ -# Time: ctor: O(n), n is number of words in the dictionary. +# Time: ctor: O(n), n is number of words in the dictionary. # lookup: O(1) # Space: O(k), k is number of unique words. +import collections + + class ValidWordAbbr(object): def __init__(self, dictionary): """ @@ -12,7 +15,7 @@ def __init__(self, dictionary): for word in dictionary: abbr = self.abbreviation(word) self.lookup_[abbr].add(word) - + def isUnique(self, word): """ diff --git a/Python/valid-anagram.py b/Python/valid-anagram.py index 0477caec1..040bdc853 100644 --- a/Python/valid-anagram.py +++ b/Python/valid-anagram.py @@ -12,6 +12,10 @@ # You may assume the string contains only lowercase alphabets. # +import collections +import string + + class Solution: # @param {string} s # @param {string} t @@ -37,13 +41,13 @@ def isAnagram(self, s, t): return False return True - + def isAnagram2(self, s, t): return all([s.count(c)==t.count(c) for c in string.ascii_lowercase]) - + def isAnagram3(self, s, t): if len(s) != len(t): - return False + return False count = collections.defaultdict(int) for c in s: count[c] += 1 diff --git a/Python/validate-ip-address.py b/Python/validate-ip-address.py index 50be7762d..6a46a8a44 100644 --- a/Python/validate-ip-address.py +++ b/Python/validate-ip-address.py @@ -1,7 +1,7 @@ # Time: O(1) # Space: O(1) -# In this problem, your job to write a function to check whether a input string +# In this problem, your job to write a function to check whether a input string # is a valid IPv4 address or IPv6 address or neither. # # IPv4 addresses are canonically represented in dot-decimal notation, @@ -46,6 +46,9 @@ # # Explanation: This is neither a IPv4 address nor a IPv6 address. +import string + + class Solution(object): def validIPAddress(self, IP): """ @@ -64,7 +67,7 @@ def validIPAddress(self, IP): if len(blocks) == 8: for i in xrange(len(blocks)): if not (1 <= len(blocks[i]) <= 4) or \ - not all(c in string.hexdigits for c in blocks[i]): + not all(c in string.hexdigits for c in blocks[i]): return "Neither" return "IPv6" return "Neither" diff --git a/Python/word-abbreviation.py b/Python/word-abbreviation.py index ef666f0a3..87f1290ad 100644 --- a/Python/word-abbreviation.py +++ b/Python/word-abbreviation.py @@ -1,6 +1,9 @@ # Time: O(n * l) ~ O(n^2 * l^2) # Space: O(n * l) +import collections + + class Solution(object): def wordsAbbreviation(self, dict): """ @@ -9,7 +12,7 @@ def wordsAbbreviation(self, dict): """ def isUnique(prefix, words): return sum(word.startswith(prefix) for word in words) == 1 - + def toAbbr(prefix, word): abbr = prefix + str(len(word) - 1 - len(prefix)) + word[-1] return abbr if len(abbr) < len(word) else word diff --git a/Python/zigzag-iterator.py b/Python/zigzag-iterator.py index 9936e2d52..56fc22313 100644 --- a/Python/zigzag-iterator.py +++ b/Python/zigzag-iterator.py @@ -1,6 +1,9 @@ # Time: O(n) # Space: O(k) +import collections + + class ZigzagIterator(object): def __init__(self, v1, v2): diff --git a/Python/zuma-game.py b/Python/zuma-game.py index 1af644c93..99d25c947 100644 --- a/Python/zuma-game.py +++ b/Python/zuma-game.py @@ -25,11 +25,11 @@ # # Input:"G", "GGGGG" # Output: 2 -# Explanation: G -> G[G] -> GG[G] -> empty +# Explanation: G -> G[G] -> GG[G] -> empty # # Input: "RBYYBBRRB", "YRBGB" # Output: 3 -# Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty +# Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty # # Note: # You may assume that the initial row of balls on the table won’t have any 3 or @@ -40,6 +40,9 @@ # is called "hand" in the input. # Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'. +import collections + + class Solution(object): def findMinStep(self, board, hand): """ @@ -63,18 +66,18 @@ def shrink(s): # Time: O(n), Space: O(n) for p in stack: result += [p[0]] * p[1] return result - + def find(board, c, j): for i in xrange(j, len(board)): if board[i] == c: return i return -1 - + def findMinStepHelper(board, hand, lookup): if not board: return 0 if not hand: return float("inf") if tuple(hand) in lookup[tuple(board)]: return lookup[tuple(board)][tuple(hand)] - + result = float("inf") for i in xrange(len(hand)): j = 0 @@ -82,7 +85,7 @@ def findMinStepHelper(board, hand, lookup): k = find(board, hand[i], j) if k == -1: break - + if k < len(board) - 1 and board[k] == board[k+1]: next_board = shrink(board[0:k] + board[k+2:]) next_hand = hand[0:i] + hand[i+1:] From 74b757731b8e9eec5d4852053d123fe0c47bfbc2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 20:16:45 +0800 Subject: [PATCH 4584/4971] Create soup-servings.py --- Python/soup-servings.py | 62 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Python/soup-servings.py diff --git a/Python/soup-servings.py b/Python/soup-servings.py new file mode 100644 index 000000000..5f0db5309 --- /dev/null +++ b/Python/soup-servings.py @@ -0,0 +1,62 @@ +# Time: O(1) +# Space: O(1) + +# There are two types of soup: type A and type B. +# Initially we have N ml of each type of soup. There are four kinds of operations: +# +# Serve 100 ml of soup A and 0 ml of soup B +# Serve 75 ml of soup A and 25 ml of soup B +# Serve 50 ml of soup A and 50 ml of soup B +# Serve 25 ml of soup A and 75 ml of soup B +# When we serve some soup, we give it to someone and we no longer have it. +# Each turn, we will choose from the four operations with equal probability 0.25. +# If the remaining volume of soup is not enough to complete the operation, +# we will serve as much as we can. +# We stop once we no longer have some quantity of both types of soup. +# +# Note that we do not have the operation where all 100 ml's of soup B are used first. +# +# Return the probability that soup A will be empty first, +# plus half the probability that A and B become empty at the same time. +# +# Example: +# Input: N = 50 +# Output: 0.625 +# Explanation: +# If we choose the first two operations, A will become empty first. +# For the third operation, A and B will become empty at the same time. +# For the fourth operation, B will become empty first. +# So the total probability of A becoming empty first plus half the probability +# that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625. +# +# Notes: +# 0 <= N <= 10^9. +# Answers within 10^-6 of the true value will be accepted as correct. + + +class Solution(object): + def soupServings(self, N): + """ + :type N: int + :rtype: float + """ + def dp(a, b, lookup): + if (a, b) in lookup: + return lookup[a, b] + if a <= 0 and b <= 0: + return 0.5 + if a <= 0: + return 1.0 + if b <= 0: + return 0.0 + lookup[a, b] = 0.25 * (dp(a-4, b, lookup) + + dp(a-3, b-1, lookup) + + dp(a-2, b-2, lookup) + + dp(a-1, b-3, lookup)) + return lookup[a, b] + + if N >= 5000: + return 1 + lookup = {} + N = (N-1)//25 + 1 + return dp(N, N, lookup) From 03ab0aae819144afa06d800c5263f7618161548b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 20:25:12 +0800 Subject: [PATCH 4585/4971] Update soup-servings.py --- Python/soup-servings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/soup-servings.py b/Python/soup-servings.py index 5f0db5309..88352571f 100644 --- a/Python/soup-servings.py +++ b/Python/soup-servings.py @@ -56,7 +56,7 @@ def dp(a, b, lookup): return lookup[a, b] if N >= 5000: - return 1 + return 1.0 lookup = {} N = (N-1)//25 + 1 return dp(N, N, lookup) From 64e66dcac702e55c7f328b0507767279092504c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 20:29:06 +0800 Subject: [PATCH 4586/4971] Update soup-servings.py --- Python/soup-servings.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/soup-servings.py b/Python/soup-servings.py index 88352571f..10529cd97 100644 --- a/Python/soup-servings.py +++ b/Python/soup-servings.py @@ -3,11 +3,11 @@ # There are two types of soup: type A and type B. # Initially we have N ml of each type of soup. There are four kinds of operations: +# 1. Serve 100 ml of soup A and 0 ml of soup B +# 2. Serve 75 ml of soup A and 25 ml of soup B +# 3. Serve 50 ml of soup A and 50 ml of soup B +# 4. Serve 25 ml of soup A and 75 ml of soup B # -# Serve 100 ml of soup A and 0 ml of soup B -# Serve 75 ml of soup A and 25 ml of soup B -# Serve 50 ml of soup A and 50 ml of soup B -# Serve 25 ml of soup A and 75 ml of soup B # When we serve some soup, we give it to someone and we no longer have it. # Each turn, we will choose from the four operations with equal probability 0.25. # If the remaining volume of soup is not enough to complete the operation, From 62e19d02a319ae5b3065a8f0ef2a003284bcb42e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 21:16:17 +0800 Subject: [PATCH 4587/4971] Create soup-servings.cpp --- C++/soup-servings.cpp | 46 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/soup-servings.cpp diff --git a/C++/soup-servings.cpp b/C++/soup-servings.cpp new file mode 100644 index 000000000..cc9ce0b13 --- /dev/null +++ b/C++/soup-servings.cpp @@ -0,0 +1,46 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +private: + template + struct PairHash { + size_t operator()(const pair& p) const { + size_t seed = 0; + seed ^= std::hash{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2); + seed ^= std::hash{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2); + return seed; + } + }; + +public: + double soupServings(int N) { + if (N > 4800) { + return 1.0; + } + unordered_map, double, PairHash> lookup; + N = (N + 24) / 25; + return dp(N, N, &lookup); + } + +private: + double dp(int a, int b, unordered_map, double, PairHash> *lookup) { + if (lookup->count(make_pair(a, b))) { + return (*lookup)[make_pair(a, b)]; + } + if (a <= 0 && b <= 0) { + return 0.5; + } + if (a <= 0) { + return 1.0; + } + if (b <= 0) { + return 0.0; + } + (*lookup)[make_pair(a, b)] = 0.25 * (dp(a - 4, b, lookup) + + dp(a - 3, b - 1, lookup) + + dp(a - 2, b - 2, lookup) + + dp(a - 1, b - 3, lookup)); + return (*lookup)[make_pair(a, b)]; + } +}; From ad245a4fa85d90bb43acfe7121ef4ed49794cc00 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 21:19:46 +0800 Subject: [PATCH 4588/4971] Update soup-servings.py --- Python/soup-servings.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/soup-servings.py b/Python/soup-servings.py index 10529cd97..97a108aa7 100644 --- a/Python/soup-servings.py +++ b/Python/soup-servings.py @@ -55,8 +55,8 @@ def dp(a, b, lookup): dp(a-1, b-3, lookup)) return lookup[a, b] - if N >= 5000: + if N >= 4800: return 1.0 lookup = {} - N = (N-1)//25 + 1 + N = (N+24)//25 return dp(N, N, lookup) From cce512b1c1e1c0e769dab690e847f292ad1957aa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 22:20:13 +0800 Subject: [PATCH 4589/4971] Create expressive-words.py --- Python/expressive-words.py | 60 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/expressive-words.py diff --git a/Python/expressive-words.py b/Python/expressive-words.py new file mode 100644 index 000000000..f88cbf49e --- /dev/null +++ b/Python/expressive-words.py @@ -0,0 +1,60 @@ +# Time: O(n + s), n is the sum of all word lengths, s is the length of S +# Space: O(1) + +# Sometimes people repeat letters to represent extra feeling, +# such as "hello" -> "heeellooo", "hi" -> "hiiii". +# Here, we have groups, of adjacent letters that are all the same character, +# and adjacent characters to the group are different. +# A group is extended if that group is length 3 or more, so "e" and "o" +# would be extended in the first example, and "i" would be extended in the second example. +# As another example, the groups of "abbcccaaaa" would be "a", "bb", "ccc", and "aaaa"; +# and "ccc" and "aaaa" are the extended groups of that string. +# +# For some given string S, a query word is stretchy +# if it can be made to be equal to S by extending some groups. +# Formally, we are allowed to repeatedly choose a group (as defined above) of characters c, +# and add some number of the same character c to it so that the length of the group is 3 or more. +# Note that we cannot extend a group of size one like "h" to a group of size two like "hh" - +# all extensions must leave the group extended - ie., at least 3 characters long. +# +# Given a list of query words, return the number of words that are stretchy. +# +# Example: +# Input: +# S = "heeellooo" +# words = ["hello", "hi", "helo"] +# Output: 1 +# Explanation: +# We can extend "e" and "o" in the word "hello" to get "heeellooo". +# We can't extend "helo" to get "heeellooo" because the group "ll" is not extended. +# +# Notes: +# - 0 <= len(S) <= 100. +# - 0 <= len(words) <= 100. +# - 0 <= len(words[i]) <= 100. +# - S and all words in words consist only of lowercase letters + +import itertools + + +class Solution(object): + def expressiveWords(self, S, words): + """ + :type S: str + :type words: List[str] + :rtype: int + """ + # Run length encoding + def RLE(S): + return itertools.izip(*[(k, len(list(grp))) + for k, grp in itertools.groupby(S)]) + + R, count = RLE(S) + result = 0 + for word in words: + R2, count2 = RLE(word) + if R2 != R: + continue + result += all(c1 >= max(c2, 3) or c1 == c2 + for c1, c2 in itertools.izip(count, count2)) + return result From 873aaa0f5652e01c1a4c530bec7094eeb7d1d2d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 22:21:08 +0800 Subject: [PATCH 4590/4971] Update expressive-words.py --- Python/expressive-words.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/expressive-words.py b/Python/expressive-words.py index f88cbf49e..bb0c21d76 100644 --- a/Python/expressive-words.py +++ b/Python/expressive-words.py @@ -1,5 +1,5 @@ # Time: O(n + s), n is the sum of all word lengths, s is the length of S -# Space: O(1) +# Space: O(l + s), l is the max word length # Sometimes people repeat letters to represent extra feeling, # such as "hello" -> "heeellooo", "hi" -> "hiiii". From 65d1096510397a55620644afa1943e97e49242b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 22:39:52 +0800 Subject: [PATCH 4591/4971] Create expressive-words.cpp --- C++/expressive-words.cpp | 44 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 C++/expressive-words.cpp diff --git a/C++/expressive-words.cpp b/C++/expressive-words.cpp new file mode 100644 index 000000000..317913ff5 --- /dev/null +++ b/C++/expressive-words.cpp @@ -0,0 +1,44 @@ +// Time: O(n + s), n is the sum of all word lengths, s is the length of S +// Space: O(l + s) + +class Solution { +public: + int expressiveWords(string S, vector& words) { + int result = 0; + const auto& R = RLE(S); + for (const auto& word : words) { + const auto& R2 = RLE(word); + if (R.key != R2.key) { + continue; + } + int i; + for (i = 0; i < R.counts.size(); ++i) { + const auto& c1 = R.counts[i]; + const auto& c2 = R2.counts[i]; + if (c1 < max(c2, 3) && c1 != c2) { + break; + } + } + if (i == R.counts.size()) { + ++result; + } + } + return result; + } + +private: + struct RLE { + string key; + vector counts; + RLE(const string& s) { + int prev = -1; + for (int i = 0; i < s.length(); ++i) { + if (i == s.length() - 1 || s[i] != s[i + 1]) { + key.push_back(s[i]); + counts.emplace_back(i - prev); + prev = i; + } + } + } + }; +}; From 0d80bcf97abb950ba772f585f364962000dde122 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 23:36:45 +0800 Subject: [PATCH 4592/4971] Create chalkboard-xor-gam.cpp --- C++/chalkboard-xor-gam.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 C++/chalkboard-xor-gam.cpp diff --git a/C++/chalkboard-xor-gam.cpp b/C++/chalkboard-xor-gam.cpp new file mode 100644 index 000000000..fab1e2406 --- /dev/null +++ b/C++/chalkboard-xor-gam.cpp @@ -0,0 +1,11 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool xorGame(vector& nums) { + return accumulate(nums.cbegin(), nums.cend(), + 0, std::bit_xor()) == 0 || + nums.size() % 2 == 0; + } +}; From 5568f30f2bcb83eb8f4dd250d8c817aaea3815f5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 23:43:34 +0800 Subject: [PATCH 4593/4971] Create chalkboard-xor-game.py --- Python/chalkboard-xor-game.py | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/chalkboard-xor-game.py diff --git a/Python/chalkboard-xor-game.py b/Python/chalkboard-xor-game.py new file mode 100644 index 000000000..2733efa2f --- /dev/null +++ b/Python/chalkboard-xor-game.py @@ -0,0 +1,43 @@ +# Time: O(n) +# Space: O(1) + +# We are given non-negative integers nums[i] which are written on a chalkboard. +# Alice and Bob take turns erasing exactly one number from the chalkboard, +# with Alice starting first. If erasing a number causes the bitwise XOR of +# all the elements of the chalkboard to become 0, then that player loses. +# (Also, we'll say the bitwise XOR of one element is that element itself, +# and the bitwise XOR of no elements is 0.) +# +# Also, if any player starts their turn with the bitwise XOR of all the elements +# of the chalkboard equal to 0, then that player wins. +# +# Return True if and only if Alice wins the game, assuming both players play optimally. +# +# Example: +# Input: nums = [1, 1, 2] +# Output: false +# Explanation: +# Alice has two choices: erase 1 or erase 2. +# If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of +# all the elements of the chalkboard is 1 XOR 2 = 3. +# Now Bob can remove any element he wants, because Alice will be the one +# to erase the last element and she will lose. +# If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of +# all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. +# +# Notes: +# - 1 <= N <= 1000. +# - 0 <= nums[i] <= 2^16. + +from operator import xor +from functools import reduce + + +class Solution(object): + def xorGame(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + return reduce(xor, nums) == 0 or \ + len(nums) % 2 == 0 From 2b6afdeac7e10248ddd6a393bc51eba35fefe449 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Apr 2018 23:58:59 +0800 Subject: [PATCH 4594/4971] Update chalkboard-xor-game.py --- Python/chalkboard-xor-game.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/chalkboard-xor-game.py b/Python/chalkboard-xor-game.py index 2733efa2f..b6c5781f2 100644 --- a/Python/chalkboard-xor-game.py +++ b/Python/chalkboard-xor-game.py @@ -16,17 +16,17 @@ # Example: # Input: nums = [1, 1, 2] # Output: false -# Explanation: -# Alice has two choices: erase 1 or erase 2. +# Explanation: +# Alice has two choices: erase 1 or erase 2. # If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of # all the elements of the chalkboard is 1 XOR 2 = 3. # Now Bob can remove any element he wants, because Alice will be the one -# to erase the last element and she will lose. +# to erase the last element and she will lose. # If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of # all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. # # Notes: -# - 1 <= N <= 1000. +# - 1 <= N <= 1000. # - 0 <= nums[i] <= 2^16. from operator import xor @@ -40,4 +40,4 @@ def xorGame(self, nums): :rtype: bool """ return reduce(xor, nums) == 0 or \ - len(nums) % 2 == 0 + len(nums) % 2 == 0 From 9daab3fa5a6c0942d09f7d8ee7a0e1ec62fb8284 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Apr 2018 00:12:55 +0800 Subject: [PATCH 4595/4971] Create subdomain-visit-count.py --- Python/subdomain-visit-count.py | 90 +++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Python/subdomain-visit-count.py diff --git a/Python/subdomain-visit-count.py b/Python/subdomain-visit-count.py new file mode 100644 index 000000000..a867eb8d6 --- /dev/null +++ b/Python/subdomain-visit-count.py @@ -0,0 +1,90 @@ +# Time: O(n), is the length of cpdomains (assuming the length of cpdomains[i] is fixed) +# Space: O(n) + +# A website domain like "discuss.leetcode.com" consists of various subdomains. +# At the top level, we have "com", at the next level, we have "leetcode.com", +# and at the lowest level, "discuss.leetcode.com". +# When we visit a domain like "discuss.leetcode.com", +# we will also visit the parent domains "leetcode.com" and "com" implicitly. +# +# Now, call a "count-paired domain" to be a count +# (representing the number of visits this domain received), +# followed by a space, followed by the address. +# An example of a count-paired domain might be "9001 discuss.leetcode.com". +# +# We are given a list cpdomains of count-paired domains. +# We would like a list of count-paired domains, +# (in the same format as the input, and in any order), +# that explicitly counts the number of visits to each subdomain. +# +# Example 1: +# Input: +# ["9001 discuss.leetcode.com"] +# Output: +# ["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"] +# Explanation: +# We only have one website domain: "discuss.leetcode.com". +# As discussed above, the subdomain "leetcode.com" and +# "com" will also be visited. So they will all be visited 9001 times. +# +# Example 2: +# Input: +# ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"] +# Output: +# ["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"] +# Explanation: +# We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, +# "intel.mail.com" once and "wiki.org" 5 times. +# For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, +# "com" 900 + 50 + 1 = 951 times, and "org" 5 times. +# +# Notes: +# - The length of cpdomains will not exceed 100. +# - The length of each domain name will not exceed 100. +# - Each address will have either 1 or 2 "." characters. +# - The input count in any count-paired domain will not exceed 10000. + +from collections import defaultdict + + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +try: + dict.iteritems +except AttributeError: + # Python 3 + def itervalues(d): + return iter(d.values()) + + def iteritems(d): + return iter(d.items()) +else: + # Python 2 + def itervalues(d): + return d.itervalues() + + def iteritems(d): + return d.iteritems() + + +class Solution: + def subdomainVisits(self, cpdomains): + """ + :type cpdomains: List[str] + :rtype: List[str] + """ + result = defaultdict(int) + for domain in cpdomains: + count, domain = domain.split() + count = int(count) + frags = domain.split('.') + curr = [] + for i in reversed(xrange(len(frags))): + curr.append(frags[i]) + result[".".join(reversed(curr))] += count + + return ["{} {}".format(count, domain) for domain, count in iteritems(result)] From 8b4cfc628adabc50e101ee1c7025292ffc90ecd6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Apr 2018 00:14:29 +0800 Subject: [PATCH 4596/4971] Update subdomain-visit-count.py --- Python/subdomain-visit-count.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/subdomain-visit-count.py b/Python/subdomain-visit-count.py index a867eb8d6..59604211c 100644 --- a/Python/subdomain-visit-count.py +++ b/Python/subdomain-visit-count.py @@ -54,7 +54,7 @@ try: - dict.iteritems + defaultdict.iteritems except AttributeError: # Python 3 def itervalues(d): From f85daed6ddff46561206fb5dc46d47c42131f4c2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Apr 2018 00:15:09 +0800 Subject: [PATCH 4597/4971] Update subdomain-visit-count.py --- Python/subdomain-visit-count.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/Python/subdomain-visit-count.py b/Python/subdomain-visit-count.py index 59604211c..5f5cbbd89 100644 --- a/Python/subdomain-visit-count.py +++ b/Python/subdomain-visit-count.py @@ -57,16 +57,10 @@ defaultdict.iteritems except AttributeError: # Python 3 - def itervalues(d): - return iter(d.values()) - def iteritems(d): return iter(d.items()) else: # Python 2 - def itervalues(d): - return d.itervalues() - def iteritems(d): return d.iteritems() From acd64df2edee458a8b5ca6951f88760c05df203a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Apr 2018 00:33:45 +0800 Subject: [PATCH 4598/4971] Create subdomain-visit-count.cpp --- C++/subdomain-visit-count.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/subdomain-visit-count.cpp diff --git a/C++/subdomain-visit-count.cpp b/C++/subdomain-visit-count.cpp new file mode 100644 index 000000000..1ffb3bd03 --- /dev/null +++ b/C++/subdomain-visit-count.cpp @@ -0,0 +1,28 @@ +// Time: O(n), is the length of cpdomains (assuming the length of cpdomains[i] is fixed) +// Space: O(n) + +class Solution { +public: + vector subdomainVisits(vector& cpdomains) { + unordered_map counts; + for (const auto& cpdomain : cpdomains) { + int i = cpdomain.find(" "); + const int count = stoi(cpdomain.substr(0, i)); + const auto& domain = cpdomain.substr(i + 1); + for (int i = -1; i < static_cast(domain.length()); ++i) { + if (i != -1 && domain[i] != '.') { + continue; + } + counts[domain.substr(i + 1)] += count; + } + } + + vector result; + for (const auto& count : counts) { + result.emplace_back(to_string(count.second)); + result.back() += " "; + result.back() += count.first; + } + return result; + } +}; From 1e0b63039edff116a313e8023bc3067f7cc20a78 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 2 Apr 2018 01:12:37 +0800 Subject: [PATCH 4599/4971] Update 3sum.py --- Python/3sum.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/3sum.py b/Python/3sum.py index 404c19099..66958d1c6 100644 --- a/Python/3sum.py +++ b/Python/3sum.py @@ -62,6 +62,7 @@ def threeSum2(self, nums): rtn.append(sorted([j, y, 0 - j - y])) return rtn + if __name__ == '__main__': result = Solution().threeSum([-1, 0, 1, 2, -1, -4]) - print result + print(result) From 62b6b8f8b254bd860306b9314016074191aa8a25 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 2 Apr 2018 22:52:32 +0800 Subject: [PATCH 4600/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index ab6480ec1..463018225 100644 --- a/README.md +++ b/README.md @@ -212,6 +212,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 796| [Rotate String](https://leetcode.com/problems/rotate-string/) | [C++](./C++/rotate-string.cpp) [Python](./Python/rotate-string.py) | _O(n)_ | _O(1)_ | Easy || `KMP Algorithm` `Rabin-Karp Algorithm` | 804| [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/) | [C++](./C++/unique-morse-code-words.cpp) [Python](./Python/unique-morse-code-words.py) | _O(n)_ | _O(n)_ | Easy ||| 806| [Number of Lines To Write String](https://leetcode.com/problems/number-of-lines-to-write-string/) | [C++](./C++/number-of-lines-to-write-string.cpp) [Python](./Python/number-of-lines-to-write-string.py) | _O(n)_ | _O(1)_ | Easy ||| +809| [Expressive Words](https://leetcode.com/problems/expressive-words/) | [C++](./C++/expressive-words.cpp) [Python](./Python/expressive-words.py) | _O(n + s)_ | _O(l + s)_ | Medium ||| ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -381,6 +382,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 748 | [Shortest Completing Word](https://leetcode.com/problems/shortest-completing-word/) | [C++](./C++/shortest-completing-word.cpp) [Python](./Python/shortest-completing-word.py) | _O(n)_ | _O(1)_ | Easy || 760 | [Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings/) | [C++](./C++/find-anagram-mappings.cpp) [Python](./Python/find-anagram-mappings.py) | _O(n)_ | _O(n)_ | Easy || 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/) | [C++](./C++/jewels-and-stones.cpp) [Python](./Python/jewels-and-stones.py) | _O(m + n)_ | _O(n)_ | Easy || +811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [C++](./C++/subdomain-visit-count.cpp) [Python](./Python/subdomain-visit-count.py) | _O(n)_ | _O(n)_ | Easy || ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -447,6 +449,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 782 | [Transform to Chessboard](https://leetcode.com/problems/transform-to-chessboard/) | [C++](./C++/transform-to-chessboard.cpp) [Python](./Python/transform-to-chessboard.py) | _O(n^2)_ | _O(n)_ | Hard || 789 | [Escape The Ghosts](https://leetcode.com/problems/escape-the-ghosts/) | [C++](./C++/escape-the-ghosts.cpp) [Python](./Python/escape-the-ghosts.py) | _O(n)_ | _O(1)_ | Medium || 800 | [Similar RGB Color](https://leetcode.com/problems/similar-rgb-color/) | [C++](./C++/similar-rgb-color.cpp) [Python](./Python/similar-rgb-color.py) | _O(1)_ | _O(1)_ | Easy |📖|| +810 | [Chalkboard XOR Game](https://leetcode.com/problems/chalkboard-xor-game/) | [C++](./C++/chalkboard-xor-game.cpp) [Python](./Python/chalkboard-xor-game.py) | _O(1)_ | _O(1)_ | Hard ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -756,6 +759,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 799 | [Champagne Tower](https://leetcode.com/problems/champagne-tower/) | [C++](./C++/champagne-tower.cpp) [Python](./Python/champagne-tower.py) | _O(n^2)_ | _O(n)_ | Medium ||| 801 | [Minimum Swaps To Make Sequences Increasing](https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/) | [C++](./C++/minimum-swaps-to-make-sequences-increasing.cpp) [Python](./Python/minimum-swaps-to-make-sequences-increasing.py) | _O(n)_ | _O(1)_ | Medium ||| 805 | [Split Array With Same Average](https://leetcode.com/problems/split-array-with-same-average/) | [C++](./C++/split-array-with-same-average.cpp) [Python](./Python/split-array-with-same-average.py) | _O(n^4)_ | _O(n^3)_ | Hard ||| +808 | [Soup Servings](https://leetcode.com/problems/soup-servings/) | [C++](./C++/soup-servings.cpp) [Python](./Python/soup-servings.py) | _O(1)_ | _O(1)_ | Medium || Memoization | ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 5487d5452810030a7f7b700d0d992b185c3834a7 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 3 Apr 2018 00:27:19 +0800 Subject: [PATCH 4601/4971] Fix flake8 related issues --- Python/01-matrix.py | 5 +++++ Python/1-bit-and-2-bit-characters.py | 20 ++++++++++++++------ Python/132-pattern.py | 6 ++++++ Python/2-keys-keyboard.py | 7 +++++-- Python/24-game.py | 26 +++++++++++++++++--------- Python/3sum-closest.py | 12 +++++++----- Python/3sum-smaller.py | 1 + Python/3sum.py | 1 + Python/4-keys-keyboard.py | 20 ++++++++++++++------ Python/4sum-ii.py | 6 ++++-- Python/4sum.py | 15 +++++++++++---- 11 files changed, 85 insertions(+), 34 deletions(-) diff --git a/Python/01-matrix.py b/Python/01-matrix.py index 46351da5a..479a22a42 100644 --- a/Python/01-matrix.py +++ b/Python/01-matrix.py @@ -35,6 +35,11 @@ import collections +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class Solution(object): def updateMatrix(self, matrix): diff --git a/Python/1-bit-and-2-bit-characters.py b/Python/1-bit-and-2-bit-characters.py index a92f26b67..4aa5410d5 100644 --- a/Python/1-bit-and-2-bit-characters.py +++ b/Python/1-bit-and-2-bit-characters.py @@ -1,25 +1,27 @@ # Time: O(n) # Space: O(1) -# We have two special characters. The first character can be represented by one bit 0. +# We have two special characters. The first character can be represented +# by one bit 0. # The second character can be represented by two bits (10 or 11). # -# Now given a string represented by several bits. Return whether the last character must +# Now given a string represented by several bits. +# Return whether the last character must # be a one-bit character or not. The given string will always end with a zero. # # Example 1: -# Input: +# Input: # bits = [1, 0, 0] # Output: True -# Explanation: +# Explanation: # The only way to decode it is two-bit character and one-bit character. # So the last character is one-bit character. # # Example 2: -# Input: +# Input: # bits = [1, 1, 1, 0] # Output: False -# Explanation: +# Explanation: # The only way to decode it is two-bit character and two-bit character. # So the last character is NOT one-bit character. # Note: @@ -27,6 +29,12 @@ # 1 <= len(bits) <= 1000. # bits[i] is always 0 or 1. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def isOneBitCharacter(self, bits): """ diff --git a/Python/132-pattern.py b/Python/132-pattern.py index 0ad03e480..15e0aecbc 100644 --- a/Python/132-pattern.py +++ b/Python/132-pattern.py @@ -27,6 +27,12 @@ # # Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0]. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def find132pattern(self, nums): """ diff --git a/Python/2-keys-keyboard.py b/Python/2-keys-keyboard.py index 24282da4d..220adbe6a 100644 --- a/Python/2-keys-keyboard.py +++ b/Python/2-keys-keyboard.py @@ -4,10 +4,12 @@ # Initially on a notepad only one character 'A' is present. # You can perform two operations on this notepad for each step: # -# Copy All: You can copy all the characters present on the notepad (partial copy is not allowed). +# Copy All: You can copy all the characters present on the notepad +# (partial copy is not allowed). # Paste: You can paste the characters which are copied last time. # Given a number n. -# You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. +# You have to get exactly n 'A' on the notepad by performing the minimum +# number of steps permitted. # Output the minimum number of steps to get n 'A'. # # Example 1: @@ -21,6 +23,7 @@ # Note: # The n will be in the range [1, 1000]. + class Solution(object): def minSteps(self, n): """ diff --git a/Python/24-game.py b/Python/24-game.py index bd91f330a..995ada2f7 100644 --- a/Python/24-game.py +++ b/Python/24-game.py @@ -14,11 +14,21 @@ # Note: # The division operator / represents real division, not integer division. # For example, 4 / (1 - 2/3) = 12. -# Every operation done is between two numbers. In particular, we cannot use - as a unary operator. -# For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed. -# You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12. +# Every operation done is between two numbers. In particular, +# we cannot use - as a unary operator. +# For example, with [1, 1, 1, 1] as input, +# the expression -1 - 1 - 1 - 1 is not allowed. +# You cannot concatenate numbers together. For example, +# if the input is [1, 2, 1, 2], we cannot write this as 12 + 12. from operator import add, sub, mul, truediv +from fractions import Fraction + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class Solution(object): def judgePoint24(self, nums): @@ -47,9 +57,6 @@ def judgePoint24(self, nums): # Time: O(n^3 * 4^n) = O(1), n = 4 # Space: O(n^2) = O(1) -from fractions import Fraction -from operator import add, sub, mul, div - class Solution2(object): def judgePoint24(self, nums): """ @@ -59,15 +66,16 @@ def judgePoint24(self, nums): def dfs(nums): if len(nums) == 1: return nums[0] == 24 - ops = [add, sub, mul, div] + ops = [add, sub, mul, truediv] for i in xrange(len(nums)): for j in xrange(len(nums)): if i == j: continue - next_nums = [nums[k] for k in xrange(len(nums)) if i != k != j] + next_nums = [nums[k] for k in xrange(len(nums)) + if i != k != j] for op in ops: if ((op is add or op is mul) and j > i) or \ - (op == div and nums[j] == 0): + (op == truediv and nums[j] == 0): continue next_nums.append(op(nums[i], nums[j])) if dfs(next_nums): diff --git a/Python/3sum-closest.py b/Python/3sum-closest.py index 742e1fa57..037308299 100644 --- a/Python/3sum-closest.py +++ b/Python/3sum-closest.py @@ -1,9 +1,10 @@ # Time: O(n^2) # Space: O(1) -# -# Given an array S of n integers, -# find three integers in S such that the sum is closest to a given number, target. -# Return the sum of the three integers. + +# Given an array S of n integers, +# find three integers in S such that the sum is closest to a given number, +# target. +# Return the sum of the three integers. # You may assume that each input would have exactly one solution. # # For example, given array S = {-1 2 1 -4}, and target = 1. @@ -36,6 +37,7 @@ def threeSumClosest(self, nums, target): i += 1 return result + if __name__ == '__main__': result = Solution().threeSumClosest([-1, 2, 1, -4], 1) - print result + print(result) diff --git a/Python/3sum-smaller.py b/Python/3sum-smaller.py index bcc9b533b..010ce9788 100644 --- a/Python/3sum-smaller.py +++ b/Python/3sum-smaller.py @@ -1,6 +1,7 @@ # Time: O(n^2) # Space: O(1) + class Solution: # @param {integer[]} nums # @param {integer} target diff --git a/Python/3sum.py b/Python/3sum.py index 66958d1c6..9418463fd 100644 --- a/Python/3sum.py +++ b/Python/3sum.py @@ -13,6 +13,7 @@ # A solution set is: # (-1, 0, 1) # (-1, -1, 2) + import collections diff --git a/Python/4-keys-keyboard.py b/Python/4-keys-keyboard.py index 38d212b56..45edbdf56 100644 --- a/Python/4-keys-keyboard.py +++ b/Python/4-keys-keyboard.py @@ -1,20 +1,28 @@ # Time: O(1) # Space: O(1) +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def maxA(self, N): """ :type N: int :rtype: int """ - if N < 7: return N - if N == 10: return 20 # the following rule doesn't hold when N = 10 + if N < 7: + return N + if N == 10: + return 20 # the following rule doesn't hold when N = 10 - n = N // 5 + 1 # n3 + n4 increases one every 5 keys + n = N // 5 + 1 # n3 + n4 increases one every 5 keys # (1) n = n3 + n4 # (2) N + 1 = 4 * n3 + 5 * n4 # 5 x (1) - (2) => 5*n - N - 1 = n3 - n3 = 5*n - N - 1 + n3 = 5*n - N - 1 n4 = n - n3 return 3**n3 * 4**n4 @@ -27,9 +35,9 @@ def maxA(self, N): :type N: int :rtype: int """ - if N < 7: return N + if N < 7: + return N dp = range(N+1) for i in xrange(7, N+1): dp[i % 6] = max(dp[(i-4) % 6]*3, dp[(i-5) % 6]*4) return dp[N % 6] - diff --git a/Python/4sum-ii.py b/Python/4sum-ii.py index a11bede5a..7ca13bab2 100644 --- a/Python/4sum-ii.py +++ b/Python/4sum-ii.py @@ -5,8 +5,10 @@ # compute how many tuples (i, j, k, l) there are # such that A[i] + B[j] + C[k] + D[l] is zero. # -# To make problem a bit easier, all A, B, C, D have same length of N where 0 <= N <= 500. -# All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. +# To make problem a bit easier, all A, B, C, D have same length of N +# where 0 <= N <= 500. +# All integers are in the range of -228 to 228 - 1 and the result +# is guaranteed to be at most 231 - 1. # # Example: # diff --git a/Python/4sum.py b/Python/4sum.py index 6f137b1ef..d2695e838 100644 --- a/Python/4sum.py +++ b/Python/4sum.py @@ -6,7 +6,8 @@ # Find all unique quadruplets in the array which gives the sum of target. # # Note: -# Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a <= b <= c <= d) +# Elements in a quadruplet (a,b,c,d) must be in non-descending order. +# (ie, a <= b <= c <= d) # The solution set must not contain duplicate quadruplets. # For example, given array S = {1 0 -1 0 -2 2}, and target = 0. # @@ -18,6 +19,11 @@ import collections +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + # Two pointer solution. (1356ms) class Solution(object): @@ -104,9 +110,10 @@ def fourSum(self, nums, target): for i in lookup.keys(): if target - i in lookup: for x in lookup[i]: - for y in lookup[target -i]: + for y in lookup[target - i]: [a, b], [c, d] = x, y - if a is not c and a is not d and b is not c and b is not d: + if a is not c and a is not d and \ + b is not c and b is not d: quad = sorted([nums[a], nums[b], nums[c], nums[d]]) if quad not in result: result.append(quad) @@ -115,4 +122,4 @@ def fourSum(self, nums, target): if __name__ == '__main__': result = Solution().fourSum([1, 0, -1, 0, -2, 2], 0) - print result + print(result) From 59435506c5aae62d860b5e008d0942af389c606a Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 3 Apr 2018 00:30:16 +0800 Subject: [PATCH 4602/4971] Fix flake8 related issues --- Python/3sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/3sum.py b/Python/3sum.py index 9418463fd..beb1fe040 100644 --- a/Python/3sum.py +++ b/Python/3sum.py @@ -1,6 +1,6 @@ # Time: O(n^2) # Space: O(1) -# + # Given an array S of n integers, # are there elements a, b, c in S such that a + b + c = 0? # Find all unique triplets in the array which gives the sum of zero. From bdd6dc441d8ef1d6363957a15a21bbc9f774ddda Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 3 Apr 2018 00:47:07 +0800 Subject: [PATCH 4603/4971] Fix flake8 related issues --- Python/3sum-closest.py | 5 ----- Python/3sum.py | 5 ----- Python/4sum.py | 5 ----- 3 files changed, 15 deletions(-) diff --git a/Python/3sum-closest.py b/Python/3sum-closest.py index 037308299..a1ece7507 100644 --- a/Python/3sum-closest.py +++ b/Python/3sum-closest.py @@ -36,8 +36,3 @@ def threeSumClosest(self, nums, target): return target i += 1 return result - - -if __name__ == '__main__': - result = Solution().threeSumClosest([-1, 2, 1, -4], 1) - print(result) diff --git a/Python/3sum.py b/Python/3sum.py index beb1fe040..7015e4208 100644 --- a/Python/3sum.py +++ b/Python/3sum.py @@ -62,8 +62,3 @@ def threeSum2(self, nums): if sorted([j, y, 0 - j - y]) not in rtn: rtn.append(sorted([j, y, 0 - j - y])) return rtn - - -if __name__ == '__main__': - result = Solution().threeSum([-1, 0, 1, 2, -1, -4]) - print(result) diff --git a/Python/4sum.py b/Python/4sum.py index d2695e838..36c5aca2d 100644 --- a/Python/4sum.py +++ b/Python/4sum.py @@ -118,8 +118,3 @@ def fourSum(self, nums, target): if quad not in result: result.append(quad) return sorted(result) - - -if __name__ == '__main__': - result = Solution().fourSum([1, 0, -1, 0, -2, 2], 0) - print(result) From 27f3fc076e39783836c5c695031cc38baaadf859 Mon Sep 17 00:00:00 2001 From: Aven Xiangwen Liu Date: Wed, 4 Apr 2018 16:35:15 -0500 Subject: [PATCH 4604/4971] Update shortest-unsorted-continuous-subarray.py --- Python/shortest-unsorted-continuous-subarray.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Python/shortest-unsorted-continuous-subarray.py b/Python/shortest-unsorted-continuous-subarray.py index bed6c7a6a..c90f4401e 100644 --- a/Python/shortest-unsorted-continuous-subarray.py +++ b/Python/shortest-unsorted-continuous-subarray.py @@ -32,3 +32,19 @@ def findUnsortedSubarray(self, nums): if nums[i] < max_from_left: right = i if nums[n-1-i] > min_from_right: left = n-1-i return right - left + 1 + #another faster easy solution + def findUnsortedSubarray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + a = sorted(nums) #sort the list + left, right = 0, len(nums) -1 #define left and right pointer + while (nums[left] == a[left] or nums[right] == a[right]): + if right - left <= 1: + return 0 + if nums[left] == a[left]: + left += 1 + if nums[right] == a[right]: + right -= 1 + return right - left + 1 From a576e113c651c96138ae0f88cb6e497674e34e5e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 5 Apr 2018 08:40:58 +0800 Subject: [PATCH 4605/4971] Update shortest-unsorted-continuous-subarray.py --- Python/shortest-unsorted-continuous-subarray.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Python/shortest-unsorted-continuous-subarray.py b/Python/shortest-unsorted-continuous-subarray.py index c90f4401e..1de3ba3fe 100644 --- a/Python/shortest-unsorted-continuous-subarray.py +++ b/Python/shortest-unsorted-continuous-subarray.py @@ -31,8 +31,11 @@ def findUnsortedSubarray(self, nums): min_from_right = min(min_from_right, nums[n-1-i]) if nums[i] < max_from_left: right = i if nums[n-1-i] > min_from_right: left = n-1-i - return right - left + 1 - #another faster easy solution + + +# Time: O(nlogn) +# Space: O(n) +class Solution2(object): def findUnsortedSubarray(self, nums): """ :type nums: List[int] From d0c658666bd24d918f07a1bc7c678520ff42611b Mon Sep 17 00:00:00 2001 From: Aven Xiangwen Liu Date: Thu, 5 Apr 2018 16:27:35 -0500 Subject: [PATCH 4606/4971] Update maximum-average-subarray-i.py --- Python/maximum-average-subarray-i.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Python/maximum-average-subarray-i.py b/Python/maximum-average-subarray-i.py index 7f39cf7a6..d59f8ccfa 100644 --- a/Python/maximum-average-subarray-i.py +++ b/Python/maximum-average-subarray-i.py @@ -20,10 +20,7 @@ def findMaxAverage(self, nums, k): :type k: int :rtype: float """ - total = 0 - for i in xrange(k): - total += nums[i] - result = total + result = total = sum(nums[:k]) for i in xrange(k, len(nums)): total += nums[i] - nums[i-k] result = max(result, total) From 9ac94f02a785c8ff5e29a9db0a7f941c7d8bda77 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 8 Apr 2018 16:01:42 +0800 Subject: [PATCH 4607/4971] Add largest-sum-of-averages.py --- Python/largest-sum-of-averages.py | 56 +++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/largest-sum-of-averages.py diff --git a/Python/largest-sum-of-averages.py b/Python/largest-sum-of-averages.py new file mode 100644 index 000000000..48b56640b --- /dev/null +++ b/Python/largest-sum-of-averages.py @@ -0,0 +1,56 @@ +# Time: O(k * n^2) +# Space: O(n) + +# We partition a row of numbers A into at most K adjacent (non-empty) groups, +# then our score is the sum of the average of each group. What is the largest +# score we can achieve? +# +# Note that our partition must use every number in A, and that scores are not +# necessarily integers. +# +# Example: +# Input: +# A = [9,1,2,3,9] +# K = 3 +# Output: 20 +# Explanation: +# The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is +# 39 + (1 + 2 + 3) / 3 + 9 = 20. +# We could have also partitioned A into [9, 1], [2], [3, 9], for example. +# That partition would lead to a score of 5 + 2 + 6 = 13, which is worse. +# +# Note: +# - 1 <= A.length <= 100. +# - 1 <= A[i] <= 10000. +# - 1 <= K <= A.length. +# Answers within 10^-6 of the correct answer will be accepted as correct. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def largestSumOfAverages(self, A, K): + """ + :type A: List[int] + :type K: int + :rtype: float + """ + accum_sum = [A[0]] + for i in xrange(1, len(A)): + accum_sum.append(A[i]+accum_sum[-1]) + + dp = [[0]*len(A) for _ in xrange(2)] + for k in xrange(1, K+1): + for i in xrange(k-1, len(A)): + if k == 1: + dp[k % 2][i] = float(accum_sum[i])/(i+1) + else: + for j in xrange(k-2, i): + dp[k % 2][i] = \ + max(dp[k % 2][i], + dp[(k-1) % 2][j] + + float(accum_sum[i]-accum_sum[j])/(i-j)) + return dp[K % 2][-1] From bac7ad156c13c163e097f6999384aa8064418c8b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Apr 2018 16:02:42 +0800 Subject: [PATCH 4608/4971] Create largest-sum-of-averages.cpp --- C++/largest-sum-of-averages.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/largest-sum-of-averages.cpp diff --git a/C++/largest-sum-of-averages.cpp b/C++/largest-sum-of-averages.cpp new file mode 100644 index 000000000..4808b9d63 --- /dev/null +++ b/C++/largest-sum-of-averages.cpp @@ -0,0 +1,29 @@ +// Time: O(k * n^2) +// Space: O(n) + +class Solution { +public: + double largestSumOfAverages(vector& A, int K) { + vector accum_sum; + accum_sum.emplace_back(A[0]); + for (int i = 1; i < A.size(); ++i) { + accum_sum.emplace_back(A[i] + accum_sum.back()); + } + + vector> dp(2, vector(A.size())); + for (int k = 1; k <= K; ++k) { + for (int i = k - 1; i < A.size(); ++i) { + if (k == 1) { + dp[k % 2][i] = static_cast(accum_sum[i]) / (i + 1); + } else { + for (int j = k - 2 ; j < i; ++j) { + dp[k % 2][i] = max(dp[k % 2][i], + dp[(k - 1) % 2][j] + + static_cast(accum_sum[i] - accum_sum[j]) / (i - j)); + } + } + } + } + return dp[K % 2].back(); + } +}; From aae934eacd70f882daac27217f12be418defbb8d Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 8 Apr 2018 16:15:24 +0800 Subject: [PATCH 4609/4971] Add largest-triangle-area.py --- Python/largest-triangle-area.py | 44 +++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/largest-triangle-area.py diff --git a/Python/largest-triangle-area.py b/Python/largest-triangle-area.py new file mode 100644 index 000000000..cf8f2b08f --- /dev/null +++ b/Python/largest-triangle-area.py @@ -0,0 +1,44 @@ +# Time: O(n^3) +# Space: O(1) + +# You have a list of points in the plane. Return the area of the largest +# triangle +# that can be formed by any 3 of the points. +# +# Example: +# Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]] +# Output: 2 +# Explanation: +# The five points are show in the figure below. The red triangle is the +# largest. +# +# Notes: +# - 3 <= points.length <= 50. +# - No points will be duplicated. +# - -50 <= points[i][j] <= 50. +# - Answers within 10^-6 of the true value will be accepted as correct. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def largestTriangleArea(self, points): + """ + :type points: List[List[int]] + :rtype: float + """ + result = 0 + for i in xrange(len(points)-2): + for j in xrange(i+1, len(points)-1): + for k in xrange(j+1, len(points)): + result = max(result, + 0.5 * abs(points[i][0] * points[j][1] + + points[j][0] * points[k][1] + + points[k][0] * points[i][1] - + points[j][0] * points[i][1] - + points[k][0] * points[j][1] - + points[i][0] * points[k][1])) + return result From 25e3d9648d6c4715dd769a5405a23b1cc0921499 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Apr 2018 16:16:26 +0800 Subject: [PATCH 4610/4971] Create largest-triangle-area.cpp --- C++/largest-triangle-area.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/largest-triangle-area.cpp diff --git a/C++/largest-triangle-area.cpp b/C++/largest-triangle-area.cpp new file mode 100644 index 000000000..2b42facfb --- /dev/null +++ b/C++/largest-triangle-area.cpp @@ -0,0 +1,23 @@ +// Time: O(n^3) +// Space: O(1) + +class Solution { +public: + double largestTriangleArea(vector>& points) { + double result = 0.0; + for (int i = 0; i < points.size() - 2; ++i) { + for (int j = i + 1; j < points.size() - 1; ++j) { + for (int k = j + 1; k < points.size(); ++k) { + result = max(result, + 0.5 * abs(points[i][0] * points[j][1] + + points[j][0] * points[k][1] + + points[k][0] * points[i][1] - + points[j][0] * points[i][1] - + points[k][0] * points[j][1] - + points[i][0] * points[k][1])); + } + } + } + return result; + } +}; From 0b00a8368d3297e8f8be0d93b17cb7e7e0a5a000 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Apr 2018 16:18:42 +0800 Subject: [PATCH 4611/4971] Create binary-tree-pruning.cpp --- C++/binary-tree-pruning.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/binary-tree-pruning.cpp diff --git a/C++/binary-tree-pruning.cpp b/C++/binary-tree-pruning.cpp new file mode 100644 index 000000000..cfb22cd9e --- /dev/null +++ b/C++/binary-tree-pruning.cpp @@ -0,0 +1,26 @@ +// 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: + TreeNode* pruneTree(TreeNode* root) { + if (!root) { + return nullptr; + } + root->left = pruneTree(root->left); + root->right = pruneTree(root->right); + if (!root->left && !root->right && root->val == 0) { + return nullptr; + } + return root; + } +}; From 399579b750ffd83c22e590891abbbee094e64098 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 8 Apr 2018 16:24:27 +0800 Subject: [PATCH 4612/4971] Create binary-tree-pruning.py --- Python/binary-tree-pruning.py | 53 +++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/binary-tree-pruning.py diff --git a/Python/binary-tree-pruning.py b/Python/binary-tree-pruning.py new file mode 100644 index 000000000..4d32ade90 --- /dev/null +++ b/Python/binary-tree-pruning.py @@ -0,0 +1,53 @@ +# Time: O(n) +# Space: O(h) + +# We are given the head node root of a binary tree, +# where additionally every node's value is either a 0 or a 1. +# +# Return the same tree where every subtree (of the given tree) +# not containing a 1 has been removed. +# +# (Recall that the subtree of a node X is X, +# plus every node that is a descendant of X.) +# +# Example 1: +# Input: [1,null,0,0,1] +# Output: [1,null,0,null,1] +# +# Explanation: +# Only the red nodes satisfy the property "every subtree not containing a 1". +# The diagram on the right represents the answer. +# +# Example 2: +# Input: [1,0,1,0,0,0,1] +# Output: [1,null,1,null,1] +# +# Example 3: +# Input: [1,1,0,1,1,0,1,0] +# Output: [1,1,0,1,1,null,1] +# +# Note: +# - The binary tree will have at most 100 nodes. +# - The value of each node will only be 0 or 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 pruneTree(self, root): + """ + :type root: TreeNode + :rtype: TreeNode + """ + if not root: + return None + root.left = self.pruneTree(root.left) + root.right = self.pruneTree(root.right) + if not root.left and not root.right and root.val == 0: + return None + return root From ab5ce88b998add38319173112c842104234a4785 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 8 Apr 2018 17:45:58 +0800 Subject: [PATCH 4613/4971] Create bus-routes.py --- Python/bus-routes.py | 67 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Python/bus-routes.py diff --git a/Python/bus-routes.py b/Python/bus-routes.py new file mode 100644 index 000000000..ddcda2572 --- /dev/null +++ b/Python/bus-routes.py @@ -0,0 +1,67 @@ +# Time: O(|V| + |E|) +# Space: O(|V| + |E|) + +# We have a list of bus routes. Each routes[i] is a bus route that +# the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], +# this means that the first bus (0-th indexed) travels in the sequence +# 1->5->7->1->5->7->1->... forever. +# +# We start at bus stop S (initially not on a bus), and we want to go to bus +# stop T. +# Travelling by buses only, what is the least number of buses we must take to +# reach our destination? +# Return -1 if it is not possible. +# +# Example: +# Input: +# routes = [[1, 2, 7], [3, 6, 7]] +# S = 1 +# T = 6 +# Output: 2 +# Explanation: +# The best strategy is take the first bus to the bus stop 7, +# then take the second bus to the bus stop 6. +# +# Note: +# - 1 <= routes.length <= 500. +# - 1 <= routes[i].length <= 500. +# - 0 <= routes[i][j] < 10 ^ 6. + +import collections + + +class Solution(object): + def numBusesToDestination(self, routes, S, T): + """ + :type routes: List[List[int]] + :type S: int + :type T: int + :rtype: int + """ + if S == T: + return 0 + + to_route = collections.defaultdict(set) + for i, route in enumerate(routes): + for stop in route: + to_route[stop].add(i) + + result = 1 + q = [S] + lookup = set([S]) + while q: + next_q = [] + for stop in q: + for i in to_route[stop]: + for next_stop in routes[i]: + if next_stop in lookup: + continue + if next_stop == T: + return result + next_q.append(next_stop) + to_route[next_stop].remove(i) + lookup.add(next_stop) + q = next_q + result += 1 + + return -1 From 86b28056f6d2ca32d8270b4b7caef4c29e395823 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Apr 2018 17:46:29 +0800 Subject: [PATCH 4614/4971] Create bus-routes.cpp --- C++/bus-routes.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/bus-routes.cpp diff --git a/C++/bus-routes.cpp b/C++/bus-routes.cpp new file mode 100644 index 000000000..459c2f3c0 --- /dev/null +++ b/C++/bus-routes.cpp @@ -0,0 +1,42 @@ +// Time: O(|V| + |E|) +// Space: O(|V| + |E|) + +class Solution { +public: + int numBusesToDestination(vector>& routes, int S, int T) { + if (S == T) { + return 0; + } + unordered_map> to_route; + for (int i = 0; i < routes.size(); ++i) { + for (const auto& stop : routes[i]) { + to_route[stop].emplace(i); + } + } + + int result = 1; + vector q({S}); + unordered_set lookup({S}); + while (!q.empty()) { + vector next_q; + for (const auto& stop : q) { + for (const auto& i : to_route[stop]) { + for (const auto& next_stop : routes[i]) { + if (lookup.count(next_stop)) { + continue; + } + if (next_stop == T) { + return result; + } + next_q.emplace_back(next_stop); + to_route[next_stop].erase(i); + lookup.emplace(next_stop); + } + } + } + swap(q, next_q); + ++result; + } + return -1; + } +}; From 526ed7722c8550778b1f8af74d6f8e17ea8d0fba Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Apr 2018 17:49:08 +0800 Subject: [PATCH 4615/4971] Update bus-routes.cpp --- C++/bus-routes.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/bus-routes.cpp b/C++/bus-routes.cpp index 459c2f3c0..815c35f2f 100644 --- a/C++/bus-routes.cpp +++ b/C++/bus-routes.cpp @@ -15,8 +15,8 @@ class Solution { } int result = 1; - vector q({S}); - unordered_set lookup({S}); + vector q{S}; + unordered_set lookup{S}; while (!q.empty()) { vector next_q; for (const auto& stop : q) { From d0e056bfffda5958b62c07f52ecd5a1bf821a01b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Apr 2018 17:55:48 +0800 Subject: [PATCH 4616/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 463018225..f39418124 100644 --- a/README.md +++ b/README.md @@ -326,6 +326,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 685 | [Redundant Connection II](https://leetcode.com/problems/redundant-connection-ii/) | [C++](./C++/redundant-connection-ii.cpp) [Python](./Python/redundant-connection-ii.py) | _O(n)_ | _O(n)_ | Hard || Union Find 687 | [Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/) | [C++](./C++/longest-univalue-path.cpp) [Python](./Python/longest-univalue-path.py) | _O(n)_ | _O(h)_ | Easy || 699 | [Falling Squares](https://leetcode.com/problems/falling-squares/) | [C++](./C++/falling-squares.cpp) [Python](./Python/falling-squares.py) | _O(nlogn)_ | _O(n)_ | Hard || Segment Tree | +814 | [Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning/) | [C++](./C++/binary-tree-pruning.cpp) [Python](./Python/binary-tree-pruning.py) | _O(n)_ | _O(h)_ | Medium || DFS | ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -450,6 +451,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 789 | [Escape The Ghosts](https://leetcode.com/problems/escape-the-ghosts/) | [C++](./C++/escape-the-ghosts.cpp) [Python](./Python/escape-the-ghosts.py) | _O(n)_ | _O(1)_ | Medium || 800 | [Similar RGB Color](https://leetcode.com/problems/similar-rgb-color/) | [C++](./C++/similar-rgb-color.cpp) [Python](./Python/similar-rgb-color.py) | _O(1)_ | _O(1)_ | Easy |📖|| 810 | [Chalkboard XOR Game](https://leetcode.com/problems/chalkboard-xor-game/) | [C++](./C++/chalkboard-xor-game.cpp) [Python](./Python/chalkboard-xor-game.py) | _O(1)_ | _O(1)_ | Hard ||| +812 | [Largest Triangle Area](https://leetcode.com/problems/largest-triangle-areae/) | [C++](./C++/largest-triangle-area.cpp) [Python](./Python/largest-triangle-area.py) | _O(n^3)_ | _O(1)_ | Easy ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -603,6 +605,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 752|[Open the Lock](https://leetcode.com/problems/open-the-lock/)| [C++](./C++/open-the-lock.cpp) [Python](./Python/open-the-lock.py)| _O(k * n^k + d)_ | _O(k * n^k + d)_ | Medium | | | 773|[Sliding Puzzle](https://leetcode.com/problems/sliding-puzzle/)| [C++](./C++/sliding-puzzle.cpp) [Python](./Python/sliding-puzzle.py)| _O((m * n) * (m * n)!)_ | _O((m * n) * (m * n)!)_ | Hard | | `A* Search Algorithm` | 787|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| [C++](./C++/cheapest-flights-within-k-stops.cpp) [Python](./Python/cheapest-flights-within-k-stops.py)| _O(\|E\| + \|V\|log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | +815|[Bus Routes](https://leetcode.com/problems/bus-routes/)| [C++](./C++/bus-routes.cpp) [Python](./Python/bus-routes.py)| _O(\|E\| + \|V\|)_ | _O(\|E\| + \|V\|)_ | Hard | | | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -760,6 +763,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 801 | [Minimum Swaps To Make Sequences Increasing](https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/) | [C++](./C++/minimum-swaps-to-make-sequences-increasing.cpp) [Python](./Python/minimum-swaps-to-make-sequences-increasing.py) | _O(n)_ | _O(1)_ | Medium ||| 805 | [Split Array With Same Average](https://leetcode.com/problems/split-array-with-same-average/) | [C++](./C++/split-array-with-same-average.cpp) [Python](./Python/split-array-with-same-average.py) | _O(n^4)_ | _O(n^3)_ | Hard ||| 808 | [Soup Servings](https://leetcode.com/problems/soup-servings/) | [C++](./C++/soup-servings.cpp) [Python](./Python/soup-servings.py) | _O(1)_ | _O(1)_ | Medium || Memoization | +813 | [Largest Sum of Averages](https://leetcode.com/problems/largest-sum-of-averages/) | [C++](./C++/largest-sum-of-averages.cpp) [Python](./Python/largest-sum-of-averages.py) | _O(k * n^2)_ | _O(n)_ | Medium || | ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 9d59230e18de9e84d857c2aed5bef17fae48fe79 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Thu, 12 Apr 2018 01:01:52 +0800 Subject: [PATCH 4617/4971] Fix flake8 related issues --- Python/accounts-merge.py | 35 ++++++++---- ...d-and-search-word-data-structure-design.py | 15 +++-- Python/add-binary.py | 12 ++-- Python/add-bold-tag-in-string.py | 12 +++- Python/add-digits.py | 10 +--- Python/add-one-row-to-tree.py | 56 ++++++++++--------- Python/add-strings.py | 6 +- Python/add-two-numbers-ii.py | 21 ++++--- Python/add-two-numbers.py | 15 ++--- Python/additive-number.py | 20 +++++-- Python/alien-dictionary.py | 3 - Python/all-oone-data-structure.py | 18 +++--- Python/all-paths-from-source-to-target.py | 16 ++++-- Python/android-unlock-patterns.py | 52 +++++++++-------- Python/arithmetic-slices-ii-subsequence.py | 20 +++++-- Python/arithmetic-slices.py | 3 +- Python/arranging-coins.py | 6 +- Python/array-nesting.py | 8 +-- Python/array-partition-i.py | 10 +++- Python/assign-cookies.py | 32 ++++++++--- Python/asteroid-collision.py | 34 +++++++---- Python/average-of-levels-in-binary-tree.py | 11 +++- 22 files changed, 257 insertions(+), 158 deletions(-) diff --git a/Python/accounts-merge.py b/Python/accounts-merge.py index 2eac67d94..dca820b6a 100644 --- a/Python/accounts-merge.py +++ b/Python/accounts-merge.py @@ -1,4 +1,5 @@ -# Time: O(nlogn), n is the number of total emails, and the max length of email is 320, p.s. {64}@{255} +# Time: O(nlogn), n is the number of total emails, +# and the max length ofemail is 320, p.s. {64}@{255} # Space: O(n) # Given a list accounts, each element accounts[i] is a list of strings, @@ -6,13 +7,16 @@ # and the rest of the elements are emails representing emails of the account. # # Now, we would like to merge these accounts. -# Two accounts definitely belong to the same person if there is some email that is common to both accounts. +# Two accounts definitely belong to the same person if there is some email +# that is common to both accounts. # Note that even if two accounts have the same name, # they may belong to different people as people could have the same name. -# A person can have any number of accounts initially, but all of their accounts definitely have the same name. +# A person can have any number of accounts initially, but all of their +# accounts definitely have the same name. # # After merging the accounts, return the accounts in the following format: -# the first element of each account is the name, and the rest of the elements are emails in sorted order. +# the first element of each account is the name, and the rest of the elements +# are emails in sorted order. # The accounts themselves can be returned in any order. # # Example 1: @@ -21,16 +25,20 @@ # ["John", "johnnybravo@mail.com"], # ["John", "johnsmith@mail.com", "john_newyork@mail.com"], # ["Mary", "mary@mail.com"]] -# Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], +# Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', +# 'johnsmith@mail.com'], # ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]] # # Explanation: -# The first and third John's are the same person as they have the common email "johnsmith@mail.com". -# The second John and Mary are different people as none of their email addresses are used by other accounts. +# The first and third John's are the same person as they have the common +# email "johnsmith@mail.com". +# The second John and Mary are different people as none of their email +# addresses are used by other accounts. # We could return these lists in any order, # for example the answer [['Mary', 'mary@mail.com'], # ['John', 'johnnybravo@mail.com'], -# ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] +# ['John', 'john00@mail.com', 'john_newyork@mail.com', +# 'johnsmith@mail.com']] # would still be accepted. # # Note: @@ -41,6 +49,11 @@ import collections +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class UnionFind(object): def __init__(self): @@ -76,11 +89,13 @@ def accountsMerge(self, accounts): if account[i] not in email_to_id: email_to_name[account[i]] = name email_to_id[account[i]] = union_find.get_id() - union_find.union_set(email_to_id[account[1]], email_to_id[account[i]]) + union_find.union_set(email_to_id[account[1]], + email_to_id[account[i]]) result = collections.defaultdict(list) for email in email_to_name.keys(): result[union_find.find_set(email_to_id[email])].append(email) for emails in result.values(): emails.sort() - return [[email_to_name[emails[0]]] + emails for emails in result.values()] + return [[email_to_name[emails[0]]] + emails + for emails in result.values()] diff --git a/Python/add-and-search-word-data-structure-design.py b/Python/add-and-search-word-data-structure-design.py index 384b97d64..aa179b3fd 100644 --- a/Python/add-and-search-word-data-structure-design.py +++ b/Python/add-and-search-word-data-structure-design.py @@ -5,7 +5,8 @@ # # void addWord(word) # bool search(word) -# search(word) can search a literal word or a regular expression string containing only letters a-z or .. +# 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: @@ -21,23 +22,25 @@ # You may assume that all words are consist of lowercase letters a-z. # + class TrieNode: # Initialize your data structure here. def __init__(self): self.is_string = False self.leaves = {} - + + 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.leaves: + if c not in curr.leaves: curr.leaves[c] = TrieNode() curr = curr.leaves[c] curr.is_string = True @@ -48,7 +51,7 @@ def addWord(self, word): # 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.is_string @@ -58,7 +61,7 @@ def searchHelper(self, word, start, curr): for c in curr.leaves: if self.searchHelper(word, start+1, curr.leaves[c]): return True - + return False # Your WordDictionary object will be instantiated and called as such: diff --git a/Python/add-binary.py b/Python/add-binary.py index a2585157c..fd43dfc73 100644 --- a/Python/add-binary.py +++ b/Python/add-binary.py @@ -9,6 +9,12 @@ # Return "100". # +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution: # @param a, a string # @param b, a string @@ -19,14 +25,10 @@ def addBinary(self, a, b): val = carry 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) if carry: result += str(carry) return result[::-1] - -if __name__ == '__main__': - result = Solution().addBinary('11', '1') - print result diff --git a/Python/add-bold-tag-in-string.py b/Python/add-bold-tag-in-string.py index 984d640aa..c8c9ac812 100644 --- a/Python/add-bold-tag-in-string.py +++ b/Python/add-bold-tag-in-string.py @@ -2,6 +2,12 @@ # Space: O(n) import collections +import functools + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 # 59ms @@ -25,7 +31,7 @@ def addBoldTag(self, s, dict): result.append("") result.append(s[i]) if lookup[i] and (i == len(s)-1 or not lookup[i+1]): - result.append(""); + result.append("") return "".join(result) @@ -42,7 +48,7 @@ def addBoldTag(self, s, words): _trie = lambda: collections.defaultdict(_trie) trie = _trie() for i, word in enumerate(words): - reduce(dict.__getitem__, word, trie).setdefault("_end") + functools.reduce(dict.__getitem__, word, trie).setdefault("_end") lookup = [False] * len(s) for i in xrange(len(s)): @@ -63,5 +69,5 @@ def addBoldTag(self, s, words): result.append("") result.append(s[i]) if lookup[i] and (i == len(s)-1 or not lookup[i+1]): - result.append(""); + result.append("") return "".join(result) diff --git a/Python/add-digits.py b/Python/add-digits.py index 5d28264e6..a5c158645 100644 --- a/Python/add-digits.py +++ b/Python/add-digits.py @@ -16,19 +16,13 @@ # Hint: # # A naive implementation of the above process is trivial. -# Could you come up with other methods? +# Could you come up with other methods? -class Solution: +class Solution(object): """ :type num: int :rtype: int """ def addDigits(self, num): return (num - 1) % 9 + 1 if num > 0 else 0 - - -if __name__ == '__main__': - s = Solution() - r = s.addDigits(12345) - print r diff --git a/Python/add-one-row-to-tree.py b/Python/add-one-row-to-tree.py index 2bda9d172..e4622bcf8 100644 --- a/Python/add-one-row-to-tree.py +++ b/Python/add-one-row-to-tree.py @@ -2,70 +2,76 @@ # Space: O(h) # Given the root of a binary tree, then value v and depth d, -# you need to add a row of nodes with value v at the given depth d. The root node is at depth 1. +# you need to add a row of nodes with value v at the given depth d. +# The root node is at depth 1. # # The adding rule is: given a positive integer depth d, # for each NOT null tree nodes N in depth d-1, create two tree nodes # with value v as N's left subtree root and right subtree root. -# And N's original left subtree should be the left subtree of the new left subtree root, -# its original right subtree should be the right subtree of the new right subtree root. +# And N's original left subtree should be the left subtree of +# the new left subtree root, +# its original right subtree should be the right subtree of +# the new right subtree root. # If depth d is 1 that means there is no depth d-1 at all, -# then create a tree node with value v as the new root of the whole original tree, +# then create a tree node with value v as the new root of +# the whole original tree, # and the original tree is the new root's left subtree. # # Example 1: -# Input: +# Input: # A binary tree as following: # 4 # / \ # 2 6 -# / \ / -# 3 1 5 +# / \ / +# 3 1 5 # # v = 1 # # d = 2 # -# Output: +# Output: # 4 # / \ # 1 1 # / \ # 2 6 -# / \ / -# 3 1 5 +# / \ / +# 3 1 5 # # Example 2: -# Input: +# Input: # A binary tree as following: # 4 -# / -# 2 -# / \ -# 3 1 +# / +# 2 +# / \ +# 3 1 # # v = 1 # # d = 3 # -# Output: +# Output: # 4 -# / +# / # 2 -# / \ +# / \ # 1 1 -# / \ +# / \ # 3 1 # Note: # 1. The given d is in range [1, maximum depth of the given tree + 1]. # 2. The given binary tree has at least one tree node. + # Definition for a binary tree node. -# class TreeNode(object): -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + class Solution(object): def addOneRow(self, root, v, d): @@ -83,6 +89,6 @@ def addOneRow(self, root, v, d): node.right = root return node if root and d >= 2: - root.left = self.addOneRow(root.left, v, d-1 if d > 2 else 1) + root.left = self.addOneRow(root.left, v, d-1 if d > 2 else 1) root.right = self.addOneRow(root.right, v, d-1 if d > 2 else 0) return root diff --git a/Python/add-strings.py b/Python/add-strings.py index b70851700..7cf47e0b9 100644 --- a/Python/add-strings.py +++ b/Python/add-strings.py @@ -22,13 +22,13 @@ def addStrings(self, num1, num2): """ result = [] i, j, carry = len(num1) - 1, len(num2) - 1, 0 - + while i >= 0 or j >= 0 or carry: if i >= 0: - carry += ord(num1[i]) - ord('0'); + carry += ord(num1[i]) - ord('0') i -= 1 if j >= 0: - carry += ord(num2[j]) - ord('0'); + carry += ord(num2[j]) - ord('0') j -= 1 result.append(str(carry % 10)) carry /= 10 diff --git a/Python/add-two-numbers-ii.py b/Python/add-two-numbers-ii.py index cde8fc554..7111e061b 100644 --- a/Python/add-two-numbers-ii.py +++ b/Python/add-two-numbers-ii.py @@ -2,24 +2,29 @@ # Space: O(m + n) # You are given two linked lists representing two non-negative numbers. -# The most significant digit comes first and each of their nodes contain a single digit. +# The most significant digit comes first and each of their nodes contain +# a single digit. # Add the two numbers and return it as a linked list. # -# You may assume the two numbers do not contain any leading zero, except the number 0 itself. +# You may assume the two numbers do not contain any leading zero, +# except the number 0 itself. # # Follow up: -# What if you cannot modify the input lists? In other words, reversing the lists is not allowed. +# What if you cannot modify the input lists? In other words, +# reversing the lists is not allowed. # # Example: # # Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) # Output: 7 -> 8 -> 0 -> 7 + # Definition for singly-linked list. -# class ListNode(object): -# def __init__(self, x): -# self.val = x -# self.next = None +class ListNode(object): + def __init__(self, x): + self.val = x + self.next = None + class Solution(object): def addTwoNumbers(self, l1, l2): @@ -44,7 +49,7 @@ def addTwoNumbers(self, l1, l2): sum += stk1.pop() if stk2: sum += stk2.pop() - + head = ListNode(sum % 10) head.next = prev prev = head diff --git a/Python/add-two-numbers.py b/Python/add-two-numbers.py index 6235ca22d..60cd35f1f 100644 --- a/Python/add-two-numbers.py +++ b/Python/add-two-numbers.py @@ -1,19 +1,23 @@ # Time: O(n) # Space: O(1) # -# You are given two linked lists representing two non-negative numbers. -# The digits are stored in reverse order and each of their nodes contain a single digit. +# You are given two linked lists representing two non-negative numbers. +# The digits are stored in reverse order and each of their nodes contain +# a single digit. # Add the two numbers and return it as a linked list. # # Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) # Output: 7 -> 0 -> 8 # + + # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None + class Solution(object): def addTwoNumbers(self, l1, l2): """ @@ -40,10 +44,3 @@ def addTwoNumbers(self, l1, l2): current.next = ListNode(1) return dummy.next - -if __name__ == '__main__': - a, a.next, a.next.next = ListNode(2), ListNode(4), ListNode(3) - 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) - diff --git a/Python/additive-number.py b/Python/additive-number.py index edde1bc02..2a60156ad 100644 --- a/Python/additive-number.py +++ b/Python/additive-number.py @@ -1,14 +1,17 @@ # Time: O(n^3) # Space: O(n) # -# Additive number is a positive integer whose digits can form additive sequence. +# 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 +# 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: +# "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 @@ -26,6 +29,12 @@ # How would you handle overflow for very large input integers? # +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def isAdditiveNumber(self, num): """ @@ -38,7 +47,7 @@ def add(a, b): val = carry 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 / 10, val % 10 res += str(val) @@ -46,14 +55,13 @@ def add(a, b): res += str(carry) return res[::-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 \ (len(s2) > 1 and s2[0] == '0'): continue - + expected = add(s1, s2) cur = s1 + s2 + expected while len(cur) < len(num): diff --git a/Python/alien-dictionary.py b/Python/alien-dictionary.py index 2274736ad..04bd2bddc 100644 --- a/Python/alien-dictionary.py +++ b/Python/alien-dictionary.py @@ -50,7 +50,6 @@ def alienOrder(self, words): return "".join(result) - # Construct the graph. def findEdges(self, word1, word2, in_degree, out_degree): str_len = min(len(word1), len(word2)) @@ -94,7 +93,6 @@ def alienOrder(self, words): return "".join(result) - # Construct the graph. def findEdges(self, word1, word2, ancestors): min_len = min(len(word1), len(word2)) @@ -103,7 +101,6 @@ def findEdges(self, word1, word2, ancestors): 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: diff --git a/Python/all-oone-data-structure.py b/Python/all-oone-data-structure.py index 55327cdd6..81589f3e9 100644 --- a/Python/all-oone-data-structure.py +++ b/Python/all-oone-data-structure.py @@ -3,15 +3,19 @@ # Implement a data structure supporting the following operations: # -# Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. +# Inc(Key) - Inserts a new key with value 1. Or increments an existing +# key by 1. # Key is guaranteed to be a non-empty string. # Dec(Key) - If Key's value is 1, remove it from the data structure. # Otherwise decrements an existing key by 1. If the key does not exist, # this function does nothing. Key is guaranteed to be a non-empty string. -# GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "". -# GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string "". +# GetMaxKey() - Returns one of the keys with maximal value. If no element +# exists, return an empty string "". +# GetMinKey() - Returns one of the keys with minimal value. If no element +# exists, return an empty string "". # Challenge: Perform all these in O(1) time complexity. + class Node(object): """ double linked list node @@ -39,16 +43,16 @@ def erase(self, node): def empty(self): return self.head.next is self.tail - + def begin(self): return self.head.next def end(self): return self.tail - + def front(self): return self.head.next - + def back(self): return self.tail.prev @@ -70,7 +74,7 @@ def inc(self, key): """ if key not in self.bucket_of_key: self.bucket_of_key[key] = self.buckets.insert(self.buckets.begin(), Node(0, set([key]))) - + bucket, next_bucket = self.bucket_of_key[key], self.bucket_of_key[key].next if next_bucket is self.buckets.end() or next_bucket.value > bucket.value+1: next_bucket = self.buckets.insert(next_bucket, Node(bucket.value+1, set())) diff --git a/Python/all-paths-from-source-to-target.py b/Python/all-paths-from-source-to-target.py index cb8feb53f..17ba7f8ea 100644 --- a/Python/all-paths-from-source-to-target.py +++ b/Python/all-paths-from-source-to-target.py @@ -3,14 +3,16 @@ # Space: O(n) # Given a directed, acyclic graph of N nodes. -# Find all possible paths from node 0 to node N-1, and return them in any order. +# Find all possible paths from node 0 to node N-1, and return them +# in any order. # -# The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. +# The graph is given as follows: the nodes are 0, 1, ..., +# graph.length - 1. # graph[i] is a list of all nodes j for which the edge (i, j) exists. # # Example: -# Input: [[1,2], [3], [3], []] -# Output: [[0,1,3],[0,2,3]] +# Input: [[1,2], [3], [3], []] +# Output: [[0,1,3],[0,2,3]] # Explanation: The graph looks like this: # 0--->1 # | | @@ -20,7 +22,9 @@ # # Note: # - The number of nodes in the graph will be in the range [2, 15]. -# - You can print different paths in any order, but you should keep the order of nodes inside one path. +# - You can print different paths in any order, but you should keep +# the order of nodes inside one path. + class Solution(object): def allPathsSourceTarget(self, graph): @@ -36,7 +40,7 @@ def dfs(graph, curr, path, result): path.append(node) dfs(graph, node, path, result) path.pop() - + result = [] dfs(graph, 0, [0], result) return result diff --git a/Python/android-unlock-patterns.py b/Python/android-unlock-patterns.py index baed693d8..e4293d456 100644 --- a/Python/android-unlock-patterns.py +++ b/Python/android-unlock-patterns.py @@ -1,6 +1,12 @@ # Time: O(9^2 * 2^9) # Space: O(9 * 2^9) +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + # DP solution. class Solution(object): def numberOfPatterns(self, m, n): @@ -44,17 +50,18 @@ def convert(i, j): if m <= number <= n: res += dp[used][i] - x1, y1 = i / 3, i % 3 + x1, y1 = divmod(i, 3) for j in xrange(9): if contain(used, j): continue - - x2, y2 = j / 3, j % 3 - if ((x1 == x2 and abs(y1 - y2) == 2) or \ - (y1 == y2 and abs(x1 - x2) == 2) or \ + + x2, y2 = divmod(j, 3) + if ((x1 == x2 and abs(y1 - y2) == 2) or + (y1 == y2 and abs(x1 - x2) == 2) or (abs(x1 - x2) == 2 and abs(y1 - y2) == 2)) and \ - not contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)): - continue + not contain(used, + convert((x1 + x2) // 2, (y1 + y2) // 2)): + continue dp[merge(used, j)][j] += dp[used][i] @@ -106,17 +113,18 @@ def convert(i, j): if not contain(used, i): continue - x1, y1 = i / 3, i % 3 + x1, y1 = divmod(i, 3) for j in xrange(9): if i == j or not contain(used, j): continue - - x2, y2 = j / 3, j % 3 - if ((x1 == x2 and abs(y1 - y2) == 2) or \ - (y1 == y2 and abs(x1 - x2) == 2) or \ + + x2, y2 = divmod(j, 3) + if ((x1 == x2 and abs(y1 - y2) == 2) or + (y1 == y2 and abs(x1 - x2) == 2) or (abs(x1 - x2) == 2 and abs(y1 - y2) == 2)) and \ - not contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)): - continue + not contain(used, + convert((x1 + x2) // 2, (y1 + y2) // 2)): + continue dp[used][i] += dp[exclude(used, i)][j] @@ -153,22 +161,22 @@ def numberOfPatternsHelper(m, n, level, used, i): if m <= level <= n: number += 1 - x1, y1 = i / 3, i % 3 + x1, y1 = divmod(i, 3) for j in xrange(9): if contain(used, j): continue - x2, y2 = j / 3, j % 3 - if ((x1 == x2 and abs(y1 - y2) == 2) or \ - (y1 == y2 and abs(x1 - x2) == 2) or \ + x2, y2 = divmod(j, 3) + if ((x1 == x2 and abs(y1 - y2) == 2) or + (y1 == y2 and abs(x1 - x2) == 2) or (abs(x1 - x2) == 2 and abs(y1 - y2) == 2)) and \ - not contain(used, convert((x1 + x2) / 2, (y1 + y2) / 2)): - continue + not contain(used, + convert((x1 + x2) // 2, (y1 + y2) // 2)): + continue number += numberOfPatternsHelper(m, n, level + 1, merge(used, j), j) - - return number + return number number = 0 # 1, 3, 7, 9 diff --git a/Python/arithmetic-slices-ii-subsequence.py b/Python/arithmetic-slices-ii-subsequence.py index adf5e643e..10379bd60 100644 --- a/Python/arithmetic-slices-ii-subsequence.py +++ b/Python/arithmetic-slices-ii-subsequence.py @@ -1,7 +1,8 @@ # Time: O(n^2) # Space: O(n * d) -# A sequence of numbers is called arithmetic if it consists of at least three elements +# A sequence of numbers is called arithmetic if it consists of +# at least three elements # and if the difference between any two consecutive elements is the same. # # For example, these are arithmetic sequences: @@ -14,15 +15,19 @@ # 1, 1, 2, 5, 7 # # A zero-indexed array A consisting of N numbers is given. -# A subsequence slice of that array is any sequence of integers (P0, P1, ..., Pk) +# A subsequence slice of that array is any sequence of integers +# (P0, P1, ..., Pk) # such that 0 ≤ P0 < P1 < ... < Pk < N. # # A subsequence slice (P0, P1, ..., Pk) of array A is called arithmetic -# if the sequence A[P0], A[P1], ..., A[Pk-1], A[Pk] is arithmetic. In particular, this means that k >= 2. +# if the sequence A[P0], A[P1], ..., A[Pk-1], A[Pk] is arithmetic. +# In particular, this means that k >= 2. # -# The function should return the number of arithmetic subsequence slices in the array A. +# The function should return the number of arithmetic subsequence +# slices in the array A. # -# The input contains N integers. Every integer is in the range of -2^31 and 2^31-1 and 0 <= N <= 1000. +# The input contains N integers. Every integer is in the range of +# -2^31 and 2^31-1 and 0 <= N <= 1000. # The output is guaranteed to be less than 2^31-1. # # @@ -44,6 +49,11 @@ import collections +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class Solution(object): def numberOfArithmeticSlices(self, A): diff --git a/Python/arithmetic-slices.py b/Python/arithmetic-slices.py index 6bdbee58a..bbbfe9fc8 100644 --- a/Python/arithmetic-slices.py +++ b/Python/arithmetic-slices.py @@ -27,6 +27,7 @@ # # return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself. + class Solution(object): def numberOfArithmeticSlices(self, A): """ @@ -40,5 +41,5 @@ def numberOfArithmeticSlices(self, A): res += i - start + 1 i += 1 i += 1 - + return res diff --git a/Python/arranging-coins.py b/Python/arranging-coins.py index 85d0c868d..16655bf91 100644 --- a/Python/arranging-coins.py +++ b/Python/arranging-coins.py @@ -4,9 +4,11 @@ # You have a total of n coins that you want to form in a staircase shape, # where every k-th row must have exactly k coins. # -# Given n, find the total number of full staircase rows that can be formed. +# Given n, find the total number of full staircase rows that can be +# formed. # -# n is a non-negative integer and fits within the range of a 32-bit signed integer. +# n is a non-negative integer and fits within the range of a 32-bit +# signed integer. # # Example 1: # diff --git a/Python/array-nesting.py b/Python/array-nesting.py index e2407e9b8..c29bbf5cd 100644 --- a/Python/array-nesting.py +++ b/Python/array-nesting.py @@ -16,7 +16,7 @@ # Example 1: # Input: A = [5,4,0,3,1,6,2] # Output: 4 -# Explanation: +# Explanation: # A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. # # One of the longest S[K]: @@ -26,6 +26,7 @@ # The elements of A are all distinct. # Each element of array A is an integer within the range [0, N-1]. + class Solution(object): def arrayNesting(self, nums): """ @@ -34,13 +35,12 @@ def arrayNesting(self, nums): """ result = 0 for num in nums: - if num != None: + if num is not None: start, count = num, 0 - while nums[start] != None: + while nums[start] is not None: temp = start start = nums[start] nums[temp] = None count += 1 result = max(result, count) return result - diff --git a/Python/array-partition-i.py b/Python/array-partition-i.py index 8c91e46f4..a1ce5c2a3 100644 --- a/Python/array-partition-i.py +++ b/Python/array-partition-i.py @@ -13,6 +13,12 @@ # n is a positive integer, which is in the range of [1, 10000]. # All the integers in the array will be in the range of [-10000, 10000]. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def arrayPairSum(self, nums): """ @@ -43,8 +49,8 @@ def arrayPairSum(self, nums): for i in xrange(0, len(nums), 2): result += nums[i] return result - - + + # Time: O(nlogn) # Space: O(n) class Solution3(object): diff --git a/Python/assign-cookies.py b/Python/assign-cookies.py index 839899646..5fc6aa07f 100644 --- a/Python/assign-cookies.py +++ b/Python/assign-cookies.py @@ -1,15 +1,20 @@ # Time: O(nlogn) # Space: O(1) -# Assume you are an awesome parent and want to give your children some cookies. -# But, you should give each child at most one cookie. Each child i has a greed factor gi, -# which is the minimum size of a cookie that the child will be content with; -# and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, +# Assume you are an awesome parent and want to give your children some +# cookies. +# But, you should give each child at most one cookie. +# Each child i has a greed factor gi, +# which is the minimum size of a cookie that the child will +# be content with; +# and each cookie j has a size sj. If sj >= gi, we can assign +# the cookie j to the child i, # and the child i will be content. -# Your goal is to maximize the number of your content children and output the maximum number. +# Your goal is to maximize the number of your content children and +# output the maximum number. # # Note: -# You may assume the greed factor is always positive. +# You may assume the greed factor is always positive. # You cannot assign more than one cookie to one child. # # Example 1: @@ -17,7 +22,8 @@ # # Output: 1 # -# Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. +# Explanation: You have 3 children and 2 cookies. +# The greed factors of 3 children are 1, 2, 3. # And even though you have 2 cookies, since their size is both 1, # you could only make the child whose greed factor is 1 content. # You need to output 1. @@ -26,10 +32,18 @@ # # Output: 2 # -# Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. -# You have 3 cookies and their sizes are big enough to gratify all of the children, +# Explanation: You have 2 children and 3 cookies. +# The greed factors of 2 children are 1, 2. +# You have 3 cookies and their sizes are big enough to gratify +# all of the children, # You need to output 2. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def findContentChildren(self, g, s): """ diff --git a/Python/asteroid-collision.py b/Python/asteroid-collision.py index 223daeaf9..670376b9d 100644 --- a/Python/asteroid-collision.py +++ b/Python/asteroid-collision.py @@ -1,46 +1,56 @@ # Time: O(n) # Space: O(n) -# We are given an array asteroids of integers representing asteroids in a row. +# We are given an array asteroids of integers representing asteroids +# in a row. # # For each asteroid, the absolute value represents its size, -# and the sign represents its direction (positive meaning right, negative meaning left). +# and the sign represents its direction (positive meaning right, +# negative meaning left). # Each asteroid moves at the same speed. # # Find out the state of the asteroids after all collisions. -# If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. +# If two asteroids meet, the smaller one will explode. +# If both are the same size, both will explode. # Two asteroids moving in the same direction will never meet. # # Example 1: -# Input: +# Input: # asteroids = [5, 10, -5] # Output: [5, 10] -# Explanation: +# Explanation: # The 10 and -5 collide resulting in 10. The 5 and 10 never collide. # Example 2: -# Input: +# Input: # asteroids = [8, -8] # Output: [] -# Explanation: +# Explanation: # The 8 and -8 collide exploding each other. # Example 3: -# Input: +# Input: # asteroids = [10, 2, -5] # Output: [10] -# Explanation: +# Explanation: # The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. # Example 4: -# Input: +# Input: # asteroids = [-2, -1, 1, 2] # Output: [-2, -1, 1, 2] -# Explanation: +# Explanation: # The -2 and -1 are moving left, while the 1 and 2 are moving right. -# Asteroids moving the same direction never meet, so no asteroids will meet each other. +# Asteroids moving the same direction never meet, +# so no asteroids will meet each other. # # Note: # - The length of asteroids will be at most 10000. # - Each asteroid will be a non-zero integer in the range [-1000, 1000]. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def asteroidCollision(self, asteroids): """ diff --git a/Python/average-of-levels-in-binary-tree.py b/Python/average-of-levels-in-binary-tree.py index 40bfe2fe0..0834e2901 100644 --- a/Python/average-of-levels-in-binary-tree.py +++ b/Python/average-of-levels-in-binary-tree.py @@ -2,7 +2,8 @@ # Space: O(h) # Given a non-empty binary tree, -# return the average value of the nodes on each level in the form of an array. +# return the average value of the nodes on each level in the form of +# an array. # # Example 1: # Input: @@ -26,6 +27,12 @@ # self.left = None # self.right = None +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def averageOfLevels(self, root): """ @@ -38,7 +45,7 @@ def averageOfLevels(self, root): total, count = 0, 0 next_q = [] for n in q: - total += n.val; + total += n.val count += 1 if n.left: next_q.append(n.left) From b2f90ce94533a8f4f0703a4df51971f6faaf6de9 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 15 Apr 2018 20:30:13 +0800 Subject: [PATCH 4618/4971] Create race-car.py --- Python/race-car.py | 72 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Python/race-car.py diff --git a/Python/race-car.py b/Python/race-car.py new file mode 100644 index 000000000..f1dfbcec3 --- /dev/null +++ b/Python/race-car.py @@ -0,0 +1,72 @@ +# Time : O(nlogn), n is the value of the target +# Space: O(n) + +# Your car starts at position 0 and speed +1 on an infinite number line. +# (Your car can go into negative positions.) +# +# Your car drives automatically according to a sequence of +# instructions A (accelerate) and R (reverse). +# +# When you get an instruction "A", your car does the following: +# position += speed, speed *= 2. +# +# When you get an instruction "R", your car does the following: +# if your speed is positive then speed = -1 , otherwise speed = 1. +# (Your position stays the same.) +# +# For example, after commands "AAR", your car goes to +# positions 0->1->3->3, and your speed goes to 1->2->4->-1. +# +# Now for some target position, say the length of the shortest +# sequence of instructions to get there. +# +# Example 1: +# Input: +# target = 3 +# Output: 2 +# Explanation: +# The shortest instruction sequence is "AA". +# Your position goes from 0->1->3. +# Example 2: +# Input: +# target = 6 +# Output: 5 +# Explanation: +# The shortest instruction sequence is "AAARA". +# Your position goes from 0->1->3->7->7->6. +# +# Note: +# - 1 <= target <= 10000. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def racecar(self, target): + dp = [0] + [float('inf')] * target + for i in xrange(1, target + 1): + # 2^(k-1) <= i < 2^k + k = i.bit_length() + + # case 1. drive exactly i at best + # seq(i) = A^k + if i == 2**k-1: + dp[i] = k + continue + + # case 2. drive cross i at 2^k-1, and turn back to i + # seq(i) = A^k => R => seq(2^k-1 - i), + dp[i] = min(dp[i], k + 1 + dp[2**k-1 - i]) + + # case 3. drive less then 2^k-1, and turn back some distance, + # and turn back again to make speed is positive + # seq(i) = shortest(seq(i), A^(k-1) => R => A^j => R => seq(i - (2^(k-1)-1) + (2^j-1)), + # where 0 <= j < k-1) + # => dp[i] = min(dp[i], (k-1) + 1 + j + 1 + dp[i - (2**(k-1)-1) + (2**j-1)]) + for j in xrange(k-1): + dp[i] = min(dp[i], k+j+1 + dp[i - 2**(k-1) + 2**j]) + + return dp[target] From 30d2b7d18832a517675254051751d91df90b0e4a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Apr 2018 20:31:34 +0800 Subject: [PATCH 4619/4971] Create race-car.cpp --- C++/race-car.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C++/race-car.cpp diff --git a/C++/race-car.cpp b/C++/race-car.cpp new file mode 100644 index 000000000..735522719 --- /dev/null +++ b/C++/race-car.cpp @@ -0,0 +1,36 @@ +// Time : O(nlogn), n is the value of the target +// Space: O(n) + +class Solution { +public: + int racecar(int target) { + vector dp(target + 1, numeric_limits::max()); + dp[0] = 0; + for (int i = 1; i <= target; ++i) { + int k = bitLength(i); + if (i == (1 << k) - 1) { + dp[i] = k; + continue; + } + dp[i] = min(dp[i], dp[(1 << k) - 1 - i] + k + 1); + for (int j = 0; j < k; ++j) { + dp[i] = min(dp[i], dp[i - (1 << (k - 1)) + (1 << j)] + k + j + 1); + } + } + return dp[target]; + } + +private: + uint32_t bitLength(uint32_t n) { + uint32_t left = 1, right = 32; + while (left <= right) { + auto mid = left + (right - left) / 2; + if ((1 << mid) > n) { + right = mid - 1; + } else { + left = mid + 1; + } + } + return left; + } +}; From c914abb80cec37419f51a9389cda8a5274c318b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Apr 2018 20:32:55 +0800 Subject: [PATCH 4620/4971] Update race-car.py --- Python/race-car.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/race-car.py b/Python/race-car.py index f1dfbcec3..76acef2e3 100644 --- a/Python/race-car.py +++ b/Python/race-car.py @@ -58,12 +58,12 @@ def racecar(self, target): continue # case 2. drive cross i at 2^k-1, and turn back to i - # seq(i) = A^k => R => seq(2^k-1 - i), + # seq(i) = A^k -> R -> seq(2^k-1 - i) dp[i] = min(dp[i], k + 1 + dp[2**k-1 - i]) # case 3. drive less then 2^k-1, and turn back some distance, # and turn back again to make speed is positive - # seq(i) = shortest(seq(i), A^(k-1) => R => A^j => R => seq(i - (2^(k-1)-1) + (2^j-1)), + # seq(i) = shortest(seq(i), A^(k-1) -> R -> A^j -> R -> seq(i - (2^(k-1)-1) + (2^j-1)), # where 0 <= j < k-1) # => dp[i] = min(dp[i], (k-1) + 1 + j + 1 + dp[i - (2**(k-1)-1) + (2**j-1)]) for j in xrange(k-1): From f886f1715f000c1139364da3166a4471a47b5b02 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 15 Apr 2018 20:33:52 +0800 Subject: [PATCH 4621/4971] Update race-car.py --- Python/race-car.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/race-car.py b/Python/race-car.py index 76acef2e3..cab073fa3 100644 --- a/Python/race-car.py +++ b/Python/race-car.py @@ -21,17 +21,17 @@ # sequence of instructions to get there. # # Example 1: -# Input: +# Input: # target = 3 # Output: 2 -# Explanation: +# Explanation: # The shortest instruction sequence is "AA". # Your position goes from 0->1->3. # Example 2: -# Input: +# Input: # target = 6 # Output: 5 -# Explanation: +# Explanation: # The shortest instruction sequence is "AAARA". # Your position goes from 0->1->3->7->7->6. # From d95ae1a7f50a7c22a6c9be4964baf8ea10b314d8 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 15 Apr 2018 20:53:53 +0800 Subject: [PATCH 4622/4971] Update race-car.py --- Python/race-car.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Python/race-car.py b/Python/race-car.py index cab073fa3..3a075e606 100644 --- a/Python/race-car.py +++ b/Python/race-car.py @@ -62,10 +62,12 @@ def racecar(self, target): dp[i] = min(dp[i], k + 1 + dp[2**k-1 - i]) # case 3. drive less then 2^k-1, and turn back some distance, - # and turn back again to make speed is positive - # seq(i) = shortest(seq(i), A^(k-1) -> R -> A^j -> R -> seq(i - (2^(k-1)-1) + (2^j-1)), + # and turn back again to make the direction is the same + # seq(i) = shortest(seq(i), A^(k-1) -> R -> A^j -> R -> + # seq(i - (2^(k-1)-1) + (2^j-1)), # where 0 <= j < k-1) - # => dp[i] = min(dp[i], (k-1) + 1 + j + 1 + dp[i - (2**(k-1)-1) + (2**j-1)]) + # => dp[i] = min(dp[i], (k-1) + 1 + j + 1 + + # dp[i - (2**(k-1)-1) + (2**j-1)]) for j in xrange(k-1): dp[i] = min(dp[i], k+j+1 + dp[i - 2**(k-1) + 2**j]) From 29498b3e9cf5caf6c09b3a9c9b3c43264dbc9638 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 15 Apr 2018 20:57:46 +0800 Subject: [PATCH 4623/4971] Update race-car.py --- Python/race-car.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/race-car.py b/Python/race-car.py index 3a075e606..dd5c924e9 100644 --- a/Python/race-car.py +++ b/Python/race-car.py @@ -46,8 +46,8 @@ class Solution(object): def racecar(self, target): - dp = [0] + [float('inf')] * target - for i in xrange(1, target + 1): + dp = [0] * (target+1) + for i in xrange(1, target+1): # 2^(k-1) <= i < 2^k k = i.bit_length() @@ -59,7 +59,7 @@ def racecar(self, target): # case 2. drive cross i at 2^k-1, and turn back to i # seq(i) = A^k -> R -> seq(2^k-1 - i) - dp[i] = min(dp[i], k + 1 + dp[2**k-1 - i]) + dp[i] = k+1 + dp[2**k-1 - i] # case 3. drive less then 2^k-1, and turn back some distance, # and turn back again to make the direction is the same From 1a36763f640ba8ca9d036067a42cdd0b403c18dc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Apr 2018 20:58:47 +0800 Subject: [PATCH 4624/4971] Update race-car.cpp --- C++/race-car.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/C++/race-car.cpp b/C++/race-car.cpp index 735522719..987655932 100644 --- a/C++/race-car.cpp +++ b/C++/race-car.cpp @@ -4,15 +4,14 @@ class Solution { public: int racecar(int target) { - vector dp(target + 1, numeric_limits::max()); - dp[0] = 0; + vector dp(target + 1); for (int i = 1; i <= target; ++i) { int k = bitLength(i); if (i == (1 << k) - 1) { dp[i] = k; continue; } - dp[i] = min(dp[i], dp[(1 << k) - 1 - i] + k + 1); + dp[i] = dp[(1 << k) - 1 - i] + k + 1; for (int j = 0; j < k; ++j) { dp[i] = min(dp[i], dp[i - (1 << (k - 1)) + (1 << j)] + k + j + 1); } From 170bda91c18e56c97abdd2a8b9c8a2f7aa439628 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 15 Apr 2018 21:35:51 +0800 Subject: [PATCH 4625/4971] Update race-car.py --- Python/race-car.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/race-car.py b/Python/race-car.py index dd5c924e9..b59aa946e 100644 --- a/Python/race-car.py +++ b/Python/race-car.py @@ -71,4 +71,4 @@ def racecar(self, target): for j in xrange(k-1): dp[i] = min(dp[i], k+j+1 + dp[i - 2**(k-1) + 2**j]) - return dp[target] + return dp[-1] From fac5a0e8d23735b3d2ef19fecf648bdf07f69a5f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Apr 2018 21:36:18 +0800 Subject: [PATCH 4626/4971] Update race-car.cpp --- C++/race-car.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/race-car.cpp b/C++/race-car.cpp index 987655932..54fab1a51 100644 --- a/C++/race-car.cpp +++ b/C++/race-car.cpp @@ -16,7 +16,7 @@ class Solution { dp[i] = min(dp[i], dp[i - (1 << (k - 1)) + (1 << j)] + k + j + 1); } } - return dp[target]; + return dp.back(); } private: From 4a62af083e476c2c458b2155ad33ce6efb0a06d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Apr 2018 22:20:23 +0800 Subject: [PATCH 4627/4971] Create most-common-word.cpp --- C++/most-common-word.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/most-common-word.cpp diff --git a/C++/most-common-word.cpp b/C++/most-common-word.cpp new file mode 100644 index 000000000..041e9943f --- /dev/null +++ b/C++/most-common-word.cpp @@ -0,0 +1,30 @@ +// Time: O(m + n), m is the size of banned, n is the size of paragraph +// Space: O(m + n) + +class Solution { +public: + string mostCommonWord(string paragraph, vector& banned) { + unordered_set lookup(banned.cbegin(), banned.cend()); + unordered_map counts; + string word; + for (const auto& c : paragraph) { + if (isalpha(c)) { + word.push_back(tolower(c)); + } else if (!word.empty()) { + ++counts[word]; + word.clear(); + } + } + if (!word.empty()) { + ++counts[word]; + } + string result; + for (const auto& kvp : counts) { + if ((result.empty() || kvp.second > counts[result]) && + !lookup.count(kvp.first)) { + result = kvp.first; + } + } + return result; + } +}; From 9aecc6b2cb771026f52be833405b454b20689d82 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 15 Apr 2018 22:25:58 +0800 Subject: [PATCH 4628/4971] Create most-common-word.py --- Python/most-common-word.py | 60 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/most-common-word.py diff --git a/Python/most-common-word.py b/Python/most-common-word.py new file mode 100644 index 000000000..6d6fc26c3 --- /dev/null +++ b/Python/most-common-word.py @@ -0,0 +1,60 @@ +# Time: O(m + n), m is the size of banned, n is the size of paragraph +# Space: O(m + n) + +# Given a paragraph and a list of banned words, +# return the most frequent word that is not in the list of banned words. +# It is guaranteed there is at least one word that isn't banned, and that the answer is unique. +# +# Words in the list of banned words are given in lowercase, and free of +# punctuation. +# Words in the paragraph are not case sensitive. +# The answer is in lowercase. +# +# Example: +# Input: +# paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." +# banned = ["hit"] +# Output: "ball" +# Explanation: +# "hit" occurs 3 times, but it is a banned word. +# "ball" occurs twice (and no other word does), so it is the most frequent +# non-banned word in the paragraph. +# Note that words in the paragraph are not case sensitive, +# that punctuation is ignored (even if adjacent to words, such as "ball,"), +# and that "hit" isn't the answer even though it occurs more because it is +# banned. +# +# Note: +# - 1 <= paragraph.length <= 1000. +# - 1 <= banned.length <= 100. +# - 1 <= banned[i].length <= 10. +# - The answer is unique, and written in lowercase +# (even if its occurrences in paragraph may have uppercase symbols, +# and even if it is a proper noun.) +# - paragraph only consists of letters, spaces, +# or the punctuation symbols !?',;. +# - Different words in paragraph are always separated by a space. +# - There are no hyphens or hyphenated words. +# - Words only consist of letters, never apostrophes or +# other punctuation symbols. + +import collections + + +class Solution(object): + def mostCommonWord(self, paragraph, banned): + """ + :type paragraph: str + :type banned: List[str] + :rtype: str + """ + lookup = set(banned) + counts = collections.Counter(word.strip("!?',;.") + for word in paragraph.lower().split()) + + result = '' + for word in counts: + if (not result or counts[word] > counts[result]) and \ + word not in lookup: + result = word + return result From 551170d77e94d9cc3cbaf6668cf88f73189ea825 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 15 Apr 2018 22:40:38 +0800 Subject: [PATCH 4629/4971] Create linked-list-components.py --- Python/linked-list-components.py | 60 ++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/linked-list-components.py diff --git a/Python/linked-list-components.py b/Python/linked-list-components.py new file mode 100644 index 000000000..eb49d7589 --- /dev/null +++ b/Python/linked-list-components.py @@ -0,0 +1,60 @@ +# Time: O(m + n), m is the number of G, n is the number of nodes +# Space: O(m) + +# We are given head, the head node of a linked list +# containing unique integer values. +# +# We are also given the list G, a subset of the values in the linked list. +# +# Return the number of connected components in G, +# where two values are connected if they appear consecutively +# in the linked list. +# +# Example 1: +# +# Input: +# head: 0->1->2->3 +# G = [0, 1, 3] +# Output: 2 +# Explanation: +# 0 and 1 are connected, so [0, 1] and [3] are the two connected components. +# Example 2: +# +# Input: +# head: 0->1->2->3->4 +# G = [0, 3, 1, 4] +# Output: 2 +# Explanation: +# 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are +# the two connected components. +# Note: +# - If N is the length of the linked list given by head, 1 <= N <= 10000. +# - The value of each node in the linked list will be in the range [0, N - 1]. +# - 1 <= G.length <= 10000. +# - G is a subset of all values in the linked list. + + +# Definition for singly-linked list. +class ListNode(object): + def __init__(self, x): + self.val = x + self.next = None + + +class Solution(object): + def numComponents(self, head, G): + """ + :type head: ListNode + :type G: List[int] + :rtype: int + """ + lookup = set(G) + dummy = ListNode(-1) + dummy.next = head + curr = dummy + result = 0 + while curr and curr.next: + if curr.val not in lookup and curr.next.val in lookup: + result += 1 + curr = curr.next + return result From 255008d5e2a5a80647349f81c0400ce1b8075468 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Apr 2018 22:41:27 +0800 Subject: [PATCH 4630/4971] Create linked-list-components.cpp --- C++/linked-list-components.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/linked-list-components.cpp diff --git a/C++/linked-list-components.cpp b/C++/linked-list-components.cpp new file mode 100644 index 000000000..2b30f20b0 --- /dev/null +++ b/C++/linked-list-components.cpp @@ -0,0 +1,28 @@ +// Time: O(m + n), m is the number of G, n is the number of nodes +// Space: O(m) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + int numComponents(ListNode* head, vector& G) { + unordered_set lookup(G.cbegin(), G.cend()); + ListNode dummy(-1); + dummy.next = head; + auto curr = &dummy; + int result = 0; + while (curr && curr->next) { + if (!lookup.count(curr->val) && lookup.count(curr->next->val)) { + ++result; + } + curr = curr->next; + } + return result; + } +}; From 9241acbb845560abea5b655fe11282619546c60d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Apr 2018 00:01:16 +0800 Subject: [PATCH 4631/4971] Create ambiguous-coordinates.cpp --- C++/ambiguous-coordinates.cpp | 45 +++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 C++/ambiguous-coordinates.cpp diff --git a/C++/ambiguous-coordinates.cpp b/C++/ambiguous-coordinates.cpp new file mode 100644 index 000000000..75dca45aa --- /dev/null +++ b/C++/ambiguous-coordinates.cpp @@ -0,0 +1,45 @@ +// Time: O(n^4) +// Space: O(n^2) + +class Solution { +public: + vector ambiguousCoordinates(string S) { + vector result; + for (int i = 1; i < S.length() - 2; ++i) { + const auto& lefts = make(S, 1, i); + const auto& rights = make(S, i + 1, S.length() - 2 - i); + for (const auto& left : lefts) { + for (const auto& right : rights) { + string s; + s += "("; + s += left; + s += ", "; + s += right; + s += ")"; + result.emplace_back(move(s)); + } + } + } + return result; + } + +private: + // Time: O(n^2) + // Space: O(n^2) + vector make(const string& S, int i, int n) { + vector result; + for (int d = 1; d <= n; ++d) { + const auto& left = S.substr(i, d); + const auto& right = S.substr(i + d, n - d); + if ((left.front() != '0' || left == "0") && + right.back() != '0') { + string s; + s += left; + s += (d < n ? "." : ""); + s += right; + result.emplace_back(move(s)); + } + } + return result; + } +}; From 4669fd9ba96ea216699db19332c341c8ce5e17ff Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Apr 2018 00:02:44 +0800 Subject: [PATCH 4632/4971] Update ambiguous-coordinates.cpp --- C++/ambiguous-coordinates.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/ambiguous-coordinates.cpp b/C++/ambiguous-coordinates.cpp index 75dca45aa..ec2780b88 100644 --- a/C++/ambiguous-coordinates.cpp +++ b/C++/ambiguous-coordinates.cpp @@ -35,7 +35,7 @@ class Solution { right.back() != '0') { string s; s += left; - s += (d < n ? "." : ""); + s += (!right.empty() ? "." : ""); s += right; result.emplace_back(move(s)); } From 7c606f590203192b882d25c6e84d29c307946af2 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 16 Apr 2018 00:06:38 +0800 Subject: [PATCH 4633/4971] Create ambiguous-coordinates.py --- Python/ambiguous-coordinates.py | 69 +++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Python/ambiguous-coordinates.py diff --git a/Python/ambiguous-coordinates.py b/Python/ambiguous-coordinates.py new file mode 100644 index 000000000..525bd9326 --- /dev/null +++ b/Python/ambiguous-coordinates.py @@ -0,0 +1,69 @@ +# Time: O(n^4) +# Space: O(n) + +# We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". +# Then, we removed all commas, decimal points, and spaces, +# and ended up with the string S. +# Return a list of strings representing all possibilities for +# what our original coordinates could have been. +# +# Our original representation never had extraneous zeroes, +# so we never started with numbers like +# "00", "0.0", "0.00", "1.0", "001", "00.01", +# or any other number that can be represented with less digits. +# Also, a decimal point within a number never occurs without +# at least one digit occuring before it, +# so we never started with numbers like ".1". +# +# The final answer list can be returned in any order. +# Also note that all coordinates in the final answer +# have exactly one space between them +# (occurring after the comma.) +# +# Example 1: +# Input: "(123)" +# Output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"] +# Example 2: +# Input: "(00011)" +# Output: ["(0.001, 1)", "(0, 0.011)"] +# Explanation: +# 0.0, 00, 0001 or 00.01 are not allowed. +# Example 3: +# Input: "(0123)" +# Output: ["(0, 123)", "(0, 12.3)", "(0, 1.23)", "(0.1, 23)", "(0.1, 2.3)", "(0.12, 3)"] +# Example 4: +# Input: "(100)" +# Output: [(10, 0)] +# Explanation: +# 1.0 is not allowed. +# +# Note: +# - 4 <= S.length <= 12. +# - S[0] = "(", S[S.length - 1] = ")", and the other elements in S are digits. + +import itertools + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def ambiguousCoordinates(self, S): + """ + :type S: str + :rtype: List[str] + """ + def make(S, i, n): + for d in xrange(1, n+1): + left = S[i:i+d] + right = S[i+d:i+n] + if ((not left.startswith('0') or left == '0') + and (not right.endswith('0'))): + yield "".join([left, '.' if right else '', right]) + + return ["({}, {})".format(*cand) + for i in xrange(1, len(S)-2) + for cand in itertools.product(make(S, 1, i), + make(S, i+1, len(S)-2-i))] From 5efab83f5470530a2029f4839530ae1535bf1f22 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 16 Apr 2018 00:13:30 +0800 Subject: [PATCH 4634/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index f39418124..3a9990d8f 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 804| [Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/) | [C++](./C++/unique-morse-code-words.cpp) [Python](./Python/unique-morse-code-words.py) | _O(n)_ | _O(n)_ | Easy ||| 806| [Number of Lines To Write String](https://leetcode.com/problems/number-of-lines-to-write-string/) | [C++](./C++/number-of-lines-to-write-string.cpp) [Python](./Python/number-of-lines-to-write-string.py) | _O(n)_ | _O(1)_ | Easy ||| 809| [Expressive Words](https://leetcode.com/problems/expressive-words/) | [C++](./C++/expressive-words.cpp) [Python](./Python/expressive-words.py) | _O(n + s)_ | _O(l + s)_ | Medium ||| +816| [Ambiguous Coordinates](https://leetcode.com/problems/ambiguous-coordinates/) | [C++](./C++/ambiguous-coordinates.cpp) [Python](./Python/ambiguous-coordinates.py) | _O(n^4)_ | _O(n)_ | Medium ||| +819| [Most Common Word](https://leetcode.com/problems/most-common-word/) | [C++](./C++/most-common-word.cpp) [Python](./Python/most-common-word.py) | _O(m + n)_ | _O(m + n)_ | Easy ||| ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -236,6 +238,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 369| [Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list/)| [C++](./C++/plus-one-linked-list.cpp) [Python](./Python/plus-one-linked-list.py) | _O(n)_ | _O(1)_ | Medium | 📖 | Two Pointers | 445| [Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/)| [C++](./C++/add-two-numbers-ii.cpp) [Python](./Python/add-two-numbers-ii.py) | _O(m + n)_ | _O(m + n)_ | Medium ||| 725 | [Split Linked List in Parts](https://leetcode.com/problems/split-linked-list-in-parts/) | [C++](./C++/split-linked-list-in-parts.cpp) [Python](./Python/split-linked-list-in-parts.py) | _O(n + k)_ | _O(1)_ | Medium || +817 | [Linked List Components](https://leetcode.com/problems/linked-list-components/) | [C++](./C++/linked-list-components.cpp) [Python](./Python/linked-list-components.py) | _O(m + n)_ | _O(m)_ | Medium || ## Stack | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -764,6 +767,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 805 | [Split Array With Same Average](https://leetcode.com/problems/split-array-with-same-average/) | [C++](./C++/split-array-with-same-average.cpp) [Python](./Python/split-array-with-same-average.py) | _O(n^4)_ | _O(n^3)_ | Hard ||| 808 | [Soup Servings](https://leetcode.com/problems/soup-servings/) | [C++](./C++/soup-servings.cpp) [Python](./Python/soup-servings.py) | _O(1)_ | _O(1)_ | Medium || Memoization | 813 | [Largest Sum of Averages](https://leetcode.com/problems/largest-sum-of-averages/) | [C++](./C++/largest-sum-of-averages.cpp) [Python](./Python/largest-sum-of-averages.py) | _O(k * n^2)_ | _O(n)_ | Medium || | +818 | [Race Car](https://leetcode.com/problems/race-car/) | [C++](./C++/race-car.cpp) [Python](./Python/race-car.py) | _O(nlogn)_ | _O(n)_ | Hard || | ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From b776b512efc9838fde677f17170d6ce3cdecb400 Mon Sep 17 00:00:00 2001 From: Aven Xiangwen Liu Date: Thu, 19 Apr 2018 15:27:37 -0500 Subject: [PATCH 4635/4971] Update image-smoother.py Another solution with getGray function simplified. --- Python/image-smoother.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Python/image-smoother.py b/Python/image-smoother.py index 44e03c24e..024e522fc 100644 --- a/Python/image-smoother.py +++ b/Python/image-smoother.py @@ -47,3 +47,25 @@ def getGray(M, i, j): for j in xrange(len(M[0])): result[i][j] = getGray(M, i, j); return result +# Another solution with getGray function simplified. +class Solution(object): + def imageSmoother(self, M): + """ + :type M: List[List[int]] + :rtype: List[List[int]] + """ + def getGray(M, i, j): + total, count = 0, 0.0 + for r in xrange(-1, 2): + for c in xrange(-1, 2): + ii, jj = i + r, j + c + if 0 <= ii < len(M) and 0 <= jj < len(M[0]): + total += M[ii][jj] + count += 1.0 + return int(total / count) + + result = [[0 for _ in xrange(len(M[0]))] for _ in xrange(len(M))] + for i in xrange(len(M)): + for j in xrange(len(M[0])): + result[i][j] = getGray(M, i, j); + return result From 9ca32e7614cfb3cc463ce73b0ad6844780145d40 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 20 Apr 2018 23:05:41 +0800 Subject: [PATCH 4636/4971] Update image-smoother.py --- Python/image-smoother.py | 27 +-------------------------- 1 file changed, 1 insertion(+), 26 deletions(-) diff --git a/Python/image-smoother.py b/Python/image-smoother.py index 024e522fc..232662103 100644 --- a/Python/image-smoother.py +++ b/Python/image-smoother.py @@ -22,32 +22,7 @@ # Note: # The value in the given matrix is in the range of [0, 255]. # The length and width of the given matrix are in the range of [1, 150]. - -class Solution(object): - def imageSmoother(self, M): - """ - :type M: List[List[int]] - :rtype: List[List[int]] - """ - def getGray(M, i, j): - directions = [[-1, -1], [0, -1], [1, -1], \ - [-1, 0], [0, 0], [1, 0], \ - [-1, 1], [0, 1], [1, 1]] - - total, count = 0, 0.0 - for direction in directions: - ii, jj = i + direction[0], j + direction[1] - if 0 <= ii < len(M) and 0 <= jj < len(M[0]): - total += M[ii][jj] - count += 1.0 - return int(total / count) - - result = [[0 for _ in xrange(len(M[0]))] for _ in xrange(len(M))] - for i in xrange(len(M)): - for j in xrange(len(M[0])): - result[i][j] = getGray(M, i, j); - return result -# Another solution with getGray function simplified. + class Solution(object): def imageSmoother(self, M): """ From 9a452ffb5a0210a2215fa0b0a6e0f49d602b6805 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 20 Apr 2018 23:10:12 +0800 Subject: [PATCH 4637/4971] Update image-smoother.cpp --- C++/image-smoother.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/C++/image-smoother.cpp b/C++/image-smoother.cpp index 57feb4300..d169ef250 100644 --- a/C++/image-smoother.cpp +++ b/C++/image-smoother.cpp @@ -17,17 +17,16 @@ class Solution { private: int getGray(const vector>& M, int i, int j) { const auto& m = M.size(), n = M[0].size(); - static const vector> directions = { {-1, -1}, {0, -1}, {1, -1}, - {-1, 0}, {0, 0}, {1, 0}, - {-1, 1}, {0, 1}, {1, 1} }; double total = 0.0; int count = 0; - for (const auto& direction : directions) { - const auto& ii = i + direction.first; - const auto& jj = j + direction.second; - if (0 <= ii && ii < m && 0 <= jj && jj < n) { - total += M[ii][jj]; - ++count; + for (int r = -1; r < 2; ++r) { + for (int c = -1; c < 2; ++c) { + const auto& ii = i + r; + const auto& jj = j + c; + if (0 <= ii && ii < m && 0 <= jj && jj < n) { + total += M[ii][jj]; + ++count; + } } } return static_cast(total / count); From 3b8f14f2751a7ac9177dc190448e9f622fe2e954 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 20 Apr 2018 23:50:08 +0800 Subject: [PATCH 4638/4971] Update image-smoother.cpp --- C++/image-smoother.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/image-smoother.cpp b/C++/image-smoother.cpp index d169ef250..2ff85ed0d 100644 --- a/C++/image-smoother.cpp +++ b/C++/image-smoother.cpp @@ -4,7 +4,7 @@ class Solution { public: vector> imageSmoother(vector>& M) { - const auto m = M.size(), n = M[0].size(); + const auto& m = M.size(), &n = M[0].size(); vector> result(M); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { @@ -16,7 +16,7 @@ class Solution { private: int getGray(const vector>& M, int i, int j) { - const auto& m = M.size(), n = M[0].size(); + const auto& m = M.size(), &n = M[0].size(); double total = 0.0; int count = 0; for (int r = -1; r < 2; ++r) { From 49ee3caeb6a783ddf5bb327c341b6dcca518fc98 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 21 Apr 2018 22:20:14 +0800 Subject: [PATCH 4639/4971] Fix flake8 related issues --- Python/balanced-binary-tree.py | 41 ++++++------- Python/base-7.py | 10 +++- Python/baseball-game.py | 42 ++++++++------ Python/basic-calculator-ii.py | 6 +- Python/basic-calculator-iii.py | 6 +- Python/basic-calculator.py | 4 +- Python/battleships-in-a-board.py | 2 +- Python/beautiful-arrangement-ii.py | 2 +- Python/beautiful-arrangement.py | 4 +- Python/best-meeting-point.py | 8 +-- Python/best-time-to-buy-and-sell-stock-ii.py | 12 ++-- Python/best-time-to-buy-and-sell-stock-iii.py | 20 +++---- Python/best-time-to-buy-and-sell-stock-iv.py | 8 +-- ...buy-and-sell-stock-with-transaction-fee.py | 2 +- Python/best-time-to-buy-and-sell-stock.py | 10 ++-- Python/binary-number-with-alternating-bits.py | 2 +- Python/binary-search-tree-iterator.py | 16 ++--- Python/binary-tree-inorder-traversal.py | 4 +- .../binary-tree-level-order-traversal-ii.py | 2 +- Python/binary-tree-level-order-traversal.py | 2 +- ...ry-tree-longest-consecutive-sequence-ii.py | 2 +- ...inary-tree-longest-consecutive-sequence.py | 4 +- Python/binary-tree-maximum-path-sum.py | 10 ++-- Python/binary-tree-paths.py | 2 +- Python/binary-tree-postorder-traversal.py | 8 +-- Python/binary-tree-preorder-traversal.py | 6 +- Python/binary-tree-right-side-view.py | 14 ++--- Python/binary-tree-tilt.py | 4 +- Python/binary-tree-upside-down.py | 26 ++++----- ...inary-tree-zigzag-level-order-traversal.py | 2 +- Python/bitwise-and-of-numbers-range.py | 2 +- Python/boundary-of-binary-tree.py | 4 +- Python/bricks-falling-when-hit.py | 12 ++-- Python/bulb-switcher-ii.py | 2 +- Python/burst-balloons.py | 20 +++---- Python/can-i-win.py | 2 +- Python/candy-crush.py | 4 +- Python/candy.py | 10 ++-- Python/cherry-pickup.py | 4 +- Python/circular-array-loop.py | 6 +- Python/climbing-stairs.py | 6 +- Python/clone-graph.py | 14 ++--- Python/closest-binary-search-tree-value-ii.py | 12 ++-- Python/coin-change-2.py | 4 +- Python/coin-change.py | 2 +- Python/combination-sum-ii.py | 24 ++++---- Python/combination-sum-iii.py | 2 +- Python/combination-sum.py | 20 +++---- Python/combinations.py | 6 +- Python/compare-version-numbers.py | 14 ++--- Python/concatenated-words.py | 10 ++-- ...ee-from-inorder-and-postorder-traversal.py | 4 +- ...ree-from-preorder-and-inorder-traversal.py | 4 +- Python/construct-string-from-binary-tree.py | 16 ++--- Python/contain-virus.py | 8 +-- Python/container-with-most-water.py | 14 ++--- Python/contains-duplicate-ii.py | 4 +- Python/contains-duplicate.py | 2 +- Python/contiguous-array.py | 2 +- Python/continuous-subarray-sum.py | 2 +- Python/convert-bst-to-greater-tree.py | 2 +- ...vert-sorted-array-to-binary-search-tree.py | 8 +-- ...nvert-sorted-list-to-binary-search-tree.py | 6 +- Python/convex-polygon.py | 2 +- Python/copy-list-with-random-pointer.py | 12 ++-- Python/count-and-say.py | 10 ++-- Python/count-binary-substrings.py | 2 +- Python/count-complete-tree-nodes.py | 10 ++-- ...ount-different-palindromic-subsequences.py | 20 +++---- Python/count-of-range-sum.py | 4 +- Python/count-of-smaller-numbers-after-self.py | 18 +++--- Python/count-primes.py | 2 +- Python/count-the-repetitions.py | 6 +- Python/count-univalue-subtrees.py | 2 +- Python/counting-bits.py | 6 +- Python/couples-holding-hands.py | 2 +- Python/course-schedule.py | 36 ++++++------ Python/cracking-the-safe.py | 6 +- Python/create-maximum-number.py | 2 +- Python/daily-temperatures.py | 2 +- Python/decode-string.py | 4 +- Python/decode-ways.py | 6 +- Python/delete-and-earn.py | 4 +- Python/design-in-memory-file-system.py | 14 ++--- Python/design-log-storage-system.py | 6 +- Python/design-phone-directory.py | 6 +- Python/diagonal-traverse.py | 8 +-- Python/diameter-of-binary-tree.py | 8 +-- Python/distinct-subsequences.py | 14 ++--- Python/distribute-candies.py | 10 ++-- Python/divide-two-integers.py | 4 +- Python/dungeon-game.py | 58 +++++++++---------- Python/edit-distance.py | 16 ++--- Python/encode-and-decode-strings.py | 6 +- Python/encode-string-with-shortest-length.py | 2 +- Python/escape-the-ghosts.py | 12 ++-- Python/evaluate-reverse-polish-notation.py | 6 +- Python/excel-sheet-column-number.py | 8 +-- Python/excel-sheet-column-title.py | 10 ++-- Python/exclusive-time-of-functions.py | 8 +-- Python/expression-add-operators.py | 18 +++--- Python/factorial-trailing-zeroes.py | 2 +- Python/find-all-anagrams-in-a-string.py | 2 +- Python/find-all-duplicates-in-an-array.py | 4 +- Python/find-bottom-left-tree-value.py | 2 +- Python/find-k-pairs-with-smallest-sums.py | 2 +- Python/find-k-th-smallest-pair-distance.py | 2 +- Python/find-largest-value-in-each-tree-row.py | 8 +-- Python/find-median-from-data-stream.py | 8 +-- ...find-minimum-in-rotated-sorted-array-ii.py | 10 ++-- Python/find-mode-in-binary-search-tree.py | 4 +- Python/find-peak-element.py | 16 ++--- Python/find-pivot-index.py | 10 ++-- Python/find-the-duplicate-number.py | 2 +- Python/first-bad-version.py | 12 ++-- Python/first-missing-positive.py | 8 +-- Python/flatten-2d-vector.py | 2 +- Python/flatten-binary-tree-to-linked-list.py | 10 ++-- Python/flatten-nested-list-iterator.py | 2 +- Python/flip-game.py | 2 +- Python/flood-fill.py | 10 ++-- Python/fraction-to-recurring-decimal.py | 10 ++-- Python/friend-circles.py | 14 ++--- Python/frog-jump.py | 12 ++-- Python/game-of-life.py | 24 ++++---- Python/gas-station.py | 8 +-- Python/generate-parentheses.py | 8 +-- Python/global-and-local-inversions.py | 2 +- Python/gray-code.py | 12 ++-- Python/guess-number-higher-or-lower-ii.py | 2 +- Python/h-index.py | 12 ++-- Python/happy-number.py | 12 ++-- Python/house-robber-ii.py | 18 +++--- Python/house-robber-iii.py | 10 ++-- Python/house-robber.py | 12 ++-- Python/image-smoother.py | 2 +- Python/implement-queue-using-stacks.py | 4 +- Python/implement-strstr.py | 10 ++-- Python/implement-trie-prefix-tree.py | 4 +- Python/increasing-subsequences.py | 4 +- ...-delete-getrandom-o1-duplicates-allowed.py | 2 +- Python/insert-delete-getrandom-o1.py | 4 +- Python/insert-interval.py | 8 +-- Python/insertion-sort-list.py | 10 ++-- Python/integer-break.py | 6 +- Python/integer-replacement.py | 6 +- Python/integer-to-english-words.py | 2 +- Python/integer-to-roman.py | 8 +-- Python/interleaving-string.py | 20 +++---- Python/intersection-of-two-arrays-ii.py | 12 ++-- Python/intersection-of-two-arrays.py | 8 +-- Python/intersection-of-two-linked-lists.py | 22 +++---- Python/ip-to-cidr.py | 2 +- Python/is-graph-bipartite.py | 8 +-- Python/is-subsequence.py | 2 +- Python/isomorphic-strings.py | 8 +-- Python/jewels-and-stones.py | 2 +- Python/judge-route-circle.py | 2 +- Python/jump-game-ii.py | 12 ++-- Python/jump-game.py | 10 ++-- Python/k-diff-pairs-in-an-array.py | 2 +- Python/k-empty-slots.py | 8 +-- Python/k-inverse-pairs-array.py | 4 +- .../k-th-smallest-in-lexicographical-order.py | 4 +- Python/k-th-symbol-in-grammar.py | 2 +- Python/keyboard-row.py | 2 +- Python/knight-probability-in-chessboard.py | 4 +- Python/kth-largest-element-in-an-array.py | 6 +- Python/kth-smallest-element-in-a-bst.py | 2 +- ...kth-smallest-element-in-a-sorted-matrix.py | 2 +- ...smallest-number-in-multiplication-table.py | 8 +-- Python/largest-bst-subtree.py | 2 +- Python/largest-number.py | 6 +- Python/largest-palindrome-product.py | 2 +- Python/largest-plus-sign.py | 2 +- Python/largest-rectangle-in-histogram.py | 6 +- Python/length-of-last-word.py | 8 +-- .../letter-combinations-of-a-phone-number.py | 16 ++--- Python/lexicographical-numbers.py | 4 +- Python/linked-list-cycle-ii.py | 6 +- Python/linked-list-cycle.py | 2 +- Python/linked-list-random-node.py | 2 +- Python/longest-absolute-file-path.py | 2 +- Python/longest-consecutive-sequence.py | 4 +- ...ngest-continuous-increasing-subsequence.py | 6 +- Python/longest-increasing-path-in-a-matrix.py | 8 +-- Python/longest-increasing-subsequence.py | 2 +- Python/longest-palindromic-substring.py | 8 +-- ...ring-with-at-most-k-distinct-characters.py | 4 +- ...ng-with-at-most-two-distinct-characters.py | 12 ++-- ...-substring-without-repeating-characters.py | 2 +- Python/longest-uncommon-subsequence-i.py | 6 +- Python/longest-univalue-path.py | 2 +- Python/longest-valid-parentheses.py | 6 +- ...est-word-in-dictionary-through-deleting.py | 4 +- Python/lru-cache.py | 18 +++--- Python/majority-element-ii.py | 4 +- Python/majority-element.py | 6 +- Python/matchsticks-to-square.py | 4 +- Python/max-chunks-to-make-sorted-ii.py | 2 +- .../max-sum-of-sub-matrix-no-larger-than-k.py | 10 ++-- Python/maximal-rectangle.py | 8 +-- Python/maximal-square.py | 26 ++++----- Python/maximum-binary-tree.py | 4 +- Python/maximum-depth-of-binary-tree.py | 4 +- Python/maximum-gap.py | 26 ++++----- Python/maximum-product-of-word-lengths.py | 2 +- Python/maximum-product-subarray.py | 2 +- Python/maximum-subarray.py | 6 +- ...imum-sum-of-3-non-overlapping-subarrays.py | 8 +-- Python/maximum-width-of-binary-tree.py | 32 +++++----- .../maximum-xor-of-two-numbers-in-an-array.py | 2 +- Python/median-of-two-sorted-arrays.py | 10 ++-- Python/meeting-rooms.py | 2 +- Python/merge-intervals.py | 6 +- Python/merge-k-sorted-lists.py | 12 ++-- Python/merge-sorted-array.py | 10 ++-- Python/merge-two-binary-trees.py | 22 +++---- Python/merge-two-sorted-lists.py | 6 +- Python/min-stack.py | 12 ++-- .../minimize-max-distance-to-gas-station.py | 2 +- Python/minimum-depth-of-binary-tree.py | 4 +- Python/minimum-distance-between-bst-nodes.py | 6 +- Python/minimum-factorization.py | 2 +- Python/minimum-genetic-mutation.py | 24 ++++---- ...inimum-moves-to-equal-array-elements-ii.py | 2 +- Python/minimum-path-sum.py | 8 +-- Python/minimum-size-subarray-sum.py | 4 +- ...imum-swaps-to-make-sequences-increasing.py | 2 +- Python/minimum-window-subsequence.py | 2 +- Python/minimum-window-substring.py | 20 +++---- Python/missing-ranges.py | 10 ++-- Python/monotone-increasing-digits.py | 4 +- Python/move-zeroes.py | 8 +-- Python/multiply-strings.py | 2 +- Python/my-calendar-i.py | 4 +- Python/my-calendar-ii.py | 4 +- Python/n-queens-ii.py | 6 +- Python/n-queens.py | 28 ++++----- Python/nested-list-weight-sum-ii.py | 2 +- Python/next-greater-element-ii.py | 4 +- Python/next-permutation.py | 12 ++-- Python/nim-game.py | 4 +- Python/non-decreasing-array.py | 6 +- ...ative-integers-without-consecutive-ones.py | 4 +- Python/number-of-1-bits.py | 6 +- Python/number-of-boomerangs.py | 6 +- Python/number-of-corner-rectangles.py | 6 +- Python/number-of-distinct-islands-ii.py | 2 +- Python/number-of-islands-ii.py | 2 +- Python/number-of-islands.py | 10 ++-- Python/number-of-lines-to-write-string.py | 10 ++-- ...umber-of-longest-increasing-subsequence.py | 2 +- ...umber-of-subarrays-with-bounded-maximum.py | 2 +- Python/odd-even-linked-list.py | 2 +- Python/one-edit-distance.py | 6 +- Python/ones-and-zeroes.py | 6 +- Python/optimal-division.py | 4 +- Python/output-contest-matches.py | 2 +- Python/pacific-atlantic-water-flow.py | 10 ++-- Python/paint-house-ii.py | 2 +- Python/paint-house.py | 8 +-- Python/palindrome-number.py | 14 ++--- Python/palindrome-partitioning-ii.py | 8 +-- Python/palindrome-partitioning.py | 16 ++--- Python/palindromic-substrings.py | 4 +- Python/parse-lisp-expression.py | 2 +- Python/partition-list.py | 13 ++--- Python/partition-to-k-equal-sum-subsets.py | 6 +- Python/pascals-triangle-ii.py | 4 +- Python/pascals-triangle.py | 4 +- Python/patching-array.py | 4 +- Python/path-sum-ii.py | 10 ++-- Python/path-sum.py | 12 ++-- Python/peeking-iterator.py | 2 +- Python/perfect-number.py | 4 +- Python/perfect-rectangle.py | 6 +- Python/perfect-squares.py | 2 +- Python/permutation-sequence.py | 8 +-- Python/permutations-ii.py | 14 ++--- Python/permutations.py | 4 +- ...ing-next-right-pointers-in-each-node-ii.py | 19 +++--- ...lating-next-right-pointers-in-each-node.py | 12 ++-- Python/pour-water.py | 24 ++++---- Python/power-of-three.py | 2 +- Python/predict-the-winner.py | 8 +-- ...er-of-set-bits-in-binary-representation.py | 2 +- Python/print-binary-tree.py | 12 ++-- Python/product-of-array-except-self.py | 4 +- Python/pyramid-transition-matrix.py | 8 +-- Python/queue-reconstruction-by-height.py | 8 +-- Python/random-pick-index.py | 2 +- Python/range-addition-ii.py | 10 ++-- Python/range-sum-query-2d-immutable.py | 2 +- Python/range-sum-query-immutable.py | 8 +-- Python/range-sum-query-mutable.py | 22 +++---- Python/ransom-note.py | 2 +- ...ters-given-read4-ii-call-multiple-times.py | 16 ++--- Python/read-n-characters-given-read4.py | 12 ++-- ...econstruct-original-digits-from-english.py | 4 +- Python/recover-binary-search-tree.py | 33 +++++------ Python/redundant-connection-ii.py | 2 +- Python/redundant-connection.py | 2 +- Python/regular-expression-matching.py | 30 +++++----- Python/relative-ranks.py | 2 +- Python/remove-9.py | 2 +- Python/remove-boxes.py | 10 ++-- Python/remove-comments.py | 26 ++++----- .../remove-duplicates-from-sorted-array-ii.py | 8 +-- Python/remove-duplicates-from-sorted-array.py | 10 ++-- .../remove-duplicates-from-sorted-list-ii.py | 8 +-- Python/remove-element.py | 4 +- Python/remove-invalid-parentheses.py | 2 +- Python/remove-k-digits.py | 2 +- Python/remove-linked-list-elements.py | 10 ++-- Python/remove-nth-node-from-end-of-list.py | 18 +++--- Python/reorder-list.py | 16 ++--- Python/repeated-dna-sequences.py | 4 +- Python/reshape-the-matrix.py | 12 ++-- Python/restore-ip-addresses.py | 12 ++-- Python/reverse-bits.py | 2 +- Python/reverse-integer.py | 18 +++--- Python/reverse-linked-list-ii.py | 17 +++--- Python/reverse-linked-list.py | 12 ++-- Python/reverse-nodes-in-k-group.py | 30 +++++----- Python/reverse-vowels-of-a-string.py | 2 +- Python/reverse-words-in-a-string-ii.py | 6 +- Python/reverse-words-in-a-string.py | 6 +- Python/roman-to-integer.py | 2 +- Python/rotate-array.py | 4 +- Python/rotate-image.py | 14 ++--- Python/rotate-list.py | 8 +-- Python/rotate-string.py | 6 +- Python/rotated-digits.py | 12 ++-- Python/russian-doll-envelopes.py | 2 +- Python/same-tree.py | 8 +-- Python/scramble-string.py | 18 +++--- Python/search-a-2d-matrix-ii.py | 6 +- Python/search-a-2d-matrix.py | 8 +-- Python/search-for-a-range.py | 8 +-- Python/search-in-rotated-sorted-array-ii.py | 10 ++-- Python/search-in-rotated-sorted-array.py | 12 ++-- Python/search-insert-position.py | 6 +- Python/self-crossing.py | 4 +- Python/self-dividing-numbers.py | 4 +- Python/sentence-screen-fitting.py | 2 +- .../serialize-and-deserialize-binary-tree.py | 14 ++--- Python/set-matrix-zeroes.py | 10 ++-- Python/set-mismatch.py | 4 +- Python/shopping-offers.py | 16 ++--- .../shortest-distance-from-all-buildings.py | 4 +- Python/shortest-palindrome.py | 12 ++-- .../shortest-unsorted-continuous-subarray.py | 2 +- Python/simplify-path.py | 4 +- Python/single-element-in-a-sorted-array.py | 2 +- Python/single-number-ii.py | 6 +- Python/single-number.py | 2 +- Python/sliding-window-maximum.py | 2 +- .../smallest-rotation-with-highest-score.py | 12 ++-- Python/sort-colors.py | 16 ++--- Python/sort-list.py | 18 +++--- Python/special-binary-string.py | 2 +- Python/spiral-matrix-ii.py | 10 ++-- Python/spiral-matrix.py | 10 ++-- ...lit-array-into-consecutive-subsequences.py | 4 +- Python/split-array-with-equal-sum.py | 2 +- Python/split-array-with-same-average.py | 2 +- Python/split-concatenated-strings.py | 6 +- Python/split-linked-list-in-parts.py | 4 +- Python/sqrtx.py | 6 +- Python/squirrel-simulation.py | 2 +- Python/strange-printer.py | 4 +- Python/string-to-integer-atoi.py | 44 +++++++------- Python/strobogrammatic-number-ii.py | 2 +- Python/strobogrammatic-number-iii.py | 4 +- Python/strong-password-checker.py | 8 +-- Python/student-attendance-record-i.py | 2 +- Python/student-attendance-record-ii.py | 4 +- Python/subarray-product-less-than-k.py | 2 +- Python/subsets-ii.py | 12 ++-- Python/subsets.py | 12 ++-- Python/subtree-of-another-tree.py | 4 +- Python/sudoku-solver.py | 6 +- Python/sum-of-left-leaves.py | 2 +- Python/sum-root-to-leaf-numbers.py | 18 +++--- Python/super-washing-machines.py | 18 +++--- Python/swap-nodes-in-pairs.py | 7 +-- Python/swim-in-rising-water.py | 6 +- Python/symmetric-tree.py | 24 ++++---- Python/tag-validator.py | 12 ++-- Python/teemo-attacking.py | 14 ++--- Python/ternary-expression-parser.py | 4 +- Python/text-justification.py | 18 +++--- Python/the-skyline-problem.py | 54 ++++++++--------- Python/total-hamming-distance.py | 2 +- Python/trapping-rain-water-ii.py | 2 +- Python/trapping-rain-water.py | 24 ++++---- Python/triangle.py | 10 ++-- Python/trim-a-binary-search-tree.py | 14 ++--- Python/two-sum-ii-input-array-is-sorted.py | 14 ++--- Python/two-sum-iii-data-structure-design.py | 12 ++-- Python/two-sum-iv-input-is-a-bst.py | 6 +- Python/unique-binary-search-trees-ii.py | 18 +++--- Python/unique-binary-search-trees.py | 6 +- Python/unique-morse-code-words.py | 2 +- Python/unique-paths-ii.py | 12 ++-- Python/unique-paths.py | 11 ++-- Python/valid-number.py | 12 ++-- Python/valid-palindrome-ii.py | 2 +- Python/valid-palindrome.py | 6 +- Python/valid-parentheses.py | 6 +- Python/valid-sudoku.py | 6 +- Python/valid-tic-tac-toe-state.py | 4 +- Python/valid-triangle-number.py | 2 +- Python/validate-binary-search-tree.py | 16 ++--- ...preorder-serialization-of-a-binary-tree.py | 6 +- Python/walls-and-gates.py | 2 +- Python/water-and-jug-problem.py | 4 +- Python/wiggle-sort-ii.py | 4 +- Python/wiggle-subsequence.py | 4 +- Python/wildcard-matching.py | 20 +++---- Python/word-break-ii.py | 12 ++-- Python/word-break.py | 8 +-- Python/word-ladder-ii.py | 18 +++--- Python/word-ladder.py | 6 +- Python/word-pattern-ii.py | 2 +- Python/word-pattern.py | 6 +- Python/word-search-ii.py | 16 ++--- Python/word-search.py | 26 ++++----- Python/word-squares.py | 4 +- Python/zigzag-conversion.py | 6 +- 431 files changed, 1782 insertions(+), 1781 deletions(-) diff --git a/Python/balanced-binary-tree.py b/Python/balanced-binary-tree.py index fbf1326ab..c65c301ba 100644 --- a/Python/balanced-binary-tree.py +++ b/Python/balanced-binary-tree.py @@ -3,37 +3,32 @@ # # Given a binary tree, determine if it is height-balanced. # -# For this problem, a height-balanced binary tree is defined as a binary tree -# in which the depth of the two subtrees of every node never differ by more than 1. +# For this problem, a height-balanced binary tree is defined as a binary +# tree +# in which the depth of the two subtrees of every node never differ by more +# than 1. # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): # @param root, a tree node # @return a boolean def isBalanced(self, root): - return (self.getHeight(root) >= 0) - - def getHeight(self, root): - if root is None: - return 0 - left_height, right_height = self.getHeight(root.left), self.getHeight(root.right) - if left_height < 0 or right_height < 0 or abs(left_height - right_height) > 1: - return -1 - return max(left_height, right_height) + 1 - -if __name__ == "__main__": - root = TreeNode(0) - root.left = TreeNode(1) - result = Solution().isBalanced(root) - print result - - root.left.left = TreeNode(2) - result = Solution().isBalanced(root) - print result + def getHeight(root): + if root is None: + return 0 + left_height, right_height = \ + getHeight(root.left), getHeight(root.right) + if left_height < 0 or right_height < 0 or \ + abs(left_height - right_height) > 1: + return -1 + return max(left_height, right_height) + 1 + return (getHeight(root) >= 0) diff --git a/Python/base-7.py b/Python/base-7.py index b6544bd02..5fbc956a7 100644 --- a/Python/base-7.py +++ b/Python/base-7.py @@ -11,9 +11,11 @@ # Output: "-10" # Note: The input will be in range of [-1e7, 1e7]. + class Solution(object): def convertToBase7(self, num): - if num < 0: return '-' + self.convertToBase7(-num) + if num < 0: + return '-' + self.convertToBase7(-num) result = '' while num: result = str(num % 7) + result @@ -27,6 +29,8 @@ def convertToBase7(self, num): :type num: int :rtype: str """ - if num < 0: return '-' + self.convertToBase7(-num) - if num < 7: return str(num) + if num < 0: + return '-' + self.convertToBase7(-num) + if num < 7: + return str(num) return self.convertToBase7(num // 7) + str(num % 7) diff --git a/Python/baseball-game.py b/Python/baseball-game.py index ede8ff9d9..309e1a45f 100644 --- a/Python/baseball-game.py +++ b/Python/baseball-game.py @@ -4,38 +4,45 @@ # You're now a baseball game point recorder. # Given a list of strings, each string can be one of the 4 following types: # -# 1. Integer (one round's score): Directly represents the number of points you get in this round. -# 2. "+" (one round's score): Represents that the points you get in this round are -# the sum of the last two valid round's points. -# 3. "D" (one round's score): Represents that the points you get in this round are -# the doubled data of the last valid round's points. -# 4. "C" (an operation, which isn't a round's score): Represents the last valid round's points -# you get were invalid and should be removed. -# -# Each round's operation is permanent and could have an impact on the round before and the round after. +# 1. Integer (one round's score): Directly represents the number of points +# you get in this round. +# 2. "+" (one round's score): Represents that the points you get in +# this round are the sum of the last two valid +# round's points. +# 3. "D" (one round's score): Represents that the points you get in this round +# are the doubled data of the last valid round's +# points. +# 4. "C" (an operation, which isn't a round's score): Represents the last +# valid round's points you get were invalid and +# should be removed. +# +# Each round's operation is permanent and could have an impact on the round +# before and the round after. # You need to return the sum of the points you could get in all the rounds. # # Example 1: # # Input: ["5","2","C","D","+"] # Output: 30 -# Explanation: +# Explanation: # Round 1: You could get 5 points. The sum is: 5. # Round 2: You could get 2 points. The sum is: 7. -# Operation 1: The round 2's data was invalid. The sum is: 5. -# Round 3: You could get 10 points (the round 2's data has been removed). The sum is: 15. +# Operation 1: The round 2's data was invalid. The sum is: 5. +# Round 3: You could get 10 points (the round 2's data has been removed). +# The sum is: 15. # Round 4: You could get 5 + 10 = 15 points. The sum is: 30. -# +# # Example 2: # # Input: ["5","-2","4","C","D","9","+","+"] # Output: 27 -# Explanation: +# Explanation: # Round 1: You could get 5 points. The sum is: 5. # Round 2: You could get -2 points. The sum is: 3. # Round 3: You could get 4 points. The sum is: 7. -# Operation 1: The round 3's data is invalid. The sum is: 3. -# Round 4: You could get -4 points (the round 3's data has been removed). The sum is: -1. +# Operation 1: The round 3's data is invalid. The sum is: 3. +# Round 4: You could get -4 points (the round 3's data has been removed). +# The sum is: -1. # Round 5: You could get 9 points. The sum is: 8. # Round 6: You could get -4 + 9 = 5 points. The sum is 13. # Round 7: You could get 9 + 5 = 14 points. The sum is 27. @@ -43,7 +50,8 @@ # Note: # The size of the input list will be between 1 and 1000. # Every integer represented in the list will be between -30000 and 30000. - + + class Solution(object): def calPoints(self, ops): """ diff --git a/Python/basic-calculator-ii.py b/Python/basic-calculator-ii.py index 4575b8a69..03df2953e 100644 --- a/Python/basic-calculator-ii.py +++ b/Python/basic-calculator-ii.py @@ -3,7 +3,7 @@ # # Implement a basic calculator to evaluate a simple expression string. # -# The expression string contains only non-negative integers, +, -, *, / +# 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. @@ -38,10 +38,10 @@ def calculate(self, s): while operators[-1] != ')': self.compute(operands, operators) operators.pop() - + while operators: self.compute(operands, operators) - + return operands[-1] def compute(self, operands, operators): diff --git a/Python/basic-calculator-iii.py b/Python/basic-calculator-iii.py index 0010d2a4d..04568b2cf 100644 --- a/Python/basic-calculator-iii.py +++ b/Python/basic-calculator-iii.py @@ -46,10 +46,10 @@ def calculate(self, s): while operators[-1] != ')': self.compute(operands, operators) operators.pop() - + while operators: self.compute(operands, operators) - + return operands[-1] def compute(self, operands, operators): @@ -63,4 +63,4 @@ def compute(self, operands, operators): operands.append(left * right) elif op == '/': operands.append(left / right) - + diff --git a/Python/basic-calculator.py b/Python/basic-calculator.py index ea4ca3245..cae7f5527 100644 --- a/Python/basic-calculator.py +++ b/Python/basic-calculator.py @@ -32,10 +32,10 @@ def calculate(self, s): while operators[-1] != ')': self.compute(operands, operators) operators.pop() - + while operators: self.compute(operands, operators) - + return operands[-1] def compute(self, operands, operators): diff --git a/Python/battleships-in-a-board.py b/Python/battleships-in-a-board.py index 9f9c49944..7d6c7490b 100644 --- a/Python/battleships-in-a-board.py +++ b/Python/battleships-in-a-board.py @@ -9,7 +9,7 @@ # Battleships can only be placed horizontally or vertically. In other words, # they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), # where N can be of any size. -# At least one horizontal or vertical cell separates between two battleships - +# At least one horizontal or vertical cell separates between two battleships - # there are no adjacent battleships. # # Example: diff --git a/Python/beautiful-arrangement-ii.py b/Python/beautiful-arrangement-ii.py index 007a28eb6..e9617beec 100644 --- a/Python/beautiful-arrangement-ii.py +++ b/Python/beautiful-arrangement-ii.py @@ -3,7 +3,7 @@ # Given two integers n and k, # you need to construct a list which contains n different positive integers ranging -# from 1 to n and obeys the following requirement: +# from 1 to n and obeys the following requirement: # Suppose this list is [a1, a2, a3, ... , an], # then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers. # diff --git a/Python/beautiful-arrangement.py b/Python/beautiful-arrangement.py index 383209c20..64327bfcd 100644 --- a/Python/beautiful-arrangement.py +++ b/Python/beautiful-arrangement.py @@ -2,7 +2,7 @@ # Space: O(n) # Suppose you have N integers from 1 to N. -# We define a beautiful arrangement as an array that is constructed by these N numbers successfully +# We define a beautiful arrangement as an array that is constructed by these N numbers successfully # if one of the following is true for the ith position (1 <= i <= N) in this array: # # The number at the ith position is divisible by i. @@ -12,7 +12,7 @@ # Example 1: # Input: 2 # Output: 2 -# Explanation: +# Explanation: # # The first beautiful arrangement is [1, 2]: # diff --git a/Python/best-meeting-point.py b/Python/best-meeting-point.py index 52b481624..ca5554f63 100644 --- a/Python/best-meeting-point.py +++ b/Python/best-meeting-point.py @@ -13,10 +13,10 @@ def minTotalDistance(self, grid): 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: @@ -28,7 +28,7 @@ def findKthLargest(self, nums, k): 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 @@ -37,6 +37,6 @@ def PartitionAroundPivot(self, left, right, pivot_idx, nums): 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 diff --git a/Python/best-time-to-buy-and-sell-stock-ii.py b/Python/best-time-to-buy-and-sell-stock-ii.py index 133ed078a..b0d12c7a9 100644 --- a/Python/best-time-to-buy-and-sell-stock-ii.py +++ b/Python/best-time-to-buy-and-sell-stock-ii.py @@ -1,13 +1,13 @@ # Time: O(n) # Space: O(1) # -# Say you have an array for which the ith element is +# 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). -# However, you may not engage in multiple transactions at the same time +# 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). +# However, you may not engage in multiple transactions at the same time # (ie, you must sell the stock before you buy again). @@ -17,7 +17,7 @@ class Solution: def maxProfit(self, prices): profit = 0 for i in xrange(len(prices) - 1): - profit += max(0, prices[i + 1] - prices[i]) + profit += max(0, prices[i + 1] - prices[i]) return profit def maxProfit2(self, prices): 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 114c1b321..89109f853 100644 --- a/Python/best-time-to-buy-and-sell-stock-iii.py +++ b/Python/best-time-to-buy-and-sell-stock-iii.py @@ -1,14 +1,14 @@ # Time: O(n) # Space: O(1) # -# Say you have an array for which the ith element +# 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. +# Design an algorithm to find the maximum profit. # You may complete at most two transactions. # # Note: -# You may not engage in multiple transactions at the same time +# You may not engage in multiple transactions at the same time # (ie, you must sell the stock before you buy again). # @@ -26,7 +26,7 @@ def maxProfit(self, prices): release1 = max(release1, hold1 + i) hold1 = max(hold1, -i); return release2 - + # Time: O(k * n) # Space: O(k) class Solution2: @@ -34,7 +34,7 @@ class Solution2: # @return an integer def maxProfit(self, prices): return self.maxAtMostKPairsProfit(prices, 2) - + def maxAtMostKPairsProfit(self, prices, k): max_buy = [float("-inf") for _ in xrange(k + 1)] max_sell = [0 for _ in xrange(k + 1)] @@ -47,7 +47,7 @@ def maxAtMostKPairsProfit(self, prices, k): return max_sell[k] # Time: O(n) -# Space: O(n) +# Space: O(n) class Solution3: # @param prices, a list of integer # @return an integer @@ -57,19 +57,19 @@ def maxProfit(self, prices): min_price = min(min_price, price) max_profit_from_left = max(max_profit_from_left, price - min_price) max_profits_from_left.append(max_profit_from_left) - + max_price, max_profit_from_right, max_profits_from_right = 0, 0, [] for i in reversed(range(len(prices))): max_price = max(max_price, prices[i]) max_profit_from_right = max(max_profit_from_right, max_price - prices[i]) max_profits_from_right.insert(0, max_profit_from_right) - + max_profit = 0 for i in range(len(prices)): max_profit = max(max_profit, max_profits_from_left[i] + max_profits_from_right[i]) - + return max_profit - + if __name__ == "__main__": result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6]) print result 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 0235f07df..2d0071909 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -2,15 +2,15 @@ # 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 + # @return an integer as the maximum profit def maxProfit(self, k, prices): if k >= len(prices) / 2: return self.maxAtMostNPairsProfit(prices) @@ -20,7 +20,7 @@ def maxProfit(self, k, prices): def maxAtMostNPairsProfit(self, prices): profit = 0 for i in xrange(len(prices) - 1): - profit += max(0, prices[i + 1] - prices[i]) + profit += max(0, prices[i + 1] - prices[i]) return profit def maxAtMostKPairsProfit(self, prices, k): diff --git a/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py b/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py index 7393b5b6e..4b622e833 100644 --- a/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py +++ b/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py @@ -39,4 +39,4 @@ def maxProfit(self, prices, fee): cash = max(cash, hold+prices[i]-fee) hold = max(hold, cash-prices[i]) return cash - + diff --git a/Python/best-time-to-buy-and-sell-stock.py b/Python/best-time-to-buy-and-sell-stock.py index 2c86c4a74..748b5e638 100644 --- a/Python/best-time-to-buy-and-sell-stock.py +++ b/Python/best-time-to-buy-and-sell-stock.py @@ -1,11 +1,11 @@ # Time: O(n) # Space: O(1) # -# Say you have an array for which the ith element +# Say you have an array for which the ith element # is the price of a given stock on day i. # -# If you were only permitted to complete at most one transaction -# (ie, buy one and sell one share of the stock), +# If you were only permitted to complete at most one transaction +# (ie, buy one and sell one share of the stock), # design an algorithm to find the maximum profit. # @@ -16,10 +16,10 @@ def maxProfit(self, prices): max_profit, min_price = 0, float("inf") for price in prices: min_price = min(min_price, price) - max_profit = max(max_profit, price - min_price) + max_profit = max(max_profit, price - min_price) return max_profit if __name__ == "__main__": result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6]) print result - + diff --git a/Python/binary-number-with-alternating-bits.py b/Python/binary-number-with-alternating-bits.py index ff066353a..e8f06d5b9 100644 --- a/Python/binary-number-with-alternating-bits.py +++ b/Python/binary-number-with-alternating-bits.py @@ -27,7 +27,7 @@ # Output: True # Explanation: # The binary representation of 10 is: 1010. - + class Solution(object): def hasAlternatingBits(self, n): """ diff --git a/Python/binary-search-tree-iterator.py b/Python/binary-search-tree-iterator.py index 428c8d4a3..ae455dea3 100644 --- a/Python/binary-search-tree-iterator.py +++ b/Python/binary-search-tree-iterator.py @@ -1,11 +1,11 @@ # Time: O(1) # 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. -# +# # Calling next() will return the next smallest number in the BST. -# +# # Note: next() and hasNext() should run in average O(1) time # and uses O(h) memory, where h is the height of the tree. # @@ -32,19 +32,19 @@ def next(self): while self.cur: self.stack.append(self.cur) self.cur = self.cur.left - + self.cur = self.stack.pop() node = self.cur self.cur = self.cur.right - + return node.val - + if __name__ == "__main__": root = TreeNode(2) root.left = TreeNode(1) - + # Your BSTIterator will be called like this: i, v = BSTIterator(root), [] while i.hasNext(): v.append(i.next()) - + print v diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py index 11448e3fa..b82319cfe 100644 --- a/Python/binary-tree-inorder-traversal.py +++ b/Python/binary-tree-inorder-traversal.py @@ -39,7 +39,7 @@ def inorderTraversal(self, root): node = curr.left while node.right and node.right != curr: node = node.right - + if node.right is None: node.right = curr curr = curr.left @@ -47,7 +47,7 @@ def inorderTraversal(self, root): result.append(curr.val) node.right = None curr = curr.right - + return result diff --git a/Python/binary-tree-level-order-traversal-ii.py b/Python/binary-tree-level-order-traversal-ii.py index a03432a5d..0973c82e2 100644 --- a/Python/binary-tree-level-order-traversal-ii.py +++ b/Python/binary-tree-level-order-traversal-ii.py @@ -3,7 +3,7 @@ # Given a binary tree, return the bottom-up level order traversal of its nodes' values. # (ie, from left to right, level by level from leaf to root). -# +# # For example: # Given binary tree {3,9,20,#,#,15,7}, # 3 diff --git a/Python/binary-tree-level-order-traversal.py b/Python/binary-tree-level-order-traversal.py index f1b8c9c47..8e48c8372 100644 --- a/Python/binary-tree-level-order-traversal.py +++ b/Python/binary-tree-level-order-traversal.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(n) # -# Given a binary tree, return the level order traversal of its nodes' values. +# Given a binary tree, return the level order traversal of its nodes' values. # (ie, from left to right, level by level). # # For example: diff --git a/Python/binary-tree-longest-consecutive-sequence-ii.py b/Python/binary-tree-longest-consecutive-sequence-ii.py index 99c88f13c..b7c0f7bec 100644 --- a/Python/binary-tree-longest-consecutive-sequence-ii.py +++ b/Python/binary-tree-longest-consecutive-sequence-ii.py @@ -36,4 +36,4 @@ def longestConsecutiveHelper(root): self.max_len = 0 longestConsecutiveHelper(root) return self.max_len - + diff --git a/Python/binary-tree-longest-consecutive-sequence.py b/Python/binary-tree-longest-consecutive-sequence.py index 769c417ee..e9c6c7444 100644 --- a/Python/binary-tree-longest-consecutive-sequence.py +++ b/Python/binary-tree-longest-consecutive-sequence.py @@ -19,10 +19,10 @@ def longestConsecutive(self, root): 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); diff --git a/Python/binary-tree-maximum-path-sum.py b/Python/binary-tree-maximum-path-sum.py index d71f6eeba..b3d25e94a 100644 --- a/Python/binary-tree-maximum-path-sum.py +++ b/Python/binary-tree-maximum-path-sum.py @@ -2,12 +2,12 @@ # Space: O(h), h is height of binary tree # # Given a binary tree, find the maximum path sum. -# +# # The path may start and end at any node in the tree. -# +# # For example: # Given the below binary tree, -# +# # 1 # / \ # 2 3 @@ -27,7 +27,7 @@ class Solution: def maxPathSum(self, root): self.maxPathSumRecu(root) return self.maxSum - + def maxPathSumRecu(self, root): if root is None: return 0 @@ -35,7 +35,7 @@ def maxPathSumRecu(self, root): right = max(0, self.maxPathSumRecu(root.right)) self.maxSum = max(self.maxSum, root.val + left + right) return root.val + max(left, right) - + if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) diff --git a/Python/binary-tree-paths.py b/Python/binary-tree-paths.py index 657e8d579..770adfdfb 100644 --- a/Python/binary-tree-paths.py +++ b/Python/binary-tree-paths.py @@ -29,7 +29,7 @@ def binaryTreePaths(self, root): result, path = [], [] self.binaryTreePathsRecu(root, path, result) return result - + def binaryTreePathsRecu(self, node, path, result): if node is None: return diff --git a/Python/binary-tree-postorder-traversal.py b/Python/binary-tree-postorder-traversal.py index c5a47b0c8..e0ae110cd 100644 --- a/Python/binary-tree-postorder-traversal.py +++ b/Python/binary-tree-postorder-traversal.py @@ -40,7 +40,7 @@ def postorderTraversal(self, root): node = cur.left while node.right and node.right != cur: node = node.right - + if node.right is None: node.right = cur cur = cur.left @@ -48,9 +48,9 @@ def postorderTraversal(self, root): result += self.traceBack(cur.left, node) node.right = None cur = cur.right - + return result - + def traceBack(self, frm, to): result, cur = [], frm while cur is not to: @@ -63,7 +63,7 @@ def traceBack(self, frm, to): # Time: O(n) # Space: O(h) -# Stack Solution +# Stack Solution class Solution2(object): def postorderTraversal(self, root): """ diff --git a/Python/binary-tree-preorder-traversal.py b/Python/binary-tree-preorder-traversal.py index 2ba22d545..9cf12ee7a 100644 --- a/Python/binary-tree-preorder-traversal.py +++ b/Python/binary-tree-preorder-traversal.py @@ -39,7 +39,7 @@ def preorderTraversal(self, root): node = curr.left while node.right and node.right != curr: node = node.right - + if node.right is None: result.append(curr.val) node.right = curr @@ -47,13 +47,13 @@ def preorderTraversal(self, root): else: node.right = None curr = curr.right - + return result # Time: O(n) # Space: O(h) -# Stack Solution +# Stack Solution class Solution2(object): def preorderTraversal(self, root): """ diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py index 56d5e3db2..effd0ad13 100644 --- a/Python/binary-tree-right-side-view.py +++ b/Python/binary-tree-right-side-view.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(h) # -# Given a binary tree, imagine yourself standing on the right side of it, +# 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: @@ -28,27 +28,27 @@ 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) +# Space: O(n) class Solution2: # @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 = [] @@ -60,7 +60,7 @@ def rightSideView(self, root): if i == len(current) - 1: result.append(node.val) current = next_level - + return result if __name__ == "__main__": diff --git a/Python/binary-tree-tilt.py b/Python/binary-tree-tilt.py index e1ed02783..76ca7e745 100644 --- a/Python/binary-tree-tilt.py +++ b/Python/binary-tree-tilt.py @@ -10,12 +10,12 @@ # The tilt of the whole tree is defined as the sum of all nodes' tilt. # # Example: -# Input: +# Input: # 1 # / \ # 2 3 # Output: 1 -# Explanation: +# Explanation: # Tilt of node 2 : 0 # Tilt of node 3 : 0 # Tilt of node 1 : |2-3| = 1 diff --git a/Python/binary-tree-upside-down.py b/Python/binary-tree-upside-down.py index 51315ff94..e68f4e923 100644 --- a/Python/binary-tree-upside-down.py +++ b/Python/binary-tree-upside-down.py @@ -1,27 +1,27 @@ # Time: O(n) # Space: O(1) # -# Given a binary tree where all the right nodes are either leaf nodes with a sibling -# (a left node that shares the same parent node) or empty, flip it upside down and -# turn it into a tree where the original right nodes turned into left leaf nodes. +# Given a binary tree where all the right nodes are either leaf nodes with a sibling +# (a left node that shares the same parent node) or empty, flip it upside down and +# turn it into a tree where the original right nodes turned into left leaf nodes. # Return the new root. -# +# # For example: # Given a binary tree {1,2,3,4,5}, -# +# # 1 # / \ # 2 3 # / \ # 4 5 -# +# # return the root of the binary tree [4,5,2,#,#,3,1]. -# +# # 4 # / \ # 5 2 # / \ -# 3 1 +# 3 1 # # Definition for a binary tree node @@ -36,7 +36,7 @@ class Solution: # @return root of the upside down tree def upsideDownBinaryTree(self, root): p, parent, parent_right = root, None, None - + while p: left = p.left p.left = parent_right @@ -44,7 +44,7 @@ def upsideDownBinaryTree(self, root): p.right = parent parent = p p = left - + return parent # Time: O(n) @@ -54,16 +54,16 @@ class Solution2: # @return root of the upside down tree def upsideDownBinaryTree(self, root): return self.upsideDownBinaryTreeRecu(root, None) - + def upsideDownBinaryTreeRecu(self, p, parent): if p is None: return parent - + root = self.upsideDownBinaryTreeRecu(p.left, p) if parent: p.left = parent.right else: p.left = None p.right = parent - + return root \ No newline at end of file diff --git a/Python/binary-tree-zigzag-level-order-traversal.py b/Python/binary-tree-zigzag-level-order-traversal.py index 7a6261e05..1a5dac583 100644 --- a/Python/binary-tree-zigzag-level-order-traversal.py +++ b/Python/binary-tree-zigzag-level-order-traversal.py @@ -2,7 +2,7 @@ # Space: O(n) # # Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). -# +# # For example: # Given binary tree {3,9,20,#,#,15,7}, # 3 diff --git a/Python/bitwise-and-of-numbers-range.py b/Python/bitwise-and-of-numbers-range.py index 369a5a803..0dc2cad71 100644 --- a/Python/bitwise-and-of-numbers-range.py +++ b/Python/bitwise-and-of-numbers-range.py @@ -1,7 +1,7 @@ # Time: O(1) # Space: O(1) # -# Given a range [m, n] where 0 <= m <= n <= 2147483647, +# 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. diff --git a/Python/boundary-of-binary-tree.py b/Python/boundary-of-binary-tree.py index ad7a6a6b3..c71ed0df4 100644 --- a/Python/boundary-of-binary-tree.py +++ b/Python/boundary-of-binary-tree.py @@ -31,7 +31,7 @@ def rightBoundary(root, nodes): else: rightBoundary(root.right, nodes) nodes.append(root.val) - + def leaves(root, nodes): if not root: return @@ -43,7 +43,7 @@ def leaves(root, nodes): if not root: return [] - + nodes = [root.val] leftBoundary(root.left, nodes) leaves(root.left, nodes) diff --git a/Python/bricks-falling-when-hit.py b/Python/bricks-falling-when-hit.py index 3a94f4bd5..9901572c7 100644 --- a/Python/bricks-falling-when-hit.py +++ b/Python/bricks-falling-when-hit.py @@ -12,19 +12,19 @@ # Return an array representing the number of bricks that will drop after each erasure in sequence. # # Example 1: -# Input: +# Input: # grid = [[1,0,0,0],[1,1,1,0]] # hits = [[1,0]] # Output: [2] -# Explanation: +# Explanation: # If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. So we should return 2. # # Example 2: -# Input: +# Input: # grid = [[1,0,0,0],[1,1,0,0]] # hits = [[1,1],[1,0]] # Output: [0,0] -# Explanation: +# Explanation: # When we erase the brick at (1, 0), the brick at (1, 1) has already disappeared due to the last move. # So each erasure will cause no bricks dropping. # Note that the erased brick (1, 0) will not be counted as a dropped brick. @@ -56,7 +56,7 @@ def union_set(self, x, y): def top(self): return self.size[self.find_set(len(self.size)-1)] - + class Solution(object): def hitBricks(self, grid, hits): @@ -67,7 +67,7 @@ def hitBricks(self, grid, hits): """ def index(C, r, c): return r*C+c - + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] R, C = len(grid), len(grid[0]) diff --git a/Python/bulb-switcher-ii.py b/Python/bulb-switcher-ii.py index 3ce93572a..3bb37192d 100644 --- a/Python/bulb-switcher-ii.py +++ b/Python/bulb-switcher-ii.py @@ -24,7 +24,7 @@ # Output: 4 # Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on]. # Note: n and m both fit in range [0, 1000]. - + class Solution(object): def flipLights(self, n, m): """ diff --git a/Python/burst-balloons.py b/Python/burst-balloons.py index acdd5c15e..4cb6ebd9c 100644 --- a/Python/burst-balloons.py +++ b/Python/burst-balloons.py @@ -1,20 +1,20 @@ # 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. +# 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. +# 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 +# Find the maximum coins you can collect by # bursting the balloons wisely. # -# Note: +# 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 @@ -38,7 +38,7 @@ def maxCoins(self, nums): 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 @@ -48,4 +48,4 @@ def maxCoins(self, nums): max_coins[left][i] + max_coins[i][right]) return max_coins[0][-1] - + diff --git a/Python/can-i-win.py b/Python/can-i-win.py index 1877b04e9..8e482cf30 100644 --- a/Python/can-i-win.py +++ b/Python/can-i-win.py @@ -53,7 +53,7 @@ def canIWinHelper(maxChoosableInteger, desiredTotal, visited, lookup): mask <<= 1 lookup[visited] = False return False - + if (1 + maxChoosableInteger) * (maxChoosableInteger / 2) < desiredTotal: return False diff --git a/Python/candy-crush.py b/Python/candy-crush.py index 782f4af05..591398830 100644 --- a/Python/candy-crush.py +++ b/Python/candy-crush.py @@ -25,7 +25,7 @@ # # Example 1: # Input: -# board = +# board = # [[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]] # Output: # [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]] @@ -43,7 +43,7 @@ def candyCrush(self, board): """ R, C = len(board), len(board[0]) changed = True - + while changed: changed = False diff --git a/Python/candy.py b/Python/candy.py index daf2f8153..eded6772a 100644 --- a/Python/candy.py +++ b/Python/candy.py @@ -2,9 +2,9 @@ # Space: O(n) # # There are N children standing in a line. Each child is assigned a rating value. -# +# # You are giving candies to these children subjected to the following requirements: -# +# # Each child must have at least one candy. # Children with a higher rating get more candies than their neighbors. # What is the minimum candies you must give? @@ -20,13 +20,13 @@ def candy(self, ratings): for i in xrange(1, len(ratings)): if ratings[i] > ratings[i - 1]: candies[i] = candies[i - 1] + 1 - + for i in reversed(xrange(1, len(ratings))): if ratings[i - 1] > ratings[i] and candies[i - 1] <= candies[i]: candies[i - 1] = candies[i] + 1 - + return reduce(operator.add, candies) - + if __name__ == "__main__": result = Solution().candy([1, 2, 3, 2, 3, 5, 2, 5]) print result diff --git a/Python/cherry-pickup.py b/Python/cherry-pickup.py index 4764f990d..f5815a5ab 100644 --- a/Python/cherry-pickup.py +++ b/Python/cherry-pickup.py @@ -20,7 +20,7 @@ # [1, 0, -1], # [1, 1, 1]] # Output: 5 -# Explanation: +# Explanation: # The player started at (0, 0) and went down, down, right right to reach (2, 2). # 4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]]. # Then, the player went left, up, up, left to return home, picking up one more cherry. @@ -38,7 +38,7 @@ def cherryPickup(self, grid): :rtype: int """ # dp holds the max # of cherries two k-length paths can pickup. - # The two k-length paths arrive at (i, k - i) and (j, k - j), + # The two k-length paths arrive at (i, k - i) and (j, k - j), # respectively. n = len(grid) dp = [[-1 for _ in xrange(n)] for _ in xrange(n)] diff --git a/Python/circular-array-loop.py b/Python/circular-array-loop.py index f1b9e10e4..32c7f87c7 100644 --- a/Python/circular-array-loop.py +++ b/Python/circular-array-loop.py @@ -26,18 +26,18 @@ def circularArrayLoop(self, nums): """ def next_index(nums, i): return (i + nums[i]) % len(nums) - + for i in xrange(len(nums)): if nums[i] == 0: continue - + slow, fast = i, i while nums[next_index(nums, slow)] * nums[i] > 0 and \ nums[next_index(nums, fast)] * nums[i] > 0 and \ nums[next_index(nums, next_index(nums, fast))] * nums[i] > 0: slow = next_index(nums, slow) fast = next_index(nums, next_index(nums, fast)) - if slow == fast: + if slow == fast: if slow == next_index(nums, slow): break return True diff --git a/Python/climbing-stairs.py b/Python/climbing-stairs.py index 6511a1dee..a6ccff427 100644 --- a/Python/climbing-stairs.py +++ b/Python/climbing-stairs.py @@ -2,8 +2,8 @@ # Space: O(1) # # You are climbing a stair case. It takes n steps to reach to the top. -# -# Each time you can either climb 1 or 2 steps. +# +# Each time you can either climb 1 or 2 steps. # In how many distinct ways can you climb to the top? @@ -15,7 +15,7 @@ class Solution: def climbStairs(self, n): prev, current = 0, 1 for i in xrange(n): - prev, current = current, prev + current, + prev, current = current, prev + current, return current # Time: O(2^n) diff --git a/Python/clone-graph.py b/Python/clone-graph.py index 87ecec311..a4a0b0338 100644 --- a/Python/clone-graph.py +++ b/Python/clone-graph.py @@ -2,21 +2,21 @@ # Space: O(n) # # Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. -# -# +# +# # OJ's undirected graph serialization: # Nodes are labeled uniquely. -# +# # We use # as a separator for each node, and , as a separator for node label and each neighbor of the node. # As an example, consider the serialized graph {0,1,2#1,2#2,2}. -# +# # The graph has a total of three nodes, and therefore contains three parts as separated by #. -# +# # First node is labeled as 0. Connect node 0 to both nodes 1 and 2. # Second node is labeled as 1. Connect node 1 to node 2. # Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle. # Visually, the graph looks like the following: -# +# # 1 # / \ # / \ @@ -38,7 +38,7 @@ def cloneGraph(self, node): return None cloned_node = UndirectedGraphNode(node.label) cloned, queue = {node:cloned_node}, [node] - + while queue: current = queue.pop() for neighbor in current.neighbors: diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py index 4672e0cc6..3abd38a54 100644 --- a/Python/closest-binary-search-tree-value-ii.py +++ b/Python/closest-binary-search-tree-value-ii.py @@ -27,11 +27,11 @@ def nextNode(stack, child1, child2): 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: @@ -39,11 +39,11 @@ def nextNode(stack, child1, child2): 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): @@ -74,7 +74,7 @@ def __init__(self, stack, child1, child2): self.cur = self.stack.pop() self.child1 = child1 self.child2 = child2 - + # @return an integer, the next node def next(self): node = None @@ -103,7 +103,7 @@ def next(self): 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 diff --git a/Python/coin-change-2.py b/Python/coin-change-2.py index d65707685..c85c9d196 100644 --- a/Python/coin-change-2.py +++ b/Python/coin-change-2.py @@ -27,9 +27,9 @@ # Explanation: the amount of 3 cannot be made up just with coins of 2. # Example 3: # -# Input: amount = 10, coins = [10] +# Input: amount = 10, coins = [10] # Output: 1 - + class Solution(object): def change(self, amount, coins): """ diff --git a/Python/coin-change.py b/Python/coin-change.py index f762c382a..093d4429b 100644 --- a/Python/coin-change.py +++ b/Python/coin-change.py @@ -35,4 +35,4 @@ def coinChange(self, coins, amount): if i + coin <= amount: amounts[i + coin] = min(amounts[i + coin], amounts[i] + 1) return amounts[amount] if amounts[amount] != INF else -1 - + diff --git a/Python/combination-sum-ii.py b/Python/combination-sum-ii.py index d11d74295..31975069d 100644 --- a/Python/combination-sum-ii.py +++ b/Python/combination-sum-ii.py @@ -1,20 +1,20 @@ # Time: O(k * C(n, k)) # Space: O(k) -# -# Given a collection of candidate numbers (C) and a target number (T), +# +# 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. -# +# # Each number in C may only be used once in the combination. -# +# # Note: # All numbers (including target) will be positive integers. # Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak). # The solution set must not contain duplicate combinations. -# For example, given candidate set 10,1,2,7,6,1,5 and target 8, -# A solution set is: -# [1, 7] -# [1, 2, 5] -# [2, 6] +# For example, given candidate set 10,1,2,7,6,1,5 and target 8, +# A solution set is: +# [1, 7] +# [1, 2, 5] +# [2, 6] # [1, 1, 6] # @@ -26,7 +26,7 @@ def combinationSum2(self, candidates, target): result = [] self.combinationSumRecu(sorted(candidates), result, 0, [], target) return result - + def combinationSumRecu(self, candidates, result, start, intermediate, target): if target == 0: result.append(list(intermediate)) @@ -41,5 +41,5 @@ def combinationSumRecu(self, candidates, result, start, intermediate, target): if __name__ == "__main__": candidates, target = [10, 1, 2, 7, 6, 1, 5], 8 - result = Solution().combinationSum2(candidates, target) - print result + result = Solution().combinationSum2(candidates, target) + print result diff --git a/Python/combination-sum-iii.py b/Python/combination-sum-iii.py index ddc4ba260..f5accf25a 100644 --- a/Python/combination-sum-iii.py +++ b/Python/combination-sum-iii.py @@ -32,7 +32,7 @@ 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)) diff --git a/Python/combination-sum.py b/Python/combination-sum.py index ce0d14f11..0120a7cdb 100644 --- a/Python/combination-sum.py +++ b/Python/combination-sum.py @@ -1,19 +1,19 @@ # Time: O(k * n^k) # Space: O(k) # -# Given a set of candidate numbers (C) and a target number (T), +# 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. -# +# # The same repeated number may be chosen from C unlimited number of times. -# +# # Note: # All numbers (including target) will be positive integers. # Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak). # The solution set must not contain duplicate combinations. -# For example, given candidate set 2,3,6,7 and target 7, -# A solution set is: -# [7] -# [2, 2, 3] +# For example, given candidate set 2,3,6,7 and target 7, +# A solution set is: +# [7] +# [2, 2, 3] # class Solution: @@ -24,7 +24,7 @@ def combinationSum(self, candidates, target): result = [] self.combinationSumRecu(sorted(candidates), result, 0, [], target) return result - + def combinationSumRecu(self, candidates, result, start, intermediate, target): if target == 0: result.append(list(intermediate)) @@ -36,5 +36,5 @@ def combinationSumRecu(self, candidates, result, start, intermediate, target): if __name__ == "__main__": candidates, target = [2, 3, 6, 7], 7 - result = Solution().combinationSum(candidates, target) - print result + result = Solution().combinationSum(candidates, target) + print result diff --git a/Python/combinations.py b/Python/combinations.py index 7a4ba2a5f..e57640ab1 100644 --- a/Python/combinations.py +++ b/Python/combinations.py @@ -2,10 +2,10 @@ # Space: O(k) # Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. -# +# # For example, # If n = 4 and k = 2, a solution is: -# +# # [ # [2,4], # [3,4], @@ -36,7 +36,7 @@ def combine(self, n, k): combination.append(i) i += 1 return result - + class Solution2(object): def combine(self, n, k): diff --git a/Python/compare-version-numbers.py b/Python/compare-version-numbers.py index 4b67b70e4..342dff213 100644 --- a/Python/compare-version-numbers.py +++ b/Python/compare-version-numbers.py @@ -4,17 +4,17 @@ # Compare two version numbers version1 and version1. # 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 +# 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: -# +# # 0.1 < 1.1 < 1.2 < 13.37 # import itertools @@ -56,12 +56,12 @@ def compareVersion(self, version1, version2): :rtype: int """ v1, v2 = version1.split("."), version2.split(".") - + if len(v1) > len(v2): v2 += ['0' for _ in xrange(len(v1) - len(v2))] elif len(v1) < len(v2): v1 += ['0' for _ in xrange(len(v2) - len(v1))] - + i = 0 while i < len(v1): if int(v1[i]) > int(v2[i]): @@ -70,7 +70,7 @@ def compareVersion(self, version1, version2): return -1 else: i += 1 - + return 0 def compareVersion2(self, version1, version2): diff --git a/Python/concatenated-words.py b/Python/concatenated-words.py index 8d89f5e36..6fceb631c 100644 --- a/Python/concatenated-words.py +++ b/Python/concatenated-words.py @@ -12,8 +12,8 @@ # # Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] # -# Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; -# "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; +# Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; +# "dogcatsdog" can be concatenated by "dog", "cats" and "dog"; # "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat". # Note: # The number of elements of the given array will not exceed 10,000 @@ -29,15 +29,15 @@ def findAllConcatenatedWordsInADict(self, words): """ lookup = set(words) result = [] - for word in words: + for word in words: dp = [False] * (len(word)+1) dp[0] = True for i in xrange(len(word)): if not dp[i]: continue - + for j in xrange(i+1, len(word)+1): - if j - i < len(word) and word[i:j] in lookup: + if j - i < len(word) and word[i:j] in lookup: dp[j] = True if dp[len(word)]: diff --git a/Python/construct-binary-tree-from-inorder-and-postorder-traversal.py b/Python/construct-binary-tree-from-inorder-and-postorder-traversal.py index 991009a93..294594fa5 100644 --- a/Python/construct-binary-tree-from-inorder-and-postorder-traversal.py +++ b/Python/construct-binary-tree-from-inorder-and-postorder-traversal.py @@ -2,7 +2,7 @@ # Space: O(n) # # Given inorder and postorder traversal of a tree, construct the binary tree. -# +# # Note: # You may assume that duplicates do not exist in the tree. # @@ -23,7 +23,7 @@ def buildTree(self, inorder, postorder): for i, num in enumerate(inorder): lookup[num] = i return self.buildTreeRecu(lookup, postorder, inorder, len(postorder), 0, len(inorder)) - + def buildTreeRecu(self, lookup, postorder, inorder, post_end, in_start, in_end): if in_start == in_end: return None diff --git a/Python/construct-binary-tree-from-preorder-and-inorder-traversal.py b/Python/construct-binary-tree-from-preorder-and-inorder-traversal.py index e3196454d..a316ecdd2 100644 --- a/Python/construct-binary-tree-from-preorder-and-inorder-traversal.py +++ b/Python/construct-binary-tree-from-preorder-and-inorder-traversal.py @@ -2,7 +2,7 @@ # Space: O(n) # # Given preorder and inorder traversal of a tree, construct the binary tree. -# +# # Note: # You may assume that duplicates do not exist in the tree. # @@ -23,7 +23,7 @@ def buildTree(self, preorder, inorder): for i, num in enumerate(inorder): lookup[num] = i return self.buildTreeRecu(lookup, preorder, inorder, 0, 0, len(inorder)) - + def buildTreeRecu(self, lookup, preorder, inorder, pre_start, in_start, in_end): if in_start == in_end: return None diff --git a/Python/construct-string-from-binary-tree.py b/Python/construct-string-from-binary-tree.py index 8bba46ba5..b2dac24ee 100644 --- a/Python/construct-string-from-binary-tree.py +++ b/Python/construct-string-from-binary-tree.py @@ -5,7 +5,7 @@ # the preorder traversing way. # # The null node needs to be represented by empty parenthesis pair "()". -# And you need to omit all the empty parenthesis pairs that don't affect +# And you need to omit all the empty parenthesis pairs that don't affect # the one-to-one mapping relationship between the string and the original binary tree. # # Example 1: @@ -13,25 +13,25 @@ # 1 # / \ # 2 3 -# / -# 4 +# / +# 4 # # Output: "1(2(4))(3)" # -# Explanation: Originallay it needs to be "1(2(4)())(3()())", -# but you need to omit all the unnecessary empty parenthesis pairs. +# Explanation: Originallay it needs to be "1(2(4)())(3()())", +# but you need to omit all the unnecessary empty parenthesis pairs. # And it will be "1(2(4))(3)". # Example 2: # Input: Binary tree: [1,2,3,null,4] # 1 # / \ # 2 3 -# \ -# 4 +# \ +# 4 # # Output: "1(2()(4))(3)" # -# Explanation: Almost the same as the first example, +# Explanation: Almost the same as the first example, # except we can't omit the first parenthesis pair to break the one-to-one mapping relationship # between the input and the output. diff --git a/Python/contain-virus.py b/Python/contain-virus.py index abf74ca92..3fc0e7569 100644 --- a/Python/contain-virus.py +++ b/Python/contain-virus.py @@ -11,7 +11,7 @@ # # Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. # Resources are limited. -# Each day, you can install walls around only one region -- +# Each day, you can install walls around only one region -- # the affected area (continuous block of infected cells) that # threatens the most uninfected cells the following night. # There will never be a tie. @@ -20,7 +20,7 @@ # If not, and the world becomes fully infected, return the number of walls used. # # Example 1: -# Input: grid = +# Input: grid = # [[0,1,0,0,0,0,0,1], # [0,1,0,0,0,0,0,1], # [0,0,0,0,0,0,0,1], @@ -38,7 +38,7 @@ # On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained. # # Example 2: -# Input: grid = +# Input: grid = # [[1,1,1], # [1,0,1], # [1,1,1]] @@ -47,7 +47,7 @@ # Notice that walls are only built on the shared boundary of two different cells. # # Example 3: -# Input: grid = +# Input: grid = # [[1,1,1,0,0,0,0,0,0], # [1,0,1,0,1,1,1,1,1], # [1,1,1,0,0,0,0,0,0]] diff --git a/Python/container-with-most-water.py b/Python/container-with-most-water.py index aa81a7018..5522e0080 100644 --- a/Python/container-with-most-water.py +++ b/Python/container-with-most-water.py @@ -1,13 +1,13 @@ # Time: O(n) # Space: O(1) # -# Given n non-negative integers a1, a2, ..., an, -# where each represents a point at coordinate (i, ai). -# n vertical lines are drawn such that the two endpoints of -# line i is at (i, ai) and (i, 0). Find two lines, -# which together with x-axis forms a container, +# Given n non-negative integers a1, a2, ..., an, +# where each represents a point at coordinate (i, ai). +# n vertical lines are drawn such that the two endpoints of +# line i is at (i, ai) and (i, 0). Find two lines, +# which together with x-axis forms a container, # such that the container contains the most water. -# +# # Note: You may not slant the container. # @@ -22,7 +22,7 @@ def maxArea(self, height): else: j -= 1 return max_area - + if __name__ == "__main__": height = [1, 2, 3, 4, 3, 2, 1, 5] result = Solution().maxArea(height) diff --git a/Python/contains-duplicate-ii.py b/Python/contains-duplicate-ii.py index 451a6bdde..ca5206a55 100644 --- a/Python/contains-duplicate-ii.py +++ b/Python/contains-duplicate-ii.py @@ -1,8 +1,8 @@ # 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 +# 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. # diff --git a/Python/contains-duplicate.py b/Python/contains-duplicate.py index 16c26a3c3..a6ba14224 100644 --- a/Python/contains-duplicate.py +++ b/Python/contains-duplicate.py @@ -2,7 +2,7 @@ # 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, +# 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. # diff --git a/Python/contiguous-array.py b/Python/contiguous-array.py index f16e9147d..104194c0b 100644 --- a/Python/contiguous-array.py +++ b/Python/contiguous-array.py @@ -27,5 +27,5 @@ def findMaxLength(self, nums): result = max(result, i - lookup[count]) else: lookup[count] = i - + return result diff --git a/Python/continuous-subarray-sum.py b/Python/continuous-subarray-sum.py index b9991538f..7e46a53bc 100644 --- a/Python/continuous-subarray-sum.py +++ b/Python/continuous-subarray-sum.py @@ -36,5 +36,5 @@ def checkSubarraySum(self, nums, k): return True else: lookup[count] = i - + return False diff --git a/Python/convert-bst-to-greater-tree.py b/Python/convert-bst-to-greater-tree.py index c0ff15309..5262d45dd 100644 --- a/Python/convert-bst-to-greater-tree.py +++ b/Python/convert-bst-to-greater-tree.py @@ -17,7 +17,7 @@ # 18 # / \ # 20 13 - + # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): diff --git a/Python/convert-sorted-array-to-binary-search-tree.py b/Python/convert-sorted-array-to-binary-search-tree.py index 4f5858c07..ac3789fb5 100644 --- a/Python/convert-sorted-array-to-binary-search-tree.py +++ b/Python/convert-sorted-array-to-binary-search-tree.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(logn) # -# Given an array where elements are sorted in ascending order, +# Given an array where elements are sorted in ascending order, # convert it to a height balanced BST. # # Definition for a binary tree node @@ -28,7 +28,7 @@ def sortedArrayToBSTRecu(self, nums, start, end): node.left = self.sortedArrayToBSTRecu(nums, start, mid) node.right = self.sortedArrayToBSTRecu(nums, mid + 1, end) return node - + def perfect_tree_pivot(self, n): """ Find the point to partition n keys for a perfect binary search tree @@ -44,8 +44,8 @@ def perfect_tree_pivot(self, n): else: return n - x // 2 # case 2 == n - (x//2 - 1) - 1 : the left subtree of the root # has more nodes and the right subtree is perfect. - - + + if __name__ == "__main__": num = [1, 2, 3] result = Solution().sortedArrayToBST(num) diff --git a/Python/convert-sorted-list-to-binary-search-tree.py b/Python/convert-sorted-list-to-binary-search-tree.py index f0624af6c..a1e2a5166 100644 --- a/Python/convert-sorted-list-to-binary-search-tree.py +++ b/Python/convert-sorted-list-to-binary-search-tree.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(logn) # -# Given a singly linked list where elements are sorted in ascending order, +# Given a singly linked list where elements are sorted in ascending order, # convert it to a height balanced BST. # # Definition for a binary tree node @@ -27,14 +27,14 @@ def sortedListToBST(self, head): current, length = current.next, length + 1 self.head = head return self.sortedListToBSTRecu(0, length) - + def sortedListToBSTRecu(self, start, end): if start == end: return None mid = start + (end - start) / 2 left = self.sortedListToBSTRecu(start, mid) current = TreeNode(self.head.val) - current.left = left + current.left = left self.head = self.head.next current.right = self.sortedListToBSTRecu(mid + 1, end) return current diff --git a/Python/convex-polygon.py b/Python/convex-polygon.py index 27286efd6..a552142c3 100644 --- a/Python/convex-polygon.py +++ b/Python/convex-polygon.py @@ -19,4 +19,4 @@ def det(A): return False prev = curr return True - + diff --git a/Python/copy-list-with-random-pointer.py b/Python/copy-list-with-random-pointer.py index 9f4e8675f..483aa2a3e 100644 --- a/Python/copy-list-with-random-pointer.py +++ b/Python/copy-list-with-random-pointer.py @@ -3,7 +3,7 @@ # # A linked list is given such that each node contains an additional random pointer # which could point to any node in the list or null. -# +# # Return a deep copy of the list. # @@ -25,14 +25,14 @@ def copyRandomList(self, head): copied.next = current.next current.next = copied current = copied.next - + # update random node in copied list current = head while current: if current.random: current.next.random = current.random.next current = current.next.next - + # split copied list from combined one dummy = RandomListNode(0) copied_current, current = dummy, head @@ -50,19 +50,19 @@ class Solution2: def copyRandomList(self, head): dummy = RandomListNode(0) current, prev, copies = head, dummy, {} - + while current: copied = RandomListNode(current.label) copies[current] = copied prev.next = copied prev, current = prev.next, current.next - + current = head while current: if current.random: copies[current].random = copies[current.random] current = current.next - + return dummy.next diff --git a/Python/count-and-say.py b/Python/count-and-say.py index f1b27c374..2bbfc3a4e 100644 --- a/Python/count-and-say.py +++ b/Python/count-and-say.py @@ -3,12 +3,12 @@ # # The count-and-say sequence is the sequence of integers beginning as follows: # 1, 11, 21, 1211, 111221, ... -# +# # 1 is read off as "one 1" or 11. # 11 is read off as "two 1s" or 21. # 21 is read off as "one 2, then one 1" or 1211. # Given an integer n, generate the nth sequence. -# +# # Note: The sequence of integers will be represented as a string. # @@ -19,11 +19,11 @@ def countAndSay(self, n): for i in xrange(n - 1): seq = self.getNext(seq) return seq - + def getNext(self, seq): i, next_seq = 0, "" while i < len(seq): - cnt = 1 + cnt = 1 while i < len(seq) - 1 and seq[i] == seq[i + 1]: cnt += 1 i += 1 @@ -35,4 +35,4 @@ def getNext(self, seq): for i in xrange(1, 4): print Solution().countAndSay(i) - + diff --git a/Python/count-binary-substrings.py b/Python/count-binary-substrings.py index f282b349a..e28ba957a 100644 --- a/Python/count-binary-substrings.py +++ b/Python/count-binary-substrings.py @@ -20,7 +20,7 @@ # Input: "10101" # Output: 4 # Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's. -# +# # Note: # s.length will be between 1 and 50,000. # s will only consist of "0" or "1" characters. diff --git a/Python/count-complete-tree-nodes.py b/Python/count-complete-tree-nodes.py index 24695387b..dcd6e490a 100644 --- a/Python/count-complete-tree-nodes.py +++ b/Python/count-complete-tree-nodes.py @@ -22,12 +22,12 @@ class Solution: 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: @@ -36,16 +36,16 @@ def countNodes(self, root): 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: diff --git a/Python/count-different-palindromic-subsequences.py b/Python/count-different-palindromic-subsequences.py index e0b4e7452..f1b5ecf1e 100644 --- a/Python/count-different-palindromic-subsequences.py +++ b/Python/count-different-palindromic-subsequences.py @@ -11,19 +11,19 @@ # Two sequences A_1, A_2, ... and B_1, B_2, ... are different if there is some i for which A_i != B_i. # # Example 1: -# Input: +# Input: # S = 'bccb' # Output: 6 -# Explanation: +# Explanation: # The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'. # Note that 'bcb' is counted only once, even though it occurs twice. # # Example 2: -# Input: +# Input: # S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba' # Output: 104860361 -# -# Explanation: +# +# Explanation: # There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7. # Note: # - The length of S will be in the range [1, 1000]. @@ -50,20 +50,20 @@ def dp(i, j, prv, nxt, lookup): result %= P lookup[i][j] = result return result - + prv = [None] * len(S) nxt = [None] * len(S) - + last = [None] * 4 for i in xrange(len(S)): last[ord(S[i])-ord('a')] = i prv[i] = tuple(last) - + last = [None] * 4 for i in reversed(xrange(len(S))): last[ord(S[i])-ord('a')] = i nxt[i] = tuple(last) - + P = 10**9 + 7 - lookup = [[None] * len(S) for _ in xrange(len(S))] + lookup = [[None] * len(S) for _ in xrange(len(S))] return dp(0, len(S)-1, prv, nxt, lookup) - 1 diff --git a/Python/count-of-range-sum.py b/Python/count-of-range-sum.py index eb87af804..01242acc0 100644 --- a/Python/count-of-range-sum.py +++ b/Python/count-of-range-sum.py @@ -39,7 +39,7 @@ def countAndMergeSort(sums, start, end, lower, upper): 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]) @@ -80,7 +80,7 @@ def countAndMergeSort(sums, start, end, lower, upper): 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]) diff --git a/Python/count-of-smaller-numbers-after-self.py b/Python/count-of-smaller-numbers-after-self.py index 7011fa583..42f49c324 100644 --- a/Python/count-of-smaller-numbers-after-self.py +++ b/Python/count-of-smaller-numbers-after-self.py @@ -1,9 +1,9 @@ # 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 +# 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: @@ -77,7 +77,7 @@ 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: @@ -114,17 +114,17 @@ def countSmaller(self, nums): 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) @@ -147,7 +147,7 @@ def insertNode(self, val): else: curr.right = node break - + # Query the smaller count of the value. def query(self, val): count = 0 @@ -160,5 +160,5 @@ def query(self, val): count += 1 + curr.count # Count the number of the smaller nodes. curr = curr.right else: # Equal. - return count + curr.count + return count + curr.count return 0 diff --git a/Python/count-primes.py b/Python/count-primes.py index 46ad88ddf..569abf3d0 100644 --- a/Python/count-primes.py +++ b/Python/count-primes.py @@ -14,7 +14,7 @@ class Solution: def countPrimes(self, n): if n <= 2: return 0 - + is_prime = [True] * n num = n / 2 for i in xrange(3, n, 2): diff --git a/Python/count-the-repetitions.py b/Python/count-the-repetitions.py index eeaee7b70..37d8b47cf 100644 --- a/Python/count-the-repetitions.py +++ b/Python/count-the-repetitions.py @@ -4,7 +4,7 @@ # Define S = [s,n] as the string S which consists of n connected strings s. # For example, ["abc", 3] ="abcabcabc". # -# On the other hand, we define that string s1 can be obtained from string s2 +# On the other hand, we define that string s1 can be obtained from string s2 # if we can remove some characters from s2 such that it becomes s1. # For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”. # @@ -38,7 +38,7 @@ def getMaxRepetitions(self, s1, n1, s2, n2): if s1[i] == s2[j]: j = (j + 1) % len(s2) count += (j == 0) - + if j in lookup: # cyclic i = lookup[j] prefix_count = repeat_count[i] @@ -47,5 +47,5 @@ def getMaxRepetitions(self, s1, n1, s2, n2): return (prefix_count + pattern_count + suffix_count) / n2 lookup[j] = k repeat_count[k] = count - + return repeat_count[n1] / n2 # not cyclic iff n1 <= s2 diff --git a/Python/count-univalue-subtrees.py b/Python/count-univalue-subtrees.py index a393f4304..c70a5ba5d 100644 --- a/Python/count-univalue-subtrees.py +++ b/Python/count-univalue-subtrees.py @@ -27,6 +27,6 @@ def isUnivalSubtrees(self, root, count): return [True, count] return [False, count] - + def isSame(self, root, child, is_uni): return not child or (is_uni and root.val == child.val) diff --git a/Python/counting-bits.py b/Python/counting-bits.py index 6ef845380..8da8a2185 100644 --- a/Python/counting-bits.py +++ b/Python/counting-bits.py @@ -2,7 +2,7 @@ # Space: O(n) # Given a non negative integer number num. For every numbers i -# in the range 0 <= i <= num calculate the number +# in the range 0 <= i <= num calculate the number # of 1's in their binary representation and return them as an array. # # Example: @@ -10,8 +10,8 @@ # # 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 +# 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 diff --git a/Python/couples-holding-hands.py b/Python/couples-holding-hands.py index 2348c41c8..0801bcd81 100644 --- a/Python/couples-holding-hands.py +++ b/Python/couples-holding-hands.py @@ -15,7 +15,7 @@ def minSwapsCouples(self, row): for couch1, couch2 in couples: adj[couch1].append(couch2) adj[couch2].append(couch1) - + result = 0 for couch in xrange(N): if not adj[couch]: continue diff --git a/Python/course-schedule.py b/Python/course-schedule.py index ecb7fbf72..ddd5fc3de 100644 --- a/Python/course-schedule.py +++ b/Python/course-schedule.py @@ -2,27 +2,27 @@ # 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 +# +# 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 +# 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 +# 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. +# 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? @@ -41,7 +41,7 @@ def canFinish(self, numCourses, prerequisites): :rtype: bool """ zero_in_degree_queue, in_degree, out_degree = collections.deque(), {}, {} - + for i, j in prerequisites: if i not in in_degree: in_degree[i] = set() @@ -49,25 +49,25 @@ def canFinish(self, numCourses, prerequisites): out_degree[j] = set() in_degree[i].add(j) out_degree[j].add(i) - + 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.popleft() - + if prerequisite in out_degree: for course in out_degree[prerequisite]: in_degree[course].discard(prerequisite) if not in_degree[course]: zero_in_degree_queue.append(course) - + del out_degree[prerequisite] - + if out_degree: return False - + return True diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py index 916fc26fc..e4874bfcd 100644 --- a/Python/cracking-the-safe.py +++ b/Python/cracking-the-safe.py @@ -16,12 +16,12 @@ # Input: n = 1, k = 2 # Output: "01" # Note: "10" will be accepted too. -# +# # Example 2: # Input: n = 2, k = 2 # Output: "00110" # Note: "01100", "10011", "11001" will be accepted too. -# +# # Note: # - n will be in the range [1, 4]. # - k will be in the range [1, 10]. @@ -88,7 +88,7 @@ def dfs(k, node, lookup, result): result.append(str(i)) dfs(k, neighbor[1:], lookup, result) break - + result = [str(k-1)]*(n-1) lookup = set() dfs(k, "".join(result), lookup, result) diff --git a/Python/create-maximum-number.py b/Python/create-maximum-number.py index af1d98541..c946b12fa 100644 --- a/Python/create-maximum-number.py +++ b/Python/create-maximum-number.py @@ -57,7 +57,7 @@ def delete_digit(nums): res = res[:i] + res[i+1:] break return res - + def merge(a, b): return [max(a, b).pop(0) for _ in xrange(len(a)+len(b))] diff --git a/Python/daily-temperatures.py b/Python/daily-temperatures.py index 841982d81..49e55ab96 100644 --- a/Python/daily-temperatures.py +++ b/Python/daily-temperatures.py @@ -25,4 +25,4 @@ def dailyTemperatures(self, temperatures): idx = stk.pop() result[idx] = i-idx stk.append(i) - return result + return result diff --git a/Python/decode-string.py b/Python/decode-string.py index ab0256f17..c3030c3b5 100644 --- a/Python/decode-string.py +++ b/Python/decode-string.py @@ -3,8 +3,8 @@ # Given an encoded string, return it's decoded string. # -# The encoding rule is: k[encoded_string], -# where the encoded_string inside the square brackets is +# The encoding rule is: k[encoded_string], +# where the encoded_string inside the square brackets is # being repeated exactly k times. Note that k is guaranteed # to be a positive integer. # diff --git a/Python/decode-ways.py b/Python/decode-ways.py index 2f474480b..7d60cfa09 100644 --- a/Python/decode-ways.py +++ b/Python/decode-ways.py @@ -2,16 +2,16 @@ # Space: O(1) # # A message containing letters from A-Z is being encoded to numbers using the following mapping: -# +# # 'A' -> 1 # 'B' -> 2 # ... # 'Z' -> 26 # Given an encoded message containing digits, determine the total number of ways to decode it. -# +# # For example, # Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). -# +# # The number of ways decoding "12" is 2. # diff --git a/Python/delete-and-earn.py b/Python/delete-and-earn.py index 4327d0d2b..4f4c82aba 100644 --- a/Python/delete-and-earn.py +++ b/Python/delete-and-earn.py @@ -12,14 +12,14 @@ # Example 1: # Input: nums = [3, 4, 2] # Output: 6 -# Explanation: +# Explanation: # Delete 4 to earn 4 points, consequently 3 is also deleted. # Then, delete 2 to earn 2 points. 6 total points are earned. # # Example 2: # Input: nums = [2, 2, 3, 3, 3, 4] # Output: 9 -# Explanation: +# Explanation: # Delete 3 to earn 3 points, deleting both 2's and the 4. # Then, delete 3 again to earn 3 points, and 3 again to earn 3 points. # 9 total points are earned. diff --git a/Python/design-in-memory-file-system.py b/Python/design-in-memory-file-system.py index ae5ee030c..0785bfff0 100644 --- a/Python/design-in-memory-file-system.py +++ b/Python/design-in-memory-file-system.py @@ -24,7 +24,7 @@ # readContentFromFile: Given a file path, return its content in string format. # # Example: -# Input: +# Input: # ["FileSystem","ls","mkdir","addContentToFile","ls","readContentFromFile"] # [[],["/"],["/a/b/c"],["/a/b/c/d","hello"],["/"],["/a/b/c/d"]] # Output: @@ -37,10 +37,10 @@ # users will not attempt to retrieve file content or list a directory or file that does not exist. # 3. You can assume that all directory names and file names only contain lower-case letters, # and same names won't exist in the same directory. - + class TrieNode(object): - + def __init__(self): self.is_file = False self.children = {} @@ -50,7 +50,7 @@ class FileSystem(object): def __init__(self): self.__root = TrieNode() - + def ls(self, path): """ @@ -58,11 +58,11 @@ def ls(self, path): :rtype: List[str] """ curr = self.__getNode(path) - + if curr.is_file: return [self.__split(path, '/')[-1]] - return sorted(curr.children.keys()) + return sorted(curr.children.keys()) def mkdir(self, path): @@ -72,7 +72,7 @@ def mkdir(self, path): """ curr = self.__putNode(path) curr.is_file = False - + def addContentToFile(self, filePath, content): """ diff --git a/Python/design-log-storage-system.py b/Python/design-log-storage-system.py index 976a44f50..ca9a90979 100644 --- a/Python/design-log-storage-system.py +++ b/Python/design-log-storage-system.py @@ -2,14 +2,14 @@ # retrieve: O(n + dlogd), n is the size of the total logs # , d is the size of the found logs # Space: O(n) - + class LogSystem(object): def __init__(self): self.__logs = [] self.__granularity = {'Year': 4, 'Month': 7, 'Day': 10, \ 'Hour': 13, 'Minute': 16, 'Second': 19} - + def put(self, id, timestamp): """ @@ -19,7 +19,7 @@ def put(self, id, timestamp): """ self.__logs.append((id, timestamp)) - + def retrieve(self, s, e, gra): """ :type s: str diff --git a/Python/design-phone-directory.py b/Python/design-phone-directory.py index d0c2af2a1..2d039ca18 100644 --- a/Python/design-phone-directory.py +++ b/Python/design-phone-directory.py @@ -28,7 +28,7 @@ def get(self): self.__curr += 1 self.__used[number] = True return number - + def check(self, number): """ @@ -38,7 +38,7 @@ def check(self, number): """ return 0 <= number < len(self.__numbers) and \ not self.__used[number] - + def release(self, number): """ @@ -52,7 +52,7 @@ def release(self, number): self.__used[number] = False self.__curr -= 1 self.__numbers[self.__curr] = number - + # Your PhoneDirectory object will be instantiated and called as such: # obj = PhoneDirectory(maxNumbers) diff --git a/Python/diagonal-traverse.py b/Python/diagonal-traverse.py index 8410476a4..639c64adf 100644 --- a/Python/diagonal-traverse.py +++ b/Python/diagonal-traverse.py @@ -26,11 +26,11 @@ def findDiagonalOrder(self, matrix): """ if not matrix or not matrix[0]: return [] - + result = [] row, col, d = 0, 0, 0 dirs = [(-1, 1), (1, -1)] - + for i in xrange(len(matrix) * len(matrix[0])): result.append(matrix[row][col]) row += dirs[d][0] @@ -50,6 +50,6 @@ def findDiagonalOrder(self, matrix): elif col < 0: col = 0 d = 1 - d - + return result - + diff --git a/Python/diameter-of-binary-tree.py b/Python/diameter-of-binary-tree.py index 736e93b3b..063a60ffc 100644 --- a/Python/diameter-of-binary-tree.py +++ b/Python/diameter-of-binary-tree.py @@ -6,12 +6,12 @@ # any two nodes in a tree. This path may or may not pass through the root. # # Example: -# Given a binary tree +# Given a binary tree # 1 # / \ # 2 3 -# / \ -# 4 5 +# / \ +# 4 5 # Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. # # Note: The length of path between two nodes is represented by the number of edges between them. @@ -34,5 +34,5 @@ def depth(root, diameter): left, diameter = depth(root.left, diameter) right, diameter = depth(root.right, diameter) return 1 + max(left, right), max(diameter, 1 + left + right) - + return depth(root, 1)[1] - 1 diff --git a/Python/distinct-subsequences.py b/Python/distinct-subsequences.py index 48709899e..5d4aad7bc 100644 --- a/Python/distinct-subsequences.py +++ b/Python/distinct-subsequences.py @@ -2,14 +2,14 @@ # Space: O(n) # # Given a string S and a string T, count the number of distinct subsequences of T in S. -# -# A subsequence of a string is a new string which is formed from the original string -# by deleting some (can be none) of the characters without disturbing the relative positions +# +# A subsequence of a string is a new string which is formed from the original string +# by deleting some (can be none) of the characters without disturbing the relative positions # of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not). -# +# # Here is an example: # S = "rabbbit", T = "rabbit" -# +# # Return 3. # @@ -23,10 +23,10 @@ def numDistinct(self, S, T): if S_char == T_char: ways[j + 1] += ways[j] return ways[len(T)] - + if __name__ == "__main__": S = "rabbbit" T = "rabbit" result = Solution().numDistinct(S, T) print result - + diff --git a/Python/distribute-candies.py b/Python/distribute-candies.py index a04064883..827919c11 100644 --- a/Python/distribute-candies.py +++ b/Python/distribute-candies.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(n) -# Given an integer array with even length, where different numbers +# Given an integer array with even length, where different numbers # in this array represent different kinds of candies. # Each number means one candy of the corresponding kind. # You need to distribute these candies equally in number to brother and sister. @@ -12,14 +12,14 @@ # Output: 3 # Explanation: # There are three different kinds of candies (1, 2 and 3), and two candies for each kind. -# Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. -# The sister has three different kinds of candies. +# Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. +# The sister has three different kinds of candies. # # Example 2: # Input: candies = [1,1,2,3] # Output: 2 -# Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. -# The sister has two different kinds of candies, the brother has only one kind of candies. +# Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. +# The sister has two different kinds of candies, the brother has only one kind of candies. # # Note: # The length of the given array is in range [2, 10,000], and will be even. diff --git a/Python/divide-two-integers.py b/Python/divide-two-integers.py index b024170f6..9e2bd8193 100644 --- a/Python/divide-two-integers.py +++ b/Python/divide-two-integers.py @@ -1,6 +1,6 @@ # Time: O(logn) = O(1) # Space: O(1) -# +# # Divide two integers without using multiplication, division and mod operator. @@ -44,7 +44,7 @@ def divide2(self, dividend, divisor): if not positive: res = -res return min(max(-2147483648, res), 2147483647) - + if __name__ == "__main__": print Solution().divide(123, 12) print Solution().divide(123, -12) diff --git a/Python/dungeon-game.py b/Python/dungeon-game.py index 9348828cb..d42e5d1a3 100644 --- a/Python/dungeon-game.py +++ b/Python/dungeon-game.py @@ -1,33 +1,33 @@ # Time: O(m * n) # Space: O(m + n) # -# The demons had captured the princess (P) and imprisoned her +# The demons had captured the princess (P) and imprisoned her # in the bottom-right corner of a dungeon. T -# he dungeon consists of M x N rooms laid out in a 2D grid. -# Our valiant knight (K) was initially positioned in the top-left room +# he dungeon consists of M x N rooms laid out in a 2D grid. +# Our valiant knight (K) was initially positioned in the top-left room # and must fight his way through the dungeon to rescue the princess. -# -# The knight has an initial health point represented by a positive integer. +# +# The knight has an initial health point represented by a positive integer. # If at any point his health point drops to 0 or below, he dies immediately. -# -# Some of the rooms are guarded by demons, -# so the knight loses health (negative integers) upon entering these rooms; +# +# Some of the rooms are guarded by demons, +# so the knight loses health (negative integers) upon entering these rooms; # other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers). -# -# In order to reach the princess as quickly as possible, +# +# In order to reach the princess as quickly as possible, # the knight decides to move only rightward or downward in each step. -# -# -# Write a function to determine the knight's minimum initial health +# +# +# Write a function to determine the knight's minimum initial health # so that he is able to rescue the princess. -# -# For example, given the dungeon below, the initial health of +# +# For example, given the dungeon below, the initial health of # the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN. -# +# # Notes: -# +# # The knight's health has no upper bound. -# Any room can contain threats or power-ups, even the first room the knight enters +# Any room can contain threats or power-ups, even the first room the knight enters # and the bottom-right room where the princess is imprisoned. # @@ -37,16 +37,16 @@ class Solution: def calculateMinimumHP(self, dungeon): DP = [float("inf") for _ in dungeon[0]] DP[-1] = 1 - + for i in reversed(xrange(len(dungeon))): DP[-1] = max(DP[-1] - dungeon[i][-1], 1) for j in reversed(xrange(len(dungeon[i]) - 1)): min_HP_on_exit = min(DP[j], DP[j + 1]) DP[j] = max(min_HP_on_exit - dungeon[i][j], 1) - + return DP[0] -# Time: O(m * n logk), where k is the possible maximum sum of loses +# Time: O(m * n logk), where k is the possible maximum sum of loses # Space: O(m + n) class Solution2: # @param dungeon, a list of lists of integers @@ -57,9 +57,9 @@ def calculateMinimumHP(self, dungeon): for room in rooms: if room < 0: maximum_loses += abs(room) - + return self.binarySearch(dungeon, maximum_loses) - + def binarySearch(self, dungeon, maximum_loses): start, end = 1, maximum_loses + 1 result = 0 @@ -70,20 +70,20 @@ def binarySearch(self, dungeon, maximum_loses): else: start = mid + 1 return start - + def DP(self, dungeon, HP): remain_HP = [0 for _ in dungeon[0]] remain_HP[0] = HP + dungeon[0][0] for j in xrange(1, len(remain_HP)): - if remain_HP[j - 1] > 0: + if remain_HP[j - 1] > 0: remain_HP[j] = max(remain_HP[j - 1] + dungeon[0][j], 0) - + for i in xrange(1, len(dungeon)): if remain_HP[0] > 0: remain_HP[0] = max(remain_HP[0] + dungeon[i][0], 0) else: remain_HP[0] = 0 - + for j in xrange(1, len(remain_HP)): remain = 0 if remain_HP[j - 1] > 0: @@ -99,9 +99,9 @@ def DP(self, dungeon, HP): [ -5, -10, 1], \ [ 10, 30, -5]] print Solution().calculateMinimumHP(dungeon) - + dungeon = [[ -200]] print Solution().calculateMinimumHP(dungeon) - + dungeon = [[0, -3]] print Solution().calculateMinimumHP(dungeon) \ No newline at end of file diff --git a/Python/edit-distance.py b/Python/edit-distance.py index 8498a2f57..2ca1e67c4 100644 --- a/Python/edit-distance.py +++ b/Python/edit-distance.py @@ -1,11 +1,11 @@ # Time: O(n * m) # Space: O(n + m) # -# Given two words word1 and word2, find the minimum number of steps +# Given two words word1 and word2, find the minimum number of steps # required to convert word1 to word2. (each operation is counted as 1 step.) -# +# # You have the following 3 operations permitted on a word: -# +# # a) Insert a character # b) Delete a character # c) Replace a character @@ -16,9 +16,9 @@ class Solution: def minDistance(self, word1, word2): if len(word1) < len(word2): return self.minDistance(word2, word1) - + distance = [i for i in xrange(len(word2) + 1)] - + for i in xrange(1, len(word1) + 1): pre_distance_i_j = distance[0] distance[0] = i @@ -37,10 +37,10 @@ def minDistance(self, word1, word2): # Space: O(n * m) class Solution2: # @return an integer - def minDistance(self, word1, word2): + def minDistance(self, word1, word2): distance = [[i] for i in xrange(len(word1) + 1)] distance[0] = [j for j in xrange(len(word2) + 1)] - + for i in xrange(1, len(word1) + 1): for j in xrange(1, len(word2) + 1): insert = distance[i][j - 1] + 1 @@ -49,7 +49,7 @@ def minDistance(self, word1, word2): if word1[i - 1] != word2[j - 1]: replace += 1 distance[i].append(min(insert, delete, replace)) - + return distance[-1][-1] if __name__ == "__main__": diff --git a/Python/encode-and-decode-strings.py b/Python/encode-and-decode-strings.py index 39445a51a..b6e33bbda 100644 --- a/Python/encode-and-decode-strings.py +++ b/Python/encode-and-decode-strings.py @@ -5,7 +5,7 @@ class Codec: def encode(self, strs): """Encodes a list of strings to a single string. - + :type strs: List[str] :rtype: str """ @@ -17,7 +17,7 @@ def encode(self, strs): def decode(self, s): """Decodes a single string to a list of strings. - + :type s: str :rtype: List[str] """ @@ -26,5 +26,5 @@ def decode(self, s): while i < len(s): l = int(s[i:i+8], 16) strs.append(s[i+8:i+8+l]) - i += 8+l + i += 8+l return strs diff --git a/Python/encode-string-with-shortest-length.py b/Python/encode-string-with-shortest-length.py index 6988e6d4c..667663b29 100644 --- a/Python/encode-string-with-shortest-length.py +++ b/Python/encode-string-with-shortest-length.py @@ -23,6 +23,6 @@ def encode_substr(dp, s, i, j): if len(dp[i][k]) + len(dp[k+1][j]) < len(dp[i][j]): dp[i][j] = dp[i][k] + dp[k+1][j] encoded_string = encode_substr(dp, s, i, j) - if len(encoded_string) < len(dp[i][j]): + if len(encoded_string) < len(dp[i][j]): dp[i][j] = encoded_string return dp[0][len(s) - 1] diff --git a/Python/escape-the-ghosts.py b/Python/escape-the-ghosts.py index be1e5f43f..0dff9431f 100644 --- a/Python/escape-the-ghosts.py +++ b/Python/escape-the-ghosts.py @@ -17,27 +17,27 @@ # Return True if and only if it is possible to escape. # # Example 1: -# Input: +# Input: # ghosts = [[1, 0], [0, 3]] # target = [0, 1] # Output: true -# Explanation: +# Explanation: # You can directly reach the destination (0, 1) at time 1, # while the ghosts located at (1, 0) or (0, 3) have no way to catch up with you. # # Example 2: -# Input: +# Input: # ghosts = [[1, 0]] # target = [2, 0] # Output: false -# Explanation: +# Explanation: # You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination. # Example 3: -# Input: +# Input: # ghosts = [[2, 0]] # target = [1, 0] # Output: false -# Explanation: +# Explanation: # The ghost can reach the target at the same time as you. # # Note: diff --git a/Python/evaluate-reverse-polish-notation.py b/Python/evaluate-reverse-polish-notation.py index e437aaf09..b64bad971 100644 --- a/Python/evaluate-reverse-polish-notation.py +++ b/Python/evaluate-reverse-polish-notation.py @@ -2,9 +2,9 @@ # Space: O(n) # # Evaluate the value of an arithmetic expression in Reverse Polish Notation. -# +# # Valid operators are +, -, *, /. Each operand may be an integer or another expression. -# +# # Some examples: # ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 # ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 @@ -23,7 +23,7 @@ def evalRPN(self, tokens): y, x = numerals.pop(), numerals.pop() numerals.append(int(operators[token](x * 1.0, y))) return numerals.pop() - + if __name__ == "__main__": print Solution().evalRPN(["2", "1", "+", "3", "*"]) print Solution().evalRPN(["4", "13", "5", "/", "+"]) diff --git a/Python/excel-sheet-column-number.py b/Python/excel-sheet-column-number.py index 667233c59..ad16cb326 100644 --- a/Python/excel-sheet-column-number.py +++ b/Python/excel-sheet-column-number.py @@ -2,18 +2,18 @@ # Space: O(1) # Related to question Excel Sheet Column Title -# +# # Given a column title as appear in an Excel sheet, return its corresponding column number. -# +# # For example: -# +# # A -> 1 # B -> 2 # C -> 3 # ... # Z -> 26 # AA -> 27 -# AB -> 28 +# AB -> 28 class Solution(object): def titleToNumber(self, s): diff --git a/Python/excel-sheet-column-title.py b/Python/excel-sheet-column-title.py index a2160e9d5..041031253 100644 --- a/Python/excel-sheet-column-title.py +++ b/Python/excel-sheet-column-title.py @@ -2,16 +2,16 @@ # Space: O(1) # Given a positive integer, return its corresponding column title as appear in an Excel sheet. -# +# # For example: -# +# # 1 -> A # 2 -> B # 3 -> C # ... # 26 -> Z # 27 -> AA -# 28 -> AB +# 28 -> AB class Solution(object): def convertToTitle(self, n): @@ -20,11 +20,11 @@ def convertToTitle(self, n): :rtype: str """ result, dvd = "", n - + while dvd: result += chr((dvd - 1) % 26 + ord('A')) dvd = (dvd - 1) / 26 - + return result[::-1] diff --git a/Python/exclusive-time-of-functions.py b/Python/exclusive-time-of-functions.py index 02127e25c..fff0bcbf7 100644 --- a/Python/exclusive-time-of-functions.py +++ b/Python/exclusive-time-of-functions.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(n) -# Given the running logs of n functions that are executed +# Given the running logs of n functions that are executed # in a nonpreemptive single threaded CPU, find the exclusive time of these functions. # # Each function has a unique id, start from 0 to n-1. @@ -19,7 +19,7 @@ # Example 1: # Input: # n = 2 -# logs = +# logs = # ["0:start:0", # "1:start:2", # "1:end:5", @@ -27,9 +27,9 @@ # Output:[3, 4] # # Explanation: -# Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. +# Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. # Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5. -# Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. +# Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. # So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time. # # Note: diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py index 15d972d3f..f26c4c7ad 100644 --- a/Python/expression-add-operators.py +++ b/Python/expression-add-operators.py @@ -1,13 +1,13 @@ # Time: O(4^n) # Space: O(n) # -# Given a string that contains only digits 0-9 -# and a target value, return all possibilities +# 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"] +# 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 -> [] @@ -47,21 +47,21 @@ def addOperatorsDFS(self, num, target, pos, operand1, operand2, expr, result): # Avoid "00...". 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() - + # Case '*': expr.append("*" + val_str) self.addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result) expr.pop() - + i += 1 - + diff --git a/Python/factorial-trailing-zeroes.py b/Python/factorial-trailing-zeroes.py index 106b59beb..bccfd7e75 100644 --- a/Python/factorial-trailing-zeroes.py +++ b/Python/factorial-trailing-zeroes.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given an integer n, return the number of trailing zeroes in n!. -# +# # Note: Your solution should be in logarithmic time complexity. # diff --git a/Python/find-all-anagrams-in-a-string.py b/Python/find-all-anagrams-in-a-string.py index e80e46ee0..4122bc0bc 100644 --- a/Python/find-all-anagrams-in-a-string.py +++ b/Python/find-all-anagrams-in-a-string.py @@ -45,7 +45,7 @@ def findAnagrams(self, s, p): cnts = [0] * 26 for c in p: cnts[ord(c) - ord('a')] += 1 - + left, right = 0, 0 while right < len(s): cnts[ord(s[right]) - ord('a')] -= 1 diff --git a/Python/find-all-duplicates-in-an-array.py b/Python/find-all-duplicates-in-an-array.py index a9f4f054d..47a601d3a 100644 --- a/Python/find-all-duplicates-in-an-array.py +++ b/Python/find-all-duplicates-in-an-array.py @@ -28,7 +28,7 @@ def findDuplicates(self, nums): else: nums[abs(i)-1] *= -1 return result - + # Time: O(n) # Space: O(1) @@ -42,7 +42,7 @@ def findDuplicates(self, nums): i = 0 while i < len(nums): if nums[i] != nums[nums[i]-1]: - nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] + nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] else: i += 1 diff --git a/Python/find-bottom-left-tree-value.py b/Python/find-bottom-left-tree-value.py index bda1f8710..15dbde147 100644 --- a/Python/find-bottom-left-tree-value.py +++ b/Python/find-bottom-left-tree-value.py @@ -12,7 +12,7 @@ # # Output: # 1 -# Example 2: +# Example 2: # Input: # # 1 diff --git a/Python/find-k-pairs-with-smallest-sums.py b/Python/find-k-pairs-with-smallest-sums.py index 272a4ccff..6a1750aee 100644 --- a/Python/find-k-pairs-with-smallest-sums.py +++ b/Python/find-k-pairs-with-smallest-sums.py @@ -24,7 +24,7 @@ # The first 2 pairs are returned from the sequence: # [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] # Example 3: -# Given nums1 = [1,2], nums2 = [3], k = 3 +# Given nums1 = [1,2], nums2 = [3], k = 3 # # Return: [1,3],[2,3] # diff --git a/Python/find-k-th-smallest-pair-distance.py b/Python/find-k-th-smallest-pair-distance.py index 6badaf3c1..970fe106a 100644 --- a/Python/find-k-th-smallest-pair-distance.py +++ b/Python/find-k-th-smallest-pair-distance.py @@ -8,7 +8,7 @@ # Input: # nums = [1,3,1] # k = 1 -# Output: 0 +# Output: 0 # Explanation: # Here are all the pairs: # (1,3) -> 2 diff --git a/Python/find-largest-value-in-each-tree-row.py b/Python/find-largest-value-in-each-tree-row.py index 0ddc4af54..0343ca2a7 100644 --- a/Python/find-largest-value-in-each-tree-row.py +++ b/Python/find-largest-value-in-each-tree-row.py @@ -4,13 +4,13 @@ # You need to find the largest value in each row of a binary tree. # # Example: -# Input: +# Input: # # 1 # / \ # 3 2 -# / \ \ -# 5 3 9 +# / \ \ +# 5 3 9 # # Output: [1, 3, 9] @@ -56,4 +56,4 @@ def largestValues(self, root): result.append(max(node.val for node in curr)) curr = [child for node in curr for child in (node.left, node.right) if child] return result - + diff --git a/Python/find-median-from-data-stream.py b/Python/find-median-from-data-stream.py index 3e3f968fb..df79d898e 100644 --- a/Python/find-median-from-data-stream.py +++ b/Python/find-median-from-data-stream.py @@ -1,11 +1,11 @@ # 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. +# 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: +# Examples: # [2,3,4] , the median is 3 # # [2,3], the median is (2 + 3) / 2 = 2.5 @@ -19,7 +19,7 @@ # add(1) # add(2) # findMedian() -> 1.5 -# add(3) +# add(3) # findMedian() -> 2 # Heap solution. diff --git a/Python/find-minimum-in-rotated-sorted-array-ii.py b/Python/find-minimum-in-rotated-sorted-array-ii.py index fcb09d212..911eacbb7 100644 --- a/Python/find-minimum-in-rotated-sorted-array-ii.py +++ b/Python/find-minimum-in-rotated-sorted-array-ii.py @@ -3,14 +3,14 @@ # # Follow up for "Find Minimum in Rotated Sorted Array": # What if duplicates are allowed? -# +# # Would this affect the run-time complexity? How and why? # Suppose a sorted array is rotated at some pivot unknown to you beforehand. -# +# # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). -# +# # Find the minimum element. -# +# # The array may contain duplicates. # @@ -43,7 +43,7 @@ def findMin(self, nums): left, right = 0, len(nums) - 1 while left < right and nums[left] >= nums[right]: mid = left + (right - left) / 2 - + if nums[mid] == nums[left]: left += 1 elif nums[mid] < nums[left]: diff --git a/Python/find-mode-in-binary-search-tree.py b/Python/find-mode-in-binary-search-tree.py index 60a53fa65..facb55471 100644 --- a/Python/find-mode-in-binary-search-tree.py +++ b/Python/find-mode-in-binary-search-tree.py @@ -39,7 +39,7 @@ def findMode(self, root): def inorder(root, prev, cnt, max_cnt, result): if not root: return prev, cnt, max_cnt - + prev, cnt, max_cnt = inorder(root.left, prev, cnt, max_cnt, result) if prev: if root.val == prev.val: @@ -53,7 +53,7 @@ def inorder(root, prev, cnt, max_cnt, result): elif cnt == max_cnt: result.append(root.val) return inorder(root.right, root, cnt, max_cnt, result) - + if not root: return [] result = [] diff --git a/Python/find-peak-element.py b/Python/find-peak-element.py index dfa85fd2d..b986c43bf 100644 --- a/Python/find-peak-element.py +++ b/Python/find-peak-element.py @@ -2,15 +2,15 @@ # Space: O(1) # A peak element is an element that is greater than its neighbors. -# +# # Given an input array where num[i] != num[i+1], # find a peak element and return its index. -# -# The array may contain multiple peaks, in that case +# +# The array may contain multiple peaks, in that case # return the index to any one of the peaks is fine. -# +# # You may imagine that num[-1] = num[n] = -infinite. -# +# # For example, in array [1, 2, 3, 1], 3 is a peak element # and your function should return the index number 2. # @@ -18,21 +18,21 @@ # Your solution should be in logarithmic complexity. -class Solution(object): +class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ left, right = 0, len(nums) - 1 - + while left < right: mid = left + (right - left) / 2 if nums[mid] > nums[mid + 1]: right = mid else: left = mid + 1 - + return left diff --git a/Python/find-pivot-index.py b/Python/find-pivot-index.py index 5ca035a46..37880950f 100644 --- a/Python/find-pivot-index.py +++ b/Python/find-pivot-index.py @@ -10,18 +10,18 @@ # you should return the left-most pivot index. # # Example 1: -# Input: +# Input: # nums = [1, 7, 3, 6, 5, 6] # Output: 3 -# Explanation: +# Explanation: # The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3. # Also, 3 is the first index where this occurs. # # Example 2: -# Input: +# Input: # nums = [1, 2, 3] # Output: -1 -# Explanation: +# Explanation: # There is no index that satisfies the conditions in the problem statement. # # Note: @@ -41,4 +41,4 @@ def pivotIndex(self, nums): return i left_sum += num return -1 - + diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py index c7c9fe49d..011afc5be 100644 --- a/Python/find-the-duplicate-number.py +++ b/Python/find-the-duplicate-number.py @@ -55,7 +55,7 @@ def findDuplicate(self, nums): if num <= mid: count += 1 if count > mid: - right = mid - 1 + right = mid - 1 else: left = mid + 1 return left diff --git a/Python/first-bad-version.py b/Python/first-bad-version.py index af2bdc0a5..32ff42d2b 100644 --- a/Python/first-bad-version.py +++ b/Python/first-bad-version.py @@ -4,16 +4,16 @@ # 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 +# 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 +# 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 +# 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. # diff --git a/Python/first-missing-positive.py b/Python/first-missing-positive.py index 134baa714..eb09936d4 100644 --- a/Python/first-missing-positive.py +++ b/Python/first-missing-positive.py @@ -2,11 +2,11 @@ # Space: O(1) # # Given an unsorted integer array, find the first missing positive integer. -# +# # For example, # Given [1,2,0] return 3, # and [3,4,-1,1] return 2. -# +# # Your algorithm should run in O(n) time and uses constant space. # @@ -20,12 +20,12 @@ def firstMissingPositive(self, A): A[A[i]-1], A[i] = A[i], A[A[i]-1] else: i += 1 - + for i, integer in enumerate(A): if integer != i + 1: return i + 1 return len(A) + 1 - + if __name__ == "__main__": print Solution().firstMissingPositive([1,2,0]) print Solution().firstMissingPositive([3,4,-1,1]) diff --git a/Python/flatten-2d-vector.py b/Python/flatten-2d-vector.py index 7b40db259..7443014cb 100644 --- a/Python/flatten-2d-vector.py +++ b/Python/flatten-2d-vector.py @@ -26,7 +26,7 @@ def hasNext(self): return self.x != len(self.vec) and self.y != len(self.vec[self.x]) def adjustNextIter(self): - while self.x != len(self.vec) and self.y == len(self.vec[self.x]): + while self.x != len(self.vec) and self.y == len(self.vec[self.x]): self.x += 1 if self.x != len(self.vec): self.y = 0 diff --git a/Python/flatten-binary-tree-to-linked-list.py b/Python/flatten-binary-tree-to-linked-list.py index 579f2e319..581275cb0 100644 --- a/Python/flatten-binary-tree-to-linked-list.py +++ b/Python/flatten-binary-tree-to-linked-list.py @@ -2,10 +2,10 @@ # Space: O(h), h is height of binary tree # # Given a binary tree, flatten it to a linked list in-place. -# +# # For example, # Given -# +# # 1 # / \ # 2 5 @@ -37,7 +37,7 @@ class Solution: # @return nothing, do it in place def flatten(self, root): return self.flattenRecu(root, None) - + def flattenRecu(self, root, list_head): if root != None: list_head = self.flattenRecu(root.right, list_head) @@ -47,7 +47,7 @@ def flattenRecu(self, root, list_head): return root else: return list_head - + class Solution2: list_head = None # @param root, a tree node @@ -60,7 +60,7 @@ def flatten(self, root): root.left = None self.list_head = root return root - + if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) diff --git a/Python/flatten-nested-list-iterator.py b/Python/flatten-nested-list-iterator.py index e9646fb69..255847377 100644 --- a/Python/flatten-nested-list-iterator.py +++ b/Python/flatten-nested-list-iterator.py @@ -59,7 +59,7 @@ def hasNext(self): self.__depth[-1][1] += 1 self.__depth.append([nestedList[i].getList(), 0]) return False - + # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] diff --git a/Python/flip-game.py b/Python/flip-game.py index 8c8760f43..b366ed982 100644 --- a/Python/flip-game.py +++ b/Python/flip-game.py @@ -29,4 +29,4 @@ def generatePossibleNextMoves(self, s): :rtype: List[str] """ return [s[:i] + "--" + s[i+2:] for i in xrange(len(s) - 1) if s[i:i+2] == "++"] - + diff --git a/Python/flood-fill.py b/Python/flood-fill.py index 7f1149a0f..701117bea 100644 --- a/Python/flood-fill.py +++ b/Python/flood-fill.py @@ -15,12 +15,12 @@ # At the end, return the modified image. # # Example 1: -# Input: +# Input: # image = [[1,1,1],[1,1,0],[1,0,1]] # sr = 1, sc = 1, newColor = 2 # Output: [[2,2,2],[2,2,0],[2,0,1]] -# Explanation: -# From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected +# Explanation: +# From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected # by a path of the same color as the starting pixel are colored with the new color. # Note the bottom corner is not colored 2, because it is not 4-directionally connected # to the starting pixel. @@ -46,11 +46,11 @@ def dfs(image, r, c, newColor, color): 0 <= c < len(image[0]) and \ image[r][c] == color): return - + image[r][c] = newColor for d in directions: dfs(image, r+d[0], c+d[1], newColor, color) - + color = image[sr][sc] if color == newColor: return image dfs(image, sr, sc, newColor, color) diff --git a/Python/fraction-to-recurring-decimal.py b/Python/fraction-to-recurring-decimal.py index 98dff2202..7fed92fb2 100644 --- a/Python/fraction-to-recurring-decimal.py +++ b/Python/fraction-to-recurring-decimal.py @@ -3,11 +3,11 @@ # Given two integers representing the numerator and denominator of a fraction, # return the fraction in string format. -# +# # If the fractional part is repeating, enclose the repeating part in parentheses. -# +# # For example, -# +# # Given numerator = 1, denominator = 2, return "0.5". # Given numerator = 2, denominator = 1, return "2". # Given numerator = 2, denominator = 3, return "0.(6)". @@ -20,8 +20,8 @@ def fractionToDecimal(self, numerator, denominator): :rtype: str """ result = "" - if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0): - result = "-" + if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0): + result = "-" dvd, dvs = abs(numerator), abs(denominator) result += str(dvd / dvs) diff --git a/Python/friend-circles.py b/Python/friend-circles.py index 19ee1f376..486294dfd 100644 --- a/Python/friend-circles.py +++ b/Python/friend-circles.py @@ -12,21 +12,21 @@ # otherwise not. And you have to output the total number of friend circles among all the students. # # Example 1: -# Input: +# Input: # [[1,1,0], # [1,1,0], # [0,0,1]] # Output: 2 -# Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. +# Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. # The 2nd student himself is in a friend circle. So return 2. # # Example 2: -# Input: +# Input: # [[1,1,0], # [1,1,1], # [0,1,1]] # Output: 1 -# Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, +# Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, # so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1. # # Note: @@ -45,12 +45,12 @@ 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: @@ -63,4 +63,4 @@ def union_set(self, x, y): if M[i][j] and i != j: circles.union_set(i, j) return circles.count - + diff --git a/Python/frog-jump.py b/Python/frog-jump.py index 447071fbe..3b1ca8637 100644 --- a/Python/frog-jump.py +++ b/Python/frog-jump.py @@ -1,8 +1,8 @@ -# Time: O(n) ~ O(n^2) +# Time: O(n) ~ O(n^2) # Space: O(n) # A frog is crossing a river. The river is divided into x units and -# at each unit there may or may not exist a stone. +# at each unit there may or may not exist a stone. # The frog can jump on a stone, but it must not jump into the water. # # Given a list of stones' positions (in units) in sorted ascending order, @@ -26,15 +26,15 @@ # third stone at the 3rd unit, and so on... # The last stone at the 17th unit. # -# Return true. The frog can jump to the last stone by jumping -# 1 unit to the 2nd stone, then 2 units to the 3rd stone, then -# 2 units to the 4th stone, then 3 units to the 6th stone, +# Return true. The frog can jump to the last stone by jumping +# 1 unit to the 2nd stone, then 2 units to the 3rd stone, then +# 2 units to the 4th stone, then 3 units to the 6th stone, # 4 units to the 7th stone, and 5 units to the 8th stone. # Example 2: # # [0,1,2,3,4,8,9,11] # -# Return false. There is no way to jump to the last stone as +# Return false. There is no way to jump to the last stone as # the gap between the 5th and 6th stone is too large. # DP with hash table diff --git a/Python/game-of-life.py b/Python/game-of-life.py index f569bde1f..8e2a4132a 100644 --- a/Python/game-of-life.py +++ b/Python/game-of-life.py @@ -1,35 +1,35 @@ # 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 +# 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). +# 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 +# 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 +# - 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 +# - Any dead cell with exactly three live neighbors # becomes a live cell, as if by reproduction. # -# Write a function to compute the next state +# Write a function to compute the next state # (after one update) of the board given its current state. # -# Follow up: +# 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 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? @@ -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 # Mark as live. + board[i][j] |= 2 # Mark as live. for i in xrange(m): for j in xrange(n): diff --git a/Python/gas-station.py b/Python/gas-station.py index 72d6a0806..30a6fe5cc 100644 --- a/Python/gas-station.py +++ b/Python/gas-station.py @@ -2,12 +2,12 @@ # Space: O(1) # # There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. -# +# # You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). # You begin the journey with an empty tank at one of the gas stations. -# +# # Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. -# +# # Note: # The solution is guaranteed to be unique. # @@ -27,7 +27,7 @@ def canCompleteCircuit(self, gas, cost): current_sum = 0 if total_sum >= 0: return start - + return -1 if __name__ == "__main__": diff --git a/Python/generate-parentheses.py b/Python/generate-parentheses.py index 0b9712875..2ffcfc194 100644 --- a/Python/generate-parentheses.py +++ b/Python/generate-parentheses.py @@ -1,11 +1,11 @@ # Time: O(4^n / n^(3/2)) ~= Catalan numbers # Space: O(n) # -# Given n pairs of parentheses, write a function to generate +# Given n pairs of parentheses, write a function to generate # all combinations of well-formed parentheses. -# +# # For example, given n = 3, a solution set is: -# +# # "((()))", "(()())", "(())()", "()(())", "()()()" # @@ -16,7 +16,7 @@ def generateParenthesis(self, n): result = [] self.generateParenthesisRecu(result, "", n, n) return result - + def generateParenthesisRecu(self, result, current, left, right): if left == 0 and right == 0: result.append(current) diff --git a/Python/global-and-local-inversions.py b/Python/global-and-local-inversions.py index 2ee8525b0..2c7e22024 100644 --- a/Python/global-and-local-inversions.py +++ b/Python/global-and-local-inversions.py @@ -30,4 +30,4 @@ def isIdealPermutation(self, A): :rtype: bool """ return all(abs(v-i) <= 1 for i,v in enumerate(A)) - + diff --git a/Python/gray-code.py b/Python/gray-code.py index 415e0f752..f54b9b421 100644 --- a/Python/gray-code.py +++ b/Python/gray-code.py @@ -2,22 +2,22 @@ # Space: O(1) # The gray code is a binary numeral system where two successive values differ in only one bit. -# -# Given a non-negative integer n representing the total number of bits in the code, +# +# Given a non-negative integer n representing the total number of bits in the code, # print the sequence of gray code. A gray code sequence must begin with 0. -# +# # For example, given n = 2, return [0,1,3,2]. Its gray code sequence is: -# +# # 00 - 0 # 01 - 1 # 11 - 3 # 10 - 2 # Note: # For a given n, a gray code sequence is not uniquely defined. -# +# # For example, [0,2,3,1] is also a valid gray code sequence according # to the above definition. -# +# # For now, the judge is able to judge based on one instance of gray code # sequence. Sorry about that. diff --git a/Python/guess-number-higher-or-lower-ii.py b/Python/guess-number-higher-or-lower-ii.py index 48e7139a8..9de4bf3bc 100644 --- a/Python/guess-number-higher-or-lower-ii.py +++ b/Python/guess-number-higher-or-lower-ii.py @@ -26,7 +26,7 @@ # Hint: # # The best strategy to play the game is to minimize the maximum loss -# you could possibly face. Another strategy is to minimize the expected loss. +# you could possibly face. Another strategy is to minimize the expected loss. # Here, we are interested in the first scenario. # Take a small example (n = 3). What do you end up paying in the worst case? # Check out this article if you're still stuck. diff --git a/Python/h-index.py b/Python/h-index.py index 4ad07afdb..ab47ad881 100644 --- a/Python/h-index.py +++ b/Python/h-index.py @@ -4,15 +4,15 @@ # 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: +# 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], +# 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 +# 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. @@ -57,7 +57,7 @@ def hIndex(self, citations): else: break return h - + # Time: O(nlogn) # Space: O(n) class Solution3(object): @@ -67,4 +67,4 @@ def hIndex(self, citations): :rtype: int """ return sum(x >= i + 1 for i, x in enumerate(sorted(citations, reverse=True))) - + diff --git a/Python/happy-number.py b/Python/happy-number.py index 7ea4a5675..588f655e5 100644 --- a/Python/happy-number.py +++ b/Python/happy-number.py @@ -3,11 +3,11 @@ # # 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 +# 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 @@ -26,7 +26,7 @@ def isHappy(self, n): lookup[n] = True n = self.nextNumber(n) return n == 1 - + def nextNumber(self, n): new = 0 for char in str(n): diff --git a/Python/house-robber-ii.py b/Python/house-robber-ii.py index 554ed4828..5f1b2fbff 100644 --- a/Python/house-robber-ii.py +++ b/Python/house-robber-ii.py @@ -3,13 +3,13 @@ # # 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 +# 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, +# 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: @@ -18,19 +18,19 @@ class Solution: 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__': diff --git a/Python/house-robber-iii.py b/Python/house-robber-iii.py index 06d4ea317..a1ed8c3a1 100644 --- a/Python/house-robber-iii.py +++ b/Python/house-robber-iii.py @@ -2,11 +2,11 @@ # 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." +# 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 +# police if two directly-linked houses were broken into on the # same night. # # Determine the maximum amount of money the thief can rob tonight @@ -16,14 +16,14 @@ # 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. # @@ -45,5 +45,5 @@ def robHelper(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)) diff --git a/Python/house-robber.py b/Python/house-robber.py index 3efd6e8a0..d94ae3b53 100644 --- a/Python/house-robber.py +++ b/Python/house-robber.py @@ -1,12 +1,12 @@ # 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 +# 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, +# 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: @@ -15,15 +15,15 @@ class Solution: 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 def rob2(self, nums): diff --git a/Python/image-smoother.py b/Python/image-smoother.py index 232662103..cd51b2fbc 100644 --- a/Python/image-smoother.py +++ b/Python/image-smoother.py @@ -22,7 +22,7 @@ # Note: # The value in the given matrix is in the range of [0, 255]. # The length and width of the given matrix are in the range of [1, 150]. - + class Solution(object): def imageSmoother(self, M): """ diff --git a/Python/implement-queue-using-stacks.py b/Python/implement-queue-using-stacks.py index 02b3e4860..9c32c8197 100644 --- a/Python/implement-queue-using-stacks.py +++ b/Python/implement-queue-using-stacks.py @@ -32,14 +32,14 @@ def push(self, x): def pop(self): self.peek() return 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 diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py index a592a3654..1e7a5919a 100644 --- a/Python/implement-strstr.py +++ b/Python/implement-strstr.py @@ -2,7 +2,7 @@ # Space: O(k) # # Implement strStr(). -# +# # Returns a pointer to the first occurrence of needle in haystack, # or null if needle is not part of haystack. # @@ -18,9 +18,9 @@ def strStr(self, haystack, needle): """ if not needle: return 0 - + return self.KMP(haystack, needle) - + def KMP(self, text, pattern): prefix = self.getPrefix(pattern) j = -1 @@ -32,7 +32,7 @@ def KMP(self, text, pattern): if j == len(pattern) - 1: return i - j return -1 - + def getPrefix(self, pattern): prefix = [-1] * len(pattern) j = -1 @@ -44,7 +44,7 @@ def getPrefix(self, pattern): prefix[i] = j return prefix - + # Time: O(n * k) # Space: O(k) class Solution2(object): diff --git a/Python/implement-trie-prefix-tree.py b/Python/implement-trie-prefix-tree.py index 0301555ad..a062f91ba 100644 --- a/Python/implement-trie-prefix-tree.py +++ b/Python/implement-trie-prefix-tree.py @@ -12,7 +12,7 @@ class TrieNode: def __init__(self): self.is_string = False self.leaves = {} - + class Trie: @@ -37,7 +37,7 @@ def search(self, word): node = self.childSearch(word) if node: return node.is_string - return False + return False # @param {string} prefix # @return {boolean} diff --git a/Python/increasing-subsequences.py b/Python/increasing-subsequences.py index e246be299..6639959bc 100644 --- a/Python/increasing-subsequences.py +++ b/Python/increasing-subsequences.py @@ -1,8 +1,8 @@ # Time: O(n * 2^n) # Space: O(n^2) -# Given an integer array, your task is -# to find all the different possible increasing +# Given an integer array, your task is +# to find all the different possible increasing # subsequences of the given array, # and the length of an increasing subsequence should be at least 2 . # diff --git a/Python/insert-delete-getrandom-o1-duplicates-allowed.py b/Python/insert-delete-getrandom-o1-duplicates-allowed.py index 3aa6ab1a7..f0dbf9c63 100644 --- a/Python/insert-delete-getrandom-o1-duplicates-allowed.py +++ b/Python/insert-delete-getrandom-o1-duplicates-allowed.py @@ -43,7 +43,7 @@ def __init__(self): """ self.__list = [] self.__used = defaultdict(list) - + def insert(self, val): """ diff --git a/Python/insert-delete-getrandom-o1.py b/Python/insert-delete-getrandom-o1.py index 136636091..9ae83a0be 100644 --- a/Python/insert-delete-getrandom-o1.py +++ b/Python/insert-delete-getrandom-o1.py @@ -45,7 +45,7 @@ def __init__(self): """ self.__set = [] self.__used = {} - + def insert(self, val): """ @@ -60,7 +60,7 @@ def insert(self, val): self.__used[val] = len(self.__set)-1 return True - + def remove(self, val): """ diff --git a/Python/insert-interval.py b/Python/insert-interval.py index 16cf7c0a7..33dd83cec 100644 --- a/Python/insert-interval.py +++ b/Python/insert-interval.py @@ -4,13 +4,13 @@ # Given a set of non-overlapping intervals, insert a new interval into the # intervals (merge if necessary). # You may assume that the intervals were initially sorted according to their start times. -# +# # Example 1: # Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. -# +# # Example 2: # Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. -# +# # This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. # Definition for an interval. @@ -18,7 +18,7 @@ class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e - + def __repr__(self): return "[{}, {}]".format(self.start, self.end) diff --git a/Python/insertion-sort-list.py b/Python/insertion-sort-list.py index fa7c9616c..30a8a7500 100644 --- a/Python/insertion-sort-list.py +++ b/Python/insertion-sort-list.py @@ -9,7 +9,7 @@ class ListNode: def __init__(self, x): self.val = x self.next = None - + def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) @@ -22,7 +22,7 @@ class Solution: def insertionSortList(self, head): if head is None or self.isSorted(head): return head - + dummy = ListNode(-2147483648) dummy.next = head cur, sorted_tail = head.next, head @@ -31,13 +31,13 @@ def insertionSortList(self, head): while prev.next.val < cur.val: prev = prev.next if prev == sorted_tail: - cur, sorted_tail = cur.next, cur + cur, sorted_tail = cur.next, cur else: cur.next, prev.next, sorted_tail.next = prev.next, cur, cur.next cur = sorted_tail.next - + return dummy.next - + def isSorted(self, head): while head and head.next: if head.val > head.next.val: diff --git a/Python/integer-break.py b/Python/integer-break.py index c2127f3e9..ca3bab0e5 100644 --- a/Python/integer-break.py +++ b/Python/integer-break.py @@ -31,15 +31,15 @@ def integerBreak(self, n): # ai <= 2 * (ai - 2) # - For each aj >= 5, we can always maximize the product by: # aj <= 3 * (aj - 3) - # + # # Conclusion 1: # - For n >= 4, the max of the product must be in the form of # 3^a * 2^b, s.t. 3a + 2b = n - # + # # 2. To maximize the product = 3^a * 2^b s.t. 3a + 2b = n # - For each b >= 3, we can always maximize the product by: # 3^a * 2^b <= 3^(a+2) * 2^(b-3) s.t. 3(a+2) + 2(b-3) = n - # + # # Conclusion 2: # - For n >= 4, the max of the product must be in the form of # 3^Q * 2^R, 0 <= R < 3 s.t. 3Q + 2R = n diff --git a/Python/integer-replacement.py b/Python/integer-replacement.py index 8ec74bf04..4820bf85a 100644 --- a/Python/integer-replacement.py +++ b/Python/integer-replacement.py @@ -49,9 +49,9 @@ def integerReplacement(self, n): else: n /= 2 result += 1 - + return result - + # Time: O(logn) # Space: O(logn) @@ -70,4 +70,4 @@ def integerReplacement(self, n): return self.integerReplacement((n - 1) / 4) + 3 else: return self.integerReplacement((n + 1) / 4) + 3 - + diff --git a/Python/integer-to-english-words.py b/Python/integer-to-english-words.py index 3c5ab64db..6097cf02f 100644 --- a/Python/integer-to-english-words.py +++ b/Python/integer-to-english-words.py @@ -57,7 +57,7 @@ def threeDigits(self, num, lookup, unit): if unit != "": res.append(unit) return " ".join(res) - + def twoDigits(self, num, lookup): if num in lookup: return lookup[num] diff --git a/Python/integer-to-roman.py b/Python/integer-to-roman.py index eed075b1b..672201a80 100644 --- a/Python/integer-to-roman.py +++ b/Python/integer-to-roman.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given an integer, convert it to a roman numeral. -# +# # Input is guaranteed to be within the range from 1 to 3999. # @@ -17,16 +17,16 @@ def intToRoman(self, num): 100: "C", 400: "CD", 500: "D", 900: "CM", \ 1000: "M"} keyset, result = sorted(numeral_map.keys()), [] - + while num > 0: for key in reversed(keyset): while num / key > 0: num -= key result += numeral_map[key] - + return "".join(result) - + if __name__ == "__main__": print Solution().intToRoman(999) print Solution().intToRoman(3999) diff --git a/Python/interleaving-string.py b/Python/interleaving-string.py index fd92f6141..8e0ff98c6 100644 --- a/Python/interleaving-string.py +++ b/Python/interleaving-string.py @@ -2,16 +2,16 @@ # Space: O(m + n) # # Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. -# +# # For example, # Given: # s1 = "aabcc", # s2 = "dbbca", -# +# # When s3 = "aadbbcbcac", return true. # When s3 = "aadbbbaccc", return false. # - + # Time: O(m * n) # Space: O(m + n) # Dynamic Programming + Sliding Window @@ -55,7 +55,7 @@ def isInterleave(self, s1, s2, s3): # Time: O(m * n) # Space: O(m * n) -# Recursive + Hash +# Recursive + Hash class Solution3: # @return a boolean def isInterleave(self, s1, s2, s3): @@ -63,22 +63,22 @@ def isInterleave(self, s1, s2, s3): if len(s1) + len(s2) != len(s3): return False return self.isInterleaveRecu(s1, s2, s3, 0, 0, 0) - + def isInterleaveRecu(self, s1, s2, s3, a, b, c): if repr([a, b]) in self.match.keys(): return self.match[repr([a, b])] - + if c == len(s3): return True - + result = False if a < len(s1) and s1[a] == s3[c]: result = result or self.isInterleaveRecu(s1, s2, s3, a + 1, b, c + 1) if b < len(s2) and s2[b] == s3[c]: result = result or self.isInterleaveRecu(s1, s2, s3, a, b + 1, c + 1) - - self.match[repr([a, b])] = result - + + self.match[repr([a, b])] = result + return result if __name__ == "__main__": diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py index 9e3f626c6..df7776dca 100644 --- a/Python/intersection-of-two-arrays-ii.py +++ b/Python/intersection-of-two-arrays-ii.py @@ -44,7 +44,7 @@ def intersect(self, nums1, nums2): """ if len(nums1) > len(nums2): return self.intersect(nums2, nums1) - + lookup = collections.defaultdict(int) for i in nums1: lookup[i] += 1 @@ -102,7 +102,7 @@ def binary_search(compare, nums, left, right, target): if left != len(nums2) and nums2[left] == i: res += i, left += 1 - + return res @@ -120,7 +120,7 @@ def intersect(self, nums1, nums2): nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time. res = [] - + it1, it2 = 0, 0 while it1 < len(nums1) and it2 < len(nums2): if nums1[it1] < nums2[it2]: @@ -131,7 +131,7 @@ def intersect(self, nums1, nums2): res += nums1[it1], it1 += 1 it2 += 1 - + return res @@ -149,7 +149,7 @@ def intersect(self, nums1, nums2): nums1.sort(), nums2.sort() # O(max(m, n) * log(max(m, n))) res = [] - + it1, it2 = 0, 0 while it1 < len(nums1) and it2 < len(nums2): if nums1[it1] < nums2[it2]: @@ -160,5 +160,5 @@ def intersect(self, nums1, nums2): res += nums1[it1], it1 += 1 it2 += 1 - + return res diff --git a/Python/intersection-of-two-arrays.py b/Python/intersection-of-two-arrays.py index e04ff0c40..fb90f68eb 100644 --- a/Python/intersection-of-two-arrays.py +++ b/Python/intersection-of-two-arrays.py @@ -22,7 +22,7 @@ def intersection(self, nums1, nums2): """ if len(nums1) > len(nums2): return self.intersection(nums2, nums1) - + lookup = set() for i in nums1: lookup.add(i) @@ -75,7 +75,7 @@ def binary_search(compare, nums, left, right, target): if left != len(nums2) and nums2[left] == i: res += i, left = binary_search(lambda x, y: x > y, nums2, left, len(nums2), i) - + return res @@ -91,7 +91,7 @@ def intersection(self, nums1, nums2): """ nums1.sort(), nums2.sort() res = [] - + it1, it2 = 0, 0 while it1 < len(nums1) and it2 < len(nums2): if nums1[it1] < nums2[it2]: @@ -103,5 +103,5 @@ def intersection(self, nums1, nums2): res += nums1[it1], it1 += 1 it2 += 1 - + return res diff --git a/Python/intersection-of-two-linked-lists.py b/Python/intersection-of-two-linked-lists.py index 328df54fb..3d18b7918 100644 --- a/Python/intersection-of-two-linked-lists.py +++ b/Python/intersection-of-two-linked-lists.py @@ -2,20 +2,20 @@ # Space: O(1) # # Write a program to find the node at which the intersection of two singly linked lists begins. -# -# +# +# # For example, the following two linked lists: -# +# # A: a1 - a2 # \ # c1 - c2 - c3 -# / +# / # B: b1 - b2 - b3 # begin to intersect at node c1. -# -# +# +# # Notes: -# +# # If the two linked lists have no intersection at all, return null. # The linked lists must retain their original structure after the function returns. # You may assume there are no cycles anywhere in the entire linked structure. @@ -34,14 +34,14 @@ class Solution: def getIntersectionNode(self, headA, headB): curA, curB = headA, headB begin, tailA, tailB = None, None, None - + # a->c->b->c # b->c->a->c while curA and curB: if curA == curB: begin = curA break - + if curA.next: curA = curA.next elif tailA is None: @@ -49,7 +49,7 @@ def getIntersectionNode(self, headA, headB): curA = headB else: break - + if curB.next: curB = curB.next elif tailB is None: @@ -57,5 +57,5 @@ def getIntersectionNode(self, headA, headB): curB = headA else: break - + return begin diff --git a/Python/ip-to-cidr.py b/Python/ip-to-cidr.py index 3c4bb3b6f..fe9a17788 100644 --- a/Python/ip-to-cidr.py +++ b/Python/ip-to-cidr.py @@ -39,7 +39,7 @@ # but our answer was the shortest possible. # # Also note that a representation beginning with say, "255.0.0.7/30" would be incorrect, -# because it includes addresses like 255.0.0.4 = 11111111 00000000 00000000 00000100 +# because it includes addresses like 255.0.0.4 = 11111111 00000000 00000000 00000100 # that are outside the specified range. # Note: # - ip will be a valid IPv4 address. diff --git a/Python/is-graph-bipartite.py b/Python/is-graph-bipartite.py index 213d8e372..5b9890e91 100644 --- a/Python/is-graph-bipartite.py +++ b/Python/is-graph-bipartite.py @@ -8,7 +8,7 @@ # one node in A and another node in B. # # The graph is given in the following form: graph[i] is a list of indexes j -# for which the edge between nodes i and j exists. +# for which the edge between nodes i and j exists. # Each node is an integer between 0 and graph.length - 1. # There are no self edges or parallel edges: graph[i] does not contain i, # and it doesn't contain any element twice. @@ -16,18 +16,18 @@ # Example 1: # Input: [[1,3], [0,2], [1,3], [0,2]] # Output: true -# Explanation: +# Explanation: # The graph looks like this: # 0----1 # | | # | | # 3----2 # We can divide the vertices into two groups: {0, 2} and {1, 3}. -# +# # Example 2: # Input: [[1,2,3], [0,2], [0,1,3], [0,2]] # Output: false -# Explanation: +# Explanation: # The graph looks like this: # 0----1 # | \ | diff --git a/Python/is-subsequence.py b/Python/is-subsequence.py index e92eceef0..a47504b7d 100644 --- a/Python/is-subsequence.py +++ b/Python/is-subsequence.py @@ -6,7 +6,7 @@ # You may assume that there is only lower case English letters in both s and t. # t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100). # -# A subsequence of a string is a new string which is formed from +# A subsequence of a string is a new string which is formed from # the original string by deleting some (can be none) of the characters # without disturbing the relative positions of the remaining characters. # (ie, "ace" is a subsequence of "abcde" while "aec" is not). diff --git a/Python/isomorphic-strings.py b/Python/isomorphic-strings.py index e22243e67..4268ab641 100644 --- a/Python/isomorphic-strings.py +++ b/Python/isomorphic-strings.py @@ -5,8 +5,8 @@ # # 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 +# 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, @@ -35,7 +35,7 @@ def isIsomorphic(self, s, t): for p, w in izip(s, t): if w not in s2t and p not in t2s: s2t[w] = p - t2s[p] = w + t2s[p] = w elif w not in s2t or s2t[w] != p: # Contradict mapping. return False @@ -48,7 +48,7 @@ class Solution2(object): 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): diff --git a/Python/jewels-and-stones.py b/Python/jewels-and-stones.py index 18fbbd812..61fa6936d 100644 --- a/Python/jewels-and-stones.py +++ b/Python/jewels-and-stones.py @@ -30,4 +30,4 @@ def numJewelsInStones(self, J, S): """ lookup = set(J) return sum(s in lookup for s in S) - + diff --git a/Python/judge-route-circle.py b/Python/judge-route-circle.py index 79cfe6d5d..8aafd1fee 100644 --- a/Python/judge-route-circle.py +++ b/Python/judge-route-circle.py @@ -14,7 +14,7 @@ # Example 2: # Input: "LL" # Output: false - + class Solution(object): def judgeCircle(self, moves): """ diff --git a/Python/jump-game-ii.py b/Python/jump-game-ii.py index 571c405d4..d99f97642 100644 --- a/Python/jump-game-ii.py +++ b/Python/jump-game-ii.py @@ -2,14 +2,14 @@ # Space: O(1) # # Given an array of non-negative integers, you are initially positioned at the first index of the array. -# +# # Each element in the array represents your maximum jump length at that position. -# +# # Your goal is to reach the last index in the minimum number of jumps. -# +# # For example: # Given array A = [2,3,1,1,4] -# +# # The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) # @@ -29,8 +29,8 @@ def jump(self, A): jump_count += 1 reachable = max(reachable, i + length) return jump_count - - + + if __name__ == "__main__": print Solution().jump([2,3,1,1,4]) print Solution().jump([3,2,1,0,4]) diff --git a/Python/jump-game.py b/Python/jump-game.py index f3e18cce6..de25a28b3 100644 --- a/Python/jump-game.py +++ b/Python/jump-game.py @@ -2,14 +2,14 @@ # Space: O(1) # # Given an array of non-negative integers, you are initially positioned at the first index of the array. -# +# # Each element in the array represents your maximum jump length at that position. -# +# # Determine if you are able to reach the last index. -# +# # For example: # A = [2,3,1,1,4], return true. -# +# # A = [3,2,1,0,4], return false. class Solution: @@ -22,7 +22,7 @@ def canJump(self, A): break reachable = max(reachable, i + length) return reachable >= len(A) - 1 - + if __name__ == "__main__": print Solution().canJump([2,3,1,1,4]) print Solution().canJump([3,2,1,0,4]) \ No newline at end of file diff --git a/Python/k-diff-pairs-in-an-array.py b/Python/k-diff-pairs-in-an-array.py index 58a4b29b5..9331f8a74 100644 --- a/Python/k-diff-pairs-in-an-array.py +++ b/Python/k-diff-pairs-in-an-array.py @@ -5,7 +5,7 @@ # Total Submissions: 20941 # Difficulty: Easy # Contributors: murali.kf370 -# Given an array of integers and an integer k, +# Given an array of integers and an integer k, # you need to find the number of unique k-diff pairs in the array. # Here a k-diff pair is defined as an integer pair (i, j), # where i and j are both numbers in the array and their absolute difference is k. diff --git a/Python/k-empty-slots.py b/Python/k-empty-slots.py index ca99f58b1..c87e9005a 100644 --- a/Python/k-empty-slots.py +++ b/Python/k-empty-slots.py @@ -18,14 +18,14 @@ # If there isn't such day, output -1. # # Example 1: -# Input: +# Input: # flowers: [1,3,2] # k: 1 # Output: 2 # Explanation: In the second day, the first and the third flower have become blooming. # # Example 2: -# Input: +# Input: # flowers: [1,2,3] # k: 1 # Output: -1 @@ -45,10 +45,10 @@ def kEmptySlots(self, flowers, k): result = float("inf") i, left, right = 0, 0, k+1 while right < len(days): - if days[i] < days[left] or days[i] <= days[right]: + if days[i] < days[left] or days[i] <= days[right]: if i == right: result = min(result, max(days[left], days[right])) left, right = i, k+1+i; i += 1 return -1 if result == float("inf") else result+1 - + diff --git a/Python/k-inverse-pairs-array.py b/Python/k-inverse-pairs-array.py index da1e592dd..1845a3c44 100644 --- a/Python/k-inverse-pairs-array.py +++ b/Python/k-inverse-pairs-array.py @@ -12,12 +12,12 @@ # Example 1: # Input: n = 3, k = 0 # Output: 1 -# Explanation: +# Explanation: # Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pair. # Example 2: # Input: n = 3, k = 1 # Output: 2 -# Explanation: +# Explanation: # The array [1,3,2] and [2,1,3] have exactly 1 inverse pair. # Note: # The integer n is in the range [1, 1000] and k is in the range [0, 1000]. diff --git a/Python/k-th-smallest-in-lexicographical-order.py b/Python/k-th-smallest-in-lexicographical-order.py index 4a969c6d5..8a15760be 100644 --- a/Python/k-th-smallest-in-lexicographical-order.py +++ b/Python/k-th-smallest-in-lexicographical-order.py @@ -78,7 +78,7 @@ def count(n, prefix): number *= 10 result -= max(number/10 - (n - prefix/10 + 1), 0) return result - + def findKthNumberHelper(n, k, cur, index): if cur: index += 1 @@ -98,5 +98,5 @@ def findKthNumberHelper(n, k, cur, index): i += 1 cur /= 10 return (0, index) - + return findKthNumberHelper(n, k, 0, 0)[0] diff --git a/Python/k-th-symbol-in-grammar.py b/Python/k-th-symbol-in-grammar.py index dbed8a5f6..8980720a1 100644 --- a/Python/k-th-symbol-in-grammar.py +++ b/Python/k-th-symbol-in-grammar.py @@ -45,5 +45,5 @@ def bitCount(n): n &= n - 1 result += 1 return result - + return bitCount(K-1) % 2 diff --git a/Python/keyboard-row.py b/Python/keyboard-row.py index 9291dcf63..ef825d00c 100644 --- a/Python/keyboard-row.py +++ b/Python/keyboard-row.py @@ -18,7 +18,7 @@ def findWords(self, words): :rtype: List[str] """ rows = [set(['q', 'w', 'e', 'r', 't', 'y','u', 'i', 'o', 'p']), - set(['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']), + set(['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']), set(['z', 'x', 'c', 'v', 'b' ,'n', 'm'])] result = [] diff --git a/Python/knight-probability-in-chessboard.py b/Python/knight-probability-in-chessboard.py index cb87d07ed..2f493ca96 100644 --- a/Python/knight-probability-in-chessboard.py +++ b/Python/knight-probability-in-chessboard.py @@ -1,6 +1,6 @@ # Time: O(k * n^2) # Space: O(n^2) - + # On an NxN chessboard, a knight starts at the r-th row and c-th column and # attempts to make exactly K moves. The rows and columns are 0 indexed, # so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1). @@ -17,7 +17,7 @@ # Example: # Input: 3, 2, 0, 0 # Output: 0.0625 -# +# # Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. # From each of those positions, there are also two moves that will keep the knight on the board. # The total probability the knight stays on the board is 0.0625. diff --git a/Python/kth-largest-element-in-an-array.py b/Python/kth-largest-element-in-an-array.py index 08dd0b788..55e1af2a9 100644 --- a/Python/kth-largest-element-in-an-array.py +++ b/Python/kth-largest-element-in-an-array.py @@ -18,7 +18,7 @@ def findKthLargest(self, nums, k): 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 @@ -27,7 +27,7 @@ def PartitionAroundPivot(self, left, right, pivot_idx, nums): 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 - + diff --git a/Python/kth-smallest-element-in-a-bst.py b/Python/kth-smallest-element-in-a-bst.py index ee7216094..89457f4e9 100644 --- a/Python/kth-smallest-element-in-a-bst.py +++ b/Python/kth-smallest-element-in-a-bst.py @@ -3,7 +3,7 @@ # Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. # -# Note: +# Note: # You may assume k is always valid, 1 ≤ k ≤ BST's total elements. # # Follow up: diff --git a/Python/kth-smallest-element-in-a-sorted-matrix.py b/Python/kth-smallest-element-in-a-sorted-matrix.py index be66a8b8f..1bf17df12 100644 --- a/Python/kth-smallest-element-in-a-sorted-matrix.py +++ b/Python/kth-smallest-element-in-a-sorted-matrix.py @@ -18,7 +18,7 @@ # k = 8, # # return 13. -# Note: +# Note: # You may assume k is always valid, 1 <= k <= n^2. from heapq import heappush, heappop diff --git a/Python/kth-smallest-number-in-multiplication-table.py b/Python/kth-smallest-number-in-multiplication-table.py index dc5ee176e..17c4225b8 100644 --- a/Python/kth-smallest-number-in-multiplication-table.py +++ b/Python/kth-smallest-number-in-multiplication-table.py @@ -9,8 +9,8 @@ # # Example 1: # Input: m = 3, n = 3, k = 5 -# Output: -# Explanation: +# Output: +# Explanation: # The Multiplication Table: # 1 2 3 # 2 4 6 @@ -19,8 +19,8 @@ # The 5-th smallest number is 3 (1, 2, 2, 3, 3). # Example 2: # Input: m = 2, n = 3, k = 6 -# Output: -# Explanation: +# Output: +# Explanation: # The Multiplication Table: # 1 2 3 # 2 4 6 diff --git a/Python/largest-bst-subtree.py b/Python/largest-bst-subtree.py index 35d18f1be..78359e2bb 100644 --- a/Python/largest-bst-subtree.py +++ b/Python/largest-bst-subtree.py @@ -25,7 +25,7 @@ def largestBSTSubtreeHelper(root): 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, root.val if root.right is not None: right_size, right_min, right_max = largestBSTSubtreeHelper(root.right) diff --git a/Python/largest-number.py b/Python/largest-number.py index 8317a617b..008d5e0e7 100644 --- a/Python/largest-number.py +++ b/Python/largest-number.py @@ -2,9 +2,9 @@ # Space: O(1) # # Given a list of non negative integers, arrange them such that they form the largest number. -# +# # For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. -# +# # Note: The result may be very large, so you need to return a string instead of an integer. # @@ -19,4 +19,4 @@ def largestNumber(self, num): if __name__ == "__main__": num = [3, 30, 34, 5, 9] - print Solution().largestNumber(num) + print Solution().largestNumber(num) diff --git a/Python/largest-palindrome-product.py b/Python/largest-palindrome-product.py index c189a0011..66c4b3fee 100644 --- a/Python/largest-palindrome-product.py +++ b/Python/largest-palindrome-product.py @@ -20,7 +20,7 @@ def largestPalindrome(self, n): """ if n == 1: return 9 - + upper, lower = 10**n-1, 10**(n-1) for i in reversed(xrange(lower, upper+1)): candidate = int(str(i) + str(i)[::-1]) diff --git a/Python/largest-plus-sign.py b/Python/largest-plus-sign.py index 5b47e514b..3d068753c 100644 --- a/Python/largest-plus-sign.py +++ b/Python/largest-plus-sign.py @@ -20,7 +20,7 @@ def orderOfLargestPlusSign(self, N, mines): for j in reversed(xrange(N)): l = 0 if (i, j) in lookup else l+1 dp[i][j] = min(dp[i][j], l) - + for j in xrange(N): l = 0 for i in xrange(N): diff --git a/Python/largest-rectangle-in-histogram.py b/Python/largest-rectangle-in-histogram.py index e3dea568b..3e4d6fa82 100644 --- a/Python/largest-rectangle-in-histogram.py +++ b/Python/largest-rectangle-in-histogram.py @@ -1,10 +1,10 @@ # Time: O(n) # Space: O(n) # -# Given n non-negative integers representing the histogram's bar +# Given n non-negative integers representing the histogram's bar # height where the width of each bar is 1, # find the area of largest rectangle in the histogram. -# +# # For example, # Given height = [2,1,5,6,2,3], # return 10. @@ -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]) - + diff --git a/Python/length-of-last-word.py b/Python/length-of-last-word.py index 0e713d1a1..ec1c239e0 100644 --- a/Python/length-of-last-word.py +++ b/Python/length-of-last-word.py @@ -2,12 +2,12 @@ # Space: O(1) # # Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. -# +# # If the last word does not exist, return 0. -# +# # Note: A word is defined as a character sequence consists of non-space characters only. -# -# For example, +# +# For example, # Given s = "Hello World", # return 5. # diff --git a/Python/letter-combinations-of-a-phone-number.py b/Python/letter-combinations-of-a-phone-number.py index c876137ca..ca3d1c347 100644 --- a/Python/letter-combinations-of-a-phone-number.py +++ b/Python/letter-combinations-of-a-phone-number.py @@ -2,11 +2,11 @@ # Space: O(n) # # Given a digit string, return all possible letter combinations that the number could represent. -# +# # A mapping of digit to letters (just like on the telephone buttons) is given below. -# +# # lookup = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] -# +# # Input:Digit string "23" # Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. # Note: @@ -19,18 +19,18 @@ class Solution: def letterCombinations(self, digits): if not digits: return [] - + lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", \ "pqrs", "tuv", "wxyz"], [""] for digit in reversed(digits): choices = lookup[int(digit)] m, n = len(choices), len(result) - result += [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] - + result[i] = choices[i / n] + result[i] + return result @@ -46,7 +46,7 @@ def letterCombinations(self, digits): "pqrs", "tuv", "wxyz"], [] self.letterCombinationsRecu(result, digits, lookup, "", 0) return result - + def letterCombinationsRecu(self, result, digits, lookup, cur, n): if n == len(digits): result.append(cur) diff --git a/Python/lexicographical-numbers.py b/Python/lexicographical-numbers.py index 789aa4d51..20e3f896a 100644 --- a/Python/lexicographical-numbers.py +++ b/Python/lexicographical-numbers.py @@ -18,7 +18,7 @@ def lexicalOrder(self, n): while i * 10**k <= n: result.append(i * 10**k) k += 1 - + num = result[-1] + 1 while num <= n and num % 10: result.append(num) @@ -31,7 +31,7 @@ def lexicalOrder(self, n): while num % 10 == 9: num /= 10 - + i = num+1 return result diff --git a/Python/linked-list-cycle-ii.py b/Python/linked-list-cycle-ii.py index 74ea144ca..281e465fc 100644 --- a/Python/linked-list-cycle-ii.py +++ b/Python/linked-list-cycle-ii.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given a linked list, return the node where the cycle begins. If there is no cycle, return null. -# +# # Follow up: # Can you solve it without using extra space? # @@ -12,13 +12,13 @@ class ListNode: def __init__(self, x): self.val = x self.next = None - + def __str__(self): if self: return "{}".format(self.val) else: return None - + class Solution: # @param head, a ListNode # @return a list node diff --git a/Python/linked-list-cycle.py b/Python/linked-list-cycle.py index b2288624d..6073a78be 100644 --- a/Python/linked-list-cycle.py +++ b/Python/linked-list-cycle.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given a linked list, determine if it has a cycle in it. -# +# # Follow up: # Can you solve it without using extra space? # diff --git a/Python/linked-list-random-node.py b/Python/linked-list-random-node.py index 1e6d7de0f..7ac0718fc 100644 --- a/Python/linked-list-random-node.py +++ b/Python/linked-list-random-node.py @@ -46,7 +46,7 @@ def getRandom(self): reservoir = curr.val if randint(1, n+1) == 1 else reservoir curr, n = curr.next, n+1 return reservoir - + # Your Solution object will be instantiated and called as such: # obj = Solution(head) diff --git a/Python/longest-absolute-file-path.py b/Python/longest-absolute-file-path.py index bc29abb10..065458aa2 100644 --- a/Python/longest-absolute-file-path.py +++ b/Python/longest-absolute-file-path.py @@ -28,7 +28,7 @@ # For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", # and its length is 32 (not including the double quotes). # -# Given a string representing the file system in the above format, +# Given a string representing the file system in the above format, # return the length of the longest absolute path to file in the abstracted file system. # If there is no file in the system, return 0. # diff --git a/Python/longest-consecutive-sequence.py b/Python/longest-consecutive-sequence.py index df70be6e9..240b109e0 100644 --- a/Python/longest-consecutive-sequence.py +++ b/Python/longest-consecutive-sequence.py @@ -2,11 +2,11 @@ # Space: O(n) # # Given an unsorted array of integers, find the length of the longest consecutive elements sequence. -# +# # For example, # Given [100, 4, 200, 1, 3, 2], # The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. -# +# # Your algorithm should run in O(n) complexity. # diff --git a/Python/longest-continuous-increasing-subsequence.py b/Python/longest-continuous-increasing-subsequence.py index c374bbea3..9ae2635e1 100644 --- a/Python/longest-continuous-increasing-subsequence.py +++ b/Python/longest-continuous-increasing-subsequence.py @@ -7,13 +7,13 @@ # Example 1: # Input: [1,3,5,4,7] # Output: 3 -# Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. +# Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. # Even though [1,3,5,7] is also an increasing subsequence, -# it's not a continuous one where 5 and 7 are separated by 4. +# it's not a continuous one where 5 and 7 are separated by 4. # Example 2: # Input: [2,2,2,2,2] # Output: 1 -# Explanation: The longest continuous increasing subsequence is [2], its length is 1. +# Explanation: The longest continuous increasing subsequence is [2], its length is 1. # Note: Length of the array will not exceed 10,000. class Solution(object): diff --git a/Python/longest-increasing-path-in-a-matrix.py b/Python/longest-increasing-path-in-a-matrix.py index f5685d3a7..c95688f2e 100644 --- a/Python/longest-increasing-path-in-a-matrix.py +++ b/Python/longest-increasing-path-in-a-matrix.py @@ -3,8 +3,8 @@ # 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 +# 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: @@ -40,7 +40,7 @@ def longestIncreasingPath(self, matrix): 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: @@ -56,5 +56,5 @@ def longestpath(matrix, i, j, max_lengths): for i in xrange(len(matrix)): for j in xrange(len(matrix[0])): res = max(res, longestpath(matrix, i, j, max_lengths)) - + return res diff --git a/Python/longest-increasing-subsequence.py b/Python/longest-increasing-subsequence.py index ac477873b..f176202be 100644 --- a/Python/longest-increasing-subsequence.py +++ b/Python/longest-increasing-subsequence.py @@ -1,7 +1,7 @@ # Time: O(nlogn) # Space: O(n) # -# Given an unsorted array of integers, +# Given an unsorted array of integers, # find the length of longest increasing subsequence. # # For example, diff --git a/Python/longest-palindromic-substring.py b/Python/longest-palindromic-substring.py index 2c0f238d9..2621a208d 100644 --- a/Python/longest-palindromic-substring.py +++ b/Python/longest-palindromic-substring.py @@ -24,7 +24,7 @@ def preProcess(s): return T T = preProcess(s) - P = [0] * len(T) + P = [0] * len(T) center, right = 0, 0 for i in xrange(1, len(T) - 1): i_mirror = 2 * center - i @@ -37,8 +37,8 @@ def preProcess(s): P[i] += 1 if i + P[i] > right: - center, right = i, i + P[i] - + center, right = i, i + P[i] + max_i = 0 for i in xrange(1, len(T) - 1): if P[i] > P[max_i]: @@ -46,6 +46,6 @@ def preProcess(s): start = (max_i - 1 - P[max_i]) / 2 return s[start : start + P[max_i]] - + if __name__ == "__main__": print Solution().longestPalindrome("abb") diff --git a/Python/longest-substring-with-at-most-k-distinct-characters.py b/Python/longest-substring-with-at-most-k-distinct-characters.py index a5f6d0c45..fd974b83c 100644 --- a/Python/longest-substring-with-at-most-k-distinct-characters.py +++ b/Python/longest-substring-with-at-most-k-distinct-characters.py @@ -13,12 +13,12 @@ def lengthOfLongestSubstringKDistinct(self, s, k): if visited[ord(char)] == 0: distinct_count += 1 visited[ord(char)] += 1 - + while distinct_count > k: visited[ord(s[start])] -= 1 if visited[ord(s[start])] == 0: distinct_count -= 1 start += 1 - + longest = max(longest, i - start + 1) return longest diff --git a/Python/longest-substring-with-at-most-two-distinct-characters.py b/Python/longest-substring-with-at-most-two-distinct-characters.py index 3a58b3024..0eb42603b 100644 --- a/Python/longest-substring-with-at-most-two-distinct-characters.py +++ b/Python/longest-substring-with-at-most-two-distinct-characters.py @@ -1,11 +1,11 @@ # Time: O(n) # Space: O(1) # -# Given a string, find the length of the longest substring T +# Given a string, find the length of the longest substring T # that contains at most 2 distinct characters. -# +# # For example, Given s = "eceba", -# +# # T is "ece" which its length is 3. # @@ -18,15 +18,15 @@ def lengthOfLongestSubstringTwoDistinct(self, s): if visited[ord(char)] == 0: distinct_count += 1 visited[ord(char)] += 1 - + while distinct_count > 2: visited[ord(s[start])] -= 1 if visited[ord(s[start])] == 0: distinct_count -= 1 start += 1 - + longest = max(longest, i - start + 1) return longest - + if __name__ == "__main__": print Solution().lengthOfLongestSubstringTwoDistinct("eceba") diff --git a/Python/longest-substring-without-repeating-characters.py b/Python/longest-substring-without-repeating-characters.py index c7f711c73..8208f643c 100644 --- a/Python/longest-substring-without-repeating-characters.py +++ b/Python/longest-substring-without-repeating-characters.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given a string, find the length of the longest substring without repeating characters. -# For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. +# For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. # For "bbbbb" the longest substring is "b", with the length of 1. # diff --git a/Python/longest-uncommon-subsequence-i.py b/Python/longest-uncommon-subsequence-i.py index 007cee665..9d64937f1 100644 --- a/Python/longest-uncommon-subsequence-i.py +++ b/Python/longest-uncommon-subsequence-i.py @@ -15,9 +15,9 @@ # Example 1: # Input: "aba", "cdc" # Output: 3 -# Explanation: The longest uncommon subsequence is "aba" (or "cdc"), -# because "aba" is a subsequence of "aba", -# but not a subsequence of any other strings in the group of two strings. +# Explanation: The longest uncommon subsequence is "aba" (or "cdc"), +# because "aba" is a subsequence of "aba", +# but not a subsequence of any other strings in the group of two strings. # Note: # # Both strings' lengths will not exceed 100. diff --git a/Python/longest-univalue-path.py b/Python/longest-univalue-path.py index 795f4d485..d7fd3b9b9 100644 --- a/Python/longest-univalue-path.py +++ b/Python/longest-univalue-path.py @@ -52,6 +52,6 @@ def dfs(node): right = (right+1) if node.right and node.right.val == node.val else 0 result[0] = max(result[0], left+right) return max(left, right) - + dfs(root) return result[0] diff --git a/Python/longest-valid-parentheses.py b/Python/longest-valid-parentheses.py index dd0376eb8..3c8888175 100644 --- a/Python/longest-valid-parentheses.py +++ b/Python/longest-valid-parentheses.py @@ -1,11 +1,11 @@ # Time: O(n) # Space: O(1) # -# Given a string containing just the characters '(' and ')', +# Given a string containing just the characters '(' and ')', # find the length of the longest valid (well-formed) parentheses substring. -# +# # For "(()", the longest valid parentheses substring is "()", which has length = 2. -# +# # Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4. # diff --git a/Python/longest-word-in-dictionary-through-deleting.py b/Python/longest-word-in-dictionary-through-deleting.py index 7437ca338..548d3797c 100644 --- a/Python/longest-word-in-dictionary-through-deleting.py +++ b/Python/longest-word-in-dictionary-through-deleting.py @@ -12,13 +12,13 @@ # Input: # s = "abpcplea", d = ["ale","apple","monkey","plea"] # -# Output: +# Output: # "apple" # Example 2: # Input: # s = "abpcplea", d = ["a","b","c"] # -# Output: +# Output: # "a" # Note: # All the strings in the input will only contain lower-case letters. diff --git a/Python/lru-cache.py b/Python/lru-cache.py index 14cc5333d..9913918fc 100644 --- a/Python/lru-cache.py +++ b/Python/lru-cache.py @@ -37,7 +37,7 @@ class LinkedList(object): def __init__(self): self.head = None self.tail = None - + def insert(self, node): node.next, node.prev = None, None # avoid dirty node if self.head is None: @@ -46,7 +46,7 @@ def insert(self, node): self.tail.next = node node.prev = self.tail self.tail = node - + def delete(self, node): if node.prev: node.prev.next = node.next @@ -65,12 +65,12 @@ def __init__(self, capacity): self.list = LinkedList() self.dict = {} self.capacity = capacity - + def _insert(self, key, val): node = ListNode(key, val) self.list.insert(node) self.dict[key] = node - + # @return an integer def get(self, key): @@ -80,7 +80,7 @@ def get(self, key): self._insert(key, val) return val return -1 - + # @param key, an integer # @param value, an integer @@ -92,8 +92,8 @@ def put(self, key, val): del self.dict[self.list.head.key] self.list.delete(self.list.head) self._insert(key, val) - - + + import collections class LRUCache2(object): def __init__(self, capacity): @@ -115,7 +115,7 @@ def put(self, key, value): self.cache.popitem(last=False) self.cache[key] = value - + if __name__ == "__main__": cache = LRUCache(3) cache.set(1, 1) @@ -124,4 +124,4 @@ def put(self, key, value): print cache.get(1) cache.set(4, 4) print cache.get(2) - + diff --git a/Python/majority-element-ii.py b/Python/majority-element-ii.py index 849bde6cb..40f02dee3 100644 --- a/Python/majority-element-ii.py +++ b/Python/majority-element-ii.py @@ -1,8 +1,8 @@ # Time: O(n) # Space: O(1) -# Given an integer array of size n, -# find all elements that appear more than [n/3] times. +# 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. import collections diff --git a/Python/majority-element.py b/Python/majority-element.py index f39f2c0d7..2f39c0403 100644 --- a/Python/majority-element.py +++ b/Python/majority-element.py @@ -3,7 +3,7 @@ # # Given an array of size n, find the majority element. # The majority element is the element that appears more than [n/2] times. -# +# # You may assume that the array is non-empty and the majority element always exist in the array. import collections @@ -15,7 +15,7 @@ def majorityElement(self, nums): :rtype: int """ idx, cnt = 0, 1 - + for i in xrange(1, len(nums)): if nums[idx] == nums[i]: cnt += 1 @@ -24,7 +24,7 @@ def majorityElement(self, nums): if cnt == 0: idx = i cnt = 1 - + return nums[idx] def majorityElement2(self, nums): diff --git a/Python/matchsticks-to-square.py b/Python/matchsticks-to-square.py index 9728cccff..18338e2ee 100644 --- a/Python/matchsticks-to-square.py +++ b/Python/matchsticks-to-square.py @@ -44,7 +44,7 @@ def makesquare(self, nums): for subset in xrange(fullset+1): subset_total_len = 0 - for i in xrange(len(nums)): + for i in xrange(len(nums)): if subset & (1 << i): subset_total_len += nums[i] @@ -56,5 +56,5 @@ def makesquare(self, nums): if valid_half_subsets[fullset ^ valid_half_subset]: return True used_subsets.append(subset) - + return False diff --git a/Python/max-chunks-to-make-sorted-ii.py b/Python/max-chunks-to-make-sorted-ii.py index 363d313f9..af0b3e7c7 100644 --- a/Python/max-chunks-to-make-sorted-ii.py +++ b/Python/max-chunks-to-make-sorted-ii.py @@ -39,7 +39,7 @@ def maxChunksToSorted(self, arr): """ def compare(i1, i2): return arr[i1]-arr[i2] if arr[i1] != arr[i2] else i1-i2 - + idxs = [i for i in xrange(len(arr))] result, max_i = 0, 0 for i, v in enumerate(sorted(idxs, cmp=compare)): diff --git a/Python/max-sum-of-sub-matrix-no-larger-than-k.py b/Python/max-sum-of-sub-matrix-no-larger-than-k.py index d21b3fe78..5d18781af 100644 --- a/Python/max-sum-of-sub-matrix-no-larger-than-k.py +++ b/Python/max-sum-of-sub-matrix-no-larger-than-k.py @@ -38,7 +38,7 @@ # Time: O(min(m, n)^2 * max(m, n)^2) # Space: O(max(m, n)) -from bisect import bisect_left, insort +from bisect import bisect_left, insort class Solution(object): def maxSumSubmatrix(self, matrix, k): @@ -59,7 +59,7 @@ def maxSumSubmatrix(self, matrix, k): for j in xrange(i, m): for l in xrange(n): sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j] - + # Find the max subarray no more than K. accu_sum_set, accu_sum = [0], 0 for sum in sums: @@ -86,7 +86,7 @@ def __init__(self, val): self.val = val self.left = None self.right = None - + def insert(self, val): # Time: O(h) = O(logn) ~ O(n) curr = self while curr: @@ -102,7 +102,7 @@ def insert(self, val): # Time: O(h) = O(logn) ~ O(n) else: curr.right = BST(val) return - + def lower_bound(self, val): # Time: O(h) = O(logn) ~ O(n) result, curr = None, self while curr: @@ -125,7 +125,7 @@ def lower_bound(self, val): # Time: O(h) = O(logn) ~ O(n) for j in xrange(i, m): for l in xrange(n): sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j] - + # Find the max subarray no more than K. accu_sum_set = BST(0) accu_sum = 0 diff --git a/Python/maximal-rectangle.py b/Python/maximal-rectangle.py index 85420c608..f4f7f374f 100644 --- a/Python/maximal-rectangle.py +++ b/Python/maximal-rectangle.py @@ -1,7 +1,7 @@ # Time: O(n^2) # Space: O(n) -# Given a 2D binary matrix filled with 0's and 1's, +# Given a 2D binary matrix filled with 0's and 1's, # find the largest rectangle containing all ones and return its area. # Ascending stack solution. @@ -49,7 +49,7 @@ def maximalRectangle(self, matrix): """ if not matrix: return 0 - + result = 0 m = len(matrix) n = len(matrix[0]) @@ -68,7 +68,7 @@ def maximalRectangle(self, matrix): H[j] = 0 R[j] = n left = j + 1 - + right = n for j in reversed(xrange(n)): if matrix[i][j] == '1': @@ -76,7 +76,7 @@ def maximalRectangle(self, matrix): result = max(result, H[j] * (R[j] - L[j])) else: right = j - + return result if __name__ == "__main__": diff --git a/Python/maximal-square.py b/Python/maximal-square.py index 2f95f9b99..bb9029526 100644 --- a/Python/maximal-square.py +++ b/Python/maximal-square.py @@ -1,7 +1,7 @@ # Time: O(n^2) # Space: O(n) # -# Given a 2D binary matrix filled with 0's and 1's, +# 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: @@ -24,12 +24,12 @@ def maximalSquare(self, matrix): 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 @@ -43,7 +43,7 @@ def maximalSquare(self, matrix): max_size = max(max_size, size[i % 2][j]) else: size[i % 2][j] = 0 - + return max_size * max_size @@ -60,12 +60,12 @@ def maximalSquare(self, matrix): 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 @@ -79,10 +79,10 @@ def maximalSquare(self, matrix): 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. @@ -92,7 +92,7 @@ class Solution3: 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]))] \ @@ -108,7 +108,7 @@ def maximalSquare(self, matrix): 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))] @@ -122,6 +122,6 @@ def maximalSquare(self, matrix): 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; - + diff --git a/Python/maximum-binary-tree.py b/Python/maximum-binary-tree.py index e32134c97..c95d5ff82 100644 --- a/Python/maximum-binary-tree.py +++ b/Python/maximum-binary-tree.py @@ -16,8 +16,8 @@ # 6 # / \ # 3 5 -# \ / -# 2 0 +# \ / +# 2 0 # \ # 1 # Note: diff --git a/Python/maximum-depth-of-binary-tree.py b/Python/maximum-depth-of-binary-tree.py index 016f720a6..2889d824a 100644 --- a/Python/maximum-depth-of-binary-tree.py +++ b/Python/maximum-depth-of-binary-tree.py @@ -2,7 +2,7 @@ # Space: O(h), h is height of binary tree # # Given a binary tree, find its maximum depth. -# +# # The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. # @@ -19,7 +19,7 @@ class Solution: def maxDepth(self, root): if root is None: return 0 - else: + else: return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 if __name__ == "__main__": diff --git a/Python/maximum-gap.py b/Python/maximum-gap.py index 2003ab711..06d771637 100644 --- a/Python/maximum-gap.py +++ b/Python/maximum-gap.py @@ -1,16 +1,16 @@ # Time: O(n) # Space: O(n) -# Given an unsorted array, find the maximum difference between -# +# Given an unsorted array, find the maximum difference between +# # the successive elements in its sorted form. -# +# # Try to solve it in linear time/space. -# +# # Return 0 if the array contains less than 2 elements. -# +# # You may assume all elements in the array are non-negative integers -# +# # and fit in the 32-bit signed integer range. # bucket sort @@ -24,7 +24,7 @@ def maximumGap(self, nums): """ if len(nums) < 2: return 0 - + # Init bucket. max_val, min_val = max(nums), min(nums) gap = max(1, (max_val - min_val) / (len(nums) - 1)) @@ -36,11 +36,11 @@ def maximumGap(self, nums): for n in nums: # min_val / max_val is in the first / last bucket. if n in (max_val, min_val): - continue + continue i = (n - min_val) / gap bucket[i]['min'] = min(bucket[i]['min'], n) bucket[i]['max'] = max(bucket[i]['max'], n) - + # 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): @@ -51,8 +51,8 @@ def maximumGap(self, nums): 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) - + max_gap = max(max_gap, max_val - pre_bucket_max) + return max_gap @@ -67,11 +67,11 @@ def maximumGap(self, nums): if len(nums) < 2: return 0 - + nums.sort() pre = nums[0] max_gap = float("-inf") - + for i in nums: max_gap = max(max_gap, i - pre) pre = i diff --git a/Python/maximum-product-of-word-lengths.py b/Python/maximum-product-of-word-lengths.py index ddc03bd4b..66a870888 100644 --- a/Python/maximum-product-of-word-lengths.py +++ b/Python/maximum-product-of-word-lengths.py @@ -2,7 +2,7 @@ # Space: O(n) # Given a string array words, find the maximum value of -# length(word[i]) * length(word[j]) where the two words +# 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. diff --git a/Python/maximum-product-subarray.py b/Python/maximum-product-subarray.py index 50d08388a..cf502bd5f 100644 --- a/Python/maximum-product-subarray.py +++ b/Python/maximum-product-subarray.py @@ -2,7 +2,7 @@ # Space: O(1) # # Find the contiguous subarray within an array (containing at least one number) which has the largest product. -# +# # For example, given the array [2,3,-2,4], # the contiguous subarray [2,3] has the largest product = 6. diff --git a/Python/maximum-subarray.py b/Python/maximum-subarray.py index 35fcd74ae..07a0fcafe 100644 --- a/Python/maximum-subarray.py +++ b/Python/maximum-subarray.py @@ -2,12 +2,12 @@ # Space: O(1) # # Find the contiguous subarray within an array (containing at least one number) which has the largest sum. -# +# # For example, given the array [-2,1,-3,4,-1,2,1,-5,4], # the contiguous subarray [4,-1,2,1] has the largest sum = 6. -# +# # click to show more practice. -# +# # More practice: # If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. # diff --git a/Python/maximum-sum-of-3-non-overlapping-subarrays.py b/Python/maximum-sum-of-3-non-overlapping-subarrays.py index 7defc2939..30b4f8a1d 100644 --- a/Python/maximum-sum-of-3-non-overlapping-subarrays.py +++ b/Python/maximum-sum-of-3-non-overlapping-subarrays.py @@ -11,7 +11,7 @@ # Example: # Input: [1,2,1,2,6,7,5,1], 2 # Output: [0, 3, 5] - # + # # Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5]. # We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger. # @@ -31,7 +31,7 @@ def maxSumOfThreeSubarrays(self, nums, k): accu = [0] for num in nums: accu.append(accu[-1]+num) - + left_pos = [0] * n total = accu[k]-accu[0] for i in xrange(k, n): @@ -40,7 +40,7 @@ def maxSumOfThreeSubarrays(self, nums, k): total = accu[i+1]-accu[i+1-k] else: left_pos[i] = left_pos[i-1] - + right_pos = [n-k] * n total = accu[n]-accu[n-k] for i in reversed(xrange(n-k)): @@ -49,7 +49,7 @@ def maxSumOfThreeSubarrays(self, nums, k): total = accu[i+k]-accu[i] else: right_pos[i] = right_pos[i+1] - + result, max_sum = [], 0 for i in xrange(k, n-2*k+1): left, right = left_pos[i-1], right_pos[i+k] diff --git a/Python/maximum-width-of-binary-tree.py b/Python/maximum-width-of-binary-tree.py index 4bb5125c0..b0362eee8 100644 --- a/Python/maximum-width-of-binary-tree.py +++ b/Python/maximum-width-of-binary-tree.py @@ -10,53 +10,53 @@ # where the null nodes between the end-nodes are also counted into the length calculation. # # Example 1: -# Input: +# Input: # # 1 # / \ # 3 2 -# / \ \ -# 5 3 9 +# / \ \ +# 5 3 9 # # Output: 4 # Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9). # Example 2: -# Input: +# Input: # # 1 -# / -# 3 -# / \ -# 5 3 +# / +# 3 +# / \ +# 5 3 # # Output: 2 # Explanation: The maximum width existing in the third level with the length 2 (5,3). # Example 3: -# Input: +# Input: # # 1 # / \ -# 3 2 -# / -# 5 +# 3 2 +# / +# 5 # # Output: 2 # Explanation: The maximum width existing in the second level with the length 2 (3,2). # Example 4: -# Input: +# Input: # # 1 # / \ # 3 2 -# / \ -# 5 9 +# / \ +# 5 9 # / \ # 6 7 # Output: 8 # Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7). # # Note: Answer will in the range of 32-bit signed integer. -# +# # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): diff --git a/Python/maximum-xor-of-two-numbers-in-an-array.py b/Python/maximum-xor-of-two-numbers-in-an-array.py index 20f541afe..6a3156b19 100644 --- a/Python/maximum-xor-of-two-numbers-in-an-array.py +++ b/Python/maximum-xor-of-two-numbers-in-an-array.py @@ -22,7 +22,7 @@ def findMaximumXOR(self, nums): :rtype: int """ result = 0 - + for i in reversed(xrange(32)): result <<= 1 prefixes = set() diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 14ce80108..2450b65bf 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -1,6 +1,6 @@ # Time: O(log(min(m, n))) # Space: O(1) - + # There are two sorted arrays nums1 and nums2 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)). @@ -13,7 +13,7 @@ def findMedianSortedArrays(self, nums1, nums2): :rtype: float """ len1, len2 = len(nums1), len(nums2) - if (len1 + len2) % 2 == 1: + if (len1 + len2) % 2 == 1: return self.getKth(nums1, nums2, (len1 + len2)/2 + 1) else: return (self.getKth(nums1, nums2, (len1 + len2)/2) + \ @@ -24,7 +24,7 @@ def getKth(self, A, B, k): if m > n: return self.getKth(B, A, k) - left, right = 0, m + left, right = 0, m while left < right: mid = left + (right - left) / 2 if 0 <= k - 1 - mid < n and A[mid] >= B[k - 1 - mid]: @@ -49,7 +49,7 @@ def findMedianSortedArrays(self, nums1, nums2): :rtype: float """ len1, len2 = len(nums1), len(nums2) - if (len1 + len2) % 2 == 1: + if (len1 + len2) % 2 == 1: return self.getKth([nums1, nums2], (len1 + len2)/2 + 1) else: return (self.getKth([nums1, nums2], (len1 + len2)/2) + \ @@ -85,4 +85,4 @@ def match(arrays, num, target): if __name__ == "__main__": print Solution().findMedianSortedArrays([1, 3, 5, 7], [2, 4, 6]) print Solution().findMedianSortedArrays([1, 3, 5], [2, 4, 6]) - + diff --git a/Python/meeting-rooms.py b/Python/meeting-rooms.py index f8ef52f66..de7d864c6 100644 --- a/Python/meeting-rooms.py +++ b/Python/meeting-rooms.py @@ -12,7 +12,7 @@ class Solution: # @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 diff --git a/Python/merge-intervals.py b/Python/merge-intervals.py index 953798275..1e279e4d6 100644 --- a/Python/merge-intervals.py +++ b/Python/merge-intervals.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given a collection of intervals, merge all overlapping intervals. -# +# # For example, # Given [1,3],[2,6],[8,10],[15,18], # return [1,6],[8,10],[15,18]. @@ -13,7 +13,7 @@ class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e - + def __repr__(self): return "[{}, {}]".format(self.start, self.end) @@ -30,7 +30,7 @@ def merge(self, intervals): result = [intervals[0]] for i in xrange(1, len(intervals)): prev, current = result[-1], intervals[i] - if current.start <= prev.end: + if current.start <= prev.end: prev.end = max(prev.end, current.end) else: result.append(current) diff --git a/Python/merge-k-sorted-lists.py b/Python/merge-k-sorted-lists.py index edc3c9d4a..0acffe1af 100644 --- a/Python/merge-k-sorted-lists.py +++ b/Python/merge-k-sorted-lists.py @@ -67,7 +67,7 @@ def mergeTwoLists(l1, l2): curr = curr.next curr.next = l1 or l2 return dummy.next - + def mergeKListsHelper(lists, begin, end): if begin > end: return None @@ -75,7 +75,7 @@ def mergeKListsHelper(lists, begin, end): return lists[begin] return mergeTwoLists(mergeKListsHelper(lists, begin, (begin + end) / 2), \ mergeKListsHelper(lists, (begin + end) / 2 + 1, end)) - + return mergeKListsHelper(lists, 0, len(lists) - 1) @@ -89,19 +89,19 @@ class Solution3: def mergeKLists(self, lists): dummy = ListNode(0) current = dummy - + heap = [] for sorted_list in lists: if sorted_list: heapq.heappush(heap, (sorted_list.val, sorted_list)) - + while heap: smallest = heapq.heappop(heap)[1] current.next = smallest current = current.next if smallest.next: heapq.heappush(heap, (smallest.next.val, smallest.next)) - + return dummy.next @@ -110,5 +110,5 @@ def mergeKLists(self, lists): list1.next = ListNode(3) list2 = ListNode(2) list2.next = ListNode(4) - + print Solution().mergeKLists([list1, list2]) diff --git a/Python/merge-sorted-array.py b/Python/merge-sorted-array.py index 5b6a275fc..b8ace9bb5 100644 --- a/Python/merge-sorted-array.py +++ b/Python/merge-sorted-array.py @@ -2,9 +2,9 @@ # Space: O(1) # # Given two sorted integer arrays A and B, merge B into A as one sorted array. -# +# # Note: -# You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. +# You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. # The number of elements initialized in A and B are m and n respectively. # @@ -16,7 +16,7 @@ class Solution: # @return nothing def merge(self, A, m, B, n): last, i, j = m + n - 1, m - 1, n - 1 - + while i >= 0 and j >= 0: if A[i] > B[j]: A[last] = A[i] @@ -24,7 +24,7 @@ def merge(self, A, m, B, n): else: A[last] = B[j] last, j = last - 1, j - 1 - + while j >= 0: A[last] = B[j] last, j = last - 1, j - 1 @@ -34,7 +34,7 @@ def merge(self, A, m, B, n): B = [2, 4, 6, 7] Solution().merge(A, 3, B, 4) print A - + # Time: O(n) # Space: O(n) diff --git a/Python/merge-two-binary-trees.py b/Python/merge-two-binary-trees.py index 3fc1c04ef..89341b1e3 100644 --- a/Python/merge-two-binary-trees.py +++ b/Python/merge-two-binary-trees.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(h) -# Given two binary trees and imagine that +# Given two binary trees and imagine that # when you put one of them to cover the other, # some nodes of the two trees are overlapped # while the others are not. @@ -12,21 +12,21 @@ # Otherwise, the NOT null node will be used as the node of new tree. # # Example 1: -# Input: -# Tree 1 Tree 2 -# 1 2 -# / \ / \ -# 3 2 1 3 -# / \ \ -# 5 4 7 -# Output: +# Input: +# Tree 1 Tree 2 +# 1 2 +# / \ / \ +# 3 2 1 3 +# / \ \ +# 5 4 7 +# Output: # Merged tree: # 3 # / \ # 4 5 -# / \ \ +# / \ \ # 5 4 7 -# +# # Note: The merging process must start from the root nodes of both trees. # Definition for a binary tree node. diff --git a/Python/merge-two-sorted-lists.py b/Python/merge-two-sorted-lists.py index 0d965d2b9..c94df5a8b 100644 --- a/Python/merge-two-sorted-lists.py +++ b/Python/merge-two-sorted-lists.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(1) # -# Merge two sorted linked lists and return it as a new list. +# Merge two sorted linked lists and return it as a new list. # The new list should be made by splicing together the nodes of the first two lists. # @@ -42,5 +42,5 @@ def mergeTwoLists(self, l1, l2): l2 = ListNode (2) l2.next = ListNode(3) print Solution().mergeTwoLists(l1, l2) - - + + diff --git a/Python/min-stack.py b/Python/min-stack.py index 12df16163..ff31748a8 100644 --- a/Python/min-stack.py +++ b/Python/min-stack.py @@ -2,7 +2,7 @@ # Space: O(1) # # Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. -# +# # push(x) -- Push element x onto stack. # pop() -- Removes the element on top of the stack. # top() -- Get the top element. @@ -13,7 +13,7 @@ class MinStack: def __init__(self): self.min = None self.stack = [] - + # @param x, an integer # @return an integer def push(self, x): @@ -38,7 +38,7 @@ def top(self): return x + self.min else: return self.min - + # @return an integer def getMin(self): return self.min @@ -67,11 +67,11 @@ def pop(self): self.minStack[-1][1] -= 1 if self.minStack[-1][1] == 0: self.minStack.pop() - + # @return an integer def top(self): return self.stack[-1] - + # @return an integer def getMin(self): return self.minStack[-1][0] @@ -80,4 +80,4 @@ def getMin(self): stack = MinStack() stack.push(-1) print [stack.top(), stack.getMin()] - + diff --git a/Python/minimize-max-distance-to-gas-station.py b/Python/minimize-max-distance-to-gas-station.py index 4b56a68e8..a8676a4a4 100644 --- a/Python/minimize-max-distance-to-gas-station.py +++ b/Python/minimize-max-distance-to-gas-station.py @@ -13,7 +13,7 @@ # # Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9 # Output: 0.500000 -# +# # Note: # - stations.length will be an integer in range [10, 2000]. # - stations[i] will be an integer in range [0, 10^8]. diff --git a/Python/minimum-depth-of-binary-tree.py b/Python/minimum-depth-of-binary-tree.py index 2833dcaab..709093e51 100644 --- a/Python/minimum-depth-of-binary-tree.py +++ b/Python/minimum-depth-of-binary-tree.py @@ -2,7 +2,7 @@ # Space: O(h), h is height of binary tree # # Given a binary tree, find its minimum depth. -# +# # The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. # @@ -19,7 +19,7 @@ class Solution: def minDepth(self, root): if root is None: return 0 - + if root.left and root.right: return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 else: diff --git a/Python/minimum-distance-between-bst-nodes.py b/Python/minimum-distance-between-bst-nodes.py index ca26974c7..dfb2ad825 100644 --- a/Python/minimum-distance-between-bst-nodes.py +++ b/Python/minimum-distance-between-bst-nodes.py @@ -16,8 +16,8 @@ # 4 # / \ # 2 6 -# / \ -# 1 3 +# / \ +# 1 3 # # while the minimum difference in this tree is 1, # it occurs between node 1 and node 2, also between node 3 and node 2. @@ -51,4 +51,4 @@ def dfs(node): self.result = float('inf') dfs(root) return self.result - + diff --git a/Python/minimum-factorization.py b/Python/minimum-factorization.py index 52d72293a..756c20e81 100644 --- a/Python/minimum-factorization.py +++ b/Python/minimum-factorization.py @@ -16,4 +16,4 @@ def smallestFactorization(self, a): result = mul*i + result mul *= 10 return result if a == 1 and result < 2**31 else 0 - + diff --git a/Python/minimum-genetic-mutation.py b/Python/minimum-genetic-mutation.py index 900510bb7..bd89371fe 100644 --- a/Python/minimum-genetic-mutation.py +++ b/Python/minimum-genetic-mutation.py @@ -1,26 +1,26 @@ # Time: O(n * b), n is the length of gene string, b is size of bank # Space: O(b) -# A gene string can be represented by an 8-character long string, -# with choices from "A","C","G","T". -# Suppose we need to investigate about a mutation (mutation from "start" to "end"), -# where ONE mutation is defined as ONE single character changed in the gene string. -# For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation. +# A gene string can be represented by an 8-character long string, +# with choices from "A","C","G","T". +# Suppose we need to investigate about a mutation (mutation from "start" to "end"), +# where ONE mutation is defined as ONE single character changed in the gene string. +# For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation. # Also, there is a given gene "bank", which records all the valid gene mutations. -# A gene must be in the bank to make it a valid gene string. +# A gene must be in the bank to make it a valid gene string. # # Now, given 3 things - start, end, bank, # your task is to determine what is the minimum number of mutations needed to -# mutate from "start" to "end". If there is no such a mutation, return -1. +# mutate from "start" to "end". If there is no such a mutation, return -1. # # NOTE: 1. Starting point is assumed to be valid, so it might not be included in the bank. # 2. If multiple mutations are needed, all mutations during in the sequence must be valid. # -# For example, -# -# bank: "AACCGGTA" -# start: "AACCGGTT" -# end: "AACCGGTA" +# For example, +# +# bank: "AACCGGTA" +# start: "AACCGGTT" +# end: "AACCGGTA" # return: 1 # # bank: "AACCGGTA", "AACCGCTA", "AAACGGTA" diff --git a/Python/minimum-moves-to-equal-array-elements-ii.py b/Python/minimum-moves-to-equal-array-elements-ii.py index ee447cd6f..49207b3bd 100644 --- a/Python/minimum-moves-to-equal-array-elements-ii.py +++ b/Python/minimum-moves-to-equal-array-elements-ii.py @@ -19,7 +19,7 @@ def PartitionAroundPivot(left, right, pivot_idx, nums): 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 diff --git a/Python/minimum-path-sum.py b/Python/minimum-path-sum.py index f6c4edfd0..af07387ca 100644 --- a/Python/minimum-path-sum.py +++ b/Python/minimum-path-sum.py @@ -1,9 +1,9 @@ # Time: O(m * n) # Space: O(m + n) # -# Given a m x n grid filled with non-negative numbers, +# Given a m x n grid filled with non-negative numbers, # find a path from top left to bottom right which minimizes the sum of all numbers along its path. -# +# # Note: You can only move either down or right at any point in time. # @@ -19,9 +19,9 @@ def minPathSum(self, grid): sum[0] += grid[i][0] for j in xrange(1, len(grid[0])): sum[j] = min(sum[j - 1], sum[j]) + grid[i][j] - + return sum[-1] - + if __name__ == "__main__": print Solution().minPathSum([[0,1] ,[1,0]]) diff --git a/Python/minimum-size-subarray-sum.py b/Python/minimum-size-subarray-sum.py index 24d56ced0..e9ba17541 100644 --- a/Python/minimum-size-subarray-sum.py +++ b/Python/minimum-size-subarray-sum.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(1) # -# Given an array of n positive integers and a positive integer s, +# 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, @@ -49,7 +49,7 @@ def minSubArrayLen(self, s, nums): min_size = min(min_size, end - i + 1) return min_size if min_size != float("inf") else 0 - + def binarySearch(self, compare, A, start, end, target): while start < end: mid = start + (end - start) / 2 diff --git a/Python/minimum-swaps-to-make-sequences-increasing.py b/Python/minimum-swaps-to-make-sequences-increasing.py index d3806d0d9..4ba4acc85 100644 --- a/Python/minimum-swaps-to-make-sequences-increasing.py +++ b/Python/minimum-swaps-to-make-sequences-increasing.py @@ -15,7 +15,7 @@ # Example: # Input: A = [1,3,5,4], B = [1,2,3,7] # Output: 1 -# Explanation: +# Explanation: # Swap A[3] and B[3]. Then the sequences are: # A = [1, 3, 5, 7] and B = [1, 2, 3, 4] # which are both strictly increasing. diff --git a/Python/minimum-window-subsequence.py b/Python/minimum-window-subsequence.py index 647dcea4c..3fb65630c 100644 --- a/Python/minimum-window-subsequence.py +++ b/Python/minimum-window-subsequence.py @@ -12,7 +12,7 @@ def minWindow(self, S, T): for j, c in enumerate(S): if c == T[0]: dp[0][j] = j - + for i in xrange(1, len(T)): prev = None dp[i%2] = [None] * len(S) diff --git a/Python/minimum-window-substring.py b/Python/minimum-window-substring.py index d006f4f1e..d70f8c212 100644 --- a/Python/minimum-window-substring.py +++ b/Python/minimum-window-substring.py @@ -3,16 +3,16 @@ # 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). -# +# # For example, # S = "ADOBECODEBANC" # T = "ABC" # Minimum window is "BANC". -# +# # Note: # If there is no such window in S that covers all characters in T, # return the emtpy string "". -# +# # If there are multiple such windows, you are guaranteed that # there will always be only one unique minimum window in S. @@ -25,32 +25,32 @@ def minWindow(self, s, t): """ current_count = [0 for i in xrange(52)] expected_count = [0 for i in xrange(52)] - + for char in t: expected_count[ord(char) - ord('a')] += 1 - + i, count, start, min_width, min_start = 0, 0, 0, float("inf"), 0 while i < len(s): current_count[ord(s[i]) - ord('a')] += 1 if current_count[ord(s[i]) - ord('a')] <= expected_count[ord(s[i]) - ord('a')]: count += 1 - + if count == len(t): while expected_count[ord(s[start]) - ord('a')] == 0 or \ current_count[ord(s[start]) - ord('a')] > expected_count[ord(s[start]) - ord('a')]: current_count[ord(s[start]) - ord('a')] -= 1 start += 1 - + if min_width > i - start + 1: min_width = i - start + 1 min_start = start i += 1 - + if min_width == float("inf"): return "" - + return s[min_start:min_start + min_width] if __name__ == "__main__": - print Solution().minWindow("ADOBECODEBANC", "ABC") + print Solution().minWindow("ADOBECODEBANC", "ABC") diff --git a/Python/missing-ranges.py b/Python/missing-ranges.py index e43b6104c..16f3a36a5 100644 --- a/Python/missing-ranges.py +++ b/Python/missing-ranges.py @@ -3,8 +3,8 @@ # # Given a sorted integer array where the range of elements are [lower, upper] inclusive, # return its missing ranges. -# -# For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, +# +# For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, # return ["2", "4->49", "51->74", "76->99"]. # @@ -23,7 +23,7 @@ def getRange(lower, upper): return "{}->{}".format(lower, upper) ranges = [] pre = lower - 1 - + for i in xrange(len(nums) + 1): if i == len(nums): cur = upper + 1 @@ -31,9 +31,9 @@ def getRange(lower, upper): cur = nums[i] if cur - pre >= 2: ranges.append(getRange(pre + 1, cur - 1)) - + pre = cur - + return ranges diff --git a/Python/monotone-increasing-digits.py b/Python/monotone-increasing-digits.py index 111fb299c..b7b1e508f 100644 --- a/Python/monotone-increasing-digits.py +++ b/Python/monotone-increasing-digits.py @@ -14,11 +14,11 @@ # Example 2: # Input: N = 1234 # Output: 1234 -# +# # Example 3: # Input: N = 332 # Output: 299 -# +# # Note: N is an integer in the range [0, 10^9]. class Solution(object): diff --git a/Python/move-zeroes.py b/Python/move-zeroes.py index fb121754c..410eb8ffe 100644 --- a/Python/move-zeroes.py +++ b/Python/move-zeroes.py @@ -2,10 +2,10 @@ # 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 +# 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 +# For example, given nums = [0, 1, 0, 3, 12], after # calling your function, nums should be [1, 3, 12, 0, 0]. # # Note: @@ -44,9 +44,9 @@ def moveZeroes(self, nums): if nums[i]: nums[pos] = nums[i] pos += 1 - + for i in xrange(pos, len(nums)): - nums[i] = 0 + nums[i] = 0 if __name__ == '__main__': diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py index 6df6c3f12..cfb6d12d8 100644 --- a/Python/multiply-strings.py +++ b/Python/multiply-strings.py @@ -2,7 +2,7 @@ # Space: O(m + n) # # Given two numbers represented as strings, return multiplication of the numbers as a string. -# +# # Note: The numbers can be arbitrarily large and are non-negative. # diff --git a/Python/my-calendar-i.py b/Python/my-calendar-i.py index 8814fc510..050d01f9b 100644 --- a/Python/my-calendar-i.py +++ b/Python/my-calendar-i.py @@ -21,7 +21,7 @@ # MyCalendar.book(10, 20); // returns true # MyCalendar.book(15, 25); // returns false # MyCalendar.book(20, 30); // returns true -# Explanation: +# Explanation: # The first event can be booked. The second can't because time 15 is already booked by another event. # The third event can be booked, as the first event takes every time less than 20, but not including 20. # @@ -87,7 +87,7 @@ def book(self, start, end): if start < j and end > i: return False self.__calendar.append((start, end)) - return True + return True # Your MyCalendar object will be instantiated and called as such: diff --git a/Python/my-calendar-ii.py b/Python/my-calendar-ii.py index 0dc4f14e6..104ccf4b5 100644 --- a/Python/my-calendar-ii.py +++ b/Python/my-calendar-ii.py @@ -25,7 +25,7 @@ # MyCalendar.book(5, 10); // returns true # MyCalendar.book(25, 55); // returns true # -# Explanation: +# Explanation: # The first two events can be booked. The third event can be double booked. # The fourth event (5, 15) can't be booked, because it would result in a triple booking. # The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked. @@ -35,7 +35,7 @@ # Note: # - The number of calls to MyCalendar.book per test case will be at most 1000. # - In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9]. - + class MyCalendarTwo(object): def __init__(self): diff --git a/Python/n-queens-ii.py b/Python/n-queens-ii.py index 56e4c8f22..ee48742e4 100644 --- a/Python/n-queens-ii.py +++ b/Python/n-queens-ii.py @@ -2,7 +2,7 @@ # Space: O(n) # # Follow up for N-Queens problem. -# +# # Now, instead outputting board configurations, return the total number of distinct solutions. # @@ -14,7 +14,7 @@ def totalNQueens(self, n): self.main_diag = [False] * (2 * n) self.anti_diag = [False] * (2 * n) return self.totalNQueensRecu([], 0, n) - + def totalNQueensRecu(self, solution, row, n): if row == n: return 1 @@ -31,7 +31,7 @@ class Solution2: # @return an integer def totalNQueens(self, n): return self.totalNQueensRecu([], 0, n) - + def totalNQueensRecu(self, solution, row, n): if row == n: return 1 diff --git a/Python/n-queens.py b/Python/n-queens.py index 9ca999b96..6140a2e53 100644 --- a/Python/n-queens.py +++ b/Python/n-queens.py @@ -1,23 +1,23 @@ # Time: O(n!) # Space: O(n) -# The n-queens puzzle is the problem of placing n queens on +# The n-queens puzzle is the problem of placing n queens on # an nxn chess board such that no two queens attack each other. -# +# # Given an integer n, return all distinct solutions to the n-queens puzzle. -# -# Each solution contains a distinct board configuration of the n-queens' placement, +# +# Each solution contains a distinct board configuration of the n-queens' placement, # where 'Q' and '.' both indicate a queen and an empty space respectively. -# +# # For example, # There exist two distinct solutions to the 4-queens puzzle: -# +# # [ # [".Q..", // Solution 1 # "...Q", # "Q...", # "..Q."], -# +# # ["..Q.", // Solution 2 # "Q...", # "...Q", @@ -43,22 +43,22 @@ def dfs(curr, cols, main_diag, anti_diag, result): dfs(curr, cols, main_diag, anti_diag, result) curr.pop() cols[i] = main_diag[row+i] = anti_diag[row-i+n] = False - + result = [] cols, main_diag, anti_diag = [False]*n, [False]*(2*n), [False]*(2*n) dfs([], cols, main_diag, anti_diag, result) return result - + # For any point (x,y), if we want the new point (p,q) don't share the same row, column, or diagonal. -# then there must have ```p+q != x+y``` and ```p-q!= x-y``` -# the former focus on eliminate 'left bottom right top' diagonal; +# then there must have ```p+q != x+y``` and ```p-q!= x-y``` +# the former focus on eliminate 'left bottom right top' diagonal; # the latter focus on eliminate 'left top right bottom' diagonal # - col_per_row: the list of column index per row # - cur_row:current row we are seraching for valid column # - xy_diff:the list of x-y -# - xy_sum:the list of x+y +# - xy_sum:the list of x+y class Solution2(object): def solveNQueens(self, n): """ @@ -75,7 +75,7 @@ def dfs(col_per_row, xy_diff, xy_sum): ress = [] dfs([], [], []) return [['.'*i + 'Q' + '.'*(n-i-1) for i in res] for res in ress] - - + + if __name__ == "__main__": print Solution().solveNQueens(8) diff --git a/Python/nested-list-weight-sum-ii.py b/Python/nested-list-weight-sum-ii.py index 0594d091c..8eb003d4f 100644 --- a/Python/nested-list-weight-sum-ii.py +++ b/Python/nested-list-weight-sum-ii.py @@ -40,7 +40,7 @@ def depthSumInverseHelper(list, depth, result): else: for l in list.getList(): depthSumInverseHelper(l, depth + 1, result) - + result = [] for list in nestedList: depthSumInverseHelper(list, 0, result) diff --git a/Python/next-greater-element-ii.py b/Python/next-greater-element-ii.py index 03ee1c106..6a75d5e1f 100644 --- a/Python/next-greater-element-ii.py +++ b/Python/next-greater-element-ii.py @@ -10,8 +10,8 @@ # Example 1: # Input: [1,2,1] # Output: [2,-1,2] -# Explanation: The first 1's next greater number is 2; -# The number 2 can't find next greater number; +# Explanation: The first 1's next greater number is 2; +# The number 2 can't find next greater number; # The second 1's next greater number needs to search circularly, which is also 2. # Note: The length of given array won't exceed 10000. diff --git a/Python/next-permutation.py b/Python/next-permutation.py index 48056e9c6..def9a572d 100644 --- a/Python/next-permutation.py +++ b/Python/next-permutation.py @@ -2,11 +2,11 @@ # Space: O(1) # # Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. -# +# # If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). -# +# # The replacement must be in-place, do not allocate extra memory. -# +# # Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. # 1,2,3 -> 1,3,2 # 3,2,1 -> 1,2,3 @@ -21,15 +21,15 @@ def nextPermutation(self, num): for i in xrange(len(num) - 1): if num[i] < num[i + 1]: k = i - + if k == -1: num.reverse() return - + for i in xrange(k + 1, len(num)): if num[i] > num[k]: l = i - + num[k], num[l] = num[l], num[k] num[k + 1:] = num[:k:-1] diff --git a/Python/nim-game.py b/Python/nim-game.py index f1eadb01a..e14d788df 100644 --- a/Python/nim-game.py +++ b/Python/nim-game.py @@ -2,13 +2,13 @@ # 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 +# 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. 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 diff --git a/Python/non-decreasing-array.py b/Python/non-decreasing-array.py index e5e51c42f..d556d531d 100644 --- a/Python/non-decreasing-array.py +++ b/Python/non-decreasing-array.py @@ -9,9 +9,9 @@ # Example 1: # Input: [4,2,3] # Output: True -# Explanation: You could modify the first +# Explanation: You could modify the first # 4 -# to +# to # 1 # to get a non-decreasing array. # Example 2: @@ -39,4 +39,4 @@ def checkPossibility(self, nums): else: prev = nums[i] return True - + diff --git a/Python/non-negative-integers-without-consecutive-ones.py b/Python/non-negative-integers-without-consecutive-ones.py index 37d59f055..5847fe8ba 100644 --- a/Python/non-negative-integers-without-consecutive-ones.py +++ b/Python/non-negative-integers-without-consecutive-ones.py @@ -7,7 +7,7 @@ # Example 1: # Input: 5 # Output: 5 -# Explanation: +# Explanation: # Here are the non-negative integers <= 5 with their corresponding binary representations: # 0 : 0 # 1 : 1 @@ -15,7 +15,7 @@ # 3 : 11 # 4 : 100 # 5 : 101 -# Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. +# Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. # Note: 1 <= n <= 10^9 class Solution(object): diff --git a/Python/number-of-1-bits.py b/Python/number-of-1-bits.py index 1d3f12f2a..065c5db7c 100644 --- a/Python/number-of-1-bits.py +++ b/Python/number-of-1-bits.py @@ -1,10 +1,10 @@ # Time: O(logn) = O(32) # Space: O(1) # -# Write a function that takes an unsigned integer +# 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, +# +# For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, # so the function should return 3. # class Solution: diff --git a/Python/number-of-boomerangs.py b/Python/number-of-boomerangs.py index e31756e0f..84ff01205 100644 --- a/Python/number-of-boomerangs.py +++ b/Python/number-of-boomerangs.py @@ -1,7 +1,7 @@ # Time: O(n^2) # Space: O(n) -# Given n points in the plane that are all pairwise distinct, +# Given n points in the plane that are all pairwise distinct, # a "boomerang" is a tuple of points (i, j, k) such that the distance # between i and j equals the distance between i and k (the order of the tuple matters). # @@ -35,11 +35,11 @@ def numberOfBoomerangs(self, points): continue dx, dy = points[i][0] - points[j][0], points[i][1] - points[j][1] group[dx**2 + dy**2] += 1 - + for _, v in group.iteritems(): if v > 1: result += v * (v-1) - + return result def numberOfBoomerangs2(self, points): diff --git a/Python/number-of-corner-rectangles.py b/Python/number-of-corner-rectangles.py index 6dbe75bee..5988e1885 100644 --- a/Python/number-of-corner-rectangles.py +++ b/Python/number-of-corner-rectangles.py @@ -7,7 +7,7 @@ # Note that only the corners need to have the value 1. Also, all four 1s used must be distinct. # # Example 1: -# Input: grid = +# Input: grid = # [[1, 0, 0, 1, 0], # [0, 0, 1, 0, 1], # [0, 0, 0, 1, 0], @@ -16,7 +16,7 @@ # Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4]. # # Example 2: -# Input: grid = +# Input: grid = # [[1, 1, 1], # [1, 1, 1], # [1, 1, 1]] @@ -24,7 +24,7 @@ # Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle. # # Example 3: -# Input: grid = +# Input: grid = # [[1, 1, 1, 1]] # Output: 0 # Explanation: Rectangles must have four distinct corners. diff --git a/Python/number-of-distinct-islands-ii.py b/Python/number-of-distinct-islands-ii.py index 4b1197c5c..49de00acc 100644 --- a/Python/number-of-distinct-islands-ii.py +++ b/Python/number-of-distinct-islands-ii.py @@ -34,7 +34,7 @@ def normalize(island): p[0] -= origin[0] p[1] -= origin[1] return min(shapes) - + islands = set() for i in xrange(len(grid)): for j in xrange(len(grid[0])): diff --git a/Python/number-of-islands-ii.py b/Python/number-of-islands-ii.py index 3c36a265e..c76a1a5df 100644 --- a/Python/number-of-islands-ii.py +++ b/Python/number-of-islands-ii.py @@ -20,7 +20,7 @@ def find_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)] diff --git a/Python/number-of-islands.py b/Python/number-of-islands.py index 89bff89d1..6f34748dd 100644 --- a/Python/number-of-islands.py +++ b/Python/number-of-islands.py @@ -1,8 +1,8 @@ # 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 +# 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: @@ -28,9 +28,9 @@ class Solution: def numIslands(self, grid): if not grid: return 0 - + row = len(grid) - col = len(grid[0]) + col = len(grid[0]) count = 0 for i in xrange(row): for j in xrange(col): @@ -43,7 +43,7 @@ def dfs(self, grid, row, col, x, y): if grid[x][y] == '0': return grid[x][y] = '0' - + if x != 0: self.dfs(grid, row, col, x - 1, y) if x != row - 1: diff --git a/Python/number-of-lines-to-write-string.py b/Python/number-of-lines-to-write-string.py index 886f139c3..b2e047002 100644 --- a/Python/number-of-lines-to-write-string.py +++ b/Python/number-of-lines-to-write-string.py @@ -11,22 +11,22 @@ # and what is the width used by the last such line? Return your answer as an integer list of length 2. # # Example : -# Input: +# Input: # widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] # S = "abcdefghijklmnopqrstuvwxyz" # Output: [3, 60] # -# Explanation: +# Explanation: # All letters have the same length of 10. To write all 26 letters, # we need two full lines and one line with 60 units. # Example : -# Input: +# Input: # widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10] # S = "bbbcccdddaaa" # Output: [2, 4] # -# Explanation: -# All letters except 'a' have the same length of 10, and +# Explanation: +# All letters except 'a' have the same length of 10, and # "bbbcccdddaa" will cover 9 * 10 + 2 * 4 = 98 units. # For the last 'a', it is written on the second line because # there is only 2 units left in the first line. diff --git a/Python/number-of-longest-increasing-subsequence.py b/Python/number-of-longest-increasing-subsequence.py index 9a45cadb1..3068056a1 100644 --- a/Python/number-of-longest-increasing-subsequence.py +++ b/Python/number-of-longest-increasing-subsequence.py @@ -14,7 +14,7 @@ # 5 subsequences' length is 1, so output 5. # Note: Length of the given array will be not exceed 2000 and the answer is guaranteed # to be fit in 32-bit signed int. - + class Solution(object): def findNumberOfLIS(self, nums): """ diff --git a/Python/number-of-subarrays-with-bounded-maximum.py b/Python/number-of-subarrays-with-bounded-maximum.py index 56aaaaffc..17ab89de5 100644 --- a/Python/number-of-subarrays-with-bounded-maximum.py +++ b/Python/number-of-subarrays-with-bounded-maximum.py @@ -8,7 +8,7 @@ # such that the value of the maximum array element in that subarray is at least L and at most R. # # Example : -# Input: +# Input: # A = [2, 1, 4, 3] # L = 2 # R = 3 diff --git a/Python/odd-even-linked-list.py b/Python/odd-even-linked-list.py index 457c48ac3..166f649f1 100644 --- a/Python/odd-even-linked-list.py +++ b/Python/odd-even-linked-list.py @@ -15,7 +15,7 @@ # # Note: # The relative order inside both the even and odd groups -# should remain as it was in the input. +# should remain as it was in the input. # The first node is considered odd, the second node even # and so on ... diff --git a/Python/one-edit-distance.py b/Python/one-edit-distance.py index 4e11cfe29..25a54f523 100644 --- a/Python/one-edit-distance.py +++ b/Python/one-edit-distance.py @@ -16,7 +16,7 @@ def isOneEditDistance(self, s, t): return self.isOneEditDistance(t, s) if n - m > 1: return False - + i, shift = 0, n - m while i < m and s[i] == t[i]: i += 1 @@ -24,9 +24,9 @@ def isOneEditDistance(self, s, t): i += 1 while i < m and s[i] == t[i + shift]: i += 1 - + return i == m - + if __name__ == "__main__": print Solution().isOneEditDistance("teacher", "acher") diff --git a/Python/ones-and-zeroes.py b/Python/ones-and-zeroes.py index 388bf960f..19a0b3f80 100644 --- a/Python/ones-and-zeroes.py +++ b/Python/ones-and-zeroes.py @@ -17,7 +17,7 @@ # Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3 # Output: 4 # -# Explanation: This are totally 4 strings can be formed +# Explanation: This are totally 4 strings can be formed # by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0” # Example 2: # Input: Array = {"10", "0", "1"}, m = 1, n = 1 @@ -42,7 +42,7 @@ def findMaxForm(self, strs, m, n): elif c == '1': one_count += 1 - for i in reversed(xrange(zero_count, m+1)): - for j in reversed(xrange(one_count, n+1)): + for i in reversed(xrange(zero_count, m+1)): + for j in reversed(xrange(one_count, n+1)): dp[i][j] = max(dp[i][j], dp[i-zero_count][j-one_count]+1) return dp[m][n] diff --git a/Python/optimal-division.py b/Python/optimal-division.py index 0435f174f..5283e2e81 100644 --- a/Python/optimal-division.py +++ b/Python/optimal-division.py @@ -13,8 +13,8 @@ # Output: "1000/(100/10/2)" # Explanation: # 1000/(100/10/2) = 1000/((100/10)/2) = 200 -# However, the bold parenthesis in "1000/((100/10)/2)" are redundant, -# since they don't influence the operation priority. So you should return "1000/(100/10/2)". +# However, the bold parenthesis in "1000/((100/10)/2)" are redundant, +# since they don't influence the operation priority. So you should return "1000/(100/10/2)". # # Other cases: # 1000/(100/10)/2 = 50 diff --git a/Python/output-contest-matches.py b/Python/output-contest-matches.py index 1606a031e..8887fbf89 100644 --- a/Python/output-contest-matches.py +++ b/Python/output-contest-matches.py @@ -11,4 +11,4 @@ def findContestMatch(self, n): while len(matches)/2: matches = ["({},{})".format(matches[i], matches[-i-1]) for i in xrange(len(matches)/2)] return matches[0] - + diff --git a/Python/pacific-atlantic-water-flow.py b/Python/pacific-atlantic-water-flow.py index 57a0566e2..628dbe9d6 100644 --- a/Python/pacific-atlantic-water-flow.py +++ b/Python/pacific-atlantic-water-flow.py @@ -5,7 +5,7 @@ # each unit cell in a continent, the "Pacific ocean" touches the left and # top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges. # -# Water can only flow in four directions (up, down, left, or right) +# Water can only flow in four directions (up, down, left, or right) # from a cell to another one with height equal or lower. # # Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean. @@ -17,7 +17,7 @@ # # Given the following 5x5 matrix: # -# Pacific ~ ~ ~ ~ ~ +# Pacific ~ ~ ~ ~ ~ # ~ 1 2 2 3 (5) * # ~ 3 2 3 (4) (4) * # ~ 2 4 (5) 3 1 * @@ -44,13 +44,13 @@ def pacificAtlanticHelper(matrix, x, y, prev_height, prev_val, visited, res): (visited[x][y] | prev_val) == visited[x][y]: return - visited[x][y] |= prev_val + visited[x][y] |= prev_val if visited[x][y] == (PACIFIC | ATLANTIC): res.append((x, y)) - + for d in [(0, -1), (0, 1), (-1, 0), (1, 0)]: pacificAtlanticHelper(matrix, x + d[0], y + d[1], matrix[x][y], visited[x][y], visited, res) - + if not matrix: return [] diff --git a/Python/paint-house-ii.py b/Python/paint-house-ii.py index 724de0c42..18557f1c2 100644 --- a/Python/paint-house-ii.py +++ b/Python/paint-house-ii.py @@ -23,7 +23,7 @@ def minCostII(self, costs): """ if not costs: return 0 - + n = len(costs) k = len(costs[0]) min_cost = [costs[0], [0] * k] diff --git a/Python/paint-house.py b/Python/paint-house.py index 24e42a96b..d59b581a8 100644 --- a/Python/paint-house.py +++ b/Python/paint-house.py @@ -9,9 +9,9 @@ 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] + \ @@ -33,11 +33,11 @@ def minCost(self, costs): """ if not costs: return 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]) diff --git a/Python/palindrome-number.py b/Python/palindrome-number.py index f7745350e..91a16269b 100644 --- a/Python/palindrome-number.py +++ b/Python/palindrome-number.py @@ -2,15 +2,15 @@ # Space: O(1) # # Determine whether an integer is a palindrome. Do this without extra space. -# +# # Some hints: # Could negative integers be palindromes? (ie, -1) -# +# # If you are thinking of converting the integer to string, note the restriction of using extra space. -# -# You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", +# +# You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", # you know that the reversed integer might overflow. How would you handle such case? -# +# # There is a more generic way of solving this problem. # @@ -20,12 +20,12 @@ def isPalindrome(self, x): if x < 0: return False copy, reverse = x, 0 - + while copy: reverse *= 10 reverse += copy % 10 copy //= 10 - + return x == reverse if __name__ == "__main__": diff --git a/Python/palindrome-partitioning-ii.py b/Python/palindrome-partitioning-ii.py index c2f3d98aa..192c6f0de 100644 --- a/Python/palindrome-partitioning-ii.py +++ b/Python/palindrome-partitioning-ii.py @@ -2,9 +2,9 @@ # Space: O(n^2) # # Given a string s, partition s such that every substring of the partition is a palindrome. -# +# # Return the minimum cuts needed for a palindrome partitioning of s. -# +# # For example, given s = "aab", # Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. # @@ -15,13 +15,13 @@ class Solution: def minCut(self, s): lookup = [[False for j in xrange(len(s))] for i in xrange(len(s))] mincut = [len(s) - 1 - i for i in xrange(len(s) + 1)] - + for i in reversed(xrange(len(s))): for j in xrange(i, len(s)): if s[i] == s[j] and (j - i < 2 or lookup[i + 1][j - 1]): lookup[i][j] = True mincut[i] = min(mincut[i], mincut[j + 1] + 1) - + return mincut[0] if __name__ == "__main__": diff --git a/Python/palindrome-partitioning.py b/Python/palindrome-partitioning.py index fbba4054f..49bec0641 100644 --- a/Python/palindrome-partitioning.py +++ b/Python/palindrome-partitioning.py @@ -2,12 +2,12 @@ # Space: O(n^2) # # Given a string s, partition s such that every substring of the partition is a palindrome. -# +# # Return all possible palindrome partitioning of s. -# +# # For example, given s = "aab", # Return -# +# # [ # ["aa","b"], # ["a","a","b"] @@ -21,12 +21,12 @@ class Solution: # @return a list of lists of string def partition(self, s): n = len(s) - + is_palindrome = [[0 for j in xrange(n)] for i in xrange(n)] for i in reversed(xrange(0, n)): for j in xrange(i, n): is_palindrome[i][j] = s[i] == s[j] and ((j - i < 2 ) or is_palindrome[i + 1][j - 1]) - + sub_partition = [[] for i in xrange(n)] for i in reversed(xrange(n)): for j in xrange(i, n): @@ -36,7 +36,7 @@ def partition(self, s): sub_partition[i].append([s[i:j + 1]] + p) else: sub_partition[i].append([s[i:j + 1]]) - + return sub_partition[0] # Time: O(2^n) @@ -49,7 +49,7 @@ def partition(self, s): result = [] self.partitionRecu(result, [], s, 0) return result - + def partitionRecu(self, result, cur, s, i): if i == len(s): result.append(list(cur)) @@ -59,7 +59,7 @@ def partitionRecu(self, result, cur, s, i): cur.append(s[i: j + 1]) self.partitionRecu(result, cur, s, j + 1) cur.pop() - + def isPalindrome(self, s): for i in xrange(len(s) / 2): if s[i] != s[-(i + 1)]: diff --git a/Python/palindromic-substrings.py b/Python/palindromic-substrings.py index 7cc38189e..5f2668515 100644 --- a/Python/palindromic-substrings.py +++ b/Python/palindromic-substrings.py @@ -25,7 +25,7 @@ def countSubstrings(self, s): """ def manacher(s): s = '^#' + '#'.join(s) + '#$' - P = [0] * len(s) + P = [0] * len(s) C, R = 0, 0 for i in xrange(1, len(s) - 1): i_mirror = 2*C-i @@ -34,6 +34,6 @@ def manacher(s): while s[i+1+P[i]] == s[i-1-P[i]]: P[i] += 1 if i+P[i] > R: - C, R = i, i+P[i] + C, R = i, i+P[i] return P return sum((max_len+1)/2 for max_len in manacher(s)) diff --git a/Python/parse-lisp-expression.py b/Python/parse-lisp-expression.py index e0ecf7b80..24ec81409 100644 --- a/Python/parse-lisp-expression.py +++ b/Python/parse-lisp-expression.py @@ -61,7 +61,7 @@ # Explanation: Even though (let x 4 x) has a deeper scope, it is outside the context # of the final x in the add-expression. That final x will equal 2. # -# Input: (let a1 3 b2 (add a1 1) b2) +# Input: (let a1 3 b2 (add a1 1) b2) # Output 4 # Explanation: Variable names can contain digits after the first character. # diff --git a/Python/partition-list.py b/Python/partition-list.py index ec5b0a3c1..076f277b8 100644 --- a/Python/partition-list.py +++ b/Python/partition-list.py @@ -2,9 +2,9 @@ # Space: O(1) # # Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. -# +# # You should preserve the original relative order of the nodes in each of the two partitions. -# +# # For example, # Given 1->4->3->2->5->2 and x = 3, # return 1->2->2->4->3->5. @@ -15,7 +15,7 @@ class ListNode: def __init__(self, x): self.val = x self.next = None - + def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) @@ -27,7 +27,7 @@ class Solution: def partition(self, head, x): dummySmaller, dummyGreater = ListNode(-1), ListNode(-1) smaller, greater = dummySmaller, dummyGreater - + while head: if head.val < x: smaller.next = head @@ -36,10 +36,10 @@ def partition(self, head, x): greater.next = head greater = greater.next head = head.next - + smaller.next = dummyGreater.next greater.next = None - + return dummySmaller.next if __name__ == "__main__": @@ -51,4 +51,3 @@ def partition(self, head, x): head.next.next.next.next.next = ListNode(2) print Solution().partition(head, 3) - \ No newline at end of file diff --git a/Python/partition-to-k-equal-sum-subsets.py b/Python/partition-to-k-equal-sum-subsets.py index 60ed1b5ce..6dd49fab1 100644 --- a/Python/partition-to-k-equal-sum-subsets.py +++ b/Python/partition-to-k-equal-sum-subsets.py @@ -28,15 +28,15 @@ def dfs(nums, target, used, todo, lookup): for i, num in enumerate(nums) \ if ((used>>i) & 1) == 0 and num <= targ) return lookup[used] - + total = sum(nums) if total%k or max(nums) > total//k: return False lookup = [None] * (1 << len(nums)) lookup[-1] = True return dfs(nums, total//k, 0, total, lookup) - - + + # Time: O(k^(n-k) * k!) # Space: O(n) # DFS solution with pruning. diff --git a/Python/pascals-triangle-ii.py b/Python/pascals-triangle-ii.py index 9f7cfd63d..d5aff1748 100644 --- a/Python/pascals-triangle-ii.py +++ b/Python/pascals-triangle-ii.py @@ -2,10 +2,10 @@ # Space: O(1) # Given an index k, return the kth row of the Pascal's triangle. -# +# # For example, given k = 3, # Return [1,3,3,1]. -# +# # Note: # Could you optimize your algorithm to use only O(k) extra space? # diff --git a/Python/pascals-triangle.py b/Python/pascals-triangle.py index 19b03a607..14194cc75 100644 --- a/Python/pascals-triangle.py +++ b/Python/pascals-triangle.py @@ -2,10 +2,10 @@ # Space: O(1) # # Given numRows, generate the first numRows of Pascal's triangle. -# +# # For example, given numRows = 5, # Return -# +# # [ # [1], # [1,1], diff --git a/Python/patching-array.py b/Python/patching-array.py index ce91f1f6e..8b9a681af 100644 --- a/Python/patching-array.py +++ b/Python/patching-array.py @@ -11,9 +11,9 @@ # nums = [1, 3], n = 6 # Return 1. # -# Combinations of nums are [1], [3], [1,3], which form +# 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: +# 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]. diff --git a/Python/path-sum-ii.py b/Python/path-sum-ii.py index df35acde8..03a2fbf3a 100644 --- a/Python/path-sum-ii.py +++ b/Python/path-sum-ii.py @@ -2,7 +2,7 @@ # 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. -# +# # For example: # Given the below binary tree and sum = 22, # 5 @@ -33,21 +33,21 @@ class Solution: def pathSum(self, root, sum): return self.pathSumRecu([], [], root, sum) - + def pathSumRecu(self, result, cur, root, sum): if root is None: return result - + if root.left is None and root.right is None and root.val == sum: result.append(cur + [root.val]) return result - + cur.append(root.val) self.pathSumRecu(result, cur, root.left, sum - root.val) self.pathSumRecu(result, cur,root.right, sum - root.val) cur.pop() return result - + if __name__ == "__main__": root = TreeNode(5) diff --git a/Python/path-sum.py b/Python/path-sum.py index b24c951a1..70040766d 100644 --- a/Python/path-sum.py +++ b/Python/path-sum.py @@ -1,9 +1,9 @@ # Time: O(n) # 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 +# 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. -# +# # For example: # Given the below binary tree and sum = 22, # 5 @@ -22,7 +22,7 @@ def __init__(self, x): self.val = x self.left = None self.right = None - + class Solution: # @param root, a tree node # @param sum, an integer @@ -30,12 +30,12 @@ class Solution: def hasPathSum(self, root, sum): if root is None: return False - + if root.left is None and root.right is None and root.val == sum: return True - + return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val) - + if __name__ == "__main__": root = TreeNode(5) root.left = TreeNode(4) diff --git a/Python/peeking-iterator.py b/Python/peeking-iterator.py index f21db1fa3..f59311e0d 100644 --- a/Python/peeking-iterator.py +++ b/Python/peeking-iterator.py @@ -48,7 +48,7 @@ def __init__(self, iterator): self.val_ = None self.has_next_ = iterator.hasNext() self.has_peeked_ = False - + def peek(self): """ diff --git a/Python/perfect-number.py b/Python/perfect-number.py index a3fefe5b5..d8d9f30cc 100644 --- a/Python/perfect-number.py +++ b/Python/perfect-number.py @@ -4,7 +4,7 @@ # We define the Perfect Number is a positive integer that is equal # to the sum of all its positive divisors except itself. # -# Now, given an integer n, write a function that returns true +# Now, given an integer n, write a function that returns true # when it is a perfect number and false when it is not. # Example: # Input: 28 @@ -20,7 +20,7 @@ def checkPerfectNumber(self, num): """ if num <= 0: return False - + sqrt_num = int(num ** 0.5) total = sum(i+num//i for i in xrange(1, sqrt_num+1) if num%i == 0) if sqrt_num ** 2 == num: diff --git a/Python/perfect-rectangle.py b/Python/perfect-rectangle.py index 7a3822f41..3cd7e513b 100644 --- a/Python/perfect-rectangle.py +++ b/Python/perfect-rectangle.py @@ -1,11 +1,11 @@ # Time: O(n) # Space: O(n) -# Given N axis-aligned rectangles where N > 0, +# Given N axis-aligned rectangles where N > 0, # determine if they all together form an exact cover of a rectangular region. # -# Each rectangle is represented as a bottom-left point and a top-right point. -# For example, a unit square is represented as [1,1,2,2]. +# Each rectangle is represented as a bottom-left point and a top-right point. +# For example, a unit square is represented as [1,1,2,2]. # (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)). # # Example 1: diff --git a/Python/perfect-squares.py b/Python/perfect-squares.py index 2cee23f58..2201bc73b 100644 --- a/Python/perfect-squares.py +++ b/Python/perfect-squares.py @@ -1,7 +1,7 @@ # Time: O(n * sqrt(n)) # Space: O(n) # -# Given a positive integer n, find the least number of perfect +# 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; diff --git a/Python/permutation-sequence.py b/Python/permutation-sequence.py index cc8b59603..9382f662c 100644 --- a/Python/permutation-sequence.py +++ b/Python/permutation-sequence.py @@ -2,10 +2,10 @@ # Space: O(n) # The set [1,2,3,...,n] contains a total of n! unique permutations. -# +# # By listing and labeling all of the permutations in order, # We get the following sequence (ie, for n = 3): -# +# # "123" # "132" # "213" @@ -13,7 +13,7 @@ # "312" # "321" # Given n and k, return the kth permutation sequence. -# +# # Note: Given n will be between 1 and 9 inclusive. import math @@ -37,6 +37,6 @@ def getPermutation(self, n, k): fact /= i return seq - + if __name__ == "__main__": print Solution().getPermutation(3, 2) diff --git a/Python/permutations-ii.py b/Python/permutations-ii.py index 2b98e265c..17a03fd77 100644 --- a/Python/permutations-ii.py +++ b/Python/permutations-ii.py @@ -2,7 +2,7 @@ # Space: O(n) # # Given a collection of numbers that might contain duplicates, return all possible unique permutations. -# +# # For example, # [1,1,2] have the following unique permutations: # [1,1,2], [1,2,1], and [2,1,1]. @@ -19,7 +19,7 @@ def permuteUnique(self, nums): used = [False] * len(nums) self.permuteUniqueRecu(result, used, [], nums) return result - + def permuteUniqueRecu(self, result, used, cur, nums): if len(cur) == len(nums): result.append(cur + []) @@ -32,13 +32,13 @@ def permuteUniqueRecu(self, result, used, cur, nums): self.permuteUniqueRecu(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): solutions = [[]] - + for num in nums: next = [] for solution in solutions: @@ -46,9 +46,9 @@ def permuteUnique(self, nums): candidate = solution[:i] + [num] + solution[i:] if candidate not in next: next.append(candidate) - - solutions = next - + + solutions = next + return solutions if __name__ == "__main__": diff --git a/Python/permutations.py b/Python/permutations.py index c615f05aa..0a56829ca 100644 --- a/Python/permutations.py +++ b/Python/permutations.py @@ -2,7 +2,7 @@ # Space: O(n) # # Given a collection of numbers, return all possible permutations. -# +# # For example, # [1,2,3] have the following permutations: # [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. @@ -17,7 +17,7 @@ def permute(self, num): used = [False] * len(num) self.permuteRecu(result, used, [], num) return result - + def permuteRecu(self, result, used, cur, num): if len(cur) == len(num): result.append(cur[:]) diff --git a/Python/populating-next-right-pointers-in-each-node-ii.py b/Python/populating-next-right-pointers-in-each-node-ii.py index e4f206e2f..2029f3293 100644 --- a/Python/populating-next-right-pointers-in-each-node-ii.py +++ b/Python/populating-next-right-pointers-in-each-node-ii.py @@ -2,11 +2,11 @@ # Space: O(1) # # Follow up for problem "Populating Next Right Pointers in Each Node". -# +# # What if the given tree could be any binary tree? Would your previous solution still work? -# +# # Note: -# +# # You may only use constant extra space. # For example, # Given the following binary tree, @@ -30,7 +30,7 @@ def __init__(self, x): self.left = None self.right = None self.next = None - + def __repr__(self): if self is None: return "Nil" @@ -50,21 +50,21 @@ def connect(self, root): next_head = cur.left elif cur.right: next_head = cur.right - + if cur.left: if prev: prev.next = cur.left prev = cur.left - + if cur.right: if prev: prev.next = cur.right prev = cur.right - + cur = cur.next head = next_head - - + + if __name__ == "__main__": root, root.left, root.right = TreeNode(1), TreeNode(2), TreeNode(3) @@ -73,4 +73,3 @@ def connect(self, root): print root print root.left print root.left.left - \ No newline at end of file diff --git a/Python/populating-next-right-pointers-in-each-node.py b/Python/populating-next-right-pointers-in-each-node.py index 79b50a7d8..54d7a63fc 100644 --- a/Python/populating-next-right-pointers-in-each-node.py +++ b/Python/populating-next-right-pointers-in-each-node.py @@ -2,18 +2,18 @@ # Space: O(1) # # Given a binary tree -# +# # struct TreeLinkNode { # TreeLinkNode *left; # TreeLinkNode *right; # TreeLinkNode *next; # } # Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. -# +# # Initially, all next pointers are set to NULL. -# +# # Note: -# +# # You may only use constant extra space. # You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). # For example, @@ -37,7 +37,7 @@ def __init__(self, x): self.left = None self.right = None self.next = None - + def __repr__(self): if self is None: return "Nil" @@ -81,4 +81,4 @@ def connect(self, root): print root print root.left print root.left.left - + diff --git a/Python/pour-water.py b/Python/pour-water.py index 7d331cac1..2b13679e8 100644 --- a/Python/pour-water.py +++ b/Python/pour-water.py @@ -33,7 +33,7 @@ # # w # # ## # ### # ######### -# 0123456 +# 0123456 # # When moving left or right, the water can only move to the same level or a lower level. # (By level, we mean the total height of the terrain plus any water in that column.) @@ -44,7 +44,7 @@ # # # # ## w# ### # ######### -# 0123456 +# 0123456 # # Since moving left will not make it fall, it stays in place. The next droplet falls: # @@ -52,7 +52,7 @@ # # w # # ## w# ### # ######### -# 0123456 +# 0123456 # # Since the new droplet moving left will eventually make it fall, it moves left. # Notice that the droplet still preferred to move left, @@ -62,13 +62,13 @@ # # w # # ## w# ### # ######### -# 0123456 +# 0123456 # # # # # # # # ##ww# ### # ######### -# 0123456 +# 0123456 # # After those steps, the third droplet falls. # Since moving left would not eventually make it fall, it tries to move right. @@ -78,13 +78,13 @@ # # w # # ##ww# ### # ######### -# 0123456 +# 0123456 # # # # # # # # ##ww#w### # ######### -# 0123456 +# 0123456 # # Finally, the fourth droplet falls. # Since moving left would not eventually make it fall, it tries to move right. @@ -94,14 +94,14 @@ # # w # # ##ww#w### # ######### -# 0123456 +# 0123456 # # The final answer is [2,2,2,3,2,2,2]: # -# # -# ####### -# ####### -# 0123456 +# # +# ####### +# ####### +# 0123456 # # Example 2: # Input: heights = [1,2,3,4], V = 2, K = 2 diff --git a/Python/power-of-three.py b/Python/power-of-three.py index 02f90144b..e81d1873e 100644 --- a/Python/power-of-three.py +++ b/Python/power-of-three.py @@ -21,7 +21,7 @@ def isPowerOfThree(self, n): """ return n > 0 and self.__max_pow3 % n == 0 - + class Solution2(object): def isPowerOfThree(self, n): return n > 0 and (math.log10(n)/math.log10(3)).is_integer() diff --git a/Python/predict-the-winner.py b/Python/predict-the-winner.py index b64a44cf3..6c871ef7a 100644 --- a/Python/predict-the-winner.py +++ b/Python/predict-the-winner.py @@ -13,10 +13,10 @@ # Example 1: # Input: [1, 5, 2] # Output: False -# Explanation: Initially, player 1 can choose between 1 and 2. +# Explanation: Initially, player 1 can choose between 1 and 2. # If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. -# If player 2 chooses 5, then player 1 will be left with 1 (or 2). -# So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. +# If player 2 chooses 5, then player 1 will be left with 1 (or 2). +# So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. # Hence, player 1 will never be the winner and you need to return False. # Example 2: # Input: [1, 5, 233, 7] @@ -45,4 +45,4 @@ def PredictTheWinner(self, nums): dp[j] = max(nums[i] - dp[j], nums[j] - dp[j - 1]) return dp[-1] >= 0 - + diff --git a/Python/prime-number-of-set-bits-in-binary-representation.py b/Python/prime-number-of-set-bits-in-binary-representation.py index ce38e8afd..f843f9714 100644 --- a/Python/prime-number-of-set-bits-in-binary-representation.py +++ b/Python/prime-number-of-set-bits-in-binary-representation.py @@ -14,7 +14,7 @@ def bitCount(n): n &= n-1 result += 1 return result - + primes = {2, 3, 5, 7, 11, 13, 17, 19} return sum(bitCount(i) in primes for i in xrange(L, R+1)) diff --git a/Python/print-binary-tree.py b/Python/print-binary-tree.py index 33b00ff1d..9d7fd5460 100644 --- a/Python/print-binary-tree.py +++ b/Python/print-binary-tree.py @@ -38,10 +38,10 @@ # 1 # / \ # 2 5 -# / -# 3 -# / -# 4 +# / +# 3 +# / +# 4 # Output: # # [["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""] @@ -49,7 +49,7 @@ # ["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""] # ["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]] # Note: The height of binary tree is in the range of [1, 10]. -# +# # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): @@ -72,7 +72,7 @@ def getHeight(root): if not root: return 0 return max(getHeight(root.left), getHeight(root.right)) + 1 - + def preorderTraversal(root, level, left, right, result): if not root: return diff --git a/Python/product-of-array-except-self.py b/Python/product-of-array-except-self.py index f9646d83a..02b3e1a83 100644 --- a/Python/product-of-array-except-self.py +++ b/Python/product-of-array-except-self.py @@ -22,11 +22,11 @@ class Solution: 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] diff --git a/Python/pyramid-transition-matrix.py b/Python/pyramid-transition-matrix.py index 413a4df90..6c3073b3d 100644 --- a/Python/pyramid-transition-matrix.py +++ b/Python/pyramid-transition-matrix.py @@ -1,6 +1,6 @@ -# Time: O((a^(b+1)-a)/(a-1)) = O(a^b) , a is the size of allowed, +# Time: O((a^(b+1)-a)/(a-1)) = O(a^b) , a is the size of allowed, # b is the length of bottom -# Space: O((a^(b+1)-a)/(a-1)) = O(a^b) +# Space: O((a^(b+1)-a)/(a-1)) = O(a^b) # We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`. # @@ -55,7 +55,7 @@ def dfs(bottom, edges, new_bottom, idx, lookup): if dfs(bottom, edges, new_bottom, idx+1, lookup): return True return False - + if len(bottom) == 1: return True if bottom in lookup: @@ -66,7 +66,7 @@ def dfs(bottom, edges, new_bottom, idx, lookup): return False new_bottom = ['A']*(len(bottom)-1) return dfs(bottom, edges, new_bottom, 0, lookup) - + edges = [[[] for _ in xrange(7)] for _ in xrange(7)] for s in allowed: edges[ord(s[0])-ord('A')][ord(s[1])-ord('A')].append(ord(s[2])-ord('A')) diff --git a/Python/queue-reconstruction-by-height.py b/Python/queue-reconstruction-by-height.py index 7863a79ff..afd5f76cd 100644 --- a/Python/queue-reconstruction-by-height.py +++ b/Python/queue-reconstruction-by-height.py @@ -1,8 +1,8 @@ # Time: O(n * sqrt(n)) # Space: O(n) -# Suppose you have a random list of people standing in a queue. -# Each person is described by a pair of integers (h, k), +# Suppose you have a random list of people standing in a queue. +# Each person is described by a pair of integers (h, k), # where h is the height of the person and k is the number of people # in front of this person who have a height greater than or equal to h. # Write an algorithm to reconstruct the queue. @@ -29,7 +29,7 @@ def reconstructQueue(self, people): blocks = [[]] for p in people: index = p[1] - + for i, block in enumerate(blocks): if index <= len(block): break @@ -39,7 +39,7 @@ def reconstructQueue(self, people): if len(block) * len(block) > len(people): blocks.insert(i+1, block[len(block)/2:]) del block[len(block)/2:] - + return [p for block in blocks for p in block] diff --git a/Python/random-pick-index.py b/Python/random-pick-index.py index f8034c6da..b812c932e 100644 --- a/Python/random-pick-index.py +++ b/Python/random-pick-index.py @@ -27,7 +27,7 @@ class Solution(object): def __init__(self, nums): """ - + :type nums: List[int] :type numsSize: int """ diff --git a/Python/range-addition-ii.py b/Python/range-addition-ii.py index e63e660d6..641bff3db 100644 --- a/Python/range-addition-ii.py +++ b/Python/range-addition-ii.py @@ -11,22 +11,22 @@ # in the matrix after performing all the operations. # # Example 1: -# Input: +# Input: # m = 3, n = 3 # operations = [[2,2],[3,3]] # Output: 4 -# Explanation: -# Initially, M = +# Explanation: +# Initially, M = # [[0, 0, 0], # [0, 0, 0], # [0, 0, 0]] # -# After performing [2,2], M = +# After performing [2,2], M = # [[1, 1, 0], # [1, 1, 0], # [0, 0, 0]] # -# After performing [3,3], M = +# After performing [3,3], M = # [[2, 2, 1], # [2, 2, 1], # [1, 1, 1]] diff --git a/Python/range-sum-query-2d-immutable.py b/Python/range-sum-query-2d-immutable.py index 786f74939..91e444fd6 100644 --- a/Python/range-sum-query-2d-immutable.py +++ b/Python/range-sum-query-2d-immutable.py @@ -57,7 +57,7 @@ def sumRegion(self, row1, col1, row2, col2): """ 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) diff --git a/Python/range-sum-query-immutable.py b/Python/range-sum-query-immutable.py index a5c6d7775..b3b503b53 100644 --- a/Python/range-sum-query-immutable.py +++ b/Python/range-sum-query-immutable.py @@ -22,18 +22,18 @@ def __init__(self, nums): :type nums: List[int] """ self.accu = [0] - for num in nums: + for num in nums: self.accu.append(self.accu[-1] + num), def sumRange(self, i, j): """ sum of elements nums[i..j], inclusive. - :type i: int + :type i: int :type j: int - :rtype: int + :rtype: int """ return self.accu[j + 1] - self.accu[i] - + # Your NumArray object will be instantiated and called as such: # numArray = NumArray(nums) diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py index d9b7db624..5e8ed8136 100644 --- a/Python/range-sum-query-mutable.py +++ b/Python/range-sum-query-mutable.py @@ -3,7 +3,7 @@ # query: O(logn) # Space: O(n) -# Given an integer array nums, find the sum of +# 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 @@ -46,7 +46,7 @@ def update(self, i, val): 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. @@ -87,21 +87,21 @@ def __init__(self, nums): 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) @@ -119,22 +119,22 @@ 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) if self.__nums[i] != val: self.__nums[i] = val updateHelper(self.__root, i, val) - + def sumRange(self, i, j): """ sum of elements nums[i..j], inclusive. diff --git a/Python/ransom-note.py b/Python/ransom-note.py index 917334555..0d175fdd4 100644 --- a/Python/ransom-note.py +++ b/Python/ransom-note.py @@ -4,7 +4,7 @@ # Given an arbitrary ransom note string and another string containing letters # from all the magazines, write a function that will return true if # the ransom note can be constructed from the magazines ; -# otherwise, it will return false. +# otherwise, it will return false. # # Each letter in the magazine string can only be used once in your ransom note. # 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 2645c5fd0..70dccb689 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 @@ -2,11 +2,11 @@ # Space: O(1) # # The API: int read4(char *buf) reads 4 characters at a time from a file. -# +# # The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. -# +# # By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file. -# +# # Note: # The read function may be called multiple times. # @@ -20,13 +20,13 @@ def read4(buf): while i < len(file_content) and i < 4: buf[i] = file_content[i] i += 1 - + if len(file_content) > 4: file_content = file_content[4:] else: file_content = "" return i - + # The read4 API is already defined for you. # @param buf, a list of characters # @return an integer @@ -37,7 +37,7 @@ def __init__(self): self.__buf4 = [''] * 4 self.__i4 = 0 self.__n4 = 0 - + def read(self, buf, n): """ :type buf: Destination buffer (List[str]) @@ -56,7 +56,7 @@ def read(self, buf, n): self.__i4 = 0 else: # Buffer has been empty. break - + return i if __name__ == "__main__": @@ -65,4 +65,4 @@ def read(self, buf, n): buf = ['' for _ in xrange(100)] file_content = "ab" print buf[:sol.read(buf, 1)] - print buf[:sol.read(buf, 2)] + print buf[:sol.read(buf, 2)] diff --git a/Python/read-n-characters-given-read4.py b/Python/read-n-characters-given-read4.py index 1581cca20..2c754e9f7 100644 --- a/Python/read-n-characters-given-read4.py +++ b/Python/read-n-characters-given-read4.py @@ -2,11 +2,11 @@ # Space: O(1) # # The API: int read4(char *buf) reads 4 characters at a time from a file. -# +# # The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. -# +# # By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file. -# +# # Note: # The read function will only be called once for each test case. # @@ -20,13 +20,13 @@ def read4(buf): while i < len(file_content) and i < 4: buf[i] = file_content[i] i += 1 - + if len(file_content) > 4: file_content = file_content[4:] else: file_content = "" return i - + class Solution(object): def read(self, buf, n): """ @@ -49,6 +49,6 @@ def read(self, buf, n): global file_content buf = ['' for _ in xrange(100)] file_content = "a" - print buf[:Solution().read(buf, 9)] + print buf[:Solution().read(buf, 9)] file_content = "abcdefghijklmnop" print buf[:Solution().read(buf, 9)] diff --git a/Python/reconstruct-original-digits-from-english.py b/Python/reconstruct-original-digits-from-english.py index ff7797bde..eb67abeab 100644 --- a/Python/reconstruct-original-digits-from-english.py +++ b/Python/reconstruct-original-digits-from-english.py @@ -30,10 +30,10 @@ def originalDigits(self, s): cnts = [Counter(_) for _ in ["zero", "one", "two", "three", \ "four", "five", "six", "seven", \ "eight", "nine"]] - + # The order for greedy method. order = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] - + # The unique char in the order. unique_chars = ['z', 'o', 'w', 't', 'u', \ 'f', 'x', 's', 'g', 'n'] diff --git a/Python/recover-binary-search-tree.py b/Python/recover-binary-search-tree.py index 0cc9ddda1..073967d9e 100644 --- a/Python/recover-binary-search-tree.py +++ b/Python/recover-binary-search-tree.py @@ -2,9 +2,9 @@ # Space: O(1) # # Two elements of a binary search tree (BST) are swapped by mistake. -# +# # Recover the tree without changing its structure. -# +# # Note: # A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? # @@ -14,8 +14,8 @@ class TreeNode: def __init__(self, x): self.val = x self.left = None - self.right = None - + self.right = None + def __repr__(self): if self: serial = [] @@ -23,21 +23,21 @@ def __repr__(self): while queue: cur = queue[0] - + if cur: serial.append(cur.val) queue.append(cur.left) queue.append(cur.right) else: serial.append("#") - + queue = queue[1:] - + while serial[-1] == "#": serial.pop() - + return repr(serial) - + else: return None @@ -46,13 +46,13 @@ class Solution: # @return a tree node def recoverTree(self, root): return self.MorrisTraversal(root) - + def MorrisTraversal(self, root): if root is None: return broken = [None, None] pre, cur = None, root - + while cur: if cur.left is None: self.detectBroken(broken, pre, cur) @@ -62,7 +62,7 @@ def MorrisTraversal(self, root): node = cur.left while node.right and node.right != cur: node = node.right - + if node.right is None: node.right =cur cur = cur.left @@ -71,20 +71,19 @@ def MorrisTraversal(self, root): node.right = None pre = cur cur = cur.right - + broken[0].val, broken[1].val = broken[1].val, broken[0].val - + return root - + def detectBroken(self, broken, pre, cur): if pre and pre.val > cur.val: if broken[0] is None: broken[0] = pre broken[1] = cur - + if __name__ == "__main__": root = TreeNode(0) root.left = TreeNode(1) print root print Solution().recoverTree(root) - \ No newline at end of file diff --git a/Python/redundant-connection-ii.py b/Python/redundant-connection-ii.py index 39f86635f..79e613c68 100644 --- a/Python/redundant-connection-ii.py +++ b/Python/redundant-connection-ii.py @@ -56,7 +56,7 @@ def union_set(self, x, y): self.count -= 1 return True - + class Solution(object): def findRedundantDirectedConnection(self, edges): """ diff --git a/Python/redundant-connection.py b/Python/redundant-connection.py index c26efe3dd..c490e4743 100644 --- a/Python/redundant-connection.py +++ b/Python/redundant-connection.py @@ -59,4 +59,4 @@ def findRedundantConnection(self, edges): if not union_find.union_set(*edge): return edge return [] - + diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py index 3101c52c7..ef240b84a 100644 --- a/Python/regular-expression-matching.py +++ b/Python/regular-expression-matching.py @@ -2,15 +2,15 @@ # Space: O(n) # # Implement regular expression matching with support for '.' and '*'. -# +# # '.' Matches any single character. # '*' Matches zero or more of the preceding element. -# +# # The matching should cover the entire input string (not partial). -# +# # The function prototype should be: # bool isMatch(const char *s, const char *p) -# +# # Some examples: # isMatch("aa","a") -> false # isMatch("aa","aa") -> true @@ -27,12 +27,12 @@ class Solution: def isMatch(self, s, p): k = 3 result = [[False for j in xrange(len(p) + 1)] for i in xrange(k)] - + result[0][0] = True for i in xrange(2, len(p) + 1): if p[i-1] == '*': result[0][i] = result[0][i-2] - + for i in xrange(1,len(s) + 1): if i > 1: result[0][0] = False @@ -41,7 +41,7 @@ def isMatch(self, s, p): 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] == '.')) - + return result[len(s) % k][len(p)] # dp @@ -51,19 +51,19 @@ class Solution2: # @return a boolean def isMatch(self, s, p): result = [[False for j in xrange(len(p) + 1)] for i in xrange(len(s) + 1)] - + result[0][0] = True for i in xrange(2, len(p) + 1): if p[i-1] == '*': result[0][i] = result[0][i-2] - + for i in xrange(1,len(s) + 1): for j in xrange(1, len(p) + 1): 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] == '.')) - + return result[len(s)][len(p)] # iteration @@ -84,7 +84,7 @@ 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() - + 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 @@ -94,19 +94,19 @@ def isMatch(self, s, p): return False else: return False - + while p_ptr < len(p) - 1 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: return not s - + if len(p) == 1 or p[1] != '*': if len(s) > 0 and (p[0] == s[0] or p[0] == '.'): return self.isMatch(s[1:], p[1:]) diff --git a/Python/relative-ranks.py b/Python/relative-ranks.py index 3b32dd9a4..35b12842f 100644 --- a/Python/relative-ranks.py +++ b/Python/relative-ranks.py @@ -9,7 +9,7 @@ # Input: [5, 4, 3, 2, 1] # Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] # Explanation: The first three athletes got the top three highest scores, -# so they got "Gold Medal", "Silver Medal" and "Bronze Medal". +# so they got "Gold Medal", "Silver Medal" and "Bronze Medal". # For the left two athletes, you just need to output # their relative ranks according to their scores. # Note: diff --git a/Python/remove-9.py b/Python/remove-9.py index ec7ad01e3..234f57714 100644 --- a/Python/remove-9.py +++ b/Python/remove-9.py @@ -1,6 +1,6 @@ # Time: O(logn) # Space: O(1) - + class Solution(object): def newInteger(self, n): """ diff --git a/Python/remove-boxes.py b/Python/remove-boxes.py index a34b96d6a..e1012647e 100644 --- a/Python/remove-boxes.py +++ b/Python/remove-boxes.py @@ -1,7 +1,7 @@ # Time: O(n^3) ~ O(n^4) # Space: O(n^3) -# Given several boxes with different colors represented by different positive numbers. +# Given several boxes with different colors represented by different positive numbers. # You may experience several rounds to remove boxes until there is no box left. # Each time you can choose some continuous boxes with the same color (composed of k boxes, k >= 1), # remove them and get k*k points. @@ -14,10 +14,10 @@ # Output: # 23 # Explanation: -# [1, 3, 2, 2, 2, 3, 4, 3, 1] -# ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) -# ----> [1, 3, 3, 3, 1] (1*1=1 points) -# ----> [1, 1] (3*3=9 points) +# [1, 3, 2, 2, 2, 3, 4, 3, 1] +# ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) +# ----> [1, 3, 3, 3, 1] (1*1=1 points) +# ----> [1, 1] (3*3=9 points) # ----> [] (2*2=4 points) # Note: The number of boxes n would not exceed 100. diff --git a/Python/remove-comments.py b/Python/remove-comments.py index 5b8707e0e..57895225a 100644 --- a/Python/remove-comments.py +++ b/Python/remove-comments.py @@ -11,15 +11,15 @@ # rest of the characters to the right of it in the same line should be ignored. # # The string /* denotes a block comment, -# which represents that all characters until the next (non-overlapping) occurrence of */ -# should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) +# which represents that all characters until the next (non-overlapping) occurrence of */ +# should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) # To be clear, the string /*/ does not yet end the block comment, as the ending would be overlapping the beginning. # # The first effective comment takes precedence over others: # if the string // occurs in a block comment, it is ignored. # Similarly, if the string /* occurs in a line or block comment, it is also ignored. # -# If a certain line of code is empty after removing comments, +# If a certain line of code is empty after removing comments, # you must not output that line: each string in the answer list will be non-empty. # # There will be no control characters, single quote, or double quote characters. @@ -34,18 +34,18 @@ # After removing the comments from the source code, return the source code in the same format. # # Example 1: -# Input: +# Input: # source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"] # # The line by line code is visualized as below: # /*Test program */ # int main() -# { -# // variable declaration +# { +# // variable declaration # int a, b, c; # /* This is a test -# multiline -# comment for +# multiline +# comment for # testing */ # a = b + c; # } @@ -54,19 +54,19 @@ # # The line by line code is visualized as below: # int main() -# { +# { # int a, b, c; # a = b + c; # } -# Explanation: -# The string +# Explanation: +# The string # /* -# denotes a block comment, including line 1 and lines 6-9. The string +# denotes a block comment, including line 1 and lines 6-9. The string # // # denotes line 4 as comments. # # Example 2: -# Input: +# Input: # source = ["a/*comment", "line", "more_comment*/b"] # Output: ["ab"] # Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", diff --git a/Python/remove-duplicates-from-sorted-array-ii.py b/Python/remove-duplicates-from-sorted-array-ii.py index 794b192ae..104161e0a 100644 --- a/Python/remove-duplicates-from-sorted-array-ii.py +++ b/Python/remove-duplicates-from-sorted-array-ii.py @@ -3,10 +3,10 @@ # # Follow up for "Remove Duplicates": # What if duplicates are allowed at most twice? -# +# # For example, # Given sorted array A = [1,1,1,2,2,3], -# +# # Your function should return length = 5, and A is now [1,1,2,2,3]. # @@ -16,7 +16,7 @@ class Solution: def removeDuplicates(self, A): if not A: return 0 - + last, i, same = 0, 1, False while i < len(A): if A[last] != A[i] or not same: @@ -24,7 +24,7 @@ def removeDuplicates(self, A): last += 1 A[last] = A[i] i += 1 - + return last + 1 if __name__ == "__main__": diff --git a/Python/remove-duplicates-from-sorted-array.py b/Python/remove-duplicates-from-sorted-array.py index 7ea358680..b2a94cc23 100644 --- a/Python/remove-duplicates-from-sorted-array.py +++ b/Python/remove-duplicates-from-sorted-array.py @@ -2,12 +2,12 @@ # Space: O(1) # # Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. -# +# # Do not allocate extra space for another array, you must do this in place with constant memory. -# +# # For example, # Given input array A = [1,1,2], -# +# # Your function should return length = 2, and A is now [1,2]. # @@ -17,14 +17,14 @@ class Solution: def removeDuplicates(self, A): if not A: return 0 - + last, i = 0, 1 while i < len(A): if A[last] != A[i]: last += 1 A[last] = A[i] i += 1 - + return last + 1 if __name__ == "__main__": diff --git a/Python/remove-duplicates-from-sorted-list-ii.py b/Python/remove-duplicates-from-sorted-list-ii.py index 0f21f2171..9d4d364be 100644 --- a/Python/remove-duplicates-from-sorted-list-ii.py +++ b/Python/remove-duplicates-from-sorted-list-ii.py @@ -3,7 +3,7 @@ # # Given a sorted linked list, delete all nodes that have duplicate numbers, # leaving only distinct numbers from the original list. -# +# # For example, # Given 1->2->3->3->4->4->5, return 1->2->5. # Given 1->1->1->2->3, return 2->3. @@ -14,7 +14,7 @@ class ListNode: def __init__(self, x): self.val = x self.next = None - + def __repr__(self): if self is None: return "Nil" @@ -40,10 +40,10 @@ def deleteDuplicates(self, head): pre = cur cur = cur.next return dummy.next - + if __name__ == "__main__": head, head.next, head.next.next = ListNode(1), ListNode(2), ListNode(3) 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) - + diff --git a/Python/remove-element.py b/Python/remove-element.py index a24b77318..edb0f237b 100644 --- a/Python/remove-element.py +++ b/Python/remove-element.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given an array and a value, remove all instances of that value in place and return the new length. -# +# # The order of elements can be changed. It doesn't matter what you leave beyond the new length. # @@ -19,6 +19,6 @@ def removeElement(self, A, elem): else: i += 1 return last + 1 - + if __name__ == "__main__": print Solution().removeElement([1, 2, 3, 4, 5, 2, 2], 2) \ No newline at end of file diff --git a/Python/remove-invalid-parentheses.py b/Python/remove-invalid-parentheses.py index 35504e3ca..348e4291e 100644 --- a/Python/remove-invalid-parentheses.py +++ b/Python/remove-invalid-parentheses.py @@ -54,7 +54,7 @@ def removeInvalidParenthesesHelper(start, left_removed, right_removed): 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. diff --git a/Python/remove-k-digits.py b/Python/remove-k-digits.py index ec30523a3..b9b9ee749 100644 --- a/Python/remove-k-digits.py +++ b/Python/remove-k-digits.py @@ -16,7 +16,7 @@ # # Input: num = "10200", k = 1 # Output: "200" -# Explanation: Remove the leading 1 and the number is 200. +# Explanation: Remove the leading 1 and the number is 200. # Note that the output must not contain leading zeroes. # Example 3: # diff --git a/Python/remove-linked-list-elements.py b/Python/remove-linked-list-elements.py index 347370e88..316f1d6de 100644 --- a/Python/remove-linked-list-elements.py +++ b/Python/remove-linked-list-elements.py @@ -21,15 +21,15 @@ 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 - - + + diff --git a/Python/remove-nth-node-from-end-of-list.py b/Python/remove-nth-node-from-end-of-list.py index ea655cd08..637c8c198 100644 --- a/Python/remove-nth-node-from-end-of-list.py +++ b/Python/remove-nth-node-from-end-of-list.py @@ -2,11 +2,11 @@ # Space: O(1) # # Given a linked list, remove the nth node from the end of list and return its head. -# +# # For example, -# +# # Given linked list: 1->2->3->4->5, and n = 2. -# +# # After removing the second node from the end, the linked list becomes 1->2->3->5. # Note: # Given n will always be valid. @@ -24,22 +24,22 @@ def __repr__(self): return "Nil" else: return "{} -> {}".format(self.val, repr(self.next)) - + class Solution: # @return a ListNode def removeNthFromEnd(self, head, n): dummy = ListNode(-1) dummy.next = head slow, fast = dummy, dummy - + for i in xrange(n): fast = fast.next - + while fast.next: slow, fast = slow.next, fast.next - + slow.next = slow.next.next - + return dummy.next if __name__ == "__main__": @@ -48,5 +48,5 @@ def removeNthFromEnd(self, head, n): head.next.next = ListNode(3) head.next.next.next = ListNode(4) head.next.next.next.next = ListNode(5) - + print Solution().removeNthFromEnd(head, 2) \ No newline at end of file diff --git a/Python/reorder-list.py b/Python/reorder-list.py index a80c0fede..8d5541c83 100644 --- a/Python/reorder-list.py +++ b/Python/reorder-list.py @@ -3,9 +3,9 @@ # # Given a singly linked list L: L0->L1->...->Ln-1->Ln, # reorder it to: L0->Ln->L1->Ln-1->L2->Ln-2->... -# +# # You must do this in-place without altering the nodes' values. -# +# # For example, # Given {1,2,3,4}, reorder it to {1,4,2,3}. # @@ -15,26 +15,26 @@ class ListNode: def __init__(self, x): self.val = x self.next = None - + def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) - + class Solution: # @param head, a ListNode # @return nothing def reorderList(self, head): if head == None or head.next == None: return head - + fast, slow, prev = head, head, None while fast != None and fast.next != None: fast, slow, prev = fast.next.next, slow.next, slow current, prev.next, prev = slow, None, None - + while current != None: current.next, prev, current = prev, current, current.next - + l1, l2 = head, prev dummy = ListNode(0) current = dummy @@ -42,7 +42,7 @@ def reorderList(self, head): while l1 != None and l2 != None: current.next, current, l1 = l1, l1, l1.next current.next, current, l2 = l2, l2, l2.next - + return dummy.next if __name__ == "__main__": diff --git a/Python/repeated-dna-sequences.py b/Python/repeated-dna-sequences.py index 901af0451..bb9373bfa 100644 --- a/Python/repeated-dna-sequences.py +++ b/Python/repeated-dna-sequences.py @@ -1,9 +1,9 @@ # Time: O(n) # Space: O(n) -# All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, +# 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, diff --git a/Python/reshape-the-matrix.py b/Python/reshape-the-matrix.py index acbe6bdb2..6c5eba08e 100644 --- a/Python/reshape-the-matrix.py +++ b/Python/reshape-the-matrix.py @@ -15,24 +15,24 @@ # output the new reshaped matrix; Otherwise, output the original matrix. # # Example 1: -# Input: -# nums = +# Input: +# nums = # [[1,2], # [3,4]] # r = 1, c = 4 -# Output: +# Output: # [[1,2,3,4]] # Explanation: # The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, # fill it row by row by using the previous list. # # Example 2: -# Input: -# nums = +# Input: +# nums = # [[1,2], # [3,4]] # r = 2, c = 4 -# Output: +# Output: # [[1,2], # [3,4]] # Explanation: diff --git a/Python/restore-ip-addresses.py b/Python/restore-ip-addresses.py index 504ce6c6c..e1e338b64 100644 --- a/Python/restore-ip-addresses.py +++ b/Python/restore-ip-addresses.py @@ -2,10 +2,10 @@ # Space: O(n * m) = O(3 * 4) # # Given a string containing only digits, restore it by returning all possible valid IP address combinations. -# +# # For example: # Given "25525511135", -# +# # return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) # @@ -16,12 +16,12 @@ def restoreIpAddresses(self, s): result = [] self.restoreIpAddressesRecur(result, s, 0, "", 0) return result - + def restoreIpAddressesRecur(self, result, s, start, current, dots): # pruning to improve performance if (4 - dots) * 3 < len(s) - start or (4 - dots) > len(s) - start: return - + if start == len(s) and dots == 4: result.append(current[:-1]) else: @@ -30,11 +30,11 @@ def restoreIpAddressesRecur(self, result, s, start, current, dots): current += s[start:i + 1] + '.' self.restoreIpAddressesRecur(result, s, i + 1, current, dots + 1) current = current[:-(i - start + 2)] - + def isValid(self, s): if len(s) == 0 or (s[0] == '0' and s != "0"): return False return int(s) < 256 - + if __name__ == "__main__": print Solution().restoreIpAddresses("0000") diff --git a/Python/reverse-bits.py b/Python/reverse-bits.py index 636684e0e..baecdb400 100644 --- a/Python/reverse-bits.py +++ b/Python/reverse-bits.py @@ -29,6 +29,6 @@ def reverseBits2(self, n): else: string = string[:2] + string[2:].zfill(32)[::-1] return int(string, 2) - + if __name__ == '__main__': print Solution().reverseBits(1) diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py index 6b213a576..8533bbe1c 100644 --- a/Python/reverse-integer.py +++ b/Python/reverse-integer.py @@ -2,21 +2,21 @@ # Space: O(1) # # Reverse digits of an integer. -# +# # Example1: x = 123, return 321 # Example2: x = -123, return -321 -# +# # click to show spoilers. -# +# # Have you thought about this? # Here are some good questions to ask before coding. Bonus points for you if you have already thought through this! -# +# # If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100. -# -# Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, +# +# Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, # then the reverse of 1000000003 overflows. How should you handle such cases? -# -# Throw an exception? Good, but what if throwing an exception is not an option? +# +# Throw an exception? Good, but what if throwing an exception is not an option? # You would then have to re-design the function (ie, add an extra parameter). @@ -34,7 +34,7 @@ def reverse(self, x): result = result * 10 + x % 10 x //= 10 return result if result <= 0x7fffffff else 0 # Handle overflow. - + def reverse2(self, x): """ :type x: int diff --git a/Python/reverse-linked-list-ii.py b/Python/reverse-linked-list-ii.py index 4314d1b6f..d18404785 100644 --- a/Python/reverse-linked-list-ii.py +++ b/Python/reverse-linked-list-ii.py @@ -2,12 +2,12 @@ # Space: O(1) # # Reverse a linked list from position m to n. Do it in-place and in one-pass. -# +# # For example: # Given 1->2->3->4->5->NULL, m = 2 and n = 4, -# +# # return 1->4->3->2->5->NULL. -# +# # Note: # Given m, n satisfy the following condition: # 1 <= m <= n <= length of list. @@ -18,7 +18,7 @@ class ListNode: def __init__(self, x): self.val = x self.next = None - + def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) @@ -30,17 +30,17 @@ class Solution: def reverseBetween(self, head, m, n): diff, dummy, cur = n - m + 1, ListNode(-1), head dummy.next = head - + last_unswapped = dummy while cur and m > 1: cur, last_unswapped, m = cur.next, cur, m - 1 - + prev, first_swapped = last_unswapped, cur while cur and diff > 0: cur.next, prev, cur, diff = prev, cur, cur.next, diff - 1 - + last_unswapped.next, first_swapped.next = prev, cur - + return dummy.next if __name__ == "__main__": @@ -50,4 +50,3 @@ def reverseBetween(self, head, m, n): head.next.next.next = ListNode(4) head.next.next.next.next = ListNode(5) print Solution().reverseBetween(head, 2, 4) - \ No newline at end of file diff --git a/Python/reverse-linked-list.py b/Python/reverse-linked-list.py index 8e8441ddc..b000888f2 100644 --- a/Python/reverse-linked-list.py +++ b/Python/reverse-linked-list.py @@ -14,7 +14,7 @@ class ListNode: def __init__(self, x): self.val = x self.next = None - + def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) @@ -31,27 +31,27 @@ def reverseList(self, head): # Time: O(n) # Space: O(n) -# Recursive solution. +# 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) diff --git a/Python/reverse-nodes-in-k-group.py b/Python/reverse-nodes-in-k-group.py index 359fce169..15f95d5fa 100644 --- a/Python/reverse-nodes-in-k-group.py +++ b/Python/reverse-nodes-in-k-group.py @@ -2,18 +2,18 @@ # Space: O(1) # # Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. -# +# # If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. -# +# # You may not alter the values in the nodes, only nodes itself may be changed. -# +# # Only constant memory is allowed. -# +# # For example, # Given this linked list: 1->2->3->4->5 -# +# # For k = 2, you should return: 2->1->4->3->5 -# +# # For k = 3, you should return: 3->2->1->4->5 # @@ -21,8 +21,8 @@ class ListNode: def __init__(self, x): self.val = x - self.next = None - + self.next = None + def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) @@ -34,27 +34,27 @@ class Solution: def reverseKGroup(self, head, k): dummy = ListNode(-1) dummy.next = head - + cur, cur_dummy = head, dummy length = 0 - + while cur: next_cur = cur.next length = (length + 1) % k - + if length == 0: next_dummy = cur_dummy.next self.reverse(cur_dummy, cur.next) cur_dummy = next_dummy - + cur = next_cur - + return dummy.next - + def reverse(self, begin, end): first = begin.next cur = first.next - + while cur != end: first.next = cur.next cur.next = begin.next diff --git a/Python/reverse-vowels-of-a-string.py b/Python/reverse-vowels-of-a-string.py index f7eb88ae2..359c71f8a 100644 --- a/Python/reverse-vowels-of-a-string.py +++ b/Python/reverse-vowels-of-a-string.py @@ -1,7 +1,7 @@ # Time: O(n) # Space: O(1) -# Write a function that takes a string as input +# Write a function that takes a string as input # and reverse only the vowels of a string. # # Example 1: diff --git a/Python/reverse-words-in-a-string-ii.py b/Python/reverse-words-in-a-string-ii.py index 6656ae327..e87268406 100644 --- a/Python/reverse-words-in-a-string-ii.py +++ b/Python/reverse-words-in-a-string-ii.py @@ -3,14 +3,14 @@ # # 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? # diff --git a/Python/reverse-words-in-a-string.py b/Python/reverse-words-in-a-string.py index 4d4bddc90..e660e205c 100644 --- a/Python/reverse-words-in-a-string.py +++ b/Python/reverse-words-in-a-string.py @@ -2,13 +2,13 @@ # Space: O(n) # # Given an input string, reverse the string word by word. -# +# # For example, # Given s = "the sky is blue", # return "blue is sky the". -# +# # click to show clarification. -# +# # Clarification: # What constitutes a word? # A sequence of non-space characters constitutes a word. diff --git a/Python/roman-to-integer.py b/Python/roman-to-integer.py index 2b858fea1..a5d2d05d9 100644 --- a/Python/roman-to-integer.py +++ b/Python/roman-to-integer.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given a roman numeral, convert it to an integer. -# +# # Input is guaranteed to be within the xrange from 1 to 3999. # diff --git a/Python/rotate-array.py b/Python/rotate-array.py index 1139d6a33..7e5484fca 100644 --- a/Python/rotate-array.py +++ b/Python/rotate-array.py @@ -60,7 +60,7 @@ def apply_cycle_permutation(self, k, offset, cycle_len, nums): nums[(offset + i * k) % len(nums)], tmp = tmp, nums[(offset + i * k) % len(nums)] nums[offset] = tmp - + class Solution3: """ :type nums: List[int] @@ -82,7 +82,7 @@ def rotate(self, nums, k): if start == curr: break start += 1 - + if __name__ == '__main__': nums = [1, 2, 3, 4, 5, 6, 7] diff --git a/Python/rotate-image.py b/Python/rotate-image.py index dabc2734f..648b4c715 100644 --- a/Python/rotate-image.py +++ b/Python/rotate-image.py @@ -2,9 +2,9 @@ # Space: O(1) # # You are given an n x n 2D matrix representing an image. -# +# # Rotate the image by 90 degrees (clockwise). -# +# # Follow up: # Could you do this in-place? # @@ -16,19 +16,19 @@ class Solution: # @return a list of lists of integers def rotate(self, matrix): n = len(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] - + # 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] - + return matrix - + # Time: O(n^2) # Space: O(n^2) class Solution2: @@ -36,7 +36,7 @@ class Solution2: # @return a list of lists of integers def rotate(self, matrix): return [list(reversed(x)) for x in zip(*matrix)] - + if __name__ == "__main__": matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print Solution().rotate(matrix) diff --git a/Python/rotate-list.py b/Python/rotate-list.py index 6a536da17..59ecb567e 100644 --- a/Python/rotate-list.py +++ b/Python/rotate-list.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given a list, rotate the list to the right by k places, where k is non-negative. -# +# # For example: # Given 1->2->3->4->5->NULL and k = 2, # return 4->5->1->2->3->NULL. @@ -13,11 +13,11 @@ class ListNode: def __init__(self, x): self.val = x self.next = None - + def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) - + class Solution(object): def rotateRight(self, head, k): """ @@ -42,7 +42,7 @@ def rotateRight(self, head, k): return cur - + if __name__ == "__main__": head = ListNode(1) head.next = ListNode(2) diff --git a/Python/rotate-string.py b/Python/rotate-string.py index b988e3bf4..3a8f5151a 100644 --- a/Python/rotate-string.py +++ b/Python/rotate-string.py @@ -32,7 +32,7 @@ def check(index): if len(A) != len(B): return False - + M, p = 10**9+7, 113 p_inv = pow(p, M-2, M) @@ -98,12 +98,12 @@ def getPrefix(pattern): if not needle: return 0 return KMP(haystack, needle) - + if len(A) != len(B): return False return strStr(A*2, B) != -1 - + # Time: O(n^2) # Space: O(n) class Solution3(object): diff --git a/Python/rotated-digits.py b/Python/rotated-digits.py index 4a0f1baf4..98223aa44 100644 --- a/Python/rotated-digits.py +++ b/Python/rotated-digits.py @@ -12,7 +12,7 @@ # Example: # Input: 10 # Output: 4 -# Explanation: +# Explanation: # There are four good numbers in the range [1, 10] : 2, 5, 6, 9. # Note that 1 and 10 are not good numbers, since they remain unchanged after rotating. # @@ -40,11 +40,11 @@ def dp(A, i, is_prefix_equal, is_good, lookup): lookup) lookup[i, is_prefix_equal, is_good] = result return lookup[i, is_prefix_equal, is_good] - + lookup = {} return dp(A, 0, True, False, lookup) - - + + # Time: O(n) # Space: O(n) class Solution2(object): @@ -66,7 +66,7 @@ def rotatedDigits(self, N): if i*10+j <= N: dp[i*10+j] = DIFF return dp.count(DIFF) - + # Time: O(nlogn) = O(n), because O(logn) = O(32) by this input # Space: O(logn) = O(1) @@ -85,4 +85,4 @@ def rotatedDigits(self, N): if diff & lookup: result += 1 return result - + diff --git a/Python/russian-doll-envelopes.py b/Python/russian-doll-envelopes.py index 2f695b9c4..50685c92b 100644 --- a/Python/russian-doll-envelopes.py +++ b/Python/russian-doll-envelopes.py @@ -3,7 +3,7 @@ # You have a number of envelopes with widths and heights given # as a pair of integers (w, h). One envelope can fit into another -# if and only if both the width and height of one envelope is greater +# if and only if both the width and height of one envelope is greater # than the width and height of the other envelope. # # What is the maximum number of envelopes can you Russian doll? diff --git a/Python/same-tree.py b/Python/same-tree.py index c7e799c94..6418ffc0e 100644 --- a/Python/same-tree.py +++ b/Python/same-tree.py @@ -2,7 +2,7 @@ # Space: O(h), h is height of binary tree # # Given two binary trees, write a function to check if they are equal or not. -# +# # Two binary trees are considered equal if they are structurally identical and the nodes have the same value. # @@ -20,12 +20,12 @@ class Solution: def isSameTree(self, p, q): if p is None and q is None: return True - + if p is not None and q is not None: return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) - + return False - + 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) diff --git a/Python/scramble-string.py b/Python/scramble-string.py index 7969954b0..2627135af 100644 --- a/Python/scramble-string.py +++ b/Python/scramble-string.py @@ -2,9 +2,9 @@ # Space: O(n^3) # # Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. -# +# # Below is one possible representation of s1 = "great": -# +# # great # / \ # gr eat @@ -13,9 +13,9 @@ # / \ # a t # To scramble the string, we may choose any non-leaf node and swap its two children. -# +# # For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". -# +# # rgeat # / \ # rg eat @@ -24,9 +24,9 @@ # / \ # a t # We say that "rgeat" is a scrambled string of "great". -# +# # Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". -# +# # rgtae # / \ # rg tae @@ -35,7 +35,7 @@ # / \ # t a # We say that "rgtae" is a scrambled string of "great". -# +# # Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. # @@ -54,7 +54,7 @@ def isScramble(self, s1, s2): for j in xrange(len(s2)): if s1[i] == s2[j]: result[1][i][j] = True - + for n in xrange(2, len(s1) + 1): for i in xrange(len(s1) - n + 1): for j in xrange(len(s2) - n + 1): @@ -63,7 +63,7 @@ def isScramble(self, s1, s2): result[k][i][j + n - k] and result[n - k][i + k][j]: result[n][i][j] = True break - + return result[n][0][0] if __name__ == "__main__": diff --git a/Python/search-a-2d-matrix-ii.py b/Python/search-a-2d-matrix-ii.py index 3540dfd6c..e61290905 100644 --- a/Python/search-a-2d-matrix-ii.py +++ b/Python/search-a-2d-matrix-ii.py @@ -30,11 +30,11 @@ def searchMatrix(self, matrix, target): m = len(matrix) if m == 0: return False - + n = len(matrix[0]) if n == 0: return False - + i, j = 0, n - 1 while i < m and j >= 0: if matrix[i][j] == target: @@ -43,5 +43,5 @@ def searchMatrix(self, matrix, target): j -= 1 else: i += 1 - + return False diff --git a/Python/search-a-2d-matrix.py b/Python/search-a-2d-matrix.py index cc0e67e95..793894f2a 100644 --- a/Python/search-a-2d-matrix.py +++ b/Python/search-a-2d-matrix.py @@ -2,13 +2,13 @@ # 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 from left to right. # The first integer of each row is greater than the last integer of the previous row. # For example, -# +# # Consider the following matrix: -# +# # [ # [1, 3, 5, 7], # [10, 11, 16, 20], @@ -26,7 +26,7 @@ def searchMatrix(self, matrix, target): """ if not matrix: return False - + m, n = len(matrix), len(matrix[0]) left, right = 0, m * n while left < right: diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py index 74bf58ac7..9d3ad9766 100644 --- a/Python/search-for-a-range.py +++ b/Python/search-for-a-range.py @@ -2,11 +2,11 @@ # Space: O(1) # # Given a sorted array of integers, find the starting and ending position of a given target value. -# +# # Your algorithm's runtime complexity must be in the order of O(log n). -# +# # If the target is not found in the array, return [-1, -1]. -# +# # For example, # Given [5, 7, 7, 8, 8, 10] and target value 8, # return [3, 4]. @@ -26,7 +26,7 @@ def searchRange(self, nums, target): # Find the first idx where nums[idx] > target right = self.binarySearch(lambda x, y: x > y, nums, target) return [left, right - 1] - + def binarySearch(self, compare, nums, target): left, right = 0, len(nums) while left < right: diff --git a/Python/search-in-rotated-sorted-array-ii.py b/Python/search-in-rotated-sorted-array-ii.py index 8649ec528..43a607f05 100644 --- a/Python/search-in-rotated-sorted-array-ii.py +++ b/Python/search-in-rotated-sorted-array-ii.py @@ -3,9 +3,9 @@ # # Follow up for "Search in Rotated Sorted Array": # What if duplicates are allowed? -# +# # Would this affect the run-time complexity? How and why? -# +# # Write a function to determine if a given target is in the array. # @@ -17,10 +17,10 @@ def search(self, nums, target): :rtype: int """ left, right = 0, len(nums) - 1 - + while left <= right: mid = left + (right - left) / 2 - + if nums[mid] == target: return True elif nums[mid] == nums[left]: @@ -32,7 +32,7 @@ def search(self, nums, target): left = mid + 1 return False - + if __name__ == "__main__": print Solution().search([3, 5, 1], 3) diff --git a/Python/search-in-rotated-sorted-array.py b/Python/search-in-rotated-sorted-array.py index d95d92382..4c93474b0 100644 --- a/Python/search-in-rotated-sorted-array.py +++ b/Python/search-in-rotated-sorted-array.py @@ -2,11 +2,11 @@ # Space: O(1) # # Suppose a sorted array is rotated at some pivot unknown to you beforehand. -# +# # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). -# +# # You are given a target value to search. If found in the array return its index, otherwise return -1. -# +# # You may assume no duplicate exists in the array. # @@ -18,10 +18,10 @@ def search(self, nums, target): :rtype: int """ left, right = 0, len(nums) - 1 - + while left <= right: mid = left + (right - left) / 2 - + if nums[mid] == target: return mid elif (nums[mid] >= nums[left] and nums[left] <= target < nums[mid]) or \ @@ -31,7 +31,7 @@ def search(self, nums, target): left = mid + 1 return -1 - + if __name__ == "__main__": print Solution().search([3, 5, 1], 3) diff --git a/Python/search-insert-position.py b/Python/search-insert-position.py index a5be023ed..89b3f18de 100644 --- a/Python/search-insert-position.py +++ b/Python/search-insert-position.py @@ -2,11 +2,11 @@ # Space: O(1) # # Given a sorted array and a target value, return the index if the target is found. -# +# # If not, return the index where it would be if it were inserted in order. -# +# # You may assume no duplicates in the array. -# +# # Here are few examples. # [1,3,5,6], 5 -> 2 # [1,3,5,6], 2 -> 1 diff --git a/Python/self-crossing.py b/Python/self-crossing.py index cdb4439ab..76fd0d7d2 100644 --- a/Python/self-crossing.py +++ b/Python/self-crossing.py @@ -46,7 +46,7 @@ def isSelfCrossing(self, x): # 2 # 3 ┌────┐ # └─══>┘1 - # 4 0 (overlapped) + # 4 0 (overlapped) return True for i in xrange(3, len(x)): @@ -61,7 +61,7 @@ def isSelfCrossing(self, x): x[i - 1] <= x[i - 3] and x[i - 5] + x[i - 1] >= x[i - 3]: # Case 2: # i-4 - # ┌──┐ + # ┌──┐ # │i<┼─┐ # i-3│ i-5│i-1 # └────┘ diff --git a/Python/self-dividing-numbers.py b/Python/self-dividing-numbers.py index 84050e5a8..d3428690d 100644 --- a/Python/self-dividing-numbers.py +++ b/Python/self-dividing-numbers.py @@ -12,7 +12,7 @@ # including the bounds if possible. # # Example 1: -# Input: +# Input: # left = 1, right = 22 # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] # @@ -33,7 +33,7 @@ def isDividingNumber(num): return False n /= 10 return True - + result = [] for num in xrange(left, right+1): if isDividingNumber(num): diff --git a/Python/sentence-screen-fitting.py b/Python/sentence-screen-fitting.py index 91f45ca0c..eb5f98046 100644 --- a/Python/sentence-screen-fitting.py +++ b/Python/sentence-screen-fitting.py @@ -12,7 +12,7 @@ def wordsTyping(self, sentence, rows, cols): def words_fit(sentence, start, cols): if len(sentence[start]) > cols: return 0 - + s, count = len(sentence[start]), 1 i = (start + 1) % len(sentence) while s + 1 + len(sentence[i]) <= cols: diff --git a/Python/serialize-and-deserialize-binary-tree.py b/Python/serialize-and-deserialize-binary-tree.py index d69f43dd0..1806df30f 100644 --- a/Python/serialize-and-deserialize-binary-tree.py +++ b/Python/serialize-and-deserialize-binary-tree.py @@ -6,10 +6,10 @@ # 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. +# 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 +# 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 @@ -20,9 +20,9 @@ # / \ # 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 +# 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. +# Note: Do not use class member/global/static variables to store states. # Your serialize and deserialize algorithms should be stateless. # @@ -36,7 +36,7 @@ class Codec: def serialize(self, root): """Encodes a tree to a single string. - + :type root: TreeNode :rtype: str """ @@ -54,7 +54,7 @@ def serializeHelper(node): def deserialize(self, data): """Decodes your encoded data to tree. - + :type data: str :rtype: TreeNode """ diff --git a/Python/set-matrix-zeroes.py b/Python/set-matrix-zeroes.py index ea770632c..4a08ded96 100644 --- a/Python/set-matrix-zeroes.py +++ b/Python/set-matrix-zeroes.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. -# +# # Follow up: # Did you use extra space? # A straight forward solution using O(mn) space is probably a bad idea. @@ -16,21 +16,21 @@ class Solution: def setZeroes(self, matrix): first_col = reduce(lambda acc, i: acc or matrix[i][0] == 0, xrange(len(matrix)), False) first_row = reduce(lambda acc, j: acc or matrix[0][j] == 0, xrange(len(matrix[0])), False) - + for i in xrange(1, len(matrix)): for j in xrange(1, len(matrix[0])): if matrix[i][j] == 0: matrix[i][0], matrix[0][j] = 0, 0 - + for i in xrange(1, len(matrix)): for j in xrange(1, len(matrix[0])): if matrix[i][0] == 0 or matrix[0][j] == 0: matrix[i][j] = 0 - + if first_col: for i in xrange(len(matrix)): matrix[i][0] = 0 - + if first_row: for j in xrange(len(matrix[0])): matrix[0][j] = 0 diff --git a/Python/set-mismatch.py b/Python/set-mismatch.py index 662ae25d4..d9a24acda 100644 --- a/Python/set-mismatch.py +++ b/Python/set-mismatch.py @@ -37,7 +37,7 @@ def findErrorNums(self, nums): # Time: O(n) -# Space: O(1) +# Space: O(1) class Solution2(object): def findErrorNums(self, nums): """ @@ -59,7 +59,7 @@ def findErrorNums(self, nums): # Time: O(n) -# Space: O(1) +# Space: O(1) class Solution3(object): def findErrorNums(self, nums): """ diff --git a/Python/shopping-offers.py b/Python/shopping-offers.py index 63fe142b0..743d8d0a3 100644 --- a/Python/shopping-offers.py +++ b/Python/shopping-offers.py @@ -19,24 +19,24 @@ # Example 1: # Input: [2,5], [[3,0,5],[1,2,10]], [3,2] # Output: 14 -# Explanation: -# There are two kinds of items, A and B. Their prices are $2 and $5 respectively. +# Explanation: +# There are two kinds of items, A and B. Their prices are $2 and $5 respectively. # In special offer 1, you can pay $5 for 3A and 0B -# In special offer 2, you can pay $10 for 1A and 2B. +# In special offer 2, you can pay $10 for 1A and 2B. # You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A. # Example 2: # Input: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1] # Output: 11 -# Explanation: -# The price of A is $2, and $3 for B, $4 for C. -# You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. -# You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. +# Explanation: +# The price of A is $2, and $3 for B, $4 for C. +# You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. +# You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. # You cannot add more items, though only $9 for 2A ,2B and 1C. # Note: # There are at most 6 kinds of items, 100 special offers. # For each item, you need to buy at most 6 of them. # You are not allowed to buy more items than you want, even if that would lower the overall price. - + class Solution(object): def shoppingOffers(self, price, special, needs): """ diff --git a/Python/shortest-distance-from-all-buildings.py b/Python/shortest-distance-from-all-buildings.py index 7b5fd2ae5..19a0b0082 100644 --- a/Python/shortest-distance-from-all-buildings.py +++ b/Python/shortest-distance-from-all-buildings.py @@ -10,7 +10,7 @@ def shortestDistance(self, grid): 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)] - + pre_level = [(x, y)] visited[x][y] = True while pre_level: @@ -24,7 +24,7 @@ def bfs(grid, dists, cnts, x, y): dists[I][J] += dist cur_level.append((I, J)) visited[I][J] = True - + pre_level = cur_level diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py index f092ca4bf..e267e597e 100644 --- a/Python/shortest-palindrome.py +++ b/Python/shortest-palindrome.py @@ -1,8 +1,8 @@ # 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 +# 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: @@ -32,7 +32,7 @@ def getPrefix(pattern): if not s: return s - + A = s + s[::-1] prefix = getPrefix(A) i = prefix[-1] @@ -60,7 +60,7 @@ def preProcess(s): return string string = preProcess(s) - palindrome = [0] * len(string) + palindrome = [0] * len(string) center, right = 0, 0 for i in xrange(1, len(string) - 1): i_mirror = 2 * center - i @@ -73,8 +73,8 @@ def preProcess(s): palindrome[i] += 1 if i + palindrome[i] > right: - center, right = i, i + palindrome[i] - + center, right = i, i + palindrome[i] + max_len = 0 for i in xrange(1, len(string) - 1): if i - palindrome[i] == 1: diff --git a/Python/shortest-unsorted-continuous-subarray.py b/Python/shortest-unsorted-continuous-subarray.py index 1de3ba3fe..637b692a0 100644 --- a/Python/shortest-unsorted-continuous-subarray.py +++ b/Python/shortest-unsorted-continuous-subarray.py @@ -31,7 +31,7 @@ def findUnsortedSubarray(self, nums): min_from_right = min(min_from_right, nums[n-1-i]) if nums[i] < max_from_left: right = i if nums[n-1-i] > min_from_right: left = n-1-i - + # Time: O(nlogn) # Space: O(n) diff --git a/Python/simplify-path.py b/Python/simplify-path.py index b55e73a11..532b544c1 100644 --- a/Python/simplify-path.py +++ b/Python/simplify-path.py @@ -2,12 +2,12 @@ # Space: O(n) # # Given an absolute path for a file (Unix-style), simplify it. -# +# # For example, # path = "/home/", => "/home" # path = "/a/./b/../../c/", => "/c" # click to show corner cases. -# +# # Corner Cases: # Did you consider the case where path = "/../"? # In this case, you should return "/". diff --git a/Python/single-element-in-a-sorted-array.py b/Python/single-element-in-a-sorted-array.py index 4a7dcb18b..ef54a8bef 100644 --- a/Python/single-element-in-a-sorted-array.py +++ b/Python/single-element-in-a-sorted-array.py @@ -12,7 +12,7 @@ # Input: [3,3,7,7,10,11,11] # Output: 10 # Note: Your solution should run in O(log n) time and O(1) space. - + class Solution(object): def singleNonDuplicate(self, nums): """ diff --git a/Python/single-number-ii.py b/Python/single-number-ii.py index e87276c96..586b80c30 100644 --- a/Python/single-number-ii.py +++ b/Python/single-number-ii.py @@ -1,8 +1,8 @@ # Time: O(n) # Space: O(1) -# +# # Given an array of integers, every element appears three times except for one. Find that single one. -# +# # Note: # Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? import collections @@ -16,7 +16,7 @@ def singleNumber(self, A): for x in A: one, two = (~x & one) | (x & ~one & ~two), (~x & two) | (x & one) return one - + class Solution2(object): # @param A, a list of integer # @return an integer diff --git a/Python/single-number.py b/Python/single-number.py index 88047ae25..742ea9c09 100644 --- a/Python/single-number.py +++ b/Python/single-number.py @@ -2,7 +2,7 @@ # Space: O(1) # # Given an array of integers, every element appears twice except for one. Find that single one. -# +# # Note: # Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? # diff --git a/Python/sliding-window-maximum.py b/Python/sliding-window-maximum.py index eeaffeedb..1fb613e50 100644 --- a/Python/sliding-window-maximum.py +++ b/Python/sliding-window-maximum.py @@ -19,7 +19,7 @@ # 1 3 -1 -3 5 [3 6 7] 7 # Therefore, return the max sliding window as [3,3,5,5,6,7]. # -# Note: +# Note: # You may assume k is always valid, ie: 1 <= k <= input array's size for non-empty array. # # Follow up: diff --git a/Python/smallest-rotation-with-highest-score.py b/Python/smallest-rotation-with-highest-score.py index c46d7421d..c37570ea0 100644 --- a/Python/smallest-rotation-with-highest-score.py +++ b/Python/smallest-rotation-with-highest-score.py @@ -1,9 +1,9 @@ # Time: O(n) # Space: O(n) -# Given an array A, we may rotate it by a non-negative integer K +# Given an array A, we may rotate it by a non-negative integer K # so that the array becomes A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1]. -# Afterward, any entries that are less than or equal to their index are worth 1 point. +# Afterward, any entries that are less than or equal to their index are worth 1 point. # # For example, if we have [2, 4, 1, 3, 0], and we rotate by K = 2, # it becomes [1, 3, 0, 2, 4]. @@ -17,8 +17,8 @@ # Example 1: # Input: [2, 3, 1, 4, 0] # Output: 3 -# Explanation: -# Scores for each K are listed below: +# Explanation: +# Scores for each K are listed below: # K = 0, A = [2,3,1,4,0], score 2 # K = 1, A = [3,1,4,0,2], score 3 # K = 2, A = [1,4,0,2,3], score 3 @@ -35,7 +35,7 @@ # Note: # - A will have length at most 20000. # - A[i] will be in the range [0, A.length]. - + class Solution(object): def bestRotation(self, A): """ @@ -49,4 +49,4 @@ def bestRotation(self, A): for i in xrange(1, N): change[i] += change[i-1] return change.index(max(change)) - + diff --git a/Python/sort-colors.py b/Python/sort-colors.py index 5e42aa69b..9a7b2b8dd 100644 --- a/Python/sort-colors.py +++ b/Python/sort-colors.py @@ -1,21 +1,21 @@ # Time: O(n) # Space: O(1) # -# Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, +# Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, # with the colors in the order red, white and blue. -# +# # Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. -# +# # Note: # You are not suppose to use the library's sort function for this problem. -# +# # click to show follow up. -# +# # Follow up: # A rather straight forward solution is a two-pass algorithm using counting sort. -# First, iterate the array counting number of 0's, 1's, and 2's, +# First, iterate the array counting number of 0's, 1's, and 2's, # then overwrite array with total number of 0's, then 1's and followed by 2's. -# +# # Could you come up with an one-pass algorithm using only constant space? # @@ -27,7 +27,7 @@ def sortColors(self, nums): """ 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] diff --git a/Python/sort-list.py b/Python/sort-list.py index 5427a88bd..d01ed7f56 100644 --- a/Python/sort-list.py +++ b/Python/sort-list.py @@ -9,43 +9,43 @@ class ListNode: def __init__(self, x): self.val = x self.next = None - + def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) class Solution: # @param head, a ListNode - # @return a ListNode + # @return a ListNode def sortList(self, head): if head == None or head.next == None: return head - + fast, slow, prev = head, head, None while fast != None and fast.next != None: prev, fast, slow = slow, fast.next.next, slow.next prev.next = None - + sorted_l1 = self.sortList(head) sorted_l2 = self.sortList(slow) - + return self.mergeTwoLists(sorted_l1, sorted_l2) - + def mergeTwoLists(self, l1, l2): dummy = ListNode(0) - + cur = dummy while l1 != None and l2 != None: if l1.val <= l2.val: cur.next, cur, l1 = l1, l1, l1.next else: cur.next, cur, l2 = l2, l2, l2.next - + if l1 != None: cur.next = l1 if l2 != None: cur.next = l2 - + return dummy.next if __name__ == "__main__": diff --git a/Python/special-binary-string.py b/Python/special-binary-string.py index b743a60fa..ab8a7ced5 100644 --- a/Python/special-binary-string.py +++ b/Python/special-binary-string.py @@ -8,7 +8,7 @@ # Every prefix of the binary string has at least as many 1's as 0's. # Given a special string S, a move consists of choosing two consecutive, non-empty, # special substrings of S, and swapping them. -# (Two strings are consecutive if the last character of the first string is +# (Two strings are consecutive if the last character of the first string is # exactly one index before the first character of the second string.) # # At the end of any number of moves, what is the lexicographically largest resulting string possible? diff --git a/Python/spiral-matrix-ii.py b/Python/spiral-matrix-ii.py index d0b870bd5..d23da6b19 100644 --- a/Python/spiral-matrix-ii.py +++ b/Python/spiral-matrix-ii.py @@ -2,10 +2,10 @@ # Space: O(1) # # Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. -# +# # For example, # Given n = 3, -# +# # You should return the following matrix: # [ # [ 1, 2, 3 ], @@ -18,9 +18,9 @@ class Solution: # @return a list of lists of integer def generateMatrix(self, n): matrix = [[0 for _ in xrange(n)] for _ in xrange(n)] - + left, right, top, bottom, num = 0, n - 1, 0, n - 1, 1 - + while left <= right and top <= bottom: for j in xrange(left, right + 1): matrix[top][j] = num @@ -37,7 +37,7 @@ def generateMatrix(self, n): matrix[i][left] = num num += 1 left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1 - + return matrix diff --git a/Python/spiral-matrix.py b/Python/spiral-matrix.py index 5071ccc54..1e0734fe1 100644 --- a/Python/spiral-matrix.py +++ b/Python/spiral-matrix.py @@ -2,10 +2,10 @@ # Space: O(1) # # Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. -# +# # For example, # Given the following matrix: -# +# # [ # [ 1, 2, 3 ], # [ 4, 5, 6 ], @@ -21,9 +21,9 @@ def spiralOrder(self, matrix): result = [] if matrix == []: return result - + left, right, top, bottom = 0, len(matrix[0]) - 1, 0, len(matrix) - 1 - + while left <= right and top <= bottom: for j in xrange(left, right + 1): result.append(matrix[top][j]) @@ -36,7 +36,7 @@ def spiralOrder(self, matrix): if left < right: result.append(matrix[i][left]) left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1 - + return result diff --git a/Python/split-array-into-consecutive-subsequences.py b/Python/split-array-into-consecutive-subsequences.py index c5c0008ca..2e6b113d5 100644 --- a/Python/split-array-into-consecutive-subsequences.py +++ b/Python/split-array-into-consecutive-subsequences.py @@ -9,14 +9,14 @@ # Input: [1,2,3,3,4,5] # Output: True # Explanation: -# You can split them into two consecutive subsequences : +# You can split them into two consecutive subsequences : # 1, 2, 3 # 3, 4, 5 # Example 2: # Input: [1,2,3,3,4,4,5,5] # Output: True # Explanation: -# You can split them into two consecutive subsequences : +# You can split them into two consecutive subsequences : # 1, 2, 3, 4, 5 # 3, 4, 5 # Example 3: diff --git a/Python/split-array-with-equal-sum.py b/Python/split-array-with-equal-sum.py index 036df2334..825e79418 100644 --- a/Python/split-array-with-equal-sum.py +++ b/Python/split-array-with-equal-sum.py @@ -9,7 +9,7 @@ def splitArray(self, nums): """ if len(nums) < 7: return False - + accumulated_sum = [0] * len(nums) accumulated_sum[0] = nums[0] for i in xrange(1, len(nums)): diff --git a/Python/split-array-with-same-average.py b/Python/split-array-with-same-average.py index aaca0d8bf..f4a83ec9f 100644 --- a/Python/split-array-with-same-average.py +++ b/Python/split-array-with-same-average.py @@ -8,7 +8,7 @@ # the average value of B is equal to the average value of C, and B and C are both non-empty. # # Example : -# Input: +# Input: # [1,2,3,4,5,6,7,8] # Output: true # Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5. diff --git a/Python/split-concatenated-strings.py b/Python/split-concatenated-strings.py index 4693b532e..4ad1d593f 100644 --- a/Python/split-concatenated-strings.py +++ b/Python/split-concatenated-strings.py @@ -17,9 +17,9 @@ # Example: # Input: "abc", "xyz" # Output: "zyxcba" -# Explanation: You can get the looped string "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-", -# where '-' represents the looped status. -# The answer string came from the fourth looped one, +# Explanation: You can get the looped string "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-", +# where '-' represents the looped status. +# The answer string came from the fourth looped one, # where you could cut from the middle character 'a' and get "zyxcba". # Note: # The input strings will only contain lowercase letters. diff --git a/Python/split-linked-list-in-parts.py b/Python/split-linked-list-in-parts.py index 27b6e791f..4189510f1 100644 --- a/Python/split-linked-list-in-parts.py +++ b/Python/split-linked-list-in-parts.py @@ -15,7 +15,7 @@ # # Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ] # Example 1: -# Input: +# Input: # root = [1, 2, 3], k = 5 # Output: [[1],[2],[3],[],[]] # Explanation: @@ -26,7 +26,7 @@ # The last element output[4] is null, but it's string representation as a ListNode is []. # # Example 2: -# Input: +# Input: # root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3 # Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] # Explanation: diff --git a/Python/sqrtx.py b/Python/sqrtx.py index 8ac7af2c8..05296b789 100644 --- a/Python/sqrtx.py +++ b/Python/sqrtx.py @@ -2,7 +2,7 @@ # Space: O(1) # Implement int sqrt(int x). -# +# # Compute and return the square root of x. class Solution(object): @@ -13,7 +13,7 @@ def mySqrt(self, x): """ if x < 2: return x - + left, right = 1, x // 2 while left <= right: mid = left + (right - left) // 2 @@ -27,4 +27,4 @@ def mySqrt(self, x): if __name__ == "__main__": print Solution().mySqrt(10) - + diff --git a/Python/squirrel-simulation.py b/Python/squirrel-simulation.py index 11935ae5e..f0057eec2 100644 --- a/Python/squirrel-simulation.py +++ b/Python/squirrel-simulation.py @@ -13,7 +13,7 @@ def minDistance(self, height, width, tree, squirrel, nuts): """ def distance(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) - + result = 0 d = float("inf") for nut in nuts: diff --git a/Python/strange-printer.py b/Python/strange-printer.py index 534463942..811933aaf 100644 --- a/Python/strange-printer.py +++ b/Python/strange-printer.py @@ -17,11 +17,11 @@ # Example 2: # Input: "aba" # Output: 2 -# Explanation: Print "aaa" first and then print "b" from +# Explanation: Print "aaa" first and then print "b" from # the second place of the string, which will cover the existing character 'a'. # # Hint: Length of the given string will not exceed 100. - + class Solution(object): def strangePrinter(self, s): """ diff --git a/Python/string-to-integer-atoi.py b/Python/string-to-integer-atoi.py index 56b6c78e8..d59faea1a 100644 --- a/Python/string-to-integer-atoi.py +++ b/Python/string-to-integer-atoi.py @@ -2,27 +2,27 @@ # Space: O(1) # # Implement atoi to convert a string to an integer. -# -# Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below +# +# Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below # and ask yourself what are the possible input cases. -# +# # Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). # You are responsible to gather all the input requirements up front. -# +# # spoilers alert... click to show requirements for atoi. -# +# # Requirements for atoi: -# The function first discards as many whitespace characters as necessary -# until the first non-whitespace character is found. Then, starting from this character, +# The function first discards as many whitespace characters as necessary +# until the first non-whitespace character is found. Then, starting from this character, # takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. -# -# The string can contain additional characters after those that +# +# The string can contain additional characters after those that # form the integral number, which are ignored and have no effect on the behavior of this function. -# -# If the first sequence of non-whitespace characters in str is not a valid integral number, +# +# If the first sequence of non-whitespace characters in str is not a valid integral number, # or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. -# -# If no valid conversion could be performed, a zero value is returned. +# +# If no valid conversion could be performed, a zero value is returned. # If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned. # @@ -35,14 +35,14 @@ def myAtoi(self, str): INT_MAX = 2147483647 INT_MIN = -2147483648 result = 0 - + if not str: return result - + i = 0 while i < len(str) and str[i].isspace(): i += 1 - + sign = 1 if str[i] == "+": i += 1 @@ -55,13 +55,13 @@ def myAtoi(self, str): return INT_MAX if sign > 0 else INT_MIN result = result * 10 + int(str[i]) i += 1 - + return sign * result if __name__ == "__main__": - print Solution().atoi("") + print Solution().atoi("") print Solution().atoi("-1") - print Solution().atoi("2147483647") - print Solution().atoi("2147483648") - print Solution().atoi("-2147483648") - print Solution().atoi("-2147483649") + print Solution().atoi("2147483647") + print Solution().atoi("2147483648") + print Solution().atoi("-2147483648") + print Solution().atoi("-2147483649") diff --git a/Python/strobogrammatic-number-ii.py b/Python/strobogrammatic-number-ii.py index da089c481..a914402b2 100644 --- a/Python/strobogrammatic-number-ii.py +++ b/Python/strobogrammatic-number-ii.py @@ -14,7 +14,7 @@ def findStrobogrammaticRecu(self, n, k): return [''] elif k == 1: return ['0', '1', '8'] - + result = [] for num in self.findStrobogrammaticRecu(n, k - 2): for key, val in self.lookup.iteritems(): diff --git a/Python/strobogrammatic-number-iii.py b/Python/strobogrammatic-number-iii.py index d45aa3d49..23bf9b7b1 100644 --- a/Python/strobogrammatic-number-iii.py +++ b/Python/strobogrammatic-number-iii.py @@ -25,7 +25,7 @@ def countStrobogrammaticUntil(self, num, can_start_with_0): count += 1 self.cache[num] = count return count - + for key, val in self.lookup.iteritems(): if can_start_with_0 or key != '0': if num[0] > key: @@ -36,7 +36,7 @@ def countStrobogrammaticUntil(self, num, can_start_with_0): elif num[0] == key: if len(num) == 2: # num is like 12". if num[-1] >= val: - count += 1 + count += 1 else: if num[-1] >= val: # num is like "102". count += self.countStrobogrammaticUntil(self.getMid(num), True); diff --git a/Python/strong-password-checker.py b/Python/strong-password-checker.py index 90269f9fc..2776c8dfa 100644 --- a/Python/strong-password-checker.py +++ b/Python/strong-password-checker.py @@ -36,7 +36,7 @@ def strongPasswordChecker(self, s): while i < len(s) and s[i] == s[i-1]: length += 1 i += 1 - + total_change_cnt += length / 3 if length % 3 == 0: one_change_cnt += 1 @@ -46,16 +46,16 @@ def strongPasswordChecker(self, s): three_change_cnt += 1 else: i += 1 - + if len(s) < 6: return max(missing_type_cnt, 6 - len(s)) elif len(s) <= 20: return max(missing_type_cnt, total_change_cnt) else: delete_cnt = len(s) - 20 - + total_change_cnt -= min(delete_cnt, one_change_cnt * 1) / 1 total_change_cnt -= min(max(delete_cnt - one_change_cnt, 0), two_change_cnt * 2) / 2 total_change_cnt -= min(max(delete_cnt - one_change_cnt - 2 * two_change_cnt, 0), three_change_cnt * 3) / 3 - + return delete_cnt + max(missing_type_cnt, total_change_cnt) diff --git a/Python/student-attendance-record-i.py b/Python/student-attendance-record-i.py index 07c836558..e63511eae 100644 --- a/Python/student-attendance-record-i.py +++ b/Python/student-attendance-record-i.py @@ -34,4 +34,4 @@ def checkRecord(self, s): if i < len(s) - 2 and s[i] == s[i+1] == s[i+2] == 'L': return False return True - + diff --git a/Python/student-attendance-record-ii.py b/Python/student-attendance-record-ii.py index 2b1cc99b6..c52793b45 100644 --- a/Python/student-attendance-record-ii.py +++ b/Python/student-attendance-record-ii.py @@ -14,11 +14,11 @@ # # Example 1: # Input: n = 2 -# Output: 8 +# Output: 8 # Explanation: # There are 8 records with length 2 will be regarded as rewardable: # "PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL" -# Only "AA" won't be regarded as rewardable owing to more than one absent times. +# Only "AA" won't be regarded as rewardable owing to more than one absent times. # Note: The value of n won't exceed 100,000. class Solution(object): diff --git a/Python/subarray-product-less-than-k.py b/Python/subarray-product-less-than-k.py index 3650ab757..9d947ca72 100644 --- a/Python/subarray-product-less-than-k.py +++ b/Python/subarray-product-less-than-k.py @@ -35,4 +35,4 @@ def numSubarrayProductLessThanK(self, nums, k): start += 1 result += i-start+1 return result - + diff --git a/Python/subsets-ii.py b/Python/subsets-ii.py index f30e20486..ebd20f0bb 100644 --- a/Python/subsets-ii.py +++ b/Python/subsets-ii.py @@ -2,13 +2,13 @@ # Space: O(1) # Given a collection of integers that might contain duplicates, S, return all possible subsets. -# +# # Note: # Elements in a subset must be in non-descending order. # The solution set must not contain duplicate subsets. # For example, # If S = [1,2,2], a solution is: -# +# # [ # [2], # [1], @@ -49,7 +49,7 @@ def subsetsWithDup(self, nums): result = [] i, count = 0, 1 << len(nums) nums.sort() - + while i < count: cur = [] for j in xrange(len(nums)): @@ -58,7 +58,7 @@ def subsetsWithDup(self, nums): if cur not in result: result.append(cur) i += 1 - + return result @@ -73,7 +73,7 @@ def subsetsWithDup(self, nums): result = [] self.subsetsWithDupRecu(result, [], sorted(nums)) return result - + def subsetsWithDupRecu(self, result, cur, nums): if not nums: if cur not in result: @@ -82,6 +82,6 @@ def subsetsWithDupRecu(self, result, cur, nums): self.subsetsWithDupRecu(result, cur, nums[1:]) self.subsetsWithDupRecu(result, cur + [nums[0]], nums[1:]) - + if __name__ == "__main__": print Solution().subsetsWithDup([1, 2, 2]) diff --git a/Python/subsets.py b/Python/subsets.py index 113b810e7..83ba120db 100644 --- a/Python/subsets.py +++ b/Python/subsets.py @@ -2,13 +2,13 @@ # Space: O(1) # Given a set of distinct integers, S, return all possible subsets. -# +# # Note: # Elements in a subset must be in non-descending order. # The solution set must not contain duplicate subsets. # For example, # If S = [1,2,3], a solution is: -# +# # [ # [3], # [1], @@ -47,7 +47,7 @@ def subsets(self, nums): result = [] i, count = 0, 1 << len(nums) nums.sort() - + while i < count: cur = [] for j in xrange(len(nums)): @@ -55,7 +55,7 @@ def subsets(self, nums): cur.append(nums[j]) result.append(cur) i += 1 - + return result @@ -68,11 +68,11 @@ def subsets(self, nums): :rtype: List[List[int]] """ return self.subsetsRecu([], sorted(nums)) - + def subsetsRecu(self, cur, nums): if not nums: return [cur] - + return self.subsetsRecu(cur, nums[1:]) + self.subsetsRecu(cur + [nums[0]], nums[1:]) diff --git a/Python/subtree-of-another-tree.py b/Python/subtree-of-another-tree.py index 9b0987f33..423941776 100644 --- a/Python/subtree-of-another-tree.py +++ b/Python/subtree-of-another-tree.py @@ -16,7 +16,7 @@ # / \ # 1 2 # Given tree t: -# 4 +# 4 # / \ # 1 2 # Return true, because t has the same structure and node values with a subtree of s. @@ -64,5 +64,5 @@ def preOrderTraverse(s, t): (isSame(s, t) or \ preOrderTraverse(s.left, t) or \ preOrderTraverse(s.right, t)) - + return preOrderTraverse(s, t) diff --git a/Python/sudoku-solver.py b/Python/sudoku-solver.py index fff654616..39835b421 100644 --- a/Python/sudoku-solver.py +++ b/Python/sudoku-solver.py @@ -2,9 +2,9 @@ # Space: (1) # # Write a program to solve a Sudoku puzzle by filling the empty cells. -# +# # Empty cells are indicated by the character '.'. -# +# # You may assume that there will be only one unique solution. # @@ -29,7 +29,7 @@ def isValid(board, x, y): j += 1 i += 1 return True - + def solver(board): for i in xrange(len(board)): for j in xrange(len(board[0])): diff --git a/Python/sum-of-left-leaves.py b/Python/sum-of-left-leaves.py index 4ca0bd5c0..fb0787415 100644 --- a/Python/sum-of-left-leaves.py +++ b/Python/sum-of-left-leaves.py @@ -34,5 +34,5 @@ def sumOfLeftLeavesHelper(root, is_left): return root.val if is_left else 0 return sumOfLeftLeavesHelper(root.left, True) + \ sumOfLeftLeavesHelper(root.right, False) - + return sumOfLeftLeavesHelper(root, False) diff --git a/Python/sum-root-to-leaf-numbers.py b/Python/sum-root-to-leaf-numbers.py index 775c1920b..faad48bff 100644 --- a/Python/sum-root-to-leaf-numbers.py +++ b/Python/sum-root-to-leaf-numbers.py @@ -2,19 +2,19 @@ # 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. -# +# # An example is the root-to-leaf path 1->2->3 which represents the number 123. -# +# # Find the total sum of all root-to-leaf numbers. -# +# # For example, -# +# # 1 # / \ # 2 3 # The root-to-leaf path 1->2 represents the number 12. # The root-to-leaf path 1->3 represents the number 13. -# +# # Return the sum = 12 + 13 = 25. # @@ -30,18 +30,18 @@ class Solution: # @return an integer def sumNumbers(self, root): return self.sumNumbersRecu(root, 0) - + def sumNumbersRecu(self, root, num): if root is None: return 0 - + if root.left is None and root.right is None: return num * 10 + root.val - + return self.sumNumbersRecu(root.left, num * 10 + root.val) + self.sumNumbersRecu(root.right, num * 10 + root.val) if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) - print Solution().sumNumbers(root) + print Solution().sumNumbers(root) diff --git a/Python/super-washing-machines.py b/Python/super-washing-machines.py index 1db926366..202cba8db 100644 --- a/Python/super-washing-machines.py +++ b/Python/super-washing-machines.py @@ -20,27 +20,27 @@ # # Output: 3 # -# Explanation: +# Explanation: # 1st move: 1 0 <-- 5 => 1 1 4 -# 2nd move: 1 <-- 1 <-- 4 => 2 1 3 -# 3rd move: 2 1 <-- 3 => 2 2 2 +# 2nd move: 1 <-- 1 <-- 4 => 2 1 3 +# 3rd move: 2 1 <-- 3 => 2 2 2 # Example2 # # Input: [0,3,0] # # Output: 2 # -# Explanation: -# 1st move: 0 <-- 3 0 => 1 2 0 -# 2nd move: 1 2 --> 0 => 1 1 1 +# Explanation: +# 1st move: 0 <-- 3 0 => 1 2 0 +# 2nd move: 1 2 --> 0 => 1 1 1 # Example3 # # Input: [0,2,0] # # Output: -1 # -# Explanation: -# It's impossible to make all the three washing machines have the same number of dresses. +# Explanation: +# It's impossible to make all the three washing machines have the same number of dresses. # Note: # The range of n is [1, 10000]. # The range of dresses number in a super washing machine is [0, 1e5]. @@ -54,7 +54,7 @@ def findMinMoves(self, machines): total = sum(machines) if total % len(machines): return -1 - result, target, curr = 0, total / len(machines), 0 + result, target, curr = 0, total / len(machines), 0 for n in machines: curr += n - target result = max(result, max(n - target, abs(curr))) diff --git a/Python/swap-nodes-in-pairs.py b/Python/swap-nodes-in-pairs.py index c11df1225..91c039f8f 100644 --- a/Python/swap-nodes-in-pairs.py +++ b/Python/swap-nodes-in-pairs.py @@ -2,10 +2,10 @@ # Space: O(1) # # Given a linked list, swap every two adjacent nodes and return its head. -# +# # For example, # Given 1->2->3->4, you should return the list as 2->1->4->3. -# +# # Your algorithm should use only constant space. # You may not modify the values in the list, only nodes itself can be changed. # @@ -15,7 +15,7 @@ class ListNode: def __init__(self, x): self.val = x self.next = None - + def __repr__(self): if self: return "{} -> {}".format(self.val, self.next) @@ -39,4 +39,3 @@ def swapPairs(self, head): head = ListNode(1) head.next, head.next.next, head.next.next.next = ListNode(2), ListNode(3), ListNode(4) print Solution().swapPairs(head) - \ No newline at end of file diff --git a/Python/swim-in-rising-water.py b/Python/swim-in-rising-water.py index 0418afd34..f2034acac 100644 --- a/Python/swim-in-rising-water.py +++ b/Python/swim-in-rising-water.py @@ -54,7 +54,7 @@ def union_set(self, x, y): return False self.set[min(x_root, y_root)] = max(x_root, y_root) return True - + class Solution(object): def swimInWater(self, grid): @@ -68,7 +68,7 @@ def swimInWater(self, grid): for j in xrange(n): positions[grid[i][j]] = (i, j) directions = ((-1, 0), (1, 0), (0, -1), (0, 1)) - + union_find = UnionFind(n**2) for elevation in xrange(n**2): i, j = positions[elevation] @@ -79,4 +79,4 @@ def swimInWater(self, grid): if union_find.find_set(0) == union_find.find_set(n**2-1): return elevation return n**2-1 - + diff --git a/Python/symmetric-tree.py b/Python/symmetric-tree.py index 709864217..3bc99e50b 100644 --- a/Python/symmetric-tree.py +++ b/Python/symmetric-tree.py @@ -1,9 +1,9 @@ # Time: O(n) # 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: -# +# # 1 # / \ # 2 2 @@ -36,24 +36,24 @@ def isSymmetric(self, root): stack = [] stack.append(root.left) stack.append(root.right) - + while stack: p, q = stack.pop(), stack.pop() - + if p is None and q is None: continue - + if p is None or q is None or p.val != q.val: return False - + stack.append(p.left) stack.append(q.right) - + stack.append(p.right) stack.append(q.left) - + return True - + # Recursive solution class Solution2: # @param root, a tree node @@ -61,9 +61,9 @@ class Solution2: def isSymmetric(self, root): if root is None: return True - + return self.isSymmetricRecu(root.left, root.right) - + def isSymmetricRecu(self, left, right): if left is None and right is None: return True @@ -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) - + diff --git a/Python/tag-validator.py b/Python/tag-validator.py index 25946efa0..7409ec413 100644 --- a/Python/tag-validator.py +++ b/Python/tag-validator.py @@ -10,7 +10,7 @@ # TAG_CONTENT. Among them, is the start tag, # and is the end tag. The TAG_NAME in start and end tags should be the same. # A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid. -# 3. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. +# 3. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. # Otherwise, the TAG_NAME is invalid. # 4. A valid TAG_CONTENT may contain other valid closed tags, # cdata and any characters (see note1) EXCEPT unmatched <, @@ -31,9 +31,9 @@ # Valid Code Examples: # Input: "

" # Output: True -# Explanation: -# The code is wrapped in a closed tag :
and
. -# The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. +# Explanation: +# The code is wrapped in a closed tag :
and
. +# The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. # Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, # it should be considered as plain text, not parsed as tag. # So TAG_CONTENT is valid, and then the code is valid. Thus return true. @@ -124,10 +124,10 @@ def validTag(s, i): if not tag: return False, i j = parseContent(s, j) - k = j + len(tag) + 2 + k = j + len(tag) + 2 if k >= len(s) or s[j:k+1] != "": return False, i return True, k+1 - + result, i = validTag(code, 0) return result and i == len(code) diff --git a/Python/teemo-attacking.py b/Python/teemo-attacking.py index 4ae1d8435..918242f76 100644 --- a/Python/teemo-attacking.py +++ b/Python/teemo-attacking.py @@ -11,18 +11,18 @@ # Example 1: # Input: [1,4], 2 # Output: 4 -# Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. -# This poisoned status will last 2 seconds until the end of time point 2. -# And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds. +# Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. +# This poisoned status will last 2 seconds until the end of time point 2. +# And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds. # So you finally need to output 4. # Example 2: # Input: [1,2], 2 # Output: 3 -# Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned. -# This poisoned status will last 2 seconds until the end of time point 2. -# However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status. +# Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned. +# This poisoned status will last 2 seconds until the end of time point 2. +# However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status. # Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, -# it will stop at the end of time point 3. +# it will stop at the end of time point 3. # So you finally need to output 3. # Note: # You may assume the length of given time series array won't exceed 10000. diff --git a/Python/ternary-expression-parser.py b/Python/ternary-expression-parser.py index f8928be3e..3f6e9b14b 100644 --- a/Python/ternary-expression-parser.py +++ b/Python/ternary-expression-parser.py @@ -17,7 +17,7 @@ def parseTernary(self, expression): first = stack.pop() stack.pop() # pop ':' second = stack.pop() - + if c == 'T': stack.append(first) else: @@ -25,5 +25,5 @@ def parseTernary(self, expression): else: stack.append(c) - + return str(stack[-1]) diff --git a/Python/text-justification.py b/Python/text-justification.py index b292c30f7..ccc5ab439 100644 --- a/Python/text-justification.py +++ b/Python/text-justification.py @@ -3,22 +3,22 @@ # # 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, +# +# 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. -# +# # 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."] # L: 16. -# +# # Return the formatted lines as: # [ # "This is an", diff --git a/Python/the-skyline-problem.py b/Python/the-skyline-problem.py index d7e17a89c..e032ac3e6 100644 --- a/Python/the-skyline-problem.py +++ b/Python/the-skyline-problem.py @@ -1,33 +1,33 @@ # 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 +# 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 +# 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 +# +# 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 +# +# 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 +# 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 +# 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], ...] # @@ -38,7 +38,7 @@ class Solution: # @return {integer[][]} def getSkyline(self, buildings): intervals = self.ComputeSkylineInInterval(buildings, 0, len(buildings)) - + res = [] last_end = -1 for interval in intervals: @@ -48,9 +48,9 @@ def getSkyline(self, buildings): 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: @@ -59,12 +59,12 @@ def ComputeSkylineInInterval(self, buildings, left_endpoint, right_endpoint): 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]) @@ -78,12 +78,12 @@ def MergeSkylines(self, left_skyline, right_skyline): 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]: diff --git a/Python/total-hamming-distance.py b/Python/total-hamming-distance.py index fac26b25b..411be8f44 100644 --- a/Python/total-hamming-distance.py +++ b/Python/total-hamming-distance.py @@ -31,4 +31,4 @@ def totalHammingDistance(self, nums): counts[(num >> i) & 1] += 1 result += counts[0] * counts[1] return result - + diff --git a/Python/trapping-rain-water-ii.py b/Python/trapping-rain-water-ii.py index 8a1037979..8408de5f1 100644 --- a/Python/trapping-rain-water-ii.py +++ b/Python/trapping-rain-water-ii.py @@ -34,7 +34,7 @@ def trapRainWater(self, heightMap): return 0 is_visited = [[False for i in xrange(n)] for j in xrange(m)] - + heap = [] for i in xrange(m): heappush(heap, [heightMap[i][0], i, 0]) diff --git a/Python/trapping-rain-water.py b/Python/trapping-rain-water.py index c2d030382..28a0a7e41 100644 --- a/Python/trapping-rain-water.py +++ b/Python/trapping-rain-water.py @@ -3,11 +3,11 @@ # # Given n non-negative integers representing an elevation map where the width of each bar is 1, # compute how much water it is able to trap after raining. -# -# For example, +# +# For example, # Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. -# -# The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. +# +# The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. # In this case, 6 units of rain water (blue section) are being trapped. # @@ -20,21 +20,21 @@ def trap(self, A): for i in xrange(len(A)): if A[top] < A[i]: top = i - + second_top = 0 for i in xrange(top): if A[second_top] < A[i]: second_top = i result += A[second_top] - A[i] - + second_top = len(A) - 1 for i in reversed(xrange(top, len(A))): if A[second_top] < A[i]: second_top = i result += A[second_top] - A[i] - + return result - + # Time: O(n) # Space: O(n) class Solution2: @@ -43,20 +43,20 @@ class Solution2: def trap(self, A): result = 0 stack = [] - + for i in xrange(len(A)): mid_height = 0 while stack: [pos, height] = stack.pop() result += (min(height, A[i]) - mid_height) * (i - pos - 1) mid_height = height - + if A[i] < height: stack.append([pos, height]) break stack.append([i, A[i]]) - + return result - + if __name__ == "__main__": print Solution().trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) diff --git a/Python/triangle.py b/Python/triangle.py index e05906104..7d2b541f6 100644 --- a/Python/triangle.py +++ b/Python/triangle.py @@ -2,7 +2,7 @@ # Space: O(n) # # Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. -# +# # For example, given the following triangle # [ # [2], @@ -11,7 +11,7 @@ # [4,1,8,3] # ] # The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). -# +# # Note: # Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. # @@ -22,7 +22,7 @@ class Solution: def minimumTotal(self, triangle): if not triangle: return 0 - + cur = triangle[0] + [float("inf")] for i in xrange(1, len(triangle)): next = [] @@ -30,9 +30,9 @@ def minimumTotal(self, triangle): for j in xrange(1, i + 1): next.append(triangle[i][j] + min(cur[j - 1], cur[j])) cur = next + [float("inf")] - + return reduce(min, cur) if __name__ == "__main__": print Solution().minimumTotal([[-1], [2, 3], [1, -1, -3]]) - + diff --git a/Python/trim-a-binary-search-tree.py b/Python/trim-a-binary-search-tree.py index 992b05378..e0f1c4c07 100644 --- a/Python/trim-a-binary-search-tree.py +++ b/Python/trim-a-binary-search-tree.py @@ -7,7 +7,7 @@ # return the new root of the trimmed binary search tree. # # Example 1: -# Input: +# Input: # 1 # / \ # 0 2 @@ -15,12 +15,12 @@ # L = 1 # R = 2 # -# Output: +# Output: # 1 # \ # 2 # Example 2: -# Input: +# Input: # 3 # / \ # 0 4 @@ -32,10 +32,10 @@ # L = 1 # R = 3 # -# Output: +# Output: # 3 -# / -# 2 +# / +# 2 # / # 1 @@ -62,4 +62,4 @@ def trimBST(self, root, L, R): return self.trimBST(root.left, L, R) root.left, root.right = self.trimBST(root.left, L, R), self.trimBST(root.right, L, R) return root - + diff --git a/Python/two-sum-ii-input-array-is-sorted.py b/Python/two-sum-ii-input-array-is-sorted.py index 247af6397..8ac26f965 100644 --- a/Python/two-sum-ii-input-array-is-sorted.py +++ b/Python/two-sum-ii-input-array-is-sorted.py @@ -1,15 +1,15 @@ # Time: O(n) # Space: O(1) # -# Given an array of integers that is already sorted in ascending order, +# Given an array of integers that is already sorted in ascending order, # find two numbers such that they add up to a specific target number. -# -# The function twoSum should return indices of the two numbers such that -# they add up to the target, where index1 must be less than index2. +# +# The function twoSum should return indices of the two numbers such that +# they add up to the target, where index1 must be less than index2. # Please note that your returned answers (both index1 and index2) are not zero-based. -# +# # You may assume that each input would have exactly one solution. -# +# # Input: numbers={2, 7, 11, 15}, target=9 # Output: index1=1, index2=2 # @@ -17,7 +17,7 @@ class Solution: def twoSum(self, nums, target): start, end = 0, len(nums) - 1 - + while start != end: sum = nums[start] + nums[end] if sum > target: diff --git a/Python/two-sum-iii-data-structure-design.py b/Python/two-sum-iii-data-structure-design.py index 808c80d91..05bf1c555 100644 --- a/Python/two-sum-iii-data-structure-design.py +++ b/Python/two-sum-iii-data-structure-design.py @@ -2,10 +2,10 @@ # Space: O(n) # Design and implement a TwoSum class. It should support the following operations: add and find. -# +# # add - Add the number to an internal data structure. # find - Find if there exists any pair of numbers which sum is equal to the value. -# +# # For example, # add(1); add(3); add(5); # find(4) -> true @@ -20,7 +20,7 @@ def __init__(self): initialize your data structure here """ self.lookup = defaultdict(int) - + def add(self, number): @@ -46,10 +46,10 @@ def find(self, value): if __name__ == "__main__": Sol = TwoSum() - + for i in (1, 3, 5): Sol.add(i) - + for i in (4, 7): print Sol.find(i) - + diff --git a/Python/two-sum-iv-input-is-a-bst.py b/Python/two-sum-iv-input-is-a-bst.py index e55b985bc..47a3b44d7 100644 --- a/Python/two-sum-iv-input-is-a-bst.py +++ b/Python/two-sum-iv-input-is-a-bst.py @@ -5,7 +5,7 @@ # return true if there exist two elements in the BST such that their sum is equal to the given target. # # Example 1: -# Input: +# Input: # 5 # / \ # 3 6 @@ -16,7 +16,7 @@ # # Output: True # Example 2: -# Input: +# Input: # 5 # / \ # 3 6 @@ -51,7 +51,7 @@ def __init__(self, root, forward): def val(self): return self.__cur - + def next(self): while self.__node or self.__s: if self.__node: diff --git a/Python/unique-binary-search-trees-ii.py b/Python/unique-binary-search-trees-ii.py index 1c7fee7ff..1b031830e 100644 --- a/Python/unique-binary-search-trees-ii.py +++ b/Python/unique-binary-search-trees-ii.py @@ -2,10 +2,10 @@ # Space: O(4^n / n^(3/2)) ~= Catalan numbers # # Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. -# +# # For example, # Given n = 3, your program should return all 5 unique BST's shown below. -# +# # 1 3 3 2 1 # \ / / / \ \ # 3 2 1 1 3 2 @@ -19,7 +19,7 @@ def __init__(self, x): self.val = x self.left = None self.right = None - + def __repr__(self): if self: serial = [] @@ -27,21 +27,21 @@ def __repr__(self): while queue: cur = queue[0] - + if cur: serial.append(cur.val) queue.append(cur.left) queue.append(cur.right) else: serial.append("#") - + queue = queue[1:] - + while serial[-1] == "#": serial.pop() - + return repr(serial) - + else: return None @@ -49,7 +49,7 @@ class Solution: # @return a list of tree node def generateTrees(self, n): return self.generateTreesRecu(1, n) - + def generateTreesRecu(self, low, high): result = [] if low > high: diff --git a/Python/unique-binary-search-trees.py b/Python/unique-binary-search-trees.py index e5debe1eb..61d446f51 100644 --- a/Python/unique-binary-search-trees.py +++ b/Python/unique-binary-search-trees.py @@ -2,10 +2,10 @@ # Space: O(1) # # Given n, how many structurally unique BST's (binary search trees) that store values 1...n? -# +# # For example, # Given n = 3, there are a total of 5 unique BST's. -# +# # 1 3 3 2 1 # \ / / / \ \ # 3 2 1 1 3 2 @@ -45,6 +45,6 @@ def numTrees(self, n): count += counts[j] * counts[i - j - 1] counts.append(count) return counts[-1] - + if __name__ == "__main__": print Solution().numTrees(3) diff --git a/Python/unique-morse-code-words.py b/Python/unique-morse-code-words.py index 3b43a876b..8729470dd 100644 --- a/Python/unique-morse-code-words.py +++ b/Python/unique-morse-code-words.py @@ -21,7 +21,7 @@ # Example: # Input: words = ["gin", "zen", "gig", "msg"] # Output: 2 -# Explanation: +# Explanation: # The transformation of each word is: # "gin" -> "--...-." # "zen" -> "--...-." diff --git a/Python/unique-paths-ii.py b/Python/unique-paths-ii.py index ee53e127e..bbe3507b1 100644 --- a/Python/unique-paths-ii.py +++ b/Python/unique-paths-ii.py @@ -2,21 +2,21 @@ # Space: O(m + n) # # Follow up for "Unique Paths": -# +# # Now consider if some obstacles are added to the grids. How many unique paths would there be? -# +# # An obstacle and empty space is marked as 1 and 0 respectively in the grid. -# +# # For example, # There is one obstacle in the middle of a 3x3 grid as illustrated below. -# +# # [ # [0,0,0], # [0,1,0], # [0,0,0] # ] # The total number of unique paths is 2. -# +# # Note: m and n will be at most 100. # @@ -29,7 +29,7 @@ def uniquePathsWithObstacles(self, obstacleGrid): :rtype: int """ m, n = len(obstacleGrid), len(obstacleGrid[0]) - + ways = [0]*n ways[0] = 1 for i in xrange(m): diff --git a/Python/unique-paths.py b/Python/unique-paths.py index c4f234a76..5bfaefa32 100644 --- a/Python/unique-paths.py +++ b/Python/unique-paths.py @@ -2,12 +2,12 @@ # Space: O(m + n) # # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). -# +# # The robot can only move either down or right at any point in time. # The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). -# +# # How many possible unique paths are there? -# +# # Note: m and n will be at most 100. # @@ -17,13 +17,12 @@ def uniquePaths(self, m, n): if m < n: return self.uniquePaths(n, m) ways = [1] * n - + for i in xrange(1, m): for j in xrange(1, n): ways[j] += ways[j - 1] - + return ways[n - 1] if __name__ == "__main__": print Solution().uniquePaths(1, 2) - \ No newline at end of file diff --git a/Python/valid-number.py b/Python/valid-number.py index 75773c0df..047584ba4 100644 --- a/Python/valid-number.py +++ b/Python/valid-number.py @@ -2,7 +2,7 @@ # Space: O(1) # # Validate if a given string is numeric. -# +# # Some examples: # "0" => true # " 0.1 " => true @@ -39,7 +39,7 @@ def isNumber(self, s): [-1, -1, -1, 7, -1, -1], # next states for state 6 [-1, 8, -1, 7, -1, -1], # next states for state 7 [-1, 8, -1, -1, -1, -1]] # next states for state 8 - + state = 0 for char in s: inputType = InputType.INVALID @@ -53,12 +53,12 @@ def isNumber(self, s): inputType = InputType.DOT elif char == 'e' or char == 'E': inputType = InputType.EXPONENT; - + state = transition_table[state][inputType]; - + if state == -1: return False; - + return state == 1 or state == 4 or state == 7 or state == 8 @@ -77,4 +77,4 @@ def isNumber(self, s): print Solution().isNumber("abc") print Solution().isNumber("1 a") print Solution().isNumber("2e10") - + diff --git a/Python/valid-palindrome-ii.py b/Python/valid-palindrome-ii.py index 5e814ca31..3cb4d2d00 100644 --- a/Python/valid-palindrome-ii.py +++ b/Python/valid-palindrome-ii.py @@ -26,7 +26,7 @@ def validPalindrome(s, left, right): return False left, right = left+1, right-1 return True - + left, right = 0, len(s)-1 while left < right: if s[left] != s[right]: diff --git a/Python/valid-palindrome.py b/Python/valid-palindrome.py index c0c562059..fbbcf7f0f 100644 --- a/Python/valid-palindrome.py +++ b/Python/valid-palindrome.py @@ -2,14 +2,14 @@ # Space: O(1) # # Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. -# +# # For example, # "A man, a plan, a canal: Panama" is a palindrome. # "race a car" is not a palindrome. -# +# # Note: # Have you consider that the string might be empty? This is a good question to ask during an interview. -# +# # For the purpose of this problem, we define empty string as valid palindrome. # diff --git a/Python/valid-parentheses.py b/Python/valid-parentheses.py index d62ef17e2..3d9d03781 100644 --- a/Python/valid-parentheses.py +++ b/Python/valid-parentheses.py @@ -3,8 +3,8 @@ # # Given a string containing just the characters '(', ')', '{', '}', '[' and ']', # determine if the input string is valid. -# -# The brackets must close in the correct order, "()" and "()[]{}" +# +# The brackets must close in the correct order, "()" and "()[]{}" # are all valid but "(]" and "([)]" are not. # @@ -18,7 +18,7 @@ def isValid(self, s): elif len(stack) == 0 or lookup[stack.pop()] != parenthese: return False return len(stack) == 0 - + if __name__ == "__main__": print Solution().isValid("()[]{}") print Solution().isValid("()[{]}") \ No newline at end of file diff --git a/Python/valid-sudoku.py b/Python/valid-sudoku.py index 610964276..24f9feb39 100644 --- a/Python/valid-sudoku.py +++ b/Python/valid-sudoku.py @@ -1,10 +1,10 @@ # Time: O(9^2) # Space: O(9) -# Determine if a Sudoku is valid, +# Determine if a Sudoku is valid, # according to: Sudoku Puzzles - The Rules. # -# The Sudoku board could be partially filled, +# The Sudoku board could be partially filled, # where empty cells are filled with the character '.'. # # A partially filled sudoku which is valid. @@ -29,7 +29,7 @@ def isValidSudoku(self, board): for m in xrange(3 * i, 3 * i + 3)]): return False return True - + def isValidList(self, xs): xs = filter(lambda x: x != '.', xs) return len(set(xs)) == len(xs) diff --git a/Python/valid-tic-tac-toe-state.py b/Python/valid-tic-tac-toe-state.py index a8df880cb..7d11d867d 100644 --- a/Python/valid-tic-tac-toe-state.py +++ b/Python/valid-tic-tac-toe-state.py @@ -5,7 +5,7 @@ # if and only if it is possible to reach this board position # during the course of a valid tic-tac-toe game. # -# The board is a 3 x 3 array, and consists of characters " ", "X", +# The board is a 3 x 3 array, and consists of characters " ", "X", # and "O". The " " character represents an empty square. # # Here are the rules of Tic-Tac-Toe: @@ -53,7 +53,7 @@ def win(board, player): return (player == board[1][1] == board[0][0] == board[2][2] or \ player == board[1][1] == board[0][2] == board[2][0]) - + FIRST, SECOND = ('X', 'O') x_count = sum(row.count(FIRST) for row in board) o_count = sum(row.count(SECOND) for row in board) diff --git a/Python/valid-triangle-number.py b/Python/valid-triangle-number.py index 6e1dbbe04..573a27fb2 100644 --- a/Python/valid-triangle-number.py +++ b/Python/valid-triangle-number.py @@ -10,7 +10,7 @@ # Input: [2,2,3,4] # Output: 3 # Explanation: -# Valid combinations are: +# Valid combinations are: # 2,3,4 (using the first 2) # 2,3,4 (using the second 2) # 2,2,3 diff --git a/Python/validate-binary-search-tree.py b/Python/validate-binary-search-tree.py index 8425ef443..d37799d21 100644 --- a/Python/validate-binary-search-tree.py +++ b/Python/validate-binary-search-tree.py @@ -1,10 +1,10 @@ # Time: O(n) # Space: O(1) -# +# # Given a binary tree, determine if it is a valid binary search tree (BST). -# +# # Assume a BST is defined as follows: -# +# # The left subtree of a node contains only nodes with keys less than the node's key. # The right subtree of a node contains only nodes with keys greater than the node's key. # Both the left and right subtrees must also be binary search trees. @@ -33,7 +33,7 @@ def isValidBST(self, root): node = cur.left while node.right and node.right != cur: node = node.right - + if node.right is None: node.right = cur cur = cur.left @@ -43,7 +43,7 @@ def isValidBST(self, root): node.right = None prev = cur cur = cur.right - + return True @@ -54,16 +54,16 @@ class Solution2: # @return a boolean def isValidBST(self, root): return self.isValidBSTRecu(root, float("-inf"), float("inf")) - + def isValidBSTRecu(self, root, low, high): if root is None: return True - + return low < root.val and root.val < high \ and self.isValidBSTRecu(root.left, low, root.val) \ and self.isValidBSTRecu(root.right, root.val, high) - + if __name__ == "__main__": root = TreeNode(2) root.left = TreeNode(1) diff --git a/Python/verify-preorder-serialization-of-a-binary-tree.py b/Python/verify-preorder-serialization-of-a-binary-tree.py index ee7d23f75..c084b07ca 100644 --- a/Python/verify-preorder-serialization-of-a-binary-tree.py +++ b/Python/verify-preorder-serialization-of-a-binary-tree.py @@ -2,7 +2,7 @@ # 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. +# 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_ @@ -15,8 +15,8 @@ # 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. +# 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 diff --git a/Python/walls-and-gates.py b/Python/walls-and-gates.py index c3113ffd2..7d287cfcc 100644 --- a/Python/walls-and-gates.py +++ b/Python/walls-and-gates.py @@ -18,4 +18,4 @@ def wallsAndGates(self, rooms): rooms[I][J] == INF: rooms[I][J] = rooms[i][j] + 1 q.append((I, J)) - + diff --git a/Python/water-and-jug-problem.py b/Python/water-and-jug-problem.py index b6dcfe954..df6f3601d 100644 --- a/Python/water-and-jug-problem.py +++ b/Python/water-and-jug-problem.py @@ -22,7 +22,7 @@ # Input: x = 2, y = 6, z = 5 # Output: False -# Bézout's identity (also called Bézout's lemma) +# Bézout's identity (also called Bézout's lemma) class Solution(object): def canMeasureWater(self, x, y, z): """ @@ -35,7 +35,7 @@ def gcd(a, b): while b: a, b = b, a%b return a - + # The problem is to solve: # - check z <= x + y # - check if there is any (a, b) integers s.t. ax + by = z diff --git a/Python/wiggle-sort-ii.py b/Python/wiggle-sort-ii.py index 15b625f07..58efd5258 100644 --- a/Python/wiggle-sort-ii.py +++ b/Python/wiggle-sort-ii.py @@ -4,7 +4,7 @@ # 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]. +# (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: @@ -45,7 +45,7 @@ def findKthLargest(nums, k): 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 diff --git a/Python/wiggle-subsequence.py b/Python/wiggle-subsequence.py index 3336a9338..abb8e6148 100644 --- a/Python/wiggle-subsequence.py +++ b/Python/wiggle-subsequence.py @@ -9,7 +9,7 @@ # is trivially a wiggle sequence. # # For example, [1,7,4,9,2,5] is a wiggle sequence because -# the differences (6,-3,5,-7,3) are alternately positive +# the differences (6,-3,5,-7,3) are alternately positive # and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are # not wiggle sequences, the first because its first two differences # are positive and the second because its last difference is zero. @@ -17,7 +17,7 @@ # Given a sequence of integers, return the length of # the longest subsequence that is a wiggle sequence. # A subsequence is obtained by deleting some number of elements -# (eventually, also zero) from the original sequence, leaving +# (eventually, also zero) from the original sequence, leaving # the remaining elements in their original order. # # Examples: diff --git a/Python/wildcard-matching.py b/Python/wildcard-matching.py index 7965368aa..f98db3e20 100644 --- a/Python/wildcard-matching.py +++ b/Python/wildcard-matching.py @@ -2,15 +2,15 @@ # Space: O(1) # # Implement wildcard pattern matching with support for '?' and '*'. -# +# # '?' Matches any single character. # '*' Matches any sequence of characters (including the empty sequence). -# +# # The matching should cover the entire input string (not partial). -# +# # The function prototype should be: # bool isMatch(const char *s, const char *p) -# +# # Some examples: # isMatch("aa","a") -> false # isMatch("aa","aa") -> true @@ -42,12 +42,12 @@ def isMatch(self, s, p): p_ptr = last_p_ptr else: return False - + while p_ptr < len(p) and p[p_ptr] == '*': p_ptr += 1 - + return p_ptr == len(p) - + # dp with rolling window # Time: O(m * n) # Space: O(m + n) @@ -68,7 +68,7 @@ def isMatch(self, s, p): 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-1] or result[(i-1) % k][j] - + return result[len(s) % k][len(p)] # dp @@ -90,7 +90,7 @@ def isMatch(self, s, p): 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-1] or result[i-1][j] - + return result[len(s)][len(p)] @@ -100,7 +100,7 @@ class Solution4: def isMatch(self, s, p): if not p or not s: return not s and not p - + if p[0] != '*': if p[0] == s[0] or p[0] == '?': return self.isMatch(s[1:], p[1:]) diff --git a/Python/word-break-ii.py b/Python/word-break-ii.py index 7dcb65c6d..e23c7ec25 100644 --- a/Python/word-break-ii.py +++ b/Python/word-break-ii.py @@ -1,16 +1,16 @@ -# Time: O(n * l^2 + n * r), l is the max length of the words, +# Time: O(n * l^2 + n * r), l is the max length of the words, # r is the number of the results. # Space: O(n^2) # -# Given a string s and a dictionary of words dict, +# Given a string s and a dictionary of words dict, # add spaces in s to construct a sentence where each word is a valid dictionary word. -# +# # Return all such possible sentences. -# +# # For example, given # s = "catsanddog", # dict = ["cat", "cats", "and", "sand", "dog"]. -# +# # A solution is ["cats and dog", "cat sand dog"]. # @@ -40,7 +40,7 @@ def wordBreak(self, s, wordDict): if can_break[-1]: self.wordBreakHelper(s, valid, 0, [], result) return result - + def wordBreakHelper(self, s, valid, start, path, result): if start == len(s): result.append(" ".join(path)) diff --git a/Python/word-break.py b/Python/word-break.py index e64e5631e..5955525de 100644 --- a/Python/word-break.py +++ b/Python/word-break.py @@ -1,13 +1,13 @@ # Time: O(n * l^2) # Space: O(n) -# Given a string s and a dictionary of words dict, +# Given a string s and a dictionary of words dict, # determine if s can be segmented into a space-separated sequence of one or more dictionary words. -# +# # For example, given # s = "leetcode", # dict = ["leet", "code"]. -# +# # Return true because "leetcode" can be segmented as "leet code". class Solution(object): @@ -33,6 +33,6 @@ def wordBreak(self, s, wordDict): return can_break[-1] - + if __name__ == "__main__": print Solution().wordBreak("leetcode", ["leet", "code"]) diff --git a/Python/word-ladder-ii.py b/Python/word-ladder-ii.py index b7ffb1180..7edc61b1c 100644 --- a/Python/word-ladder-ii.py +++ b/Python/word-ladder-ii.py @@ -2,11 +2,11 @@ # Space: O(d) # # Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: -# +# # Only one letter can be changed at a time # Each intermediate word must exist in the dictionary # For example, -# +# # Given: # start = "hit" # end = "cog" @@ -30,13 +30,13 @@ class Solution: def findLadders(self, start, end, dict): dict.add(start) dict.add(end) - - result, cur, visited, found, trace = [], [start], set([start]), False, {word: [] for word in dict} + + result, cur, visited, found, trace = [], [start], set([start]), False, {word: [] for word in dict} while cur and not found: for word in cur: visited.add(word) - + next = set() for word in cur: for i in xrange(len(word)): @@ -48,18 +48,18 @@ def findLadders(self, start, end, dict): next.add(candidate) trace[candidate].append(word) cur = next - + if found: self.backtrack(result, trace, [], end) - + return result - + def backtrack(self, result, trace, path, word): if not trace[word]: result.append([word] + path) else: for prev in trace[word]: self.backtrack(result, trace, [word] + path, prev) - + if __name__ == "__main__": print Solution().findLadders("hit", "cog", set(["hot","dot","dog","lot","log"])) diff --git a/Python/word-ladder.py b/Python/word-ladder.py index 3a97d25a8..ff2b0cb70 100644 --- a/Python/word-ladder.py +++ b/Python/word-ladder.py @@ -2,18 +2,18 @@ # 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: -# +# # Only one letter can be changed at a time # Each intermediate word must exist in the dictionary # For example, -# +# # Given: # start = "hit" # end = "cog" # dict = ["hot","dot","dog","lot","log"] # As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", # return its length 5. -# +# # Note: # Return 0 if there is no such transformation sequence. # All words have the same length. diff --git a/Python/word-pattern-ii.py b/Python/word-pattern-ii.py index 2d12cd67c..774795858 100644 --- a/Python/word-pattern-ii.py +++ b/Python/word-pattern-ii.py @@ -1,7 +1,7 @@ # 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) +# Space: O(n + c) class Solution(object): def wordPatternMatch(self, pattern, str): diff --git a/Python/word-pattern.py b/Python/word-pattern.py index 7bace4ebd..ef0db71b9 100644 --- a/Python/word-pattern.py +++ b/Python/word-pattern.py @@ -32,12 +32,12 @@ def wordPattern(self, pattern, str): if w not in w2p and p not in p2w: # Build mapping. Space: O(c) w2p[w] = p - p2w[p] = w + 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: @@ -75,7 +75,7 @@ def wordPattern(self, pattern, str): if w not in w2p and p not in p2w: # Build mapping. Space: O(c) w2p[w] = p - p2w[p] = w + p2w[p] = w elif w not in w2p or w2p[w] != p: # Contradict mapping. return False diff --git a/Python/word-search-ii.py b/Python/word-search-ii.py index 4c6acdaac..c317e6b2d 100644 --- a/Python/word-search-ii.py +++ b/Python/word-search-ii.py @@ -3,7 +3,7 @@ # # 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 +# 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, @@ -48,30 +48,30 @@ def findWords(self, board, words): trie = TrieNode() for word in words: trie.insert(word) - + for i in xrange(len(board)): for j in xrange(len(board[0])): if self.findWordsRecu(board, trie, 0, i, j, visited, [], result): return True - + return result.keys() - + 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.leaves: return - + cur_word.append(board[i][j]) next_node = trie.leaves[board[i][j]] if next_node.is_string: result["".join(cur_word)] = True - + visited[i][j] = True 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) + self.findWordsRecu(board, next_node, cur + 1, i, j - 1, visited, cur_word, result) visited[i][j] = False cur_word.pop() diff --git a/Python/word-search.py b/Python/word-search.py index 3166d0b00..719540086 100644 --- a/Python/word-search.py +++ b/Python/word-search.py @@ -2,14 +2,14 @@ # Space: O(l) # # Given a 2D board and a word, find if the word exists in the grid. -# -# The word can be constructed from letters of sequentially adjacent cell, -# where "adjacent" cells are those horizontally or vertically neighboring. +# +# The word can 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. -# +# # For example, # Given board = -# +# # [ # "ABCE", # "SFCS", @@ -26,30 +26,30 @@ class Solution: # @return a boolean def exist(self, board, word): visited = [[False for j in xrange(len(board[0]))] for i in xrange(len(board))] - + for i in xrange(len(board)): for j in xrange(len(board[0])): if self.existRecu(board, word, 0, i, j, visited): return True - + return False - + def existRecu(self, board, word, cur, i, j, visited): if cur == len(word): return True - + if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or visited[i][j] or board[i][j] != word[cur]: return False - + visited[i][j] = True result = self.existRecu(board, word, cur + 1, i + 1, j, visited) or\ self.existRecu(board, word, cur + 1, i - 1, j, visited) or\ self.existRecu(board, word, cur + 1, i, j + 1, visited) or\ - self.existRecu(board, word, cur + 1, i, j - 1, visited) + self.existRecu(board, word, cur + 1, i, j - 1, visited) visited[i][j] = False - + return result - + if __name__ == "__main__": board = [ "ABCE", diff --git a/Python/word-squares.py b/Python/word-squares.py index 59d69b9e6..21d6bbf43 100644 --- a/Python/word-squares.py +++ b/Python/word-squares.py @@ -34,11 +34,11 @@ def wordSquares(self, words): curr.pop() return result - + def wordSquaresHelper(self, words, trie, curr, result): if len(curr) >= len(words[0]): return result.append(list(curr)) - + node = trie for s in curr: node = node.children[ord(s[len(curr)]) - ord('a')] diff --git a/Python/zigzag-conversion.py b/Python/zigzag-conversion.py index f5381a1b5..5a1d04cee 100644 --- a/Python/zigzag-conversion.py +++ b/Python/zigzag-conversion.py @@ -1,15 +1,15 @@ # Time: O(n) # Space: O(1) # -# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: +# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: # (you may want to display this pattern in a fixed font for better legibility) -# +# # P A H N # A P L S I I G # Y I R # And then read line by line: "PAHNAPLSIIGYIR" # Write the code that will take a string and make this conversion given a number of rows: -# +# # string convert(string text, int nRows); # convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". # From adbdf8e5d2ce64085794fc67b0b4dd38b600896a Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 21 Apr 2018 23:14:41 +0800 Subject: [PATCH 4640/4971] Fix flake8 related issues --- Python/basic-calculator-ii.py | 11 +++++- Python/basic-calculator-iii.py | 12 ++++-- Python/basic-calculator-iv.py | 37 ++++++++++++------- Python/basic-calculator.py | 8 +++- Python/battleships-in-a-board.py | 20 +++++++--- Python/beautiful-arrangement-ii.py | 15 +++++--- Python/beautiful-arrangement.py | 22 +++++++---- Python/best-meeting-point.py | 16 ++++++-- Python/best-time-to-buy-and-sell-stock-ii.py | 13 ++++--- Python/best-time-to-buy-and-sell-stock-iii.py | 34 ++++++++++------- Python/best-time-to-buy-and-sell-stock-iv.py | 20 ++++++---- ...ime-to-buy-and-sell-stock-with-cooldown.py | 15 ++++++-- ...buy-and-sell-stock-with-transaction-fee.py | 7 +++- Python/best-time-to-buy-and-sell-stock.py | 8 +--- Python/binary-number-with-alternating-bits.py | 4 +- Python/binary-search-tree-iterator.py | 16 ++------ Python/binary-tree-inorder-traversal.py | 11 +----- .../binary-tree-level-order-traversal-ii.py | 14 ++----- Python/binary-tree-level-order-traversal.py | 16 +++----- ...ry-tree-longest-consecutive-sequence-ii.py | 2 +- ...inary-tree-longest-consecutive-sequence.py | 3 +- Python/binary-tree-maximum-path-sum.py | 15 +++----- Python/binary-tree-paths.py | 3 +- Python/binary-tree-postorder-traversal.py | 11 +----- Python/binary-tree-preorder-traversal.py | 11 +----- Python/binary-tree-right-side-view.py | 18 +++------ Python/binary-tree-tilt.py | 3 +- Python/binary-tree-upside-down.py | 19 ++++++---- .../binary-tree-vertical-order-traversal.py | 9 ++++- ...inary-tree-zigzag-level-order-traversal.py | 20 ++++------ Python/binary-watch.py | 26 +++++++++---- Python/bitwise-and-of-numbers-range.py | 11 +++--- Python/bold-words-in-string.py | 12 ++++-- Python/bomb-enemy.py | 9 ++++- Python/boundary-of-binary-tree.py | 1 + Python/brick-wall.py | 25 +++++++++---- Python/bricks-falling-when-hit.py | 27 +++++++++----- Python/bulb-switcher-ii.py | 28 +++++++++----- Python/bulls-and-cows.py | 8 ++-- Python/burst-balloons.py | 15 ++++++-- 40 files changed, 336 insertions(+), 239 deletions(-) diff --git a/Python/basic-calculator-ii.py b/Python/basic-calculator-ii.py index 03df2953e..57dca8ff5 100644 --- a/Python/basic-calculator-ii.py +++ b/Python/basic-calculator-ii.py @@ -4,7 +4,8 @@ # 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. +# operators and empty spaces . The integer division should truncate toward +# zero. # # You may assume that the given expression is always valid. # @@ -15,6 +16,12 @@ # Note: Do not use the eval built-in library function. # +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution: # @param {string} s # @return {integer} @@ -24,7 +31,7 @@ def calculate(self, s): for i in reversed(xrange(len(s))): if s[i].isdigit(): operand += s[i] - if i == 0 or not s[i-1].isdigit(): + if i == 0 or not s[i-1].isdigit(): operands.append(int(operand[::-1])) operand = "" elif s[i] == ')' or s[i] == '*' or s[i] == '/': diff --git a/Python/basic-calculator-iii.py b/Python/basic-calculator-iii.py index 04568b2cf..43c67b25a 100644 --- a/Python/basic-calculator-iii.py +++ b/Python/basic-calculator-iii.py @@ -6,7 +6,8 @@ # The expression string may contain open ( and closing parentheses ), # the plus + or minus sign -, non-negative integers and empty spaces . # -# The expression string contains only non-negative integers, +, -, *, / operators , +# The expression string contains only non-negative integers, +, -, *, / +# operators , # open ( and closing parentheses ) and empty spaces . # The integer division should truncate toward zero. # @@ -21,6 +22,12 @@ # # Note: Do not use the eval built-in library function. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def calculate(self, s): """ @@ -32,7 +39,7 @@ def calculate(self, s): for i in reversed(xrange(len(s))): if s[i].isdigit(): operand += s[i] - if i == 0 or not s[i-1].isdigit(): + if i == 0 or not s[i-1].isdigit(): operands.append(int(operand[::-1])) operand = "" elif s[i] == ')' or s[i] == '*' or s[i] == '/': @@ -63,4 +70,3 @@ def compute(self, operands, operators): operands.append(left * right) elif op == '/': operands.append(left / right) - diff --git a/Python/basic-calculator-iv.py b/Python/basic-calculator-iv.py index ddb15ab7c..e4238e5da 100644 --- a/Python/basic-calculator-iv.py +++ b/Python/basic-calculator-iv.py @@ -1,4 +1,5 @@ -# Time: +: O(d * t), t is the number of terms, d is the average degree of terms +# Time: +: O(d * t), t is the number of terms, +# d is the average degree of terms # -: O(d * t) # *: O(d * t^2) # eval: O(d * t) @@ -6,10 +7,14 @@ # Space: O(e + d * t), e is the number of evalvars # Given an expression such as expression = "e + 8 - a + 5" and -# an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), -# return a list of tokens representing the simplified expression, such as ["-1*a","14"] -# - An expression alternates chunks and symbols, with a space separating each chunk and symbol. -# - A chunk is either an expression in parentheses, a variable, or a non-negative integer. +# an evaluation map such as {"e": 1} +# (given in terms of evalvars = ["e"] and evalints = [1]), +# return a list of tokens representing the simplified expression, +# such as ["-1*a","14"] +# - An expression alternates chunks and symbols, +# with a space separating each chunk and symbol. +# - A chunk is either an expression in parentheses, a variable, +# or a non-negative integer. # - A variable is a string of lowercase letters (not including digits.) # Note that variables can be multiple letters, and note that variables never # have a leading coefficient or unary operator like "2x" or "-x". @@ -20,15 +25,19 @@ # # The format of the output is as follows: # - For each term of free variables with non-zero coefficient, -# we write the free variables within a term in sorted order lexicographically. +# we write the free variables within a term in sorted order +# lexicographically. # For example, we would never write a term like "b*a*c", only "a*b*c". # - Terms have degree equal to the number of free variables being multiplied, # counting multiplicity. (For example, "a*a*b*c" has degree 4.) # We write the largest degree terms of our answer first, -# breaking ties by lexicographic order ignoring the leading coefficient of the term. -# - The leading coefficient of the term is placed directly to the left with an asterisk separating it -# from the variables (if they exist.) A leading coefficient of 1 is still printed. -# - An example of a well formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] +# breaking ties by lexicographic order ignoring the leading coefficient of +# the term. +# - The leading coefficient of the term is placed directly to the left with an +# asterisk separating it from the variables (if they exist.) +# A leading coefficient of 1 is still printed. +# - An example of a well formatted answer is +# ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] # - Terms (including constant terms) with coefficient 0 are not included. # For example, an expression of "0" has an output of []. # @@ -50,7 +59,8 @@ # Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = [] # Output: ["5*a*b*c"] # -# Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))", +# Input: expression = +# "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))", # evalvars = [], evalints = [] # Output: # ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c", @@ -120,8 +130,9 @@ def eval(self, lookup): return result def to_list(self): - return ["*".join((str(v),) + k) \ - for k, v in sorted(self.items(), key=lambda(k, _): (-len(k), k)) \ + return ["*".join((str(v),) + k) + for k, v in sorted(self.items(), + key=lambda(k, _): (-len(k), k)) if v] diff --git a/Python/basic-calculator.py b/Python/basic-calculator.py index cae7f5527..21cb994d9 100644 --- a/Python/basic-calculator.py +++ b/Python/basic-calculator.py @@ -14,6 +14,12 @@ # "(1+(4+5+2)-3)+(6+8)" = 23 # +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution: # @param {string} s # @return {integer} @@ -23,7 +29,7 @@ def calculate(self, s): for i in reversed(xrange(len(s))): if s[i].isdigit(): operand += s[i] - if i == 0 or not s[i-1].isdigit(): + if i == 0 or not s[i-1].isdigit(): operands.append(int(operand[::-1])) operand = "" elif s[i] == ')' or s[i] == '+' or s[i] == '-': diff --git a/Python/battleships-in-a-board.py b/Python/battleships-in-a-board.py index 7d6c7490b..23ccf5273 100644 --- a/Python/battleships-in-a-board.py +++ b/Python/battleships-in-a-board.py @@ -2,12 +2,14 @@ # Space: O(1) # Given an 2D board, count how many different battleships are in it. -# The battleships are represented with 'X's, empty slots are represented with '.'s. +# The battleships are represented with 'X's, empty slots are represented with +# '.'s. # You may assume the following rules: # # You receive a valid board, made of only battleships or empty slots. # Battleships can only be placed horizontally or vertically. In other words, -# they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), +# they can only be made of the shape 1xN (1 row, N columns) or Nx1 +# (N rows, 1 column), # where N can be of any size. # At least one horizontal or vertical cell separates between two battleships - # there are no adjacent battleships. @@ -21,9 +23,15 @@ # ...X # XXXX # ...X -# This is not a valid board - as battleships will always have a cell separating between them. +# This is not a valid board - as battleships will always have a cell +# separating between them. # Your algorithm should not modify the value of the board. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class Solution(object): def countBattleships(self, board): @@ -37,7 +45,7 @@ def countBattleships(self, board): cnt = 0 for i in xrange(len(board)): for j in xrange(len(board[0])): - cnt += int(board[i][j] == 'X' and \ - (i == 0 or board[i - 1][j] != 'X') and \ - (j == 0 or board[i][j - 1] != 'X')) + cnt += int(board[i][j] == 'X' and + (i == 0 or board[i - 1][j] != 'X') and + (j == 0 or board[i][j - 1] != 'X')) return cnt diff --git a/Python/beautiful-arrangement-ii.py b/Python/beautiful-arrangement-ii.py index e9617beec..8fe260d8e 100644 --- a/Python/beautiful-arrangement-ii.py +++ b/Python/beautiful-arrangement-ii.py @@ -2,28 +2,31 @@ # Space: O(1) # Given two integers n and k, -# you need to construct a list which contains n different positive integers ranging -# from 1 to n and obeys the following requirement: +# you need to construct a list which contains n different positive integers +# ranging from 1 to n and obeys the following requirement: # Suppose this list is [a1, a2, a3, ... , an], -# then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers. +# then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has +# exactly k distinct integers. # # If there are multiple answers, print any of them. # # Example 1: # Input: n = 3, k = 1 # Output: [1, 2, 3] -# Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, -# and the [1, 1] has exactly 1 distinct integer: 1. +# Explanation: The [1, 2, 3] has three different positive integers ranging +# from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1. # # Example 2: # Input: n = 3, k = 2 # Output: [1, 3, 2] -# Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, +# Explanation: The [1, 3, 2] has three different positive integers ranging +# from 1 to 3, # and the [2, 1] has exactly 2 distinct integers: 1 and 2. # # Note: # The n and k are in the range 1 <= k < n <= 10^4. + class Solution(object): def constructArray(self, n, k): """ diff --git a/Python/beautiful-arrangement.py b/Python/beautiful-arrangement.py index 64327bfcd..8110e4b80 100644 --- a/Python/beautiful-arrangement.py +++ b/Python/beautiful-arrangement.py @@ -2,8 +2,10 @@ # Space: O(n) # Suppose you have N integers from 1 to N. -# We define a beautiful arrangement as an array that is constructed by these N numbers successfully -# if one of the following is true for the ith position (1 <= i <= N) in this array: +# We define a beautiful arrangement as an array that is constructed by +# these N numbers successfully +# if one of the following is true for +# the ith position (1 <= i <= N) in this array: # # The number at the ith position is divisible by i. # i is divisible by the number at the ith position. @@ -28,21 +30,27 @@ # Note: # N is a positive integer and will not exceed 15. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def countArrangement(self, N): """ :type N: int :rtype: int """ - def countArrangementHelper(n, arrangement): + def countArrangementHelper(n, arr): if n <= 0: return 1 count = 0 for i in xrange(n): - if arrangement[i] % n == 0 or n % arrangement[i] == 0: - arrangement[i], arrangement[n-1] = arrangement[n-1], arrangement[i] - count += countArrangementHelper(n - 1, arrangement) - arrangement[i], arrangement[n-1] = arrangement[n-1], arrangement[i] + if arr[i] % n == 0 or n % arr[i] == 0: + arr[i], arr[n-1] = arr[n-1], arr[i] + count += countArrangementHelper(n - 1, arr) + arr[i], arr[n-1] = arr[n-1], arr[i] return count return countArrangementHelper(N, range(1, N+1)) diff --git a/Python/best-meeting-point.py b/Python/best-meeting-point.py index ca5554f63..0a3333eaa 100644 --- a/Python/best-meeting-point.py +++ b/Python/best-meeting-point.py @@ -3,6 +3,12 @@ from random import randint +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def minTotalDistance(self, grid): """ @@ -14,14 +20,16 @@ def minTotalDistance(self, grid): 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]) + 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) + 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: @@ -35,7 +43,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] diff --git a/Python/best-time-to-buy-and-sell-stock-ii.py b/Python/best-time-to-buy-and-sell-stock-ii.py index b0d12c7a9..fcd3ee4d1 100644 --- a/Python/best-time-to-buy-and-sell-stock-ii.py +++ b/Python/best-time-to-buy-and-sell-stock-ii.py @@ -10,6 +10,11 @@ # However, you may not engage in multiple transactions at the same time # (ie, you must sell the stock before you buy again). +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class Solution: # @param prices, a list of integer @@ -21,9 +26,5 @@ def maxProfit(self, prices): return profit def maxProfit2(self, prices): - return sum(map(lambda x: max(prices[x + 1] - prices[x], 0), range(len(prices[:-1])))) - - -if __name__ == "__main__": - result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6]) - print result + return sum(map(lambda x: max(prices[x + 1] - prices[x], 0), + xrange(len(prices[:-1])))) 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 89109f853..d7e002f73 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,13 @@ # (ie, you must sell the stock before you buy again). # -# Time: O(n) -# Space: O(1) -class Solution: +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): # @param prices, a list of integer # @return an integer def maxProfit(self, prices): @@ -22,14 +26,15 @@ def maxProfit(self, prices): release1, release2 = 0, 0 for i in prices: release2 = max(release2, hold2 + i) - hold2 = max(hold2, release1 - i) + hold2 = max(hold2, release1 - i) release1 = max(release1, hold1 + i) - hold1 = max(hold1, -i); + hold1 = max(hold1, -i) return release2 + # Time: O(k * n) # Space: O(k) -class Solution2: +class Solution2(object): # @param prices, a list of integer # @return an integer def maxProfit(self, prices): @@ -46,13 +51,15 @@ def maxAtMostKPairsProfit(self, prices, k): return max_sell[k] + # Time: O(n) # Space: O(n) -class Solution3: +class Solution3(object): # @param prices, a list of integer # @return an integer def maxProfit(self, prices): - min_price, max_profit_from_left, max_profits_from_left = float("inf"), 0, [] + min_price, max_profit_from_left, max_profits_from_left = \ + float("inf"), 0, [] for price in prices: min_price = min(min_price, price) max_profit_from_left = max(max_profit_from_left, price - min_price) @@ -61,15 +68,14 @@ def maxProfit(self, prices): max_price, max_profit_from_right, max_profits_from_right = 0, 0, [] for i in reversed(range(len(prices))): max_price = max(max_price, prices[i]) - max_profit_from_right = max(max_profit_from_right, max_price - prices[i]) + max_profit_from_right = max(max_profit_from_right, + max_price - prices[i]) max_profits_from_right.insert(0, max_profit_from_right) max_profit = 0 for i in range(len(prices)): - max_profit = max(max_profit, max_profits_from_left[i] + max_profits_from_right[i]) + max_profit = max(max_profit, + max_profits_from_left[i] + + max_profits_from_right[i]) return max_profit - -if __name__ == "__main__": - result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6]) - print result 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 2d0071909..e69119480 100644 --- a/Python/best-time-to-buy-and-sell-stock-iv.py +++ b/Python/best-time-to-buy-and-sell-stock-iv.py @@ -1,15 +1,24 @@ # 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. +# 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. +# 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). +# You may not engage in multiple transactions at the same time +# (ie, you must sell the stock before you buy again). # -class Solution: +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): # @return an integer as the maximum profit def maxProfit(self, k, prices): if k >= len(prices) / 2: @@ -33,6 +42,3 @@ def maxAtMostKPairsProfit(self, prices, k): max_sell[j] = max(max_sell[j], max_buy[j] + prices[i]) return max_sell[k] - -if __name__ == "__main__": - print Solution().maxAtMostKPairsProfit([1, 2, 3, 4], 2) 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 index 2e95e742b..23ecb097e 100644 --- a/Python/best-time-to-buy-and-sell-stock-with-cooldown.py +++ b/Python/best-time-to-buy-and-sell-stock-with-cooldown.py @@ -1,7 +1,8 @@ # 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. +# 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 @@ -18,6 +19,12 @@ # transactions = [buy, sell, cooldown, buy, sell] # +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def maxProfit(self, prices): """ @@ -30,9 +37,11 @@ def maxProfit(self, prices): 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]) + 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]) + return max(coolDown[(len(prices) - 1) % 2], + sell[(len(prices) - 1) % 2]) diff --git a/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py b/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py index 4b622e833..e97c4038f 100644 --- a/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py +++ b/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py @@ -27,6 +27,12 @@ # - 0 < prices[i] < 50000. # - 0 <= fee < 50000. +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def maxProfit(self, prices, fee): """ @@ -39,4 +45,3 @@ def maxProfit(self, prices, fee): cash = max(cash, hold+prices[i]-fee) hold = max(hold, cash-prices[i]) return cash - diff --git a/Python/best-time-to-buy-and-sell-stock.py b/Python/best-time-to-buy-and-sell-stock.py index 748b5e638..4d94fa9ae 100644 --- a/Python/best-time-to-buy-and-sell-stock.py +++ b/Python/best-time-to-buy-and-sell-stock.py @@ -9,7 +9,8 @@ # design an algorithm to find the maximum profit. # -class Solution: + +class Solution(object): # @param prices, a list of integer # @return an integer def maxProfit(self, prices): @@ -18,8 +19,3 @@ def maxProfit(self, prices): min_price = min(min_price, price) max_profit = max(max_profit, price - min_price) return max_profit - -if __name__ == "__main__": - result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6]) - print result - diff --git a/Python/binary-number-with-alternating-bits.py b/Python/binary-number-with-alternating-bits.py index e8f06d5b9..cf9d838ed 100644 --- a/Python/binary-number-with-alternating-bits.py +++ b/Python/binary-number-with-alternating-bits.py @@ -28,6 +28,7 @@ # Explanation: # The binary representation of 10 is: 1010. + class Solution(object): def hasAlternatingBits(self, n): """ @@ -36,6 +37,7 @@ def hasAlternatingBits(self, n): """ n, curr = divmod(n, 2) while n > 0: - if curr == n % 2: return False + if curr == n % 2: + return False n, curr = divmod(n, 2) return True diff --git a/Python/binary-search-tree-iterator.py b/Python/binary-search-tree-iterator.py index ae455dea3..525ec44fe 100644 --- a/Python/binary-search-tree-iterator.py +++ b/Python/binary-search-tree-iterator.py @@ -10,14 +10,16 @@ # and uses O(h) memory, where h is the height of the tree. # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class BSTIterator: + +class BSTIterator(object): # @param root, a binary search tree's root node def __init__(self, root): self.stack = [] @@ -38,13 +40,3 @@ def next(self): self.cur = self.cur.right return node.val - -if __name__ == "__main__": - root = TreeNode(2) - root.left = TreeNode(1) - - # Your BSTIterator will be called like this: - i, v = BSTIterator(root), [] - while i.hasNext(): v.append(i.next()) - - print v diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py index b82319cfe..05f925fb8 100644 --- a/Python/binary-tree-inorder-traversal.py +++ b/Python/binary-tree-inorder-traversal.py @@ -15,8 +15,9 @@ # Note: Recursive solution is trivial, could you do it iteratively? # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None @@ -72,11 +73,3 @@ def inorderTraversal(self, root): stack.append((root, True)) stack.append((root.left, False)) return result - - -if __name__ == "__main__": - root = TreeNode(1) - root.right = TreeNode(2) - root.right.left = TreeNode(3) - result = Solution().inorderTraversal(root) - print result diff --git a/Python/binary-tree-level-order-traversal-ii.py b/Python/binary-tree-level-order-traversal-ii.py index 0973c82e2..4989e83f8 100644 --- a/Python/binary-tree-level-order-traversal-ii.py +++ b/Python/binary-tree-level-order-traversal-ii.py @@ -1,7 +1,8 @@ # Time: O(n) # Space: O(n) -# Given a binary tree, return the bottom-up level order traversal of its nodes' values. +# Given a binary tree, return the bottom-up level order traversal +# of its nodes' values. # (ie, from left to right, level by level from leaf to root). # # For example: @@ -18,6 +19,7 @@ # [3] # ] + # Definition for a binary tree node class TreeNode(object): def __init__(self, x): @@ -48,13 +50,3 @@ def levelOrderBottom(self, root): result.append(vals) return result[::-1] - - -if __name__ == "__main__": - root = TreeNode(3) - root.left = TreeNode(9) - root.right = TreeNode(20) - root.right.left = TreeNode(15) - root.right.right = TreeNode(7) - result = Solution().levelOrderBottom(root) - print result diff --git a/Python/binary-tree-level-order-traversal.py b/Python/binary-tree-level-order-traversal.py index 8e48c8372..218219e60 100644 --- a/Python/binary-tree-level-order-traversal.py +++ b/Python/binary-tree-level-order-traversal.py @@ -18,14 +18,17 @@ # [15,7] # ] # + + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): # @param root, a tree node # @return a list of lists of integers def levelOrder(self, root): @@ -43,12 +46,3 @@ def levelOrder(self, root): current = next_level result.append(vals) return result - -if __name__ == "__main__": - root = TreeNode(3) - root.left = TreeNode(9) - root.right = TreeNode(20) - root.right.left = TreeNode(15) - root.right.right = TreeNode(7) - result = Solution().levelOrder(root) - print result \ No newline at end of file diff --git a/Python/binary-tree-longest-consecutive-sequence-ii.py b/Python/binary-tree-longest-consecutive-sequence-ii.py index b7c0f7bec..d1c9b3018 100644 --- a/Python/binary-tree-longest-consecutive-sequence-ii.py +++ b/Python/binary-tree-longest-consecutive-sequence-ii.py @@ -8,6 +8,7 @@ # self.left = None # self.right = None + class Solution(object): def longestConsecutive(self, root): """ @@ -36,4 +37,3 @@ def longestConsecutiveHelper(root): self.max_len = 0 longestConsecutiveHelper(root) return self.max_len - diff --git a/Python/binary-tree-longest-consecutive-sequence.py b/Python/binary-tree-longest-consecutive-sequence.py index e9c6c7444..aa75421c2 100644 --- a/Python/binary-tree-longest-consecutive-sequence.py +++ b/Python/binary-tree-longest-consecutive-sequence.py @@ -8,6 +8,7 @@ # self.left = None # self.right = None + class Solution(object): def longestConsecutive(self, root): """ @@ -25,7 +26,7 @@ def longestConsecutiveHelper(root): cur_len = 1 if root.left and root.left.val == root.val + 1: - cur_len = max(cur_len, left_len + 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) diff --git a/Python/binary-tree-maximum-path-sum.py b/Python/binary-tree-maximum-path-sum.py index b3d25e94a..0c3089e4e 100644 --- a/Python/binary-tree-maximum-path-sum.py +++ b/Python/binary-tree-maximum-path-sum.py @@ -13,15 +13,19 @@ # 2 3 # Return 6. # + + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): maxSum = float("-inf") + # @param root, a tree node # @return an integer def maxPathSum(self, root): @@ -35,10 +39,3 @@ def maxPathSumRecu(self, root): right = max(0, self.maxPathSumRecu(root.right)) self.maxSum = max(self.maxSum, root.val + left + right) return root.val + max(left, right) - -if __name__ == "__main__": - root = TreeNode(1) - root.left = TreeNode(2) - root.right = TreeNode(3) - result = Solution().maxPathSum(root) - print result diff --git a/Python/binary-tree-paths.py b/Python/binary-tree-paths.py index 770adfdfb..b32775adc 100644 --- a/Python/binary-tree-paths.py +++ b/Python/binary-tree-paths.py @@ -22,7 +22,8 @@ # self.left = None # self.right = None -class Solution: + +class Solution(object): # @param {TreeNode} root # @return {string[]} def binaryTreePaths(self, root): diff --git a/Python/binary-tree-postorder-traversal.py b/Python/binary-tree-postorder-traversal.py index e0ae110cd..6984e8692 100644 --- a/Python/binary-tree-postorder-traversal.py +++ b/Python/binary-tree-postorder-traversal.py @@ -15,8 +15,9 @@ # Note: Recursive solution is trivial, could you do it iteratively? # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None @@ -82,11 +83,3 @@ def postorderTraversal(self, root): stack.append((root.right, False)) stack.append((root.left, False)) return result - - -if __name__ == "__main__": - root = TreeNode(1) - root.right = TreeNode(2) - root.right.left = TreeNode(3) - result = Solution().postorderTraversal(root) - print result diff --git a/Python/binary-tree-preorder-traversal.py b/Python/binary-tree-preorder-traversal.py index 9cf12ee7a..ed1edbfe1 100644 --- a/Python/binary-tree-preorder-traversal.py +++ b/Python/binary-tree-preorder-traversal.py @@ -15,8 +15,9 @@ # Note: Recursive solution is trivial, could you do it iteratively? # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None @@ -72,11 +73,3 @@ def preorderTraversal(self, root): stack.append((root.left, False)) stack.append((root, True)) return result - - -if __name__ == "__main__": - root = TreeNode(1) - root.right = TreeNode(2) - root.right.left = TreeNode(3) - result = Solution().preorderTraversal(root) - print result diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py index effd0ad13..24e427261 100644 --- a/Python/binary-tree-right-side-view.py +++ b/Python/binary-tree-right-side-view.py @@ -14,14 +14,16 @@ # You should return [1, 3, 4]. # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): # @param root, a tree node # @return a list of integers def rightSideView(self, root): @@ -39,10 +41,11 @@ def rightSideViewDFS(self, node, depth, result): self.rightSideViewDFS(node.right, depth+1, result) self.rightSideViewDFS(node.left, depth+1, result) + # BFS solution # Time: O(n) # Space: O(n) -class Solution2: +class Solution2(object): # @param root, a tree node # @return a list of integers def rightSideView(self, root): @@ -62,12 +65,3 @@ 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 diff --git a/Python/binary-tree-tilt.py b/Python/binary-tree-tilt.py index 76ca7e745..4b7de9125 100644 --- a/Python/binary-tree-tilt.py +++ b/Python/binary-tree-tilt.py @@ -22,7 +22,8 @@ # Tilt of binary tree : 0 + 0 + 1 = 1 # Note: # -# The sum of node values in any subtree won't exceed the range of 32-bit integer. +# The sum of node values in any subtree won't exceed +# the range of 32-bit integer. # Definition for a binary tree node. diff --git a/Python/binary-tree-upside-down.py b/Python/binary-tree-upside-down.py index e68f4e923..9f58a714c 100644 --- a/Python/binary-tree-upside-down.py +++ b/Python/binary-tree-upside-down.py @@ -1,9 +1,11 @@ # Time: O(n) # Space: O(1) # -# Given a binary tree where all the right nodes are either leaf nodes with a sibling -# (a left node that shares the same parent node) or empty, flip it upside down and -# turn it into a tree where the original right nodes turned into left leaf nodes. +# Given a binary tree where all the right nodes are +# either leaf nodes with a sibling +# (a left node that shares the same parent node) or empty, +# flip it upside down and turn it into a tree +# where the original right nodes turned into left leaf nodes. # Return the new root. # # For example: @@ -24,14 +26,16 @@ # 3 1 # + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): # @param root, a tree node # @return root of the upside down tree def upsideDownBinaryTree(self, root): @@ -47,9 +51,10 @@ def upsideDownBinaryTree(self, root): return parent + # Time: O(n) # Space: O(n) -class Solution2: +class Solution2(object): # @param root, a tree node # @return root of the upside down tree def upsideDownBinaryTree(self, root): @@ -66,4 +71,4 @@ def upsideDownBinaryTreeRecu(self, p, parent): p.left = None p.right = parent - return root \ No newline at end of file + return root diff --git a/Python/binary-tree-vertical-order-traversal.py b/Python/binary-tree-vertical-order-traversal.py index 6790d59fd..b57e04b99 100644 --- a/Python/binary-tree-vertical-order-traversal.py +++ b/Python/binary-tree-vertical-order-traversal.py @@ -10,6 +10,11 @@ import collections +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + # BFS + hash solution. class Solution(object): @@ -24,5 +29,5 @@ def verticalOrder(self, root): 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 [] + return [cols[i] for i in xrange(min(cols.keys()), + max(cols.keys()) + 1)] if cols else [] diff --git a/Python/binary-tree-zigzag-level-order-traversal.py b/Python/binary-tree-zigzag-level-order-traversal.py index 1a5dac583..2b2261a33 100644 --- a/Python/binary-tree-zigzag-level-order-traversal.py +++ b/Python/binary-tree-zigzag-level-order-traversal.py @@ -1,7 +1,9 @@ # Time: O(n) # Space: O(n) # -# Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). +# Given a binary tree, return the zigzag level order traversal of +# its nodes' values. (ie, from left to right, then right to left +# for the next level and alternate between). # # For example: # Given binary tree {3,9,20,#,#,15,7}, @@ -17,14 +19,17 @@ # [15,7] # ] # + + # Definition for a binary tree node -class TreeNode: +class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None -class Solution: + +class Solution(object): # @param root, a tree node # @return a list of lists of integers def zigzagLevelOrder(self, root): @@ -46,12 +51,3 @@ def zigzagLevelOrder(self, root): level += 1 current = next_level return result - -if __name__ == "__main__": - root = TreeNode(3) - root.left = TreeNode(9) - root.right = TreeNode(20) - root.right.left = TreeNode(15) - root.right.right = TreeNode(7) - result = Solution().zigzagLevelOrder(root) - print result \ No newline at end of file diff --git a/Python/binary-watch.py b/Python/binary-watch.py index eab47e94b..fa988a86e 100644 --- a/Python/binary-watch.py +++ b/Python/binary-watch.py @@ -4,20 +4,29 @@ # A binary watch has 4 LEDs on the top which represent the hours (0-11), # and the 6 LEDs on the bottom represent the minutes (0-59). # -# Each LED represents a zero or one, with the least significant bit on the right. +# Each LED represents a zero or one, with the least significant bit +# on the right. # # For example, the above binary watch reads "3:25". # -# Given a non-negative integer n which represents the number of LEDs that are currently on, +# Given a non-negative integer n which represents the number of LEDs +# that are currently on, # return all possible times the watch could represent. # # Example: # # Input: n = 1 -# Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] +# Return: ["1:00", "2:00", "4:00", "8:00", "0:01", +# "0:02", "0:04", "0:08", "0:16", "0:32"] # Note: # The order of output does not matter. -# The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00". +# The hour must not contain a leading zero, for example "01:00" is not valid, +# it should be "1:00". + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 class Solution(object): @@ -33,13 +42,14 @@ def bit_count(bits): count += 1 return count - return ['%d:%02d' % (h, m) - for h in xrange(12) for m in xrange(60) - if bit_count(h) + bit_count(m) == num] + return ['%d:%02d' % (h, m) for h in xrange(12) for m in xrange(60) + if bit_count(h) + bit_count(m) == num] def readBinaryWatch2(self, num): """ :type num: int :rtype: List[str] """ - return ['{0}:{1}'.format(str(h), str(m).zfill(2)) for h in range(12) for m in range(60) if (bin(h) + bin(m)).count('1') == num] + return ['{0}:{1}'.format(str(h), str(m).zfill(2)) + for h in range(12) for m in range(60) + if (bin(h) + bin(m)).count('1') == num] diff --git a/Python/bitwise-and-of-numbers-range.py b/Python/bitwise-and-of-numbers-range.py index 0dc2cad71..418018793 100644 --- a/Python/bitwise-and-of-numbers-range.py +++ b/Python/bitwise-and-of-numbers-range.py @@ -7,7 +7,8 @@ # For example, given the range [5, 7], you should return 4. # -class Solution: + +class Solution(object): # @param m, an integer # @param n, an integer # @return an integer @@ -16,7 +17,8 @@ def rangeBitwiseAnd(self, m, n): n &= n - 1 return n -class Solution2: + +class Solution2(object): # @param m, an integer # @param n, an integer # @return an integer @@ -25,7 +27,4 @@ def rangeBitwiseAnd(self, m, n): while diff: diff >>= 1 i += 1 - return n&m >> i << i - -if __name__ == '__main__': - print Solution().rangeBitwiseAnd(5, 7) + return n & m >> i << i diff --git a/Python/bold-words-in-string.py b/Python/bold-words-in-string.py index 0f794f228..7e08e8a84 100644 --- a/Python/bold-words-in-string.py +++ b/Python/bold-words-in-string.py @@ -2,6 +2,12 @@ # Space: O(t) , t is the size of trie import collections +import functools + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 class Solution(object): @@ -14,7 +20,7 @@ def boldWords(self, words, S): _trie = lambda: collections.defaultdict(_trie) trie = _trie() for i, word in enumerate(words): - reduce(dict.__getitem__, word, trie).setdefault("_end") + functools.reduce(dict.__getitem__, word, trie).setdefault("_end") lookup = [False] * len(S) for i in xrange(len(S)): @@ -35,7 +41,7 @@ def boldWords(self, words, S): result.append("") result.append(S[i]) if lookup[i] and (i == len(S)-1 or not lookup[i+1]): - result.append(""); + result.append("") return "".join(result) @@ -61,5 +67,5 @@ def boldWords(self, words, S): result.append("") result.append(S[i]) if lookup[i] and (i == len(S)-1 or not lookup[i+1]): - result.append(""); + result.append("") return "".join(result) diff --git a/Python/bomb-enemy.py b/Python/bomb-enemy.py index 7da26b0b3..576085c87 100644 --- a/Python/bomb-enemy.py +++ b/Python/bomb-enemy.py @@ -1,6 +1,12 @@ # Time: O(m * n) # Space: O(m * n) +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def maxKilledEnemies(self, grid): """ @@ -34,6 +40,7 @@ def maxKilledEnemies(self, grid): up[j] += 1 left += 1 else: - result = max(result, left + up[j] + right[i][j] + down[i][j]) + result = max(result, + left + up[j] + right[i][j] + down[i][j]) return result diff --git a/Python/boundary-of-binary-tree.py b/Python/boundary-of-binary-tree.py index c71ed0df4..348e2c2c6 100644 --- a/Python/boundary-of-binary-tree.py +++ b/Python/boundary-of-binary-tree.py @@ -8,6 +8,7 @@ # self.left = None # self.right = None + class Solution(object): def boundaryOfBinaryTree(self, root): """ diff --git a/Python/brick-wall.py b/Python/brick-wall.py index 767290085..7124e7469 100644 --- a/Python/brick-wall.py +++ b/Python/brick-wall.py @@ -1,15 +1,20 @@ # Time: O(n), n is the total number of the bricks # Space: O(m), m is the total number different widths -# There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. -# The bricks have the same height but different width. You want to draw a vertical line from +# There is a brick wall in front of you. The wall is rectangular +# and has several rows of bricks. +# The bricks have the same height but different width. +# You want to draw a vertical line from # the top to the bottom and cross the least bricks. # -# The brick wall is represented by a list of rows. Each row is a list of integers representing the +# The brick wall is represented by a list of rows. +# Each row is a list of integers representing the # width of each brick in this row from left to right. # -# If your line go through the edge of a brick, then the brick is not considered as crossed. -# You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks. +# If your line go through the edge of a brick, +# then the brick is not considered as crossed. +# You need to find out how to draw the line to cross the least bricks and +# return the number of crossed bricks. # # You cannot draw a line just along one of the two vertical edges of the wall, # in which case the line will obviously cross no bricks. @@ -25,13 +30,19 @@ # Output: 2 # # Note: -# The width sum of bricks in different rows are the same and won't exceed INT_MAX. +# The width sum of bricks in different rows are the same and +# won't exceed INT_MAX. # The number of bricks in each row is in range [1,10,000]. # The height of wall is in range [1,10,000]. # Total number of bricks of the wall won't exceed 20,000. import collections +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class Solution(object): def leastBricks(self, wall): @@ -46,5 +57,5 @@ def leastBricks(self, wall): for i in xrange(len(row)-1): width += row[i] widths[width] += 1 - result = min(result, len(wall) - widths[width]); + result = min(result, len(wall) - widths[width]) return result diff --git a/Python/bricks-falling-when-hit.py b/Python/bricks-falling-when-hit.py index 9901572c7..2d568ee0c 100644 --- a/Python/bricks-falling-when-hit.py +++ b/Python/bricks-falling-when-hit.py @@ -2,14 +2,17 @@ # Space: O(r * c) # We have a grid of 1s and 0s; the 1s in a cell represent bricks. -# A brick will not drop if and only if it is directly connected to the top of the grid, +# A brick will not drop if and +# only if it is directly connected to the top of the grid, # or at least one of its (4-way) adjacent bricks will not drop. # -# We will do some erasures sequentially. Each time we want to do the erasure at the location (i, j), +# We will do some erasures sequentially. +# Each time we want to do the erasure at the location (i, j), # the brick (if it exists) on that location will disappear, # and then some other bricks may drop because of that erasure. # -# Return an array representing the number of bricks that will drop after each erasure in sequence. +# Return an array representing the number of bricks that +# will drop after each erasure in sequence. # # Example 1: # Input: @@ -17,7 +20,8 @@ # hits = [[1,0]] # Output: [2] # Explanation: -# If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. So we should return 2. +# If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. +# So we should return 2. # # Example 2: # Input: @@ -25,17 +29,21 @@ # hits = [[1,1],[1,0]] # Output: [0,0] # Explanation: -# When we erase the brick at (1, 0), the brick at (1, 1) has already disappeared due to the last move. +# When we erase the brick at (1, 0), the brick at (1, 1) +# has already disappeared due to the last move. # So each erasure will cause no bricks dropping. # Note that the erased brick (1, 0) will not be counted as a dropped brick. # # Note: # - The number of rows and columns in the grid will be in the range [1, 200]. # - The number of erasures will not exceed the area of the grid. -# - It is guaranteed that each erasure will be different from any other erasure, and located inside the grid. -# - An erasure may refer to a location with no brick - if it does, no bricks drop. +# - It is guaranteed that each erasure will be different from +# any other erasure, and located inside the grid. +# - An erasure may refer to a location with no brick - +# if it does, no bricks drop. -class UnionFind: + +class UnionFind(object): def __init__(self, n): self.set = range(n+1) self.size = [1]*(n+1) @@ -78,7 +86,8 @@ def index(C, r, c): union_find = UnionFind(R*C) for r, row in enumerate(hit_grid): for c, val in enumerate(row): - if not val: continue + if not val: + continue if r == 0: union_find.union_set(index(C, r, c), R*C) if r and hit_grid[r-1][c]: diff --git a/Python/bulb-switcher-ii.py b/Python/bulb-switcher-ii.py index 3bb37192d..e41844686 100644 --- a/Python/bulb-switcher-ii.py +++ b/Python/bulb-switcher-ii.py @@ -1,11 +1,14 @@ # Time: O(1) # Space: O(1) -# There is a room with n lights which are turned on initially and 4 buttons on the wall. +# There is a room with n lights which are turned on initially and +# 4 buttons on the wall. # After performing exactly m unknown operations towards buttons, -# you need to return how many different kinds of status of the n lights could be. +# you need to return how many different kinds of status of +# the n lights could be. # -# Suppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below: +# Suppose n lights are labeled as number [1, 2, 3 ..., n], +# function of these 4 buttons are given below: # 1. Flip all the lights. # 3. Flip lights with even numbers. # 3. Flip lights with odd numbers. @@ -22,9 +25,11 @@ # Example 3: # Input: n = 3, m = 1. # Output: 4 -# Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on]. +# Explanation: Status can be: [off, on, off], [on, off, on], +# [off, off, off], [off, on, on]. # Note: n and m both fit in range [0, 1000]. + class Solution(object): def flipLights(self, n, m): """ @@ -32,9 +37,14 @@ def flipLights(self, n, m): :type m: int :rtype: int """ - if m == 0: return 1 - if n == 1: return 2 - if m == 1 and n == 2: return 3 - if m == 1 or n == 2: return 4 - if m == 2: return 7 + if m == 0: + return 1 + if n == 1: + return 2 + if m == 1 and n == 2: + return 3 + if m == 1 or n == 2: + return 4 + if m == 2: + return 7 return 8 diff --git a/Python/bulls-and-cows.py b/Python/bulls-and-cows.py index ead89679c..b9c0b5cc6 100644 --- a/Python/bulls-and-cows.py +++ b/Python/bulls-and-cows.py @@ -33,8 +33,9 @@ # One pass solution. -from collections import defaultdict -from itertools import izip +from collections import defaultdict, Counter +from itertools import izip, imap + class Solution(object): def getHint(self, secret, guess): @@ -64,9 +65,6 @@ def getHint(self, secret, guess): # Two pass solution. -from collections import Counter -from itertools import imap - class Solution2(object): def getHint(self, secret, guess): """ diff --git a/Python/burst-balloons.py b/Python/burst-balloons.py index 4cb6ebd9c..ef84fff11 100644 --- a/Python/burst-balloons.py +++ b/Python/burst-balloons.py @@ -29,6 +29,12 @@ # coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 # +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def maxCoins(self, nums): """ @@ -43,9 +49,10 @@ def maxCoins(self, nums): 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]) + 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 02c3aaad0deb2a0e7ecb440e6e4a5e60d796a174 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sat, 21 Apr 2018 23:31:21 +0800 Subject: [PATCH 4641/4971] Fix flake8 related issues --- Python/basic-calculator-iv.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Python/basic-calculator-iv.py b/Python/basic-calculator-iv.py index e4238e5da..b8c1ac620 100644 --- a/Python/basic-calculator-iv.py +++ b/Python/basic-calculator-iv.py @@ -74,6 +74,11 @@ import collections import itertools +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class Poly(collections.Counter): def __init__(self, expr=None): @@ -132,7 +137,7 @@ def eval(self, lookup): def to_list(self): return ["*".join((str(v),) + k) for k, v in sorted(self.items(), - key=lambda(k, _): (-len(k), k)) + key=lambda x: (-len(x[0]), x[0])) if v] From 9578a5f4c9197e5de1bb4a83b6edcb0d83b6b986 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Apr 2018 17:29:15 +0800 Subject: [PATCH 4642/4971] Create short-encoding-of-words.cpp --- C++/short-encoding-of-words.cpp | 45 +++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 C++/short-encoding-of-words.cpp diff --git a/C++/short-encoding-of-words.cpp b/C++/short-encoding-of-words.cpp new file mode 100644 index 000000000..c1adde4d5 --- /dev/null +++ b/C++/short-encoding-of-words.cpp @@ -0,0 +1,45 @@ +// Time: O(n), n is the total sum of the lengths of words +// Space: O(t), t is the number of nodes in trie + +class Solution { +public: + int minimumLengthEncoding(vector& words) { + unordered_set unique_words(words.cbegin(), words.cend()); + vector leaves; + TrieNode trie; + for (auto word : unique_words) { + reverse(word.begin(), word.end()); + leaves.emplace_back(trie.Insert(word)); + } + int result = 0; + int i = 0; + for (const auto& word: unique_words) { + if (leaves[i++]->leaves.empty()) { + result += word.length() + 1; + } + } + return result; + } + +private: + struct TrieNode { + unordered_map leaves; + + TrieNode *Insert(const string& s) { + auto* p = this; + for (const auto& c : s) { + if (!p->leaves[c - 'a']) { + p->leaves[c - 'a'] = new TrieNode; + } + p = p->leaves[c - 'a']; + } + return p; + } + + ~TrieNode() { + for (auto& node : leaves) { + delete node.second; + } + } + }; +}; From c1ea4710ef9cb6445adff38aa60b16b7d2fdfed8 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 22 Apr 2018 17:29:51 +0800 Subject: [PATCH 4643/4971] Create short-encoding-of-words.py --- Python/short-encoding-of-words.py | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/short-encoding-of-words.py diff --git a/Python/short-encoding-of-words.py b/Python/short-encoding-of-words.py new file mode 100644 index 000000000..89d8fc3c6 --- /dev/null +++ b/Python/short-encoding-of-words.py @@ -0,0 +1,48 @@ +# Time: O(n), n is the total sum of the lengths of words +# Space: O(t), t is the number of nodes in trie + +# Given a list of words, we may encode it by writing a reference +# string S and a list of indexes A. +# +# For example, if the list of words is ["time", "me", "bell"], +# we can write it as S = "time#bell#" +# and indexes = [0, 2, 5]. +# +# Then for each index, we will recover the word by reading from +# the reference string from that +# index until we reach a "#" character. +# +# What is the length of the shortest reference string S possible +# that encodes the given words? +# +# Example: +# +# Input: words = ["time", "me", "bell"] +# Output: 10 +# Explanation: S = "time#bell#" and indexes = [0, 2, 5]. +# +# Note: +# 1. 1 <= words.length <= 2000. +# 2. 1 <= words[i].length <= 7. +# 3. Each word has only lowercase letters. + +import collections +import functools + + +class Solution(object): + def minimumLengthEncoding(self, words): + """ + :type words: List[str] + :rtype: int + """ + words = list(set(words)) + _trie = lambda: collections.defaultdict(_trie) + trie = _trie() + + nodes = [functools.reduce(dict.__getitem__, word[::-1], trie) + for word in words] + + return sum(len(word) + 1 + for i, word in enumerate(words) + if len(nodes[i]) == 0) From 76f241d0b5503d45f383772aa4543d66ad8f29bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Apr 2018 17:52:43 +0800 Subject: [PATCH 4644/4971] Create shortest-distance-to-a-character.cpp --- C++/shortest-distance-to-a-character.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/shortest-distance-to-a-character.cpp diff --git a/C++/shortest-distance-to-a-character.cpp b/C++/shortest-distance-to-a-character.cpp new file mode 100644 index 000000000..f7df3a1ee --- /dev/null +++ b/C++/shortest-distance-to-a-character.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector shortestToChar(string S, char C) { + vector result(S.length(), S.length()); + int prev = -S.length(); + for (int i = 0; i < S.length(); ++i) { + if (S[i] == C) { + prev = i; + } + result[i] = min(result[i], abs(i - prev)); + } + for (int i = S.length() - 1; i >= 0; --i) { + if (S[i] == C) { + prev = i; + } + result[i] = min(result[i], abs(i - prev)); + } + return result; + } +}; From 3765a32bcbdb6eb5ee15c1b029586a840f47f7d5 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 22 Apr 2018 17:53:29 +0800 Subject: [PATCH 4645/4971] Create shortest-distance-to-a-character.py --- Python/shortest-distance-to-a-character.py | 40 ++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/shortest-distance-to-a-character.py diff --git a/Python/shortest-distance-to-a-character.py b/Python/shortest-distance-to-a-character.py new file mode 100644 index 000000000..a5d0b9bf4 --- /dev/null +++ b/Python/shortest-distance-to-a-character.py @@ -0,0 +1,40 @@ +# Time: O(n) +# Space: O(n) + +# Given a string S and a character C, +# return an array of integers representing the shortest distance +# from the character C in the string. +# +# Example 1: +# +# Input: S = "loveleetcode", C = 'e' +# Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] +# +# Note: +# - S string length is in [1, 10000]. +# - C is a single character, and guaranteed to be in string S. +# - All letters in S and C are lowercase. + +import itertools + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def shortestToChar(self, S, C): + """ + :type S: str + :type C: str + :rtype: List[int] + """ + result = [len(S)] * len(S) + prev = -len(S) + for i in itertools.chain(xrange(len(S)), + reversed(xrange(len(S)))): + if S[i] == C: + prev = i + result[i] = min(result[i], abs(i-prev)) + return result From 804b7aa609ce1fde97f81f839776501352a59a89 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 22 Apr 2018 18:13:04 +0800 Subject: [PATCH 4646/4971] Create card-flipping-game.py --- Python/card-flipping-game.py | 49 ++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/card-flipping-game.py diff --git a/Python/card-flipping-game.py b/Python/card-flipping-game.py new file mode 100644 index 000000000..e39e2633b --- /dev/null +++ b/Python/card-flipping-game.py @@ -0,0 +1,49 @@ +# Time: O(n) +# Space: O(n) + +# On a table are N cards, with a positive integer printed on the front +# and back of each card (possibly different). +# +# We flip any number of cards, and after we choose one card. +# +# If the number X on the back of the chosen card is not on the front of +# any card, then this number X is good. +# +# What is the smallest number that is good? If no number is good, output 0. +# +# Here, fronts[i] and backs[i] represent the number on the front and back of +# card i. +# +# A flip swaps the front and back numbers, so the value on the front is +# now on the back and vice versa. +# +# Example: +# +# Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3] +# Output: 2 +# Explanation: If we flip the second card, the fronts are [1,3,4,4,7] and +# the backs are [1,2,4,1,3]. +# We choose the second card, which has number 2 on the back, +# and it isn't on the front of any card, so 2 is good. +# +# Note: +# - 1 <= fronts.length == backs.length <= 1000. +# - 1 <= fronts[i] <= 2000. +# - 1 <= backs[i] <= 2000. + +import itertools + + +class Solution(object): + def flipgame(self, fronts, backs): + """ + :type fronts: List[int] + :type backs: List[int] + :rtype: int + """ + same = {n for i, n in enumerate(fronts) if n == backs[i]} + result = float("inf") + for n in itertools.chain(fronts, backs): + if n not in same: + result = min(result, n) + return result if result < float("inf") else 0 From ef33da01b9ea017f6a1e43253ccb80891db5250e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Apr 2018 18:14:01 +0800 Subject: [PATCH 4647/4971] Create card-flipping-game.cpp --- C++/card-flipping-game.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/card-flipping-game.cpp diff --git a/C++/card-flipping-game.cpp b/C++/card-flipping-game.cpp new file mode 100644 index 000000000..17a29c47b --- /dev/null +++ b/C++/card-flipping-game.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int flipgame(vector& fronts, vector& backs) { + unordered_set same; + for (int i = 0; i < fronts.size(); ++i) { + if (fronts[i] == backs[i]) { + same.emplace(fronts[i]); + } + } + int result = numeric_limits::max(); + for (const auto& n : fronts) { + if (!same.count(n)) { + result = min(result, n); + } + } + for (const auto& n : backs) { + if (!same.count(n)) { + result = min(result, n); + } + } + return result != numeric_limits::max() ? result : 0; + } +}; From 375ccd62e6e597f6d1bb9ea60f90e50b90d6c99c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Apr 2018 18:37:01 +0800 Subject: [PATCH 4648/4971] Create binary-trees-with-factors.cpp --- C++/binary-trees-with-factors.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/binary-trees-with-factors.cpp diff --git a/C++/binary-trees-with-factors.cpp b/C++/binary-trees-with-factors.cpp new file mode 100644 index 000000000..3a451ba9b --- /dev/null +++ b/C++/binary-trees-with-factors.cpp @@ -0,0 +1,23 @@ +// Time: O(n^2) +// Space: O(n) + +class Solution { +public: + int numFactoredBinaryTrees(vector& A) { + static const int M = 1e9 + 7; + sort(A.begin(), A.end()); + unordered_map dp; + for (int i = 0; i < A.size(); ++i) { + dp[A[i]] = 1; + for (int j = 0; j < i; ++j) { + if (A[i] % A[j] == 0 && dp.count(A[i] / A[j])) { + dp[A[i]] = (dp[A[i]] + dp[A[j]] * dp[A[i] / A[j]]) % M; + } + } + } + return accumulate(dp.cbegin(), dp.cend(), 0L, + [](int64_t x, const pair& p) { + return x + p.second; + }) % M; + } +}; From ab16c9adeaa4aa9ce72da63e396f0863a3fa33c7 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 22 Apr 2018 18:40:31 +0800 Subject: [PATCH 4649/4971] Create binary-trees-with-factors.py --- Python/binary-trees-with-factors.py | 48 +++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/binary-trees-with-factors.py diff --git a/Python/binary-trees-with-factors.py b/Python/binary-trees-with-factors.py new file mode 100644 index 000000000..1afe4a291 --- /dev/null +++ b/Python/binary-trees-with-factors.py @@ -0,0 +1,48 @@ +# Time: O(n^2) +# Space: O(n) + +# Given an array of unique integers, each integer is strictly greater than 1. +# We make a binary tree using these integers and each number may be used for +# any number of times. +# Each non-leaf node's value should be equal to the product of the values of +# it's children. +# How many binary trees can we make? Return the answer modulo 10 ** 9 + 7. +# +# Example 1: +# +# Input: A = [2, 4] +# Output: 3 +# Explanation: We can make these trees: [2], [4], [4, 2, 2] +# Example 2: +# +# Input: A = [2, 4, 5, 10] +# Output: 7 +# Explanation: We can make these trees: +# [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]. +# +# Note: +# - 1 <= A.length <= 1000. +# - 2 <= A[i] <= 10 ^ 9. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def numFactoredBinaryTrees(self, A): + """ + :type A: List[int] + :rtype: int + """ + M = 10**9 + 7 + A.sort() + dp = {} + for i in xrange(len(A)): + dp[A[i]] = 1 + for j in xrange(i): + if A[i] % A[j] == 0 and A[i] // A[j] in dp: + dp[A[i]] += dp[A[j]] * dp[A[i] // A[j]] + dp[A[i]] %= M + return sum(dp.values()) % M From 05b609e6fe65afa18ff14ccba937cb35b0d7a8d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Apr 2018 18:47:40 +0800 Subject: [PATCH 4650/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 3a9990d8f..673e4d75c 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 795 | [Number of Subarrays with Bounded Maximum](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/) | [C++](./C++/number-of-subarrays-with-bounded-maximum.cpp) [Python](./Python/number-of-subarrays-with-bounded-maximum.py) | _O(n)_ | _O(1)_ | Medium || 803 | [Bricks Falling When Hit](https://leetcode.com/problems/bricks-falling-when-hit/) | [C++](./C++/bricks-falling-when-hit.cpp) [Python](./Python/bricks-falling-when-hit.py) | _O(r * c)_ | _O(r * c)_ | Hard || Union Find 807 | [Max Increase to Keep City Skyline](https://leetcode.com/problems/max-increase-to-keep-city-skyline/) | [C++](./C++/max-increase-to-keep-city-skyline.cpp) [Python](./Python/max-increase-to-keep-city-skyline.py) | _O(n^2)_ | _O(n)_ | Medium || +821 | [Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/) | [C++](./C++/shortest-distance-to-a-character.cpp) [Python](./Python/shortest-distance-to-a-character.py) | _O(n)_ | _O(n)_ | Easy || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -215,6 +216,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 809| [Expressive Words](https://leetcode.com/problems/expressive-words/) | [C++](./C++/expressive-words.cpp) [Python](./Python/expressive-words.py) | _O(n + s)_ | _O(l + s)_ | Medium ||| 816| [Ambiguous Coordinates](https://leetcode.com/problems/ambiguous-coordinates/) | [C++](./C++/ambiguous-coordinates.cpp) [Python](./Python/ambiguous-coordinates.py) | _O(n^4)_ | _O(n)_ | Medium ||| 819| [Most Common Word](https://leetcode.com/problems/most-common-word/) | [C++](./C++/most-common-word.cpp) [Python](./Python/most-common-word.py) | _O(m + n)_ | _O(m + n)_ | Easy ||| +820| [Short Encoding of Words](https://leetcode.com/problems/short-encoding-of-words/) | [C++](./C++/short-encoding-of-wordss.cpp) [Python](./Python/short-encoding-of-words.py) | _O(n)_ | _O(t)_ | Medium || Trie | ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -387,6 +389,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 760 | [Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings/) | [C++](./C++/find-anagram-mappings.cpp) [Python](./Python/find-anagram-mappings.py) | _O(n)_ | _O(n)_ | Easy || 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/) | [C++](./C++/jewels-and-stones.cpp) [Python](./Python/jewels-and-stones.py) | _O(m + n)_ | _O(n)_ | Easy || 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [C++](./C++/subdomain-visit-count.cpp) [Python](./Python/subdomain-visit-count.py) | _O(n)_ | _O(n)_ | Easy || +822 | [Card Flipping Game](https://leetcode.com/problems/card-flipping-game/) | [C++](./C++/card-flipping-game.cpp) [Python](./Python/card-flipping-game.py) | _O(n)_ | _O(n)_ | Medium || ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -768,6 +771,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 808 | [Soup Servings](https://leetcode.com/problems/soup-servings/) | [C++](./C++/soup-servings.cpp) [Python](./Python/soup-servings.py) | _O(1)_ | _O(1)_ | Medium || Memoization | 813 | [Largest Sum of Averages](https://leetcode.com/problems/largest-sum-of-averages/) | [C++](./C++/largest-sum-of-averages.cpp) [Python](./Python/largest-sum-of-averages.py) | _O(k * n^2)_ | _O(n)_ | Medium || | 818 | [Race Car](https://leetcode.com/problems/race-car/) | [C++](./C++/race-car.cpp) [Python](./Python/race-car.py) | _O(nlogn)_ | _O(n)_ | Hard || | +823 | [Binary Trees With Factors](https://leetcode.com/problems/binary-trees-with-factors/) | [C++](./C++/binary-trees-with-factors.cpp) [Python](./Python/binary-trees-with-factors.py) | _O(n^2)_ | _O(n)_ | Medium || | ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 3431cf1fe5d8f98cdfd550ae30c387e9033259ea Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Apr 2018 18:49:25 +0800 Subject: [PATCH 4651/4971] Update shortest-distance-to-a-character.cpp --- C++/shortest-distance-to-a-character.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/shortest-distance-to-a-character.cpp b/C++/shortest-distance-to-a-character.cpp index f7df3a1ee..872ae0daf 100644 --- a/C++/shortest-distance-to-a-character.cpp +++ b/C++/shortest-distance-to-a-character.cpp @@ -1,5 +1,5 @@ // Time: O(n) -// Space: O(n) +// Space: O(1) class Solution { public: From 528401b2c5cab29e301814da1754f0c0c41bdcd1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Apr 2018 18:49:38 +0800 Subject: [PATCH 4652/4971] Update shortest-distance-to-a-character.py --- Python/shortest-distance-to-a-character.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/shortest-distance-to-a-character.py b/Python/shortest-distance-to-a-character.py index a5d0b9bf4..80099f9f9 100644 --- a/Python/shortest-distance-to-a-character.py +++ b/Python/shortest-distance-to-a-character.py @@ -1,5 +1,5 @@ # Time: O(n) -# Space: O(n) +# Space: O(1) # Given a string S and a character C, # return an array of integers representing the shortest distance From c0a1952d55748ec3ecc62e3d980a8e2389d5e004 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 22 Apr 2018 18:50:04 +0800 Subject: [PATCH 4653/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 673e4d75c..23976df57 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 795 | [Number of Subarrays with Bounded Maximum](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/) | [C++](./C++/number-of-subarrays-with-bounded-maximum.cpp) [Python](./Python/number-of-subarrays-with-bounded-maximum.py) | _O(n)_ | _O(1)_ | Medium || 803 | [Bricks Falling When Hit](https://leetcode.com/problems/bricks-falling-when-hit/) | [C++](./C++/bricks-falling-when-hit.cpp) [Python](./Python/bricks-falling-when-hit.py) | _O(r * c)_ | _O(r * c)_ | Hard || Union Find 807 | [Max Increase to Keep City Skyline](https://leetcode.com/problems/max-increase-to-keep-city-skyline/) | [C++](./C++/max-increase-to-keep-city-skyline.cpp) [Python](./Python/max-increase-to-keep-city-skyline.py) | _O(n^2)_ | _O(n)_ | Medium || -821 | [Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/) | [C++](./C++/shortest-distance-to-a-character.cpp) [Python](./Python/shortest-distance-to-a-character.py) | _O(n)_ | _O(n)_ | Easy || +821 | [Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/) | [C++](./C++/shortest-distance-to-a-character.cpp) [Python](./Python/shortest-distance-to-a-character.py) | _O(n)_ | _O(1)_ | Easy || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From c1baa454d3449f2291ffdce30c4f70b73067d1c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Apr 2018 15:40:38 +0800 Subject: [PATCH 4654/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 23976df57..3e9785493 100644 --- a/README.md +++ b/README.md @@ -607,7 +607,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 666| [Path Sum IV](https://leetcode.com/problems/path-sum-iv/)| [C++](./C++/path-sum-iv.cpp) [Python](./Python/path-sum-iv.py) | _O(n)_ | _O(w)_ | Medium |📖| Topological Sort | 675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | 742|[Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree/)| [C++](./C++/closest-leaf-in-a-binary-tree.cpp) [Python](./Python/closest-leaf-in-a-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | | | -743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O(\|E\| + \|V\|log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | +743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O((\|E\| + \|V\|) * log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | 752|[Open the Lock](https://leetcode.com/problems/open-the-lock/)| [C++](./C++/open-the-lock.cpp) [Python](./Python/open-the-lock.py)| _O(k * n^k + d)_ | _O(k * n^k + d)_ | Medium | | | 773|[Sliding Puzzle](https://leetcode.com/problems/sliding-puzzle/)| [C++](./C++/sliding-puzzle.cpp) [Python](./Python/sliding-puzzle.py)| _O((m * n) * (m * n)!)_ | _O((m * n) * (m * n)!)_ | Hard | | `A* Search Algorithm` | 787|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| [C++](./C++/cheapest-flights-within-k-stops.cpp) [Python](./Python/cheapest-flights-within-k-stops.py)| _O(\|E\| + \|V\|log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | From 038d1dc8e541fe85f46783c3ab235704c2f67a8f Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Apr 2018 15:41:11 +0800 Subject: [PATCH 4655/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3e9785493..5f8cfa59e 100644 --- a/README.md +++ b/README.md @@ -610,7 +610,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O((\|E\| + \|V\|) * log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | 752|[Open the Lock](https://leetcode.com/problems/open-the-lock/)| [C++](./C++/open-the-lock.cpp) [Python](./Python/open-the-lock.py)| _O(k * n^k + d)_ | _O(k * n^k + d)_ | Medium | | | 773|[Sliding Puzzle](https://leetcode.com/problems/sliding-puzzle/)| [C++](./C++/sliding-puzzle.cpp) [Python](./Python/sliding-puzzle.py)| _O((m * n) * (m * n)!)_ | _O((m * n) * (m * n)!)_ | Hard | | `A* Search Algorithm` | -787|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| [C++](./C++/cheapest-flights-within-k-stops.cpp) [Python](./Python/cheapest-flights-within-k-stops.py)| _O(\|E\| + \|V\|log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | +787|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| [C++](./C++/cheapest-flights-within-k-stops.cpp) [Python](./Python/cheapest-flights-within-k-stops.py)| _O((\|E\| + \|V\|) * log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | 815|[Bus Routes](https://leetcode.com/problems/bus-routes/)| [C++](./C++/bus-routes.cpp) [Python](./Python/bus-routes.py)| _O(\|E\| + \|V\|)_ | _O(\|E\| + \|V\|)_ | Hard | | | ## Depth-First Search From 47ca44dd80dbf3e446ba4035ff4f9bc0ef71d2cd Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Apr 2018 15:41:39 +0800 Subject: [PATCH 4656/4971] Update network-delay-time.py --- Python/network-delay-time.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index f4251b59a..2232101fe 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -1,4 +1,4 @@ -# Time: O(|E| + |V|log|V|) +# Time: O((|E| + |V|) * log|V|) # Space: O(|E| + |V|) # There are N network nodes, labelled 1 to N. From dc4a4f796a7a559eb021f49ac01f7d2fe637208e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Apr 2018 15:42:04 +0800 Subject: [PATCH 4657/4971] Update network-delay-time.cpp --- C++/network-delay-time.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/network-delay-time.cpp b/C++/network-delay-time.cpp index 444e033dd..7b226d905 100644 --- a/C++/network-delay-time.cpp +++ b/C++/network-delay-time.cpp @@ -1,4 +1,4 @@ -// Time: O(|E| + |V|log|V|) +// Time: O((|E| + |V|) * log|V|) // Space: O(|E| + |V|) // Dijkstra's algorithm From fe703d9615ffcf1de69558b3e48e9b84b2b5c853 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Apr 2018 15:42:21 +0800 Subject: [PATCH 4658/4971] Update cheapest-flights-within-k-stops.cpp --- C++/cheapest-flights-within-k-stops.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/cheapest-flights-within-k-stops.cpp b/C++/cheapest-flights-within-k-stops.cpp index 7a8e22cda..cc0be8b47 100644 --- a/C++/cheapest-flights-within-k-stops.cpp +++ b/C++/cheapest-flights-within-k-stops.cpp @@ -1,4 +1,4 @@ -// Time: O(|E| + |V|log|V|) +// Time: O((|E| + |V|) * log|V|) // Space: O(|E| + |V|) class Solution { From 27ac99c0535709ac0fd36af49c68c1603e0f52d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 24 Apr 2018 15:42:53 +0800 Subject: [PATCH 4659/4971] Update cheapest-flights-within-k-stops.py --- Python/cheapest-flights-within-k-stops.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/cheapest-flights-within-k-stops.py b/Python/cheapest-flights-within-k-stops.py index f104bea2c..953bb5617 100644 --- a/Python/cheapest-flights-within-k-stops.py +++ b/Python/cheapest-flights-within-k-stops.py @@ -1,4 +1,4 @@ -# Time: O(|E| + |V|log|V|) +# Time: O((|E| + |V|) * log|V|) # Space: O(|E| + |V|) # There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w. From f9c087041b38677f1d0a635880c8941440a39fe9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Apr 2018 13:53:40 +0800 Subject: [PATCH 4660/4971] Update network-delay-time.py --- Python/network-delay-time.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index 2232101fe..2a4dc3919 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -1,4 +1,4 @@ -# Time: O((|E| + |V|) * log|V|) +# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) # Space: O(|E| + |V|) # There are N network nodes, labelled 1 to N. From 7df5d3038f8e3e06689c0b891c8d59064d05ec8d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Apr 2018 13:53:56 +0800 Subject: [PATCH 4661/4971] Update cheapest-flights-within-k-stops.cpp --- C++/cheapest-flights-within-k-stops.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/cheapest-flights-within-k-stops.cpp b/C++/cheapest-flights-within-k-stops.cpp index cc0be8b47..e6d12e3b3 100644 --- a/C++/cheapest-flights-within-k-stops.cpp +++ b/C++/cheapest-flights-within-k-stops.cpp @@ -1,4 +1,4 @@ -// Time: O((|E| + |V|) * log|V|) +// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) // Space: O(|E| + |V|) class Solution { From 5ed3f2273845462e921a180e6b6525788d6ff3a4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Apr 2018 13:54:24 +0800 Subject: [PATCH 4662/4971] Update network-delay-time.cpp --- C++/network-delay-time.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/network-delay-time.cpp b/C++/network-delay-time.cpp index 7b226d905..3c8c9e0fe 100644 --- a/C++/network-delay-time.cpp +++ b/C++/network-delay-time.cpp @@ -1,4 +1,4 @@ -// Time: O((|E| + |V|) * log|V|) +// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) // Space: O(|E| + |V|) // Dijkstra's algorithm From 5f869a28f8258057caac166371a5d2f32e29cf47 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Apr 2018 13:58:33 +0800 Subject: [PATCH 4663/4971] Update cheapest-flights-within-k-stops.py --- Python/cheapest-flights-within-k-stops.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/cheapest-flights-within-k-stops.py b/Python/cheapest-flights-within-k-stops.py index 953bb5617..00cb552b5 100644 --- a/Python/cheapest-flights-within-k-stops.py +++ b/Python/cheapest-flights-within-k-stops.py @@ -1,4 +1,4 @@ -# Time: O((|E| + |V|) * log|V|) +# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) # Space: O(|E| + |V|) # There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w. From dac933b3e5e6c5564400b065c2eba5637e286fee Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Apr 2018 13:59:57 +0800 Subject: [PATCH 4664/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5f8cfa59e..33a94ad2c 100644 --- a/README.md +++ b/README.md @@ -607,10 +607,10 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 666| [Path Sum IV](https://leetcode.com/problems/path-sum-iv/)| [C++](./C++/path-sum-iv.cpp) [Python](./Python/path-sum-iv.py) | _O(n)_ | _O(w)_ | Medium |📖| Topological Sort | 675|[Cut Off Trees for Golf Event](https://leetcode.com/problems/cut-off-trees-for-golf-event/)| [C++](./C++/cut-off-trees-for-golf-event.cpp) [Python](./Python/cut-off-trees-for-golf-event.py)| _O(t * m * n)_ | _O(m * n)_ | Hard | | `A* Search Algorithm` | 742|[Closest Leaf in a Binary Tree](https://leetcode.com/problems/closest-leaf-in-a-binary-tree/)| [C++](./C++/closest-leaf-in-a-binary-tree.cpp) [Python](./Python/closest-leaf-in-a-binary-tree.py)| _O(n)_ | _O(n)_ | Medium | | | -743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O((\|E\| + \|V\|) * log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | +743|[Network Delay Time](https://leetcode.com/problems/network-delay-time/)| [C++](./C++/network-delay-time.cpp) [Python](./Python/network-delay-time.py)| _O(\|E\| * log\|V\|)_ | _O(\|E\|)_ | Medium | | `Dijkstra's algorithm` | 752|[Open the Lock](https://leetcode.com/problems/open-the-lock/)| [C++](./C++/open-the-lock.cpp) [Python](./Python/open-the-lock.py)| _O(k * n^k + d)_ | _O(k * n^k + d)_ | Medium | | | 773|[Sliding Puzzle](https://leetcode.com/problems/sliding-puzzle/)| [C++](./C++/sliding-puzzle.cpp) [Python](./Python/sliding-puzzle.py)| _O((m * n) * (m * n)!)_ | _O((m * n) * (m * n)!)_ | Hard | | `A* Search Algorithm` | -787|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| [C++](./C++/cheapest-flights-within-k-stops.cpp) [Python](./Python/cheapest-flights-within-k-stops.py)| _O((\|E\| + \|V\|) * log\|V\|)_ | _O(\|E\| + \|V\|)_ | Medium | | `Dijkstra's algorithm` | +787|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| [C++](./C++/cheapest-flights-within-k-stops.cpp) [Python](./Python/cheapest-flights-within-k-stops.py)| _O(\|E\| * log\|V\|)_ | _O(\|E\|)_ | Medium | | `Dijkstra's algorithm` | 815|[Bus Routes](https://leetcode.com/problems/bus-routes/)| [C++](./C++/bus-routes.cpp) [Python](./Python/bus-routes.py)| _O(\|E\| + \|V\|)_ | _O(\|E\| + \|V\|)_ | Hard | | | ## Depth-First Search From cc1b3b7638efbd10b9e69821865ce6b219409926 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Apr 2018 14:00:24 +0800 Subject: [PATCH 4665/4971] Update network-delay-time.cpp --- C++/network-delay-time.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/network-delay-time.cpp b/C++/network-delay-time.cpp index 3c8c9e0fe..f3489d721 100644 --- a/C++/network-delay-time.cpp +++ b/C++/network-delay-time.cpp @@ -1,5 +1,5 @@ // Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) -// Space: O(|E| + |V|) +// Space: O(|E| + |V|) = O(|E|) // Dijkstra's algorithm class Solution { From a09e58c731098f3319bdb8db0b3b185b0c590edd Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Apr 2018 14:00:32 +0800 Subject: [PATCH 4666/4971] Update network-delay-time.py --- Python/network-delay-time.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index 2a4dc3919..347d39690 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -1,5 +1,5 @@ # Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) -# Space: O(|E| + |V|) +# Space: O(|E| + |V|) = O(|E|) # There are N network nodes, labelled 1 to N. # From 5f454b114de9de8a47ace17e91e8e2520e7a0338 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Apr 2018 14:00:40 +0800 Subject: [PATCH 4667/4971] Update cheapest-flights-within-k-stops.cpp --- C++/cheapest-flights-within-k-stops.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/cheapest-flights-within-k-stops.cpp b/C++/cheapest-flights-within-k-stops.cpp index e6d12e3b3..cd2eada48 100644 --- a/C++/cheapest-flights-within-k-stops.cpp +++ b/C++/cheapest-flights-within-k-stops.cpp @@ -1,5 +1,5 @@ // Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) -// Space: O(|E| + |V|) +// Space: O(|E| + |V|) = O(|E|) class Solution { public: From a1fc7311ddc50eb43f43fc51d3290f2c91fd4fa1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 25 Apr 2018 14:00:48 +0800 Subject: [PATCH 4668/4971] Update cheapest-flights-within-k-stops.py --- Python/cheapest-flights-within-k-stops.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/cheapest-flights-within-k-stops.py b/Python/cheapest-flights-within-k-stops.py index 00cb552b5..f3a130f1e 100644 --- a/Python/cheapest-flights-within-k-stops.py +++ b/Python/cheapest-flights-within-k-stops.py @@ -1,5 +1,5 @@ # Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) -# Space: O(|E| + |V|) +# Space: O(|E| + |V|) = O(|E|) # There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w. # From 3c48035c560ace2c98bf53535ee82856774a4fa7 Mon Sep 17 00:00:00 2001 From: Zhiliang Gong Date: Sat, 28 Apr 2018 17:18:32 -0500 Subject: [PATCH 4669/4971] hanle strings with spaces --- Python/string-to-integer-atoi.py | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/Python/string-to-integer-atoi.py b/Python/string-to-integer-atoi.py index d59faea1a..221ef98bd 100644 --- a/Python/string-to-integer-atoi.py +++ b/Python/string-to-integer-atoi.py @@ -27,7 +27,7 @@ # class Solution(object): - def myAtoi(self, str): + def atoi(self, str): """ :type str: str :rtype: int @@ -43,23 +43,27 @@ def myAtoi(self, str): while i < len(str) and str[i].isspace(): i += 1 - sign = 1 - if str[i] == "+": - i += 1 - elif str[i] == "-": - sign = -1 - i += 1 + if len(str) == i: + return result + else: + sign = 1 + if str[i] == "+": + i += 1 + elif str[i] == "-": + sign = -1 + i += 1 - while i < len(str) and '0' <= str[i] <= '9': - if result > (INT_MAX - int(str[i])) / 10: - return INT_MAX if sign > 0 else INT_MIN - result = result * 10 + int(str[i]) - i += 1 + while i < len(str) and '0' <= str[i] <= '9': + if result > (INT_MAX - int(str[i])) / 10: + return INT_MAX if sign > 0 else INT_MIN + result = result * 10 + int(str[i]) + i += 1 - return sign * result + return sign * result if __name__ == "__main__": print Solution().atoi("") + print Solution().atoi(" ") print Solution().atoi("-1") print Solution().atoi("2147483647") print Solution().atoi("2147483648") From c62ceaab233b0e2f60d5553e6b6f359cc6e0ae35 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Apr 2018 17:24:12 +0800 Subject: [PATCH 4670/4971] Update string-to-integer-atoi.py --- Python/string-to-integer-atoi.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/Python/string-to-integer-atoi.py b/Python/string-to-integer-atoi.py index 221ef98bd..6266344fb 100644 --- a/Python/string-to-integer-atoi.py +++ b/Python/string-to-integer-atoi.py @@ -45,21 +45,22 @@ def atoi(self, str): if len(str) == i: return result - else: - sign = 1 - if str[i] == "+": - i += 1 - elif str[i] == "-": - sign = -1 - i += 1 - while i < len(str) and '0' <= str[i] <= '9': - if result > (INT_MAX - int(str[i])) / 10: - return INT_MAX if sign > 0 else INT_MIN - result = result * 10 + int(str[i]) - i += 1 + sign = 1 + if str[i] == "+": + i += 1 + elif str[i] == "-": + sign = -1 + i += 1 + + while i < len(str) and '0' <= str[i] <= '9': + if result > (INT_MAX - int(str[i])) / 10: + return INT_MAX if sign > 0 else INT_MIN + result = result * 10 + int(str[i]) + i += 1 + + return sign * result - return sign * result if __name__ == "__main__": print Solution().atoi("") From 0983a44a77bd6598c615d00e6475adb8fe9f6ddd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Apr 2018 17:26:35 +0800 Subject: [PATCH 4671/4971] Create goat-latin.cpp --- C++/goat-latin.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/goat-latin.cpp diff --git a/C++/goat-latin.cpp b/C++/goat-latin.cpp new file mode 100644 index 000000000..f74c09720 --- /dev/null +++ b/C++/goat-latin.cpp @@ -0,0 +1,33 @@ +// Time: O(n + w^2), n = w * l, +// n is the length of S, +// w is the number of words, +// l is the average of word lengths +// Space: O(l) + +class Solution { +public: + string toGoatLatin(string S) { + unordered_set vowel{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; + string result, word; + int count = 0; + for (int i = 0; i < S.length(); ++i) { + if (S[i] != ' ') { + word.push_back(S[i]); + if (i != S.length() - 1) { + continue; + } + } + if (!vowel.count(word.front())) { + word.push_back(word.front()); + word = word.substr(1); + } + word += "ma"; + word += string(++count, 'a'); + result += word; + result += " "; + word.clear(); + } + result.pop_back(); + return result; + } +}; From e94a475b09f86f0d8aab2dcce9c7ca9b5cc1606b Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 29 Apr 2018 17:30:43 +0800 Subject: [PATCH 4672/4971] Create goat-latin.py --- Python/goat-latin.py | 54 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/goat-latin.py diff --git a/Python/goat-latin.py b/Python/goat-latin.py new file mode 100644 index 000000000..df8e5b915 --- /dev/null +++ b/Python/goat-latin.py @@ -0,0 +1,54 @@ +# A sentence S is given, composed of words separated by spaces. +# Each word consists of lowercase and uppercase letters only. +# +# We would like to convert the sentence to "Goat Latin" +# (a made-up language similar to Pig Latin.) +# +# The rules of Goat Latin are as follows: +# +# If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of +# the word. +# For example, the word 'apple' becomes 'applema'. +# +# If a word begins with a consonant (i.e. not a vowel), +# remove the first letter and append it to the end, then add "ma". +# For example, the word "goat" becomes "oatgma". +# +# Add one letter 'a' to the end of each word per its word index in the +# sentence, +# starting with 1. +# For example, the first word gets "a" added to the end, +# the second word gets "aa" added to the end and so on. +# Return the final sentence representing the conversion from S to Goat Latin. +# +# Example 1: +# +# Input: "I speak Goat Latin" +# Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" +# Example 2: +# +# Input: "The quick brown fox jumped over the lazy dog" +# Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa +# overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" +# +# Notes: +# - S contains only uppercase, lowercase and spaces. Exactly one space between +# each word. +# - 1 <= S.length <= 100. + + +class Solution(object): + def toGoatLatin(self, S): + """ + :type S: str + :rtype: str + """ + vowel = set('aeiouAEIOU') + + def convert(word): + if word[0] not in vowel: + word = word[1:] + word[:1] + return word + 'ma' + + return " ".join(convert(word) + 'a'*i + for i, word in enumerate(S.split(), 1)) From 6340fa8ed00477ee0d43d69645ed0ca0270983f9 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 29 Apr 2018 17:38:17 +0800 Subject: [PATCH 4673/4971] Update goat-latin.py --- Python/goat-latin.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/Python/goat-latin.py b/Python/goat-latin.py index df8e5b915..b986120aa 100644 --- a/Python/goat-latin.py +++ b/Python/goat-latin.py @@ -1,3 +1,9 @@ +# Time: O(n + w^2), n = w * l, +# n is the length of S, +# w is the number of word, +# l is the average length of word +# Space: O(n) + # A sentence S is given, composed of words separated by spaces. # Each word consists of lowercase and uppercase letters only. # @@ -43,12 +49,10 @@ def toGoatLatin(self, S): :type S: str :rtype: str """ - vowel = set('aeiouAEIOU') - - def convert(word): - if word[0] not in vowel: - word = word[1:] + word[:1] - return word + 'ma' - - return " ".join(convert(word) + 'a'*i - for i, word in enumerate(S.split(), 1)) + def convert(): + vowel = set('aeiouAEIOU') + for i, word in enumerate(S.split(), 1): + if word[0] not in vowel: + word = word[1:] + word[:1] + yield word + 'ma' + 'a'*i + return " ".join(convert()) From c1548bbadb28033f8c328836725651828a4274b2 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 29 Apr 2018 17:39:11 +0800 Subject: [PATCH 4674/4971] Update goat-latin.py --- Python/goat-latin.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/goat-latin.py b/Python/goat-latin.py index b986120aa..fe1c3e56d 100644 --- a/Python/goat-latin.py +++ b/Python/goat-latin.py @@ -49,10 +49,10 @@ def toGoatLatin(self, S): :type S: str :rtype: str """ - def convert(): + def convert(S): vowel = set('aeiouAEIOU') for i, word in enumerate(S.split(), 1): if word[0] not in vowel: word = word[1:] + word[:1] yield word + 'ma' + 'a'*i - return " ".join(convert()) + return " ".join(convert(S)) From 596fb0beed193abb523f8bf2e583429e6f8f8572 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Apr 2018 17:42:49 +0800 Subject: [PATCH 4675/4971] Update string-to-integer-atoi.py --- Python/string-to-integer-atoi.py | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/Python/string-to-integer-atoi.py b/Python/string-to-integer-atoi.py index 6266344fb..ae716b3ec 100644 --- a/Python/string-to-integer-atoi.py +++ b/Python/string-to-integer-atoi.py @@ -27,7 +27,7 @@ # class Solution(object): - def atoi(self, str): + def myAtoi(self, str): """ :type str: str :rtype: int @@ -60,13 +60,3 @@ def atoi(self, str): i += 1 return sign * result - - -if __name__ == "__main__": - print Solution().atoi("") - print Solution().atoi(" ") - print Solution().atoi("-1") - print Solution().atoi("2147483647") - print Solution().atoi("2147483648") - print Solution().atoi("-2147483648") - print Solution().atoi("-2147483649") From 71ea00e39c68ef9c6711ab0d07be755e11cdde1c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Apr 2018 17:53:39 +0800 Subject: [PATCH 4676/4971] Update string-to-integer-atoi.cpp --- C++/string-to-integer-atoi.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/C++/string-to-integer-atoi.cpp b/C++/string-to-integer-atoi.cpp index c8de958d5..06a67c731 100644 --- a/C++/string-to-integer-atoi.cpp +++ b/C++/string-to-integer-atoi.cpp @@ -17,6 +17,10 @@ class Solution { ++i; } + if (i == str.length()) { + return 0; + } + // Parse sign. if (str[i] == '+') { ++i; From 5f31e729ce6752c2f0a6b7f19f76c2a7e95636b9 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 29 Apr 2018 20:20:25 +0800 Subject: [PATCH 4677/4971] Create friends-of-appropriate-ages.py --- Python/friends-of-appropriate-ages.py | 61 +++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/friends-of-appropriate-ages.py diff --git a/Python/friends-of-appropriate-ages.py b/Python/friends-of-appropriate-ages.py new file mode 100644 index 000000000..b1ccb730d --- /dev/null +++ b/Python/friends-of-appropriate-ages.py @@ -0,0 +1,61 @@ +# Time: O(a^2 + n), a is the number of ages, +# n is the number of people +# Space: O(a) + +# Some people will make friend requests. +# The list of their ages is given and ages[i] is the age of the ith person. +# +# Person A will NOT friend request person B (B != A) +# if any of the following conditions are true: +# +# age[B] <= 0.5 * age[A] + 7 +# age[B] > age[A] +# age[B] > 100 && age[A] < 100 +# Otherwise, A will friend request B. +# +# Note that if A requests B, B does not necessarily request A. +# Also, people will not friend request themselves. +# +# How many total friend requests are made? +# +# Example 1: +# +# Input: [16,16] +# Output: 2 +# Explanation: 2 people friend request each other. +# Example 2: +# +# Input: [16,17,18] +# Output: 2 +# Explanation: Friend requests are made 17 -> 16, 18 -> 17. +# Example 3: +# +# Input: [20,30,100,110,120] +# Output: +# Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. +# +# Notes: +# - 1 <= ages.length <= 20000. +# - 1 <= ages[i] <= 120. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + +import collections + + +class Solution(object): + def numFriendRequests(self, ages): + """ + :type ages: List[int] + :rtype: int + """ + def request(a, b): + return 0.5*a+7 < b <= a + + c = collections.Counter(ages) + return sum(int(request(a, b)) * c[a]*(c[b]-int(a == b)) + for a in c + for b in c) From 36baad3065302ee83c0821be5aeeb39b43ef3faa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Apr 2018 20:21:44 +0800 Subject: [PATCH 4678/4971] Create friends-of-appropriate-ages.cpp --- C++/friends-of-appropriate-ages.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/friends-of-appropriate-ages.cpp diff --git a/C++/friends-of-appropriate-ages.cpp b/C++/friends-of-appropriate-ages.cpp new file mode 100644 index 000000000..b1cdfe6c6 --- /dev/null +++ b/C++/friends-of-appropriate-ages.cpp @@ -0,0 +1,27 @@ +// Time: O(a^2 + n), a is the number of ages, +// n is the number of people +// Space: O(a) + +class Solution { +public: + int numFriendRequests(vector& ages) { + unordered_map count; + for (const auto &age : ages) { + ++count[age]; + } + int result = 0; + for (const auto &a: count) { + for (const auto &b: count) { + if (request(a.first, b.first)) { + result += a.second * (b.second - (a.first == b.first ? 1 : 0)); + } + } + } + return result; + } + +private: + bool request(int a, int b) { + return 0.5 * a + 7 < b && b <= a; + } +}; From 4cfeada92462ab8c7d3455f4b12e507c1dc90967 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Apr 2018 20:35:42 +0800 Subject: [PATCH 4679/4971] Create most-profit-assigning-work.cpp --- C++/most-profit-assigning-work.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/most-profit-assigning-work.cpp diff --git a/C++/most-profit-assigning-work.cpp b/C++/most-profit-assigning-work.cpp new file mode 100644 index 000000000..6e042201e --- /dev/null +++ b/C++/most-profit-assigning-work.cpp @@ -0,0 +1,24 @@ +// Time: O(mlogm + nlogn), m is the number of workers, +// , n is the number of jobs +// Space: O(n) + +class Solution { +public: + int maxProfitAssignment(vector& difficulty, vector& profit, vector& worker) { + vector> jobs; + for (int i = 0; i < profit.size(); ++i) { + jobs.emplace_back(difficulty[i], profit[i]); + } + sort(jobs.begin(), jobs.end()); + sort(worker.begin(), worker.end()); + + int result = 0, i = 0, max_profit = 0; + for (const auto& ability: worker) { + while (i < profit.size() && jobs[i].first <= ability) { + max_profit = max(max_profit, jobs[i++].second); + } + result += max_profit; + } + return result; + } +}; From cc8d7fb60b571aa4d3f4dac3d5777e2b6a28815a Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 29 Apr 2018 20:40:58 +0800 Subject: [PATCH 4680/4971] Create most-profit-assigning-work.py --- Python/most-profit-assigning-work.py | 52 ++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/most-profit-assigning-work.py diff --git a/Python/most-profit-assigning-work.py b/Python/most-profit-assigning-work.py new file mode 100644 index 000000000..d81c72f0c --- /dev/null +++ b/Python/most-profit-assigning-work.py @@ -0,0 +1,52 @@ +# Time: O(mlogm + nlogn), m is the number of workers, +# , n is the number of jobs +# Space: O(n) + +# We have jobs: difficulty[i] is the difficulty of the ith job, +# and profit[i] is the profit of the ith job. +# +# Now we have some workers. worker[i] is the ability of the ith worker, +# which means that this worker can only complete a job with difficulty +# at most worker[i]. +# +# Every worker can be assigned at most one job, but one job can be completed +# multiple times. +# +# For example, if 3 people attempt the same job that pays $1, then the total +# profit will be $3. +# If a worker cannot complete any job, his profit is $0. +# +# What is the most profit we can make? +# +# Example 1: +# +# Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], +# worker = [4,5,6,7] +# Output: 100 +# Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and +# they get profit of [20,20,30,30] seperately. +# +# Notes: +# - 1 <= difficulty.length = profit.length <= 10000 +# - 1 <= worker.length <= 10000 +# - difficulty[i], profit[i], worker[i] are in range [1, 10^5] + + +class Solution(object): + def maxProfitAssignment(self, difficulty, profit, worker): + """ + :type difficulty: List[int] + :type profit: List[int] + :type worker: List[int] + :rtype: int + """ + jobs = zip(difficulty, profit) + jobs.sort() + worker.sort() + result, i, max_profit = 0, 0, 0 + for ability in worker: + while i < len(jobs) and jobs[i][0] <= ability: + max_profit = max(max_profit, jobs[i][1]) + i += 1 + result += max_profit + return result From 97a4a531bc05f7dd5a172b5d4657b300744c954f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 29 Apr 2018 21:06:55 +0800 Subject: [PATCH 4681/4971] Create making-a-large-island.py --- Python/making-a-large-island.py | 77 +++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Python/making-a-large-island.py diff --git a/Python/making-a-large-island.py b/Python/making-a-large-island.py new file mode 100644 index 000000000..669a6bd06 --- /dev/null +++ b/Python/making-a-large-island.py @@ -0,0 +1,77 @@ +# Time: O(n^2) +# Space: O(n^2) + +# In a 2D grid of 0s and 1s, we change at most one 0 to a 1. +# +# After, what is the size of the largest island? +# (An island is a 4-directionally connected group of 1s). +# +# Example 1: +# +# Input: [[1, 0], [0, 1]] +# Output: 3 +# Explanation: Change one 0 to 1 and connect two 1s, +# then we get an island with area = 3. +# Example 2: +# +# Input: [[1, 1], [1, 0]] +# Output: 4 +# Explanation: Change the 0 to 1 and make the island bigger, +# only one island with area = 1. +# Example 3: +# +# Input: [[1, 1], [1, 1]] +# Output: 4 +# Explanation: Can't change any 0 to 1, only one island with area = 1. +# +# Notes: +# - 1 <= grid.length = grid[0].length <= 50. +# - 0 <= grid[i][j] <= 1. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def largestIsland(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + + def dfs(r, c, index, grid): + if not (0 <= r < len(grid) and + 0 <= c < len(grid[0]) and + grid[r][c] == 1): + return 0 + result = 1 + grid[r][c] = index + for d in directions: + result += dfs(r+d[0], c+d[1], index, grid) + return result + + area = {} + index = 2 + for r in xrange(len(grid)): + for c in xrange(len(grid[r])): + if grid[r][c] == 1: + area[index] = dfs(r, c, index, grid) + index += 1 + + result = max(area.values() or [0]) + for r in xrange(len(grid)): + for c in xrange(len(grid[r])): + if grid[r][c] == 0: + seen = set() + for d in directions: + nr, nc = r+d[0], c+d[1] + if not (0 <= nr < len(grid) and + 0 <= nc < len(grid[0]) and + grid[nr][nc] > 1): + continue + seen.add(grid[nr][nc]) + result = max(result, 1 + sum(area[i] for i in seen)) + return result From c046ef50106affea5313d6cbdff15196f12a8084 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Apr 2018 21:22:53 +0800 Subject: [PATCH 4682/4971] Create making-a-large-island.cpp --- C++/making-a-large-island.cpp | 60 +++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 C++/making-a-large-island.cpp diff --git a/C++/making-a-large-island.cpp b/C++/making-a-large-island.cpp new file mode 100644 index 000000000..02af3f7a1 --- /dev/null +++ b/C++/making-a-large-island.cpp @@ -0,0 +1,60 @@ +// Time: O(n^2) +// Space: O(n^2) + +class Solution { +public: + int largestIsland(vector>& grid) { + int result = 0; + unordered_map area; + int index = 2; + for (int r = 0; r < grid.size(); ++r) { + for (int c = 0; c < grid[r].size(); ++c) { + if (grid[r][c] != 1) { + continue; + } + area[index] = dfs(r, c, index, &grid); + result = max(result, area[index++]); + } + } + + for (int r = 0; r < grid.size(); ++r) { + for (int c = 0; c < grid[r].size(); ++c) { + if (grid[r][c] != 0) { + continue; + } + unordered_set seen; + for (const auto& d :directions) { + int nr = r + d.first, nc = c + d.second; + if (0 <= nr && nr < grid.size() && + 0 <= nc && nc < grid[0].size() && + grid[nr][nc] > 1) { + seen.emplace(grid[nr][nc]); + } + } + int sum = 0; + for (const auto& i : seen) { + sum += area[i]; + } + result = max(result, 1 + sum); + } + } + return result; + } + +private: + const vector> directions{{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; + + int dfs(int r, int c, int index, vector> *grid) { + if (!(0 <= r && r < grid->size() && + 0 <= c && c < (*grid)[0].size() && + (*grid)[r][c] == 1)) { + return 0; + } + int result = 1; + (*grid)[r][c] = index; + for (const auto& d :directions) { + result += dfs(r + d.first, c + d.second, index, grid); + } + return result; + } +}; From 3b185b28d00c9b18aa159f8bdf216df329c9ba82 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 29 Apr 2018 21:35:52 +0800 Subject: [PATCH 4683/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 33a94ad2c..8b4af7dd2 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 816| [Ambiguous Coordinates](https://leetcode.com/problems/ambiguous-coordinates/) | [C++](./C++/ambiguous-coordinates.cpp) [Python](./Python/ambiguous-coordinates.py) | _O(n^4)_ | _O(n)_ | Medium ||| 819| [Most Common Word](https://leetcode.com/problems/most-common-word/) | [C++](./C++/most-common-word.cpp) [Python](./Python/most-common-word.py) | _O(m + n)_ | _O(m + n)_ | Easy ||| 820| [Short Encoding of Words](https://leetcode.com/problems/short-encoding-of-words/) | [C++](./C++/short-encoding-of-wordss.cpp) [Python](./Python/short-encoding-of-words.py) | _O(n)_ | _O(t)_ | Medium || Trie | +824| [Goat Latin](https://leetcode.com/problems/goat-latin/) | [C++](./C++/goat-latin.cpp) [Python](./Python/goat-latin.py) | _O(n + w^2)_ | _O(l)_ | Easy ||| ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -390,6 +391,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/) | [C++](./C++/jewels-and-stones.cpp) [Python](./Python/jewels-and-stones.py) | _O(m + n)_ | _O(n)_ | Easy || 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [C++](./C++/subdomain-visit-count.cpp) [Python](./Python/subdomain-visit-count.py) | _O(n)_ | _O(n)_ | Easy || 822 | [Card Flipping Game](https://leetcode.com/problems/card-flipping-game/) | [C++](./C++/card-flipping-game.cpp) [Python](./Python/card-flipping-game.py) | _O(n)_ | _O(n)_ | Medium || +825 | [Friends Of Appropriate Ages](https://leetcode.com/problems/friends-of-appropriate-ages/) | [C++](./C++/friends-of-appropriate-ages.cpp) [Python](./Python/friends-of-appropriate-ages.py) | _O(a^2 + n)_ | _O(a)_ | Medium || ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -502,6 +504,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 567| [Permutation in String](https://leetcode.com/problems/permutation-in-string/) | [C++](./C++/permutation-in-string.cpp) [Python](./Python/permutation-in-string.py) | _O(n)_ | _O(1)_ | Medium || 611| [Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/) | [C++](./C++/valid-triangle-number.cpp) [Python](./Python/valid-triangle-number.py) | _O(n^2)_ | _O(1)_ | Medium || 777| [Swap Adjacent in LR String](https://leetcode.com/problems/swap-adjacent-in-lr-string/) | [C++](./C++/swap-adjacent-in-lr-string.cpp) [Python](./Python/swap-adjacent-in-lr-string.py) | _O(n)_ | _O(1)_ | Medium || +826| [Most Profit Assigning Work](https://leetcode.com/problems/most-profit-assigning-work/) | [C++](./C++/most-profit-assigning-work.cpp) [Python](./Python/most-profit-assigning-work.py) | _O(mlogm + nlogn)_ | _O(n)_ | Medium || ## Recursion | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -650,6 +653,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 785| [Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/) | [C++](./C++/is-graph-bipartite.cpp) [Python](./Python/is-graph-bipartite.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium ||| 797| [All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target/) | [C++](./C++/all-paths-from-source-to-target.cpp) [Python](./Python/all-paths-from-source-to-target.py) | _O(p + r * n)_ | _O(n)_ | Medium ||| 802| [Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) | [C++](./C++/find-eventual-safe-states.cpp) [Python](./Python/find-eventual-safe-states.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium ||| +827| [Making A Large Island](https://leetcode.com/problems/making-a-large-island/) | [C++](./C++/making-a-large-island.cpp) [Python](./Python/making-a-large-island.py) | _O(n^2)_ | _O(n^2)_ | Hard ||| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 9d94b6badef614278b2c6949850cbb7cec1fccf1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 6 May 2018 22:55:52 +0800 Subject: [PATCH 4684/4971] Create unique-letter-string.cpp --- C++/unique-letter-string.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/unique-letter-string.cpp diff --git a/C++/unique-letter-string.cpp b/C++/unique-letter-string.cpp new file mode 100644 index 000000000..155422ffb --- /dev/null +++ b/C++/unique-letter-string.cpp @@ -0,0 +1,23 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int uniqueLetterString(string S) { + static const int M = 1e9 + 7; + int result = 0; + vector> index(26, vector(2, -1)); + for (int i = 0; i < S.length(); ++i) { + int c = S[i] - 'A'; + result = (result + (i - index[c][1]) * + (index[c][1] - index[c][0])) % M; + index[c][0] = index[c][1]; + index[c][1] = i; + } + for (int c = 0; c < 26; ++c) { + result = (result + (S.length() - index[c][1]) * + (index[c][1] - index[c][0])) % M; + } + return result; + } +}; From 77f5a5bf633752b5e8f4ff9516c76f25b2ac881f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 6 May 2018 22:59:30 +0800 Subject: [PATCH 4685/4971] Create # Time: O(n) # Space: O(1) # A character is unique in string S if it occurs exactly once in it. # # For example, in string S = LETTER, # the only unique characters are L and R. # # Let's define UNIQ(S) as the number of unique characters in string S. # # For example, UNIQ(LETTER) = 2. # # Given a string S, calculate the sum of UNIQ(substring) over # all non-empty substrings of S. # # If there are two or more equal substrings at different positions in S, # we consider them different. # # Since the answer can be very large, retrun the answer modulo 10 ^ 9 + 7. # # Example 1: # # Input: ABC # Output: 10 # Explanation: All possible substrings are: A,B,C,AB,BC and ABC. # Evey substring is composed with only unique letters. # Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 # Example 2: # # Input: ABA # Output: 8 # Explanation: The same as example 1, except uni(ABA) = 1. # # Note: 0 <= S.length <= 10000. class Solution(object): def uniqueLetterString(self, S): --- Python/unique-letter-string.py | 55 ++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/unique-letter-string.py diff --git a/Python/unique-letter-string.py b/Python/unique-letter-string.py new file mode 100644 index 000000000..55dd8c180 --- /dev/null +++ b/Python/unique-letter-string.py @@ -0,0 +1,55 @@ +# Time: O(n) +# Space: O(1) + +# A character is unique in string S if it occurs exactly once in it. +# +# For example, in string S = "LETTER", +# the only unique characters are "L" and "R". +# +# Let's define UNIQ(S) as the number of unique characters in string S. +# +# For example, UNIQ("LETTER") = 2. +# +# Given a string S, calculate the sum of UNIQ(substring) over +# all non-empty substrings of S. +# +# If there are two or more equal substrings at different positions in S, +# we consider them different. +# +# Since the answer can be very large, retrun the answer modulo 10 ^ 9 + 7. +# +# Example 1: +# +# Input: "ABC" +# Output: 10 +# Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC". +# Evey substring is composed with only unique letters. +# Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 +# Example 2: +# +# Input: "ABA" +# Output: 8 +# Explanation: The same as example 1, except uni("ABA") = 1. +# +# Note: 0 <= S.length <= 10000. + +import string + + +class Solution(object): + def uniqueLetterString(self, S): + """ + :type S: str + :rtype: int + """ + M = 10**9 + 7 + index = {c: [-1, -1] for c in string.ascii_uppercase} + result = 0 + for i, c in enumerate(S): + k, j = index[c] + result += (i-j) * (j-k) + index[c] = [j, i] + for c in index: + k, j = index[c] + result += (len(S)-j) * (j-k) + return result % M From a3d3fc377affda5212c7e5aea19346f4beb30737 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 7 May 2018 00:03:46 +0800 Subject: [PATCH 4686/4971] Create consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 47 +++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/consecutive-numbers-sum.py diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py new file mode 100644 index 000000000..1ff101d31 --- /dev/null +++ b/Python/consecutive-numbers-sum.py @@ -0,0 +1,47 @@ +# Time: O(sqrt(n)) +# Space: O(1) + +# Given a positive integer N, +# how many ways can we write it as a sum of +# consecutive positive integers? +# +# Example 1: +# +# Input: 5 +# Output: 2 +# Explanation: 5 = 5 = 2 + 3 +# Example 2: +# +# Input: 9 +# Output: 3 +# Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4 +# Example 3: +# +# Input: 15 +# Output: 4 +# Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 +# Note: 1 <= N <= 10 ^ 9. + + +class Solution(object): + def consecutiveNumbersSum(self, N): + """ + :type N: int + :rtype: int + """ + # if prime factorization of N is 2^k * p1^a * p2^b * .. + # => result is the number of all odd factors = (a+1) * (b+1) + ... + result = 1 + i = 3 + while N % 2 == 0: + N /= 2 + while i*i <= N: + count = 0 + while N % i == 0: + N /= i + count += 1 + result *= count + 1 + i += 2 + if N > 1: + result *= 2 + return result From 83d7cdf76865b717063b00b62d9a7cf8c2541ad5 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 7 May 2018 00:05:40 +0800 Subject: [PATCH 4687/4971] Update consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py index 1ff101d31..45de4f942 100644 --- a/Python/consecutive-numbers-sum.py +++ b/Python/consecutive-numbers-sum.py @@ -40,7 +40,7 @@ def consecutiveNumbersSum(self, N): while N % i == 0: N /= i count += 1 - result *= count + 1 + result *= count+1 i += 2 if N > 1: result *= 2 From 4a4f10cc08f277832aec0d6cd513e92fbf19e7f3 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 7 May 2018 00:07:08 +0800 Subject: [PATCH 4688/4971] Update consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py index 45de4f942..bc711967a 100644 --- a/Python/consecutive-numbers-sum.py +++ b/Python/consecutive-numbers-sum.py @@ -32,9 +32,9 @@ def consecutiveNumbersSum(self, N): # if prime factorization of N is 2^k * p1^a * p2^b * .. # => result is the number of all odd factors = (a+1) * (b+1) + ... result = 1 - i = 3 while N % 2 == 0: N /= 2 + i = 3 while i*i <= N: count = 0 while N % i == 0: From 2964e5f6de22ee53cd401fd3b7a9c450c798f15e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 00:09:27 +0800 Subject: [PATCH 4689/4971] Create consecutive-numbers-sum.cpp --- C++/consecutive-numbers-sum.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/consecutive-numbers-sum.cpp diff --git a/C++/consecutive-numbers-sum.cpp b/C++/consecutive-numbers-sum.cpp new file mode 100644 index 000000000..800f8031a --- /dev/null +++ b/C++/consecutive-numbers-sum.cpp @@ -0,0 +1,24 @@ +// Time: O(sqrt(n)) +// Space: O(1) + +class Solution { +public: + int consecutiveNumbersSum(int N) { + int result = 1; + while (N % 2 == 0) { + N /= 2; + } + for (int i = 3; i * i <= N; i += 2) { + int count = 0; + while (N % i == 0) { + N /= i; + ++count; + } + result *= count + 1; + } + if (N > 1) { + result *= 2; + } + return result; + } +}; From 5455da0c49bca5086d39bcec9944330ac15bf7a8 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 7 May 2018 00:16:44 +0800 Subject: [PATCH 4690/4971] Create positions-of-large-groups.py --- Python/positions-of-large-groups.py | 52 +++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/positions-of-large-groups.py diff --git a/Python/positions-of-large-groups.py b/Python/positions-of-large-groups.py new file mode 100644 index 000000000..3b01e950f --- /dev/null +++ b/Python/positions-of-large-groups.py @@ -0,0 +1,52 @@ +# Time: O(n) +# Space: O(1) + +# In a string S of lowercase letters, +# these letters form consecutive groups of the same character. +# +# For example, a string like S = "abbxxxxzyy" has +# the groups "a", "bb", "xxxx", "z" and "yy". +# +# Call a group large if it has 3 or more characters. +# We would like the starting and ending positions of every large group. +# +# The final answer should be in lexicographic order. +# +# Example 1: +# +# Input: "abbxxxxzzy" +# Output: [[3,6]] +# Explanation: "xxxx" is the single large group with starting 3 +# and ending positions 6. +# Example 2: +# +# Input: "abc" +# Output: [] +# Explanation: We have "a","b" and "c" but no large group. +# Example 3: +# +# Input: "abcdddeeeeaabbbcd" +# Output: [[3,5],[6,9],[12,14]] +# +# Note: 1 <= S.length <= 1000 + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def largeGroupPositions(self, S): + """ + :type S: str + :rtype: List[List[int]] + """ + result = [] + i = 0 + for j in xrange(len(S)): + if j == len(S)-1 or S[j] != S[j+1]: + if j-i+1 >= 3: + result.append([i, j]) + i = j+1 + return result From c17e8c5a0ded86d16988f4b77257b417ac760434 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 00:20:57 +0800 Subject: [PATCH 4691/4971] Create positions-of-large-groups.cpp --- C++/positions-of-large-groups.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/positions-of-large-groups.cpp diff --git a/C++/positions-of-large-groups.cpp b/C++/positions-of-large-groups.cpp new file mode 100644 index 000000000..0395ccdab --- /dev/null +++ b/C++/positions-of-large-groups.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector> largeGroupPositions(string S) { + vector> result; + for (int i = 0, j = 0; j < S.length(); ++j) { + if (j == S.length() - 1 || S[j] != S[j + 1]) { + if (j - i + 1 >= 3) { + result.emplace_back(vector{i, j}); + } + i = j + 1; + } + } + return result; + } +}; From 7243f887fa290f3dc7e3f110ef5db64c62e7d209 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 00:52:04 +0800 Subject: [PATCH 4692/4971] Create masking-personal-information.cpp --- C++/masking-personal-information.cpp | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/masking-personal-information.cpp diff --git a/C++/masking-personal-information.cpp b/C++/masking-personal-information.cpp new file mode 100644 index 000000000..ba0f4399c --- /dev/null +++ b/C++/masking-personal-information.cpp @@ -0,0 +1,29 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + string maskPII(string S) { + auto at = S.find("@"); + if (at != string::npos) { + transform(S.begin(), S.end(), S.begin(), ::tolower); + return S.substr(0, 1) + "*****" + S.substr(at - 1); + } + string digits; + for (const auto& c : S) { + if (::isdigit(c)) { + digits.push_back(c); + } + } + string local{"***-***-"}; + local += digits.substr(digits.length() - 4); + if (digits.length() == 10) { + return local; + } + return digits.length() == 10 ? + local : "+" + + string(digits.length() - 10, '*') + + "-" + + local; + } +}; From 1811a6ac0453cac3c666abd0b88b2dcdb094f9c9 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 7 May 2018 01:04:45 +0800 Subject: [PATCH 4693/4971] Create masking-personal-information.py --- Python/masking-personal-information.py | 86 ++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Python/masking-personal-information.py diff --git a/Python/masking-personal-information.py b/Python/masking-personal-information.py new file mode 100644 index 000000000..ff473d5c6 --- /dev/null +++ b/Python/masking-personal-information.py @@ -0,0 +1,86 @@ +# Time: O(1) +# Space: O(1) + +# We are given a personal information string S, +# which may represent either an email address or a phone number. +# +# We would like to mask this personal information according to the following +# rules: +# +# 1. Email address: +# We define a name to be a string of length ≥ 2 consisting of only lowercase +# letters a-z or uppercase letters A-Z. +# An email address starts with a name, followed by the symbol '@', followed by +# a name, followed by the dot '.' and followed by a name. +# All email addresses are guaranteed to be valid and in the format of +# "name1@name2.name3". +# To mask an email, all names must be converted to lowercase and all letters +# between the first and last letter of the first name must be replaced by +# 5 asterisks '*'. +# +# 2. Phone number: +# A phone number is a string consisting of only the digits 0-9 or the +# characters from the set {'+', '-', '(', ')', ' '}. You may assume +# a phone number contains 10 to 13 digits. +# The last 10 digits make up the local number, while the digits before those +# make up the country code. Note that the country code is optional. We want to +# expose only the last 4 digits and mask all other digits. +# The local number should be formatted and masked as "***-***-1111", +# where 1 represents the exposed digits. +# To mask a phone number with country code like "+111 111 111 1111", +# we write it in the form "+***-***-***-1111". The '+' sign and the first '-' +# sign before the local number should only exist if there is a country code. +# For example, a 12 digit phone number mask should start with "+**-". +# +# Note that extraneous characters like "(", ")", " ", as well as extra dashes +# or plus signs not part of the above formatting scheme should be removed. +# +# Return the correct "mask" of the information provided. +# +# Example 1: +# +# Input: "LeetCode@LeetCode.com" +# Output: "l*****e@leetcode.com" +# Explanation: All names are converted to lowercase, and the letters between +# the first and last letter of the first name is replaced by 5 asterisks. +# Therefore, "leetcode" -> "l*****e". +# Example 2: +# +# Input: "AB@qq.com" +# Output: "a*****b@qq.com" +# Explanation: There must be 5 asterisks between the first and last letter +# of the first name "ab". Therefore, "ab" -> "a*****b". +# Example 3: +# +# Input: "1(234)567-890" +# Output: "***-***-7890" +# Explanation: 10 digits in the phone number, which means all digits make up +# the local number. +# Example 4: +# +# Input: "86-(10)12345678" +# Output: "+**-***-***-5678" +# Explanation: 12 digits, 2 digits for country code and 10 digits for local +# number. +# Notes: +# +# S.length <= 40. +# Emails have length at least 8. +# Phone numbers have length at least 10. + + +class Solution(object): + def maskPII(self, S): + """ + :type S: str + :rtype: str + """ + if '@' in S: + first, after = S.split('@') + return "{}*****{}@{}".format(first[0], first[-1], after).lower() + + digits = filter(lambda x: x.isdigit(), S) + local = "***-***-{}".format(digits[-4:]) + if len(digits) == 10: + return local + return "+{}-{}".format('*' * (len(digits) - 10), local) From 656790058fa198e530934bb4120605b896176f46 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 01:13:19 +0800 Subject: [PATCH 4694/4971] Update README.md --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8b4af7dd2..07df22306 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 803 | [Bricks Falling When Hit](https://leetcode.com/problems/bricks-falling-when-hit/) | [C++](./C++/bricks-falling-when-hit.cpp) [Python](./Python/bricks-falling-when-hit.py) | _O(r * c)_ | _O(r * c)_ | Hard || Union Find 807 | [Max Increase to Keep City Skyline](https://leetcode.com/problems/max-increase-to-keep-city-skyline/) | [C++](./C++/max-increase-to-keep-city-skyline.cpp) [Python](./Python/max-increase-to-keep-city-skyline.py) | _O(n^2)_ | _O(n)_ | Medium || 821 | [Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/) | [C++](./C++/shortest-distance-to-a-character.cpp) [Python](./Python/shortest-distance-to-a-character.py) | _O(n)_ | _O(1)_ | Easy || +830 | [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/) | [C++](./C++/positions-of-large-groups.cpp) [Python](./Python/positions-of-large-groups.py) | _O(n)_ | _O(1)_ | Easy || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -218,6 +219,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 819| [Most Common Word](https://leetcode.com/problems/most-common-word/) | [C++](./C++/most-common-word.cpp) [Python](./Python/most-common-word.py) | _O(m + n)_ | _O(m + n)_ | Easy ||| 820| [Short Encoding of Words](https://leetcode.com/problems/short-encoding-of-words/) | [C++](./C++/short-encoding-of-wordss.cpp) [Python](./Python/short-encoding-of-words.py) | _O(n)_ | _O(t)_ | Medium || Trie | 824| [Goat Latin](https://leetcode.com/problems/goat-latin/) | [C++](./C++/goat-latin.cpp) [Python](./Python/goat-latin.py) | _O(n + w^2)_ | _O(l)_ | Easy ||| +831| [Masking Personal Information](https://leetcode.com/problems/masking-personal-information/) | [C++](./C++/masking-personal-information.cpp) [Python](./Python/masking-personal-information.py) | _O(1)_ | _O(1)_ | Medium ||| ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -459,7 +461,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 789 | [Escape The Ghosts](https://leetcode.com/problems/escape-the-ghosts/) | [C++](./C++/escape-the-ghosts.cpp) [Python](./Python/escape-the-ghosts.py) | _O(n)_ | _O(1)_ | Medium || 800 | [Similar RGB Color](https://leetcode.com/problems/similar-rgb-color/) | [C++](./C++/similar-rgb-color.cpp) [Python](./Python/similar-rgb-color.py) | _O(1)_ | _O(1)_ | Easy |📖|| 810 | [Chalkboard XOR Game](https://leetcode.com/problems/chalkboard-xor-game/) | [C++](./C++/chalkboard-xor-game.cpp) [Python](./Python/chalkboard-xor-game.py) | _O(1)_ | _O(1)_ | Hard ||| -812 | [Largest Triangle Area](https://leetcode.com/problems/largest-triangle-areae/) | [C++](./C++/largest-triangle-area.cpp) [Python](./Python/largest-triangle-area.py) | _O(n^3)_ | _O(1)_ | Easy ||| +812 | [Largest Triangle Area](https://leetcode.com/problems/largest-triangle-area/) | [C++](./C++/largest-triangle-area.cpp) [Python](./Python/largest-triangle-area.py) | _O(n^3)_ | _O(1)_ | Easy ||| +829 | [Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/) | [C++](./C++/consecutive-numbers-sum.cpp) [Python](./Python/consecutive-numbers-sum.py) | _O(sqrt(n))_ | _O(1)_ | Medium ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -505,6 +508,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 611| [Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/) | [C++](./C++/valid-triangle-number.cpp) [Python](./Python/valid-triangle-number.py) | _O(n^2)_ | _O(1)_ | Medium || 777| [Swap Adjacent in LR String](https://leetcode.com/problems/swap-adjacent-in-lr-string/) | [C++](./C++/swap-adjacent-in-lr-string.cpp) [Python](./Python/swap-adjacent-in-lr-string.py) | _O(n)_ | _O(1)_ | Medium || 826| [Most Profit Assigning Work](https://leetcode.com/problems/most-profit-assigning-work/) | [C++](./C++/most-profit-assigning-work.cpp) [Python](./Python/most-profit-assigning-work.py) | _O(mlogm + nlogn)_ | _O(n)_ | Medium || +828| [Unique Letter String](https://leetcode.com/problems/unique-letter-string/) | [C++](./C++/unique-letter-string.cpp) [Python](./Python/unique-letter-string.py) | _O(n)_ | _O(1)_ | Hard || ## Recursion | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 902cde0fc7094ce6487bad3f30b5dd665cbfa2d1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 01:15:05 +0800 Subject: [PATCH 4695/4971] Update consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py index bc711967a..a164a5bd4 100644 --- a/Python/consecutive-numbers-sum.py +++ b/Python/consecutive-numbers-sum.py @@ -30,7 +30,7 @@ def consecutiveNumbersSum(self, N): :rtype: int """ # if prime factorization of N is 2^k * p1^a * p2^b * .. - # => result is the number of all odd factors = (a+1) * (b+1) + ... + # => result is the number of all odd factors = (a+1) * (b+1) * ... result = 1 while N % 2 == 0: N /= 2 From 68abd5afecf601d1804457ebb961f3a5222014d5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 01:19:14 +0800 Subject: [PATCH 4696/4971] Update masking-personal-information.cpp --- C++/masking-personal-information.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/C++/masking-personal-information.cpp b/C++/masking-personal-information.cpp index ba0f4399c..0fc04861c 100644 --- a/C++/masking-personal-information.cpp +++ b/C++/masking-personal-information.cpp @@ -20,10 +20,6 @@ class Solution { if (digits.length() == 10) { return local; } - return digits.length() == 10 ? - local : "+" + - string(digits.length() - 10, '*') + - "-" + - local; + return "+" + string(digits.length() - 10, '*') + "-" + local; } }; From 9641234ac5897ec3f1a5f6cf0b5a822e7b103ae8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 13:49:12 +0800 Subject: [PATCH 4697/4971] Update consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py index a164a5bd4..e95417c84 100644 --- a/Python/consecutive-numbers-sum.py +++ b/Python/consecutive-numbers-sum.py @@ -29,8 +29,13 @@ def consecutiveNumbersSum(self, N): :type N: int :rtype: int """ + # x + x+1 + x+2 + ... + x+l-1 = N = 2^k * M + # => l*x + (l-1)*l/2 = N + # => x = (N -(l-1)*l/2)/l= 2^k * M/l - (l-1)/2 is integer + # => l could be 2 or any odd factor of M (excluding M) + # => the answer is the number of all odd factors of M # if prime factorization of N is 2^k * p1^a * p2^b * .. - # => result is the number of all odd factors = (a+1) * (b+1) * ... + # => answer is the number of all odd factors = (a+1) * (b+1) * ... result = 1 while N % 2 == 0: N /= 2 From 4204e69685c1da06183f6ee30801dbe67d07c072 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 13:56:21 +0800 Subject: [PATCH 4698/4971] Update consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 1 - 1 file changed, 1 deletion(-) diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py index e95417c84..a56f1d41c 100644 --- a/Python/consecutive-numbers-sum.py +++ b/Python/consecutive-numbers-sum.py @@ -32,7 +32,6 @@ def consecutiveNumbersSum(self, N): # x + x+1 + x+2 + ... + x+l-1 = N = 2^k * M # => l*x + (l-1)*l/2 = N # => x = (N -(l-1)*l/2)/l= 2^k * M/l - (l-1)/2 is integer - # => l could be 2 or any odd factor of M (excluding M) # => the answer is the number of all odd factors of M # if prime factorization of N is 2^k * p1^a * p2^b * .. # => answer is the number of all odd factors = (a+1) * (b+1) * ... From f762525c352abe33910761ee33851a55dca770ad Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 13:58:02 +0800 Subject: [PATCH 4699/4971] Update consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py index a56f1d41c..e95417c84 100644 --- a/Python/consecutive-numbers-sum.py +++ b/Python/consecutive-numbers-sum.py @@ -32,6 +32,7 @@ def consecutiveNumbersSum(self, N): # x + x+1 + x+2 + ... + x+l-1 = N = 2^k * M # => l*x + (l-1)*l/2 = N # => x = (N -(l-1)*l/2)/l= 2^k * M/l - (l-1)/2 is integer + # => l could be 2 or any odd factor of M (excluding M) # => the answer is the number of all odd factors of M # if prime factorization of N is 2^k * p1^a * p2^b * .. # => answer is the number of all odd factors = (a+1) * (b+1) * ... From e68227161bc62a4ec883552f3eb6fe7f50ff5e1a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 14:05:35 +0800 Subject: [PATCH 4700/4971] Update consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py index e95417c84..8e45e5714 100644 --- a/Python/consecutive-numbers-sum.py +++ b/Python/consecutive-numbers-sum.py @@ -32,7 +32,8 @@ def consecutiveNumbersSum(self, N): # x + x+1 + x+2 + ... + x+l-1 = N = 2^k * M # => l*x + (l-1)*l/2 = N # => x = (N -(l-1)*l/2)/l= 2^k * M/l - (l-1)/2 is integer - # => l could be 2 or any odd factor of M (excluding M) + # => l could be 2 or any odd factor of M (excluding M), + # set x = 2^k * M/l - (l-1)/2 is integer, and also unique # => the answer is the number of all odd factors of M # if prime factorization of N is 2^k * p1^a * p2^b * .. # => answer is the number of all odd factors = (a+1) * (b+1) * ... From 4cb6b3a3e1b74dd83812469c472accfc22e4d699 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 14:06:08 +0800 Subject: [PATCH 4701/4971] Update consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py index 8e45e5714..e1a47915b 100644 --- a/Python/consecutive-numbers-sum.py +++ b/Python/consecutive-numbers-sum.py @@ -29,7 +29,7 @@ def consecutiveNumbersSum(self, N): :type N: int :rtype: int """ - # x + x+1 + x+2 + ... + x+l-1 = N = 2^k * M + # x + x+1 + x+2 + ... + x+l-1 = N = 2^k * M, where M is odd # => l*x + (l-1)*l/2 = N # => x = (N -(l-1)*l/2)/l= 2^k * M/l - (l-1)/2 is integer # => l could be 2 or any odd factor of M (excluding M), From ea0b2f6f027e5439f35fe274fbf77a0099cd3d2f Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 14:06:40 +0800 Subject: [PATCH 4702/4971] Update consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py index e1a47915b..ef5f51486 100644 --- a/Python/consecutive-numbers-sum.py +++ b/Python/consecutive-numbers-sum.py @@ -30,8 +30,8 @@ def consecutiveNumbersSum(self, N): :rtype: int """ # x + x+1 + x+2 + ... + x+l-1 = N = 2^k * M, where M is odd - # => l*x + (l-1)*l/2 = N - # => x = (N -(l-1)*l/2)/l= 2^k * M/l - (l-1)/2 is integer + # => l*x + (l-1)*l/2 = 2^k * M + # => x = (2^k * M -(l-1)*l/2)/l= 2^k * M/l - (l-1)/2 is integer # => l could be 2 or any odd factor of M (excluding M), # set x = 2^k * M/l - (l-1)/2 is integer, and also unique # => the answer is the number of all odd factors of M From 7bf6b41bb7cc4dd36c2330d009e502efaf4519ed Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 7 May 2018 14:07:16 +0800 Subject: [PATCH 4703/4971] Update consecutive-numbers-sum.py --- Python/consecutive-numbers-sum.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/consecutive-numbers-sum.py b/Python/consecutive-numbers-sum.py index ef5f51486..40cf7e04f 100644 --- a/Python/consecutive-numbers-sum.py +++ b/Python/consecutive-numbers-sum.py @@ -32,8 +32,8 @@ def consecutiveNumbersSum(self, N): # x + x+1 + x+2 + ... + x+l-1 = N = 2^k * M, where M is odd # => l*x + (l-1)*l/2 = 2^k * M # => x = (2^k * M -(l-1)*l/2)/l= 2^k * M/l - (l-1)/2 is integer - # => l could be 2 or any odd factor of M (excluding M), - # set x = 2^k * M/l - (l-1)/2 is integer, and also unique + # => l could be 2 or any odd factor of M (excluding M) + # s.t. x = 2^k * M/l - (l-1)/2 is integer, and also unique # => the answer is the number of all odd factors of M # if prime factorization of N is 2^k * p1^a * p2^b * .. # => answer is the number of all odd factors = (a+1) * (b+1) * ... From ce75632507739a38e505ecfc2a082f3dfbc0b721 Mon Sep 17 00:00:00 2001 From: xfbao1986 Date: Wed, 9 May 2018 11:52:08 +0900 Subject: [PATCH 4704/4971] little change for solution 2 --- Python/two-sum.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Python/two-sum.py b/Python/two-sum.py index 9a1ed7008..0e17bbc0b 100644 --- a/Python/two-sum.py +++ b/Python/two-sum.py @@ -32,14 +32,14 @@ def twoSum2(self, nums, target): :type target: int :rtype: List[int] """ - k = 0 for i in nums: j = target - i - k += 1 - tmp_nums = nums[k:] + tmp_nums_start_index = nums.index(i) + 1 + tmp_nums = nums[tmp_nums_start_index:] if j in tmp_nums: - return [k - 1, tmp_nums.index(j) + k] + return [nums.index(i), tmp_nums_start_index + tmp_nums.index(j)] if __name__ == '__main__': - print Solution().twoSum((2, 7, 11, 15), 9) + print(Solution().twoSum((2, 7, 11, 15), 9)) + print(Solution().twoSum2((2, 7, 11, 15), 9)) From c82479ae559713a69f6661f25bfda7dcc73c29a8 Mon Sep 17 00:00:00 2001 From: xfbao1986 Date: Thu, 10 May 2018 17:46:03 +0900 Subject: [PATCH 4705/4971] one more solution for median-of-two-sorted-arrays --- Python/median-of-two-sorted-arrays.py | 41 ++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py index 2450b65bf..a5d2e957e 100644 --- a/Python/median-of-two-sorted-arrays.py +++ b/Python/median-of-two-sorted-arrays.py @@ -81,8 +81,47 @@ def match(arrays, num, target): return binary_search(arrays, left, right, k, match) +class Solution_3(object): + def findMedianSortedArrays(self, A, B): + + if A is None and B is None: + return -1.0 + lenA = len(A) + lenB = len(B) + lenn = lenA + lenB; + + indexA,indexB,indexC = 0,0,0 + C = [False for i in xrange(lenn)] + while indexA < lenA and indexB < lenB: + if A[indexA] < B[indexB]: + C[indexC] = A[indexA] + indexC += 1 + indexA += 1 + else: + C[indexC] = B[indexB] + indexC += 1 + indexB += 1 + + while indexA < lenA: + C[indexC] = A[indexA] + indexC += 1 + indexA += 1 + + while indexB < lenB: + C[indexC] = B[indexB] + indexC += 1 + indexB += 1 + + indexM1 = (lenn - 1) / 2 + indexM2 = lenn / 2 + + if (lenn % 2 == 0): + return (C[indexM1] + C[indexM2]) / 2.0 + else: + return C[indexM2] / 1.0 if __name__ == "__main__": print Solution().findMedianSortedArrays([1, 3, 5, 7], [2, 4, 6]) - print Solution().findMedianSortedArrays([1, 3, 5], [2, 4, 6]) + print Solution_Generic().findMedianSortedArrays([1, 3, 5], [2, 4, 6]) + print Solution_3().findMedianSortedArrays([1, 3, 5], [2, 4, 6]) From 424c872c6546bbaa13c37b99f6ab59dd1b98a63d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 May 2018 22:37:55 +0800 Subject: [PATCH 4706/4971] Create find-and-replace-in-string.cpp --- C++/find-and-replace-in-string.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/find-and-replace-in-string.cpp diff --git a/C++/find-and-replace-in-string.cpp b/C++/find-and-replace-in-string.cpp new file mode 100644 index 000000000..6e95a712f --- /dev/null +++ b/C++/find-and-replace-in-string.cpp @@ -0,0 +1,18 @@ +// Time: O(n * m), m is the number of targets +// Space: O(n) + +class Solution { +public: + string findReplaceString(string S, vector& indexes, vector& sources, vector& targets) { + vector> bucket(S.size()); + for (auto i = 0; i < indexes.size(); ++i) { + if (S.find(sources[i], indexes[i]) == indexes[i]) { + bucket[indexes[i]] = {sources[i].size(), targets[i]}; + } + } + for (int i = S.size() - 1; i >= 0; --i) { + S.replace(i, bucket[i].first, bucket[i].second); + } + return S; + } +}; From 1e72169fcc85b51706bf5ae276f7e907e8aae47c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 May 2018 22:59:38 +0800 Subject: [PATCH 4707/4971] Update find-and-replace-in-string.cpp --- C++/find-and-replace-in-string.cpp | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/C++/find-and-replace-in-string.cpp b/C++/find-and-replace-in-string.cpp index 6e95a712f..cf2c273f8 100644 --- a/C++/find-and-replace-in-string.cpp +++ b/C++/find-and-replace-in-string.cpp @@ -1,18 +1,25 @@ -// Time: O(n * m), m is the number of targets +// Time: O(n + m), m is the number of targets // Space: O(n) class Solution { public: string findReplaceString(string S, vector& indexes, vector& sources, vector& targets) { vector> bucket(S.size()); - for (auto i = 0; i < indexes.size(); ++i) { + for (int i = 0; i < indexes.size(); ++i) { if (S.find(sources[i], indexes[i]) == indexes[i]) { bucket[indexes[i]] = {sources[i].size(), targets[i]}; } } - for (int i = S.size() - 1; i >= 0; --i) { - S.replace(i, bucket[i].first, bucket[i].second); + string result; + int i = 0, last = 0; + for (i = 0; i < S.length(); ++i) { + if (bucket[i].first) { + result += S.substr(last, i - last); + result += bucket[i].second; + last = i + bucket[i].first; + } } - return S; + result += S.substr(last, i - last); + return result; } }; From 30f4b2f99ebd169e39bdfb0a6a5e16a104112f83 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 May 2018 23:15:14 +0800 Subject: [PATCH 4708/4971] Update find-and-replace-in-string.cpp --- C++/find-and-replace-in-string.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/C++/find-and-replace-in-string.cpp b/C++/find-and-replace-in-string.cpp index cf2c273f8..a5f4363a1 100644 --- a/C++/find-and-replace-in-string.cpp +++ b/C++/find-and-replace-in-string.cpp @@ -11,15 +11,15 @@ class Solution { } } string result; - int i = 0, last = 0; - for (i = 0; i < S.length(); ++i) { + int last = 0; + for (int i = 0; i < S.length(); ++i) { if (bucket[i].first) { - result += S.substr(last, i - last); result += bucket[i].second; last = i + bucket[i].first; + } else if (i >= last) { + result.push_back(S[i]); } } - result += S.substr(last, i - last); return result; } }; From dbd9e79b34da802b06b51294e309bdce6b8be20a Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 13 May 2018 23:20:52 +0800 Subject: [PATCH 4709/4971] Create find-and-replace-in-string.py --- Python/find-and-replace-in-string.py | 76 ++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Python/find-and-replace-in-string.py diff --git a/Python/find-and-replace-in-string.py b/Python/find-and-replace-in-string.py new file mode 100644 index 000000000..941aa68d5 --- /dev/null +++ b/Python/find-and-replace-in-string.py @@ -0,0 +1,76 @@ +# Time: O(n * m), m is the number of targets +# Space: O(n) + +# To some string S, we will perform some replacement operations that +# replace groups of letters with new ones (not necessarily the same size). +# +# Each replacement operation has 3 parameters: a starting index i, +# a source word x and a target word y. +# The rule is that if x starts at position i in the original string S, +# then we will replace that occurrence of x with y. If not, we do nothing. +# +# For example, if we have S = "abcd" and we have some replacement operation +# i = 2, x = "cd", y = "ffff", then because "cd" starts at position 2 +# in the original string S, we will replace it with "ffff". +# +# Using another example on S = "abcd", if we have both the replacement +# operation +# i = 0, x = "ab", y = "eee", as well as another replacement operation i = 2, +# x = "ec", y = "ffff", this second operation does nothing because in the +# original string S[2] = 'c', which doesn't match x[0] = 'e'. +# +# All these operations occur simultaneously. +# It's guaranteed that there won't be any overlap in replacement: +# for example, S = "abc", indexes = [0, 1], sources = ["ab","bc"] +# is not a valid test case. +# +# Example 1: +# +# Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], +# targets = ["eee","ffff"] +# Output: "eeebffff" +# Explanation: "a" starts at index 0 in S, so it's replaced by "eee". +# "cd" starts at index 2 in S, so it's replaced by "ffff". +# Example 2: +# +# Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"], +# targets = ["eee","ffff"] +# Output: "eeecd" +# Explanation: "ab" starts at index 0 in S, so it's replaced by "eee". +# "ec" doesn't starts at index 2 in the original S, so we do nothing. +# Notes: +# 1. 0 <= indexes.length = sources.length = targets.length <= 100 +# 2. 0 < indexes[i] < S.length <= 1000 +# 3. All characters in given inputs are lowercase letters. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def findReplaceString(self, S, indexes, sources, targets): + """ + :type S: str + :type indexes: List[int] + :type sources: List[str] + :type targets: List[str] + :rtype: str + """ + S = list(S) + bucket = [None] * len(S) + for i in xrange(len(indexes)): + if all(indexes[i]+k < len(S) and + S[indexes[i]+k] == sources[i][k] + for k in xrange(len(sources[i]))): + bucket[indexes[i]] = (len(sources[i]), list(targets[i])) + result = [] + last = 0 + for i in xrange(len(S)): + if bucket[i]: + result.extend(bucket[i][1]) + last = i + bucket[i][0] + elif i >= last: + result.append(S[i]) + return "".join(result) From 98901eb0f8ba66eb5c5c59f0feaec8e46c999d6e Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 13 May 2018 23:22:00 +0800 Subject: [PATCH 4710/4971] Update find-and-replace-in-string.py --- Python/find-and-replace-in-string.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/find-and-replace-in-string.py b/Python/find-and-replace-in-string.py index 941aa68d5..7f085d4ed 100644 --- a/Python/find-and-replace-in-string.py +++ b/Python/find-and-replace-in-string.py @@ -1,4 +1,4 @@ -# Time: O(n * m), m is the number of targets +# Time: O(n + m), m is the number of targets # Space: O(n) # To some string S, we will perform some replacement operations that From c35abbb6d58e5e59e5a1a824a97ae1023fca63ca Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 13 May 2018 23:31:29 +0800 Subject: [PATCH 4711/4971] Create flipping-an-image.py --- Python/flipping-an-image.py | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Python/flipping-an-image.py diff --git a/Python/flipping-an-image.py b/Python/flipping-an-image.py new file mode 100644 index 000000000..33440f036 --- /dev/null +++ b/Python/flipping-an-image.py @@ -0,0 +1,47 @@ +# Time: O(n) +# Space: O(1) + +# Given a binary matrix A, we want to flip the image horizontally, +# then invert it, and return the resulting image. +# +# To flip an image horizontally means that each row of the image is reversed. +# For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. +# +# To invert an image means that each 0 is replaced by 1, and each 1 is +# replaced by 0. +# For example, inverting [0, 1, 1] results in [1, 0, 0]. +# +# Example 1: +# +# Input: [[1,1,0],[1,0,1],[0,0,0]] +# Output: [[1,0,0],[0,1,0],[1,1,1]] +# Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. +# Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] +# Example 2: +# +# Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] +# Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] +# Explanation: First reverse each row: +# [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. +# Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] +# +# Notes: +# 1. 1 <= A.length = A[0].length <= 20 +# 2. 0 <= A[i][j] <= 1 + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def flipAndInvertImage(self, A): + """ + :type A: List[List[int]] + :rtype: List[List[int]] + """ + for row in A: + for i in xrange((len(row)+1) // 2): + row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1 + return A From b5e407dea10e60bc44b86dab3f79fd88cfaa5d11 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 13 May 2018 23:37:36 +0800 Subject: [PATCH 4712/4971] Create flipping-an-image.cpp --- C++/flipping-an-image.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/flipping-an-image.cpp diff --git a/C++/flipping-an-image.cpp b/C++/flipping-an-image.cpp new file mode 100644 index 000000000..230eee713 --- /dev/null +++ b/C++/flipping-an-image.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + vector> flipAndInvertImage(vector>& A) { + for (auto& row : A) { + for (int i = 0; i < (row.size() + 1) / 2; ++i) { + row[i] ^= 1; + if (i != row.size() + ~i) { + row[row.size() + ~i] ^= 1; + } + swap(row[i], row[row.size() + ~i]); + } + } + return A; + } +}; From da4630dadfe897cad3f29ad8d0669a6f7fc1f004 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 May 2018 00:41:01 +0800 Subject: [PATCH 4713/4971] Create sum-of-distances-in-tree.cpp --- C++/sum-of-distances-in-tree.cpp | 51 ++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 C++/sum-of-distances-in-tree.cpp diff --git a/C++/sum-of-distances-in-tree.cpp b/C++/sum-of-distances-in-tree.cpp new file mode 100644 index 000000000..d88e32289 --- /dev/null +++ b/C++/sum-of-distances-in-tree.cpp @@ -0,0 +1,51 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + vector sumOfDistancesInTree(int N, vector>& edges) { + unordered_map> graph; + for (const auto& edge : edges) { + graph[edge[0]].emplace_back(edge[1]); + graph[edge[1]].emplace_back(edge[0]); + } + + vector count(N, 1); + vector result(N, 0); + + dfs(graph, 0, -1, &count, &result); + dfs2(graph, 0, -1, &count, &result); + return result; + } + +private: + void dfs(const unordered_map>& graph, + int node, int parent, + vector *count, vector *result) { + if (!graph.count(node)) { + return; + } + for (const auto& nei : graph.at(node)) { + if (nei != parent) { + dfs(graph, nei, node, count, result); + (*count)[node] += (*count)[nei]; + (*result)[node] += (*result)[nei] + (*count)[nei]; + } + } + } + + void dfs2(const unordered_map>& graph, + int node, int parent, + vector *count, vector *result) { + if (!graph.count(node)) { + return; + } + for (const auto& nei : graph.at(node)) { + if (nei != parent) { + (*result)[nei] = (*result)[node] - (*count)[nei] + + count->size() - (*count)[nei]; + dfs2(graph, nei, node, count, result); + } + } + } +}; From c83e342ecd11c2d8aefffe8b2b42dbc82102c0bc Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 14 May 2018 00:44:28 +0800 Subject: [PATCH 4714/4971] Create sum-of-distances-in-tree.py --- Python/sum-of-distances-in-tree.py | 61 ++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/sum-of-distances-in-tree.py diff --git a/Python/sum-of-distances-in-tree.py b/Python/sum-of-distances-in-tree.py new file mode 100644 index 000000000..7d172e200 --- /dev/null +++ b/Python/sum-of-distances-in-tree.py @@ -0,0 +1,61 @@ +# Time: O(n) +# Space: O(n) + +# An undirected, connected tree with N nodes +# labelled 0...N-1 and N-1 edges are given. +# +# The ith edge connects nodes edges[i][0] and edges[i][1] together. +# +# Return a list ans, where ans[i] is the sum of the distances +# between node i and all other nodes. +# +# Example 1: +# +# Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] +# Output: [8,12,6,10,10,10] +# Explanation: +# Here is a diagram of the given tree: +# 0 +# / \ +# 1 2 +# /|\ +# 3 4 5 +# We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) +# equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer[0] = 8, and so on. +# Note: 1 <= N <= 10000 + +import collections + + +class Solution(object): + def sumOfDistancesInTree(self, N, edges): + """ + :type N: int + :type edges: List[List[int]] + :rtype: List[int] + """ + def dfs(graph, node, parent, count, result): + for nei in graph[node]: + if nei != parent: + dfs(graph, nei, node, count, result) + count[node] += count[nei] + result[node] += result[nei] + count[nei] + + def dfs2(graph, node, parent, count, result): + for nei in graph[node]: + if nei != parent: + result[nei] = result[node] - count[nei] + \ + len(count) - count[nei] + dfs2(graph, nei, node, count, result) + + graph = collections.defaultdict(list) + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + count = [1] * N + result = [0] * N + + dfs(graph, 0, None, count, result) + dfs2(graph, 0, None, count, result) + return result From a972601730c8630aca0be3880beb6c514b7b376d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 May 2018 01:06:20 +0800 Subject: [PATCH 4715/4971] Create image-overlap.cpp --- C++/image-overlap.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/image-overlap.cpp diff --git a/C++/image-overlap.cpp b/C++/image-overlap.cpp new file mode 100644 index 000000000..205ca8eed --- /dev/null +++ b/C++/image-overlap.cpp @@ -0,0 +1,26 @@ +// Time: O(n^4) +// Space: O(n^2) + +class Solution { +public: + int largestOverlap(vector>& A, vector>& B) { + vector count(pow(2 * A.size() - 1, 2)); + for (int i = 0; i < A.size(); ++i) { + for (int j = 0; j < A[i].size(); ++j) { + if (!A[i][j]) { + continue; + } + for (int m = 0; m < B.size(); ++m) { + for (int n = 0; n < B[m].size(); ++n) { + if (!B[m][n]) { + continue; + } + ++count[(A.size() - 1 + i - m) * (2 * A.size() - 1) + + A.size() - 1 + j - n]; + } + } + } + } + return *max_element(count.cbegin(), count.cend()); + } +}; From e3e166fdb44917036f808168c2b406c4cf9d3192 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 14 May 2018 01:09:06 +0800 Subject: [PATCH 4716/4971] Create image-overlap.py --- Python/image-overlap.py | 50 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/image-overlap.py diff --git a/Python/image-overlap.py b/Python/image-overlap.py new file mode 100644 index 000000000..ba533a8ad --- /dev/null +++ b/Python/image-overlap.py @@ -0,0 +1,50 @@ +# Time: O(n^4) +# Space: O(n^2) + +# Two images A and B are given, represented as binary, +# square matrices of the same size. +# (A binary matrix has only 0s and 1s as values.) +# +# We translate one image however we choose (sliding it left, right, up, +# or down any number of units), and place it on top of the other image. +# After, the overlap of this translation is the number of positions that +# have a 1 in both images. +# (Note also that a translation does not include any kind of rotation.) +# +# What is the largest possible overlap? +# +# Example 1: +# +# Input: A = [[1,1,0], +# [0,1,0], +# [0,1,0]] +# B = [[0,0,0], +# [0,1,1], +# [0,0,1]] +# Output: 3 +# Explanation: We slide A to right by 1 unit and down by 1 unit. +# +# Notes: +# 1. 1 <= A.length = A[0].length = B.length = B[0].length <= 30 +# 2. 0 <= A[i][j], B[i][j] <= 1 + + +class Solution(object): + def largestOverlap(self, A, B): + """ + :type A: List[List[int]] + :type B: List[List[int]] + :rtype: int + """ + count = [0] * (2*len(A)-1)**2 + for i, row in enumerate(A): + for j, v in enumerate(row): + if not v: + continue + for i2, row2 in enumerate(B): + for j2, v2 in enumerate(row2): + if not v2: + continue + count[(len(A)-1+i-i2)*(2*len(A)-1) + + len(A)-1+j-j2] += 1 + return max(count) From de6bb204091fdcb89da18c3fec43417d94bf2eea Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 May 2018 01:15:40 +0800 Subject: [PATCH 4717/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 07df22306..298c83b5c 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 807 | [Max Increase to Keep City Skyline](https://leetcode.com/problems/max-increase-to-keep-city-skyline/) | [C++](./C++/max-increase-to-keep-city-skyline.cpp) [Python](./Python/max-increase-to-keep-city-skyline.py) | _O(n^2)_ | _O(n)_ | Medium || 821 | [Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/) | [C++](./C++/shortest-distance-to-a-character.cpp) [Python](./Python/shortest-distance-to-a-character.py) | _O(n)_ | _O(1)_ | Easy || 830 | [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/) | [C++](./C++/positions-of-large-groups.cpp) [Python](./Python/positions-of-large-groups.py) | _O(n)_ | _O(1)_ | Easy || +832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [C++](./C++/flipping-an-image.cpp) [Python](./Python/flipping-an-images.py) | _O(n)_ | _O(1)_ | Easy || +835 | [Image Overlap](https://leetcode.com/problems/image-overlap/) | [C++](./C++/image-overlap.cpp) [Python](./Python/image-overlap.py) | _O(n^4)_ | _O(n^2)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -220,6 +222,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 820| [Short Encoding of Words](https://leetcode.com/problems/short-encoding-of-words/) | [C++](./C++/short-encoding-of-wordss.cpp) [Python](./Python/short-encoding-of-words.py) | _O(n)_ | _O(t)_ | Medium || Trie | 824| [Goat Latin](https://leetcode.com/problems/goat-latin/) | [C++](./C++/goat-latin.cpp) [Python](./Python/goat-latin.py) | _O(n + w^2)_ | _O(l)_ | Easy ||| 831| [Masking Personal Information](https://leetcode.com/problems/masking-personal-information/) | [C++](./C++/masking-personal-information.cpp) [Python](./Python/masking-personal-information.py) | _O(1)_ | _O(1)_ | Medium ||| +833| [Find And Replace in String](https://leetcode.com/problems/find-and-replace-in-string/) | [C++](./C++/find-and-replace-in-string.cpp) [Python](./Python/find-and-replace-in-string.py) | _O(n + m)_ | _O(n)_ | Medium ||| ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -658,6 +661,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 797| [All Paths From Source to Target](https://leetcode.com/problems/all-paths-from-source-to-target/) | [C++](./C++/all-paths-from-source-to-target.cpp) [Python](./Python/all-paths-from-source-to-target.py) | _O(p + r * n)_ | _O(n)_ | Medium ||| 802| [Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) | [C++](./C++/find-eventual-safe-states.cpp) [Python](./Python/find-eventual-safe-states.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium ||| 827| [Making A Large Island](https://leetcode.com/problems/making-a-large-island/) | [C++](./C++/making-a-large-island.cpp) [Python](./Python/making-a-large-island.py) | _O(n^2)_ | _O(n^2)_ | Hard ||| +834| [Sum of Distances in Tree](https://leetcode.com/problems/sum-of-distances-in-tree/) | [C++](./C++/sum-of-distances-in-tree.cpp) [Python](./Python/sum-of-distances-in-tree.py) | _O(n)_ | _O(n)_ | Hard ||| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 1bd59b4c786e2c41ba3033752ffe95b3d3d9bb50 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 May 2018 01:17:15 +0800 Subject: [PATCH 4718/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 298c83b5c..8ddce3e69 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 807 | [Max Increase to Keep City Skyline](https://leetcode.com/problems/max-increase-to-keep-city-skyline/) | [C++](./C++/max-increase-to-keep-city-skyline.cpp) [Python](./Python/max-increase-to-keep-city-skyline.py) | _O(n^2)_ | _O(n)_ | Medium || 821 | [Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/) | [C++](./C++/shortest-distance-to-a-character.cpp) [Python](./Python/shortest-distance-to-a-character.py) | _O(n)_ | _O(1)_ | Easy || 830 | [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/) | [C++](./C++/positions-of-large-groups.cpp) [Python](./Python/positions-of-large-groups.py) | _O(n)_ | _O(1)_ | Easy || -832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [C++](./C++/flipping-an-image.cpp) [Python](./Python/flipping-an-images.py) | _O(n)_ | _O(1)_ | Easy || +832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [C++](./C++/flipping-an-image.cpp) [Python](./Python/flipping-an-image.py) | _O(n)_ | _O(1)_ | Easy || 835 | [Image Overlap](https://leetcode.com/problems/image-overlap/) | [C++](./C++/image-overlap.cpp) [Python](./Python/image-overlap.py) | _O(n^4)_ | _O(n^2)_ | Medium || ## String From 9c322ccb2c668ca76eeeefc0c63ca99bced2d10c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 May 2018 01:17:53 +0800 Subject: [PATCH 4719/4971] Update flipping-an-image.py --- Python/flipping-an-image.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/flipping-an-image.py b/Python/flipping-an-image.py index 33440f036..9de3b1071 100644 --- a/Python/flipping-an-image.py +++ b/Python/flipping-an-image.py @@ -1,4 +1,4 @@ -# Time: O(n) +# Time: O(n^2) # Space: O(1) # Given a binary matrix A, we want to flip the image horizontally, From 36673a552d068b943e5236c28f5a3887c2e878f0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 May 2018 01:18:24 +0800 Subject: [PATCH 4720/4971] Update flipping-an-image.cpp --- C++/flipping-an-image.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flipping-an-image.cpp b/C++/flipping-an-image.cpp index 230eee713..2d98d888f 100644 --- a/C++/flipping-an-image.cpp +++ b/C++/flipping-an-image.cpp @@ -1,4 +1,4 @@ -// Time: O(n) +// Time: O(n^2) // Space: O(1) class Solution { From d17144fe86265c9cd6e98436f627da0c6fedaea4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 May 2018 01:18:44 +0800 Subject: [PATCH 4721/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8ddce3e69..9e3336565 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 807 | [Max Increase to Keep City Skyline](https://leetcode.com/problems/max-increase-to-keep-city-skyline/) | [C++](./C++/max-increase-to-keep-city-skyline.cpp) [Python](./Python/max-increase-to-keep-city-skyline.py) | _O(n^2)_ | _O(n)_ | Medium || 821 | [Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/) | [C++](./C++/shortest-distance-to-a-character.cpp) [Python](./Python/shortest-distance-to-a-character.py) | _O(n)_ | _O(1)_ | Easy || 830 | [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/) | [C++](./C++/positions-of-large-groups.cpp) [Python](./Python/positions-of-large-groups.py) | _O(n)_ | _O(1)_ | Easy || -832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [C++](./C++/flipping-an-image.cpp) [Python](./Python/flipping-an-image.py) | _O(n)_ | _O(1)_ | Easy || +832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [C++](./C++/flipping-an-image.cpp) [Python](./Python/flipping-an-image.py) | _O(n^2)_ | _O(1)_ | Easy || 835 | [Image Overlap](https://leetcode.com/problems/image-overlap/) | [C++](./C++/image-overlap.cpp) [Python](./Python/image-overlap.py) | _O(n^4)_ | _O(n^2)_ | Medium || ## String From 49f062cf60b7013d28e21213582f2013b75bc38b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 14 May 2018 01:58:09 +0800 Subject: [PATCH 4722/4971] Update flipping-an-image.cpp --- C++/flipping-an-image.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/flipping-an-image.cpp b/C++/flipping-an-image.cpp index 2d98d888f..db029043a 100644 --- a/C++/flipping-an-image.cpp +++ b/C++/flipping-an-image.cpp @@ -9,8 +9,8 @@ class Solution { row[i] ^= 1; if (i != row.size() + ~i) { row[row.size() + ~i] ^= 1; + swap(row[i], row[row.size() + ~i]); } - swap(row[i], row[row.size() + ~i]); } } return A; From 1024bc1315821a206274f754ec461c28e1383823 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 15 May 2018 06:19:31 +0800 Subject: [PATCH 4723/4971] Update sum-of-distances-in-tree.py --- Python/sum-of-distances-in-tree.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/sum-of-distances-in-tree.py b/Python/sum-of-distances-in-tree.py index 7d172e200..8e96d8874 100644 --- a/Python/sum-of-distances-in-tree.py +++ b/Python/sum-of-distances-in-tree.py @@ -39,13 +39,13 @@ def dfs(graph, node, parent, count, result): if nei != parent: dfs(graph, nei, node, count, result) count[node] += count[nei] - result[node] += result[nei] + count[nei] + result[node] += result[nei]+count[nei] def dfs2(graph, node, parent, count, result): for nei in graph[node]: if nei != parent: - result[nei] = result[node] - count[nei] + \ - len(count) - count[nei] + result[nei] = result[node]-count[nei] + \ + len(count)-count[nei] dfs2(graph, nei, node, count, result) graph = collections.defaultdict(list) From 37e84b101c913be79265176a280f08d8034316ad Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 21 May 2018 22:01:12 +0800 Subject: [PATCH 4724/4971] Create rectangle-overlap.py --- Python/rectangle-overlap.py | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/rectangle-overlap.py diff --git a/Python/rectangle-overlap.py b/Python/rectangle-overlap.py new file mode 100644 index 000000000..bc42db74f --- /dev/null +++ b/Python/rectangle-overlap.py @@ -0,0 +1,40 @@ +# Time: O(1) +# Space: O(1) + +# A rectangle is represented as a list [x1, y1, x2, y2], +# where (x1, y1) are the coordinates of its bottom-left corner, +# and (x2, y2) are the coordinates of its top-right corner. +# +# Two rectangles overlap if +# the area of their intersection is positive. +# To be clear, two rectangles that only +# touch at the corner or edges do not overlap. +# +# Given two rectangles, return whether they overlap. +# +# Example 1: +# +# Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] +# Output: true +# Example 2: +# +# Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] +# Output: false +# Notes: +# +# Both rectangles rec1 and rec2 are lists of 4 integers. +# All coordinates in rectangles will be between -10^9 and 10^9. + + +class Solution(object): + def isRectangleOverlap(self, rec1, rec2): + """ + :type rec1: List[int] + :type rec2: List[int] + :rtype: bool + """ + def intersect(p_left, p_right, q_left, q_right): + return max(p_left, q_left) < min(p_right, q_right) + + return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) and + intersect(rec1[1], rec1[3], rec2[1], rec2[3])) From 55943f05e0849260ba85091cc633f993529b3b09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 May 2018 22:03:41 +0800 Subject: [PATCH 4725/4971] Create rectangle-overlap.cpp --- C++/rectangle-overlap.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/rectangle-overlap.cpp diff --git a/C++/rectangle-overlap.cpp b/C++/rectangle-overlap.cpp new file mode 100644 index 000000000..e1b15f366 --- /dev/null +++ b/C++/rectangle-overlap.cpp @@ -0,0 +1,15 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + bool isRectangleOverlap(vector& rec1, vector& rec2) { + return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) && + intersect(rec1[1], rec1[3], rec2[1], rec2[3])); + } + +private: + bool intersect(int p_left, int p_right, int q_left, int q_right) { + return max(p_left, q_left) < min(p_right, q_right); + } +}; From 407f4829a809ff4544e7fbeb07439c8e9479e895 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 May 2018 22:50:05 +0800 Subject: [PATCH 4726/4971] Create new-21-game.cpp --- C++/new-21-game.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/new-21-game.cpp diff --git a/C++/new-21-game.cpp b/C++/new-21-game.cpp new file mode 100644 index 000000000..4743fde6a --- /dev/null +++ b/C++/new-21-game.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + double new21Game(int N, int K, int W) { + if (K == 0 || N >= K + W) { + return 1.0f; + } + vector dp(N + 1); + dp[0] = 1.0f; + double W_sum = 1.0f, result = 0.0f; + for (int i = 1; i <= N; ++i) { + dp[i] = W_sum / W; + if (i < K) { + W_sum += dp[i]; + } else { + result += dp[i]; + } + if (i - W >= 0) { + W_sum -= dp[i - W]; + } + } + return result; + } +}; From fdbba1a37f631aba433cd3f620001167f50e3fd2 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 21 May 2018 23:09:11 +0800 Subject: [PATCH 4727/4971] Create push-dominoes.py --- Python/push-dominoes.py | 80 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Python/push-dominoes.py diff --git a/Python/push-dominoes.py b/Python/push-dominoes.py new file mode 100644 index 000000000..fee075b24 --- /dev/null +++ b/Python/push-dominoes.py @@ -0,0 +1,80 @@ +# Time: O(n) +# Space: O(n) + +# There are N dominoes in a line, and we place each domino vertically upright. +# +# In the beginning, +# we simultaneously push some of the dominoes either to the left or +# to the right. +# +# After each second, +# each domino that is falling to the left pushes the adjacent domino +# on the left. +# +# Similarly, the dominoes falling to the right push their adjacent dominoes +# standing on the right. +# +# When a vertical domino has dominoes falling on it from both sides, +# it stays still due to the balance of the forces. +# +# For the purposes of this question, +# we will consider that a falling domino expends no additional force to a +# falling or already fallen domino. +# +# Given a string "S" representing the initial state. S[i] = 'L', +# if the i-th domino has been pushed to the left; S[i] = 'R', +# if the i-th domino has been pushed to the right; S[i] = '.', +# if the i-th domino has not been pushed. +# +# Return a string representing the final state. +# +# Example 1: +# +# Input: ".L.R...LR..L.." +# Output: "LL.RR.LLRRLL.." +# Example 2: +# +# Input: "RR.L" +# Output: "RR.L" +# Explanation: The first domino expends no additional force +# on the second domino. +# Note: +# - 0 <= N <= 10^5 +# - String dominoes contains only 'L', 'R' and '.' + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def pushDominoes(self, dominoes): + """ + :type dominoes: str + :rtype: str + """ + force = [0]*len(dominoes) + + f = 0 + for i in xrange(len(dominoes)): + if dominoes[i] == 'R': + f = len(dominoes) + elif dominoes[i] == 'L': + f = 0 + else: + f = max(f-1, 0) + force[i] += f + + f = 0 + for i in reversed(xrange(len(dominoes))): + if dominoes[i] == 'L': + f = len(dominoes) + elif dominoes[i] == 'R': + f = 0 + else: + f = max(f-1, 0) + force[i] -= f + + return "".join('.' if f == 0 else 'R' if f > 0 else 'L' + for f in force) From 9f596199074a0fa1172bd12c4004276a57911b63 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 May 2018 23:14:04 +0800 Subject: [PATCH 4728/4971] Create push-dominoes.cpp --- C++/push-dominoes.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 C++/push-dominoes.cpp diff --git a/C++/push-dominoes.cpp b/C++/push-dominoes.cpp new file mode 100644 index 000000000..33779062d --- /dev/null +++ b/C++/push-dominoes.cpp @@ -0,0 +1,38 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + string pushDominoes(string dominoes) { + vector force(dominoes.length()); + + int f = 0; + for (int i = 0; i < dominoes.length(); ++i) { + if (dominoes[i] == 'R') { + f = dominoes.length(); + } else if (dominoes[i] == 'L') { + f = 0; + } else { + f = max(f - 1, 0); + } + force[i] += f; + } + + f = 0; + for (int i = dominoes.length() - 1; i >= 0; --i) { + if (dominoes[i] == 'L') { + f = dominoes.length(); + } else if (dominoes[i] == 'R') { + f = 0; + } else { + f = max(f - 1, 0); + } + force[i] -= f; + } + string result; + for (const auto& f : force) { + result.push_back((f == 0) ? '.' : ((f > 0) ? 'R' : 'L')); + } + return result; + } +}; From 02db769cb6b6ddfd803d376bf91a546b5fe391c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 May 2018 23:41:06 +0800 Subject: [PATCH 4729/4971] Create similar-string-groups.cpp --- C++/similar-string-groups.cpp | 60 +++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 C++/similar-string-groups.cpp diff --git a/C++/similar-string-groups.cpp b/C++/similar-string-groups.cpp new file mode 100644 index 000000000..5419e4445 --- /dev/null +++ b/C++/similar-string-groups.cpp @@ -0,0 +1,60 @@ +// Time: O(n^2 * l), l is the average length of words +// Space: O(n) + +class Solution { +public: + int numSimilarGroups(vector& A) { + UnionFind union_find(A.size()); + for (int i = 0; i < A.size(); ++i) { + for (int j = 0; j < i; ++j) { + if (isSimilar(A[i], A[j])) { + union_find.union_set(i, j); + } + } + } + return union_find.count(); + } + +private: + bool isSimilar(const string &a, const string &b) { + int diff = 0; + for (int i = 0; i < a.length(); ++i) { + if (a[i] != b[i]) { + ++diff; + } + } + return diff == 2; + } + + class UnionFind { + public: + UnionFind(const int n) : set_(n), count_(n) { + iota(set_.begin(), set_.end(), 0); + } + + int find_set(const int x) { + if (set_[x] != x) { + set_[x] = find_set(set_[x]); // Path compression. + } + return set_[x]; + } + + bool union_set(const int x, const int y) { + int x_root = find_set(x), y_root = find_set(y); + if (x_root == y_root) { + return false; + } + set_[min(x_root, y_root)] = max(x_root, y_root); + --count_; + return true; + } + + int count() const { + return count_; + } + + private: + vector set_; + int count_; + }; +}; From bbfae4063da7006e410b191d194d50b94cce4abf Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 May 2018 23:42:26 +0800 Subject: [PATCH 4730/4971] Update similar-string-groups.cpp --- C++/similar-string-groups.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/C++/similar-string-groups.cpp b/C++/similar-string-groups.cpp index 5419e4445..47d3db0c6 100644 --- a/C++/similar-string-groups.cpp +++ b/C++/similar-string-groups.cpp @@ -12,7 +12,7 @@ class Solution { } } } - return union_find.count(); + return union_find.size(); } private: @@ -28,7 +28,7 @@ class Solution { class UnionFind { public: - UnionFind(const int n) : set_(n), count_(n) { + UnionFind(const int n) : set_(n), size_(n) { iota(set_.begin(), set_.end(), 0); } @@ -45,16 +45,16 @@ class Solution { return false; } set_[min(x_root, y_root)] = max(x_root, y_root); - --count_; + --size_; return true; } - int count() const { - return count_; + int size() const { + return size_; } private: vector set_; - int count_; + int size_; }; }; From 26b8c59f3cab844763abd4733427eec74ef39f8b Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 21 May 2018 23:43:03 +0800 Subject: [PATCH 4731/4971] Update similar-string-groups.cpp --- C++/similar-string-groups.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/similar-string-groups.cpp b/C++/similar-string-groups.cpp index 47d3db0c6..7b7d3732a 100644 --- a/C++/similar-string-groups.cpp +++ b/C++/similar-string-groups.cpp @@ -16,7 +16,7 @@ class Solution { } private: - bool isSimilar(const string &a, const string &b) { + bool isSimilar(const string& a, const string& b) { int diff = 0; for (int i = 0; i < a.length(); ++i) { if (a[i] != b[i]) { From f03c5adc6ebc9b559e3105ec8f467c59be9bc81a Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Tue, 22 May 2018 00:26:37 +0800 Subject: [PATCH 4732/4971] Create similar-string-groups.py --- Python/similar-string-groups.py | 94 +++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 Python/similar-string-groups.py diff --git a/Python/similar-string-groups.py b/Python/similar-string-groups.py new file mode 100644 index 000000000..4dcfb845d --- /dev/null +++ b/Python/similar-string-groups.py @@ -0,0 +1,94 @@ +# Time: O(n*l*min(n, l^2)) +# Space: O(n*l^3) + +# Two strings X and Y are similar if we can swap two letters +# (in different positions) of X, so that it equals Y. +# +# For example, "tars" and "rats" are similar (swapping at positions 0 and 2), +# and "rats" and "arts" are similar, but "star" is not similar to +# "tars", "rats", or "arts". +# +# Together, these form two connected groups by similarity: +# {"tars", "rats", "arts"} and {"star"}. +# Notice that "tars" and "arts" are in the same group +# even though they are not similar. +# Formally, each group is such that a word is in the group +# if and only if it is similar +# to at least one other word in the group. +# +# We are given a list A of unique strings. +# Every string in A is an anagram of every other string in A. +# How many groups are there? +# +# Example 1: +# +# Input: ["tars","rats","arts","star"] +# Output: 2 +# +# Note: +# - A.length <= 2000 +# - A[i].length <= 1000 +# - A.length * A[i].length <= 20000 +# - All words in A consist of lowercase letters only. +# - All words in A have the same length and are anagrams of each other. +# - The judging time limit has been increased for this question. + +import collections +import itertools + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class UnionFind(object): + def __init__(self, n): + self.set = range(n) + self.__size = 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: + return False + self.set[min(x_root, y_root)] = max(x_root, y_root) + self.__size -= 1 + return True + + def size(self): + return self.__size + + +class Solution(object): + def numSimilarGroups(self, A): + def isSimilar(a, b): + diff = 0 + for x, y in itertools.izip(a, b): + if x != y: + diff += 1 + return diff == 2 + + N, L = len(A), len(A[0]) + union_find = UnionFind(N) + if N < L*L: + for (i1, word1), (i2, word2) in \ + itertools.combinations(enumerate(A), 2): + if isSimilar(word1, word2): + union_find.union_set(i1, i2) + else: + buckets = collections.defaultdict(list) + for i in xrange(len(A)): + word = list(A[i]) + for j1, j2 in itertools.combinations(xrange(L), 2): + word[j1], word[j2] = word[j2], word[j1] + buckets["".join(word)].append(i) + word[j1], word[j2] = word[j2], word[j1] + for word in A: + for i1, i2 in itertools.combinations(buckets[word], 2): + union_find.union_set(i1, i2) + return union_find.size() From c5279e5e93bd376e732de25a0d5d6d9bcf59b5a0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 00:48:46 +0800 Subject: [PATCH 4733/4971] Update similar-string-groups.py --- Python/similar-string-groups.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/similar-string-groups.py b/Python/similar-string-groups.py index 4dcfb845d..d45cbff37 100644 --- a/Python/similar-string-groups.py +++ b/Python/similar-string-groups.py @@ -84,6 +84,7 @@ def isSimilar(a, b): buckets = collections.defaultdict(list) for i in xrange(len(A)): word = list(A[i]) + buckets["".join(word)].append(i) for j1, j2 in itertools.combinations(xrange(L), 2): word[j1], word[j2] = word[j2], word[j1] buckets["".join(word)].append(i) From 2e531128b020f55e5d7345de972bc71b59d903a3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 00:51:46 +0800 Subject: [PATCH 4734/4971] Update similar-string-groups.cpp --- C++/similar-string-groups.cpp | 83 +++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/C++/similar-string-groups.cpp b/C++/similar-string-groups.cpp index 7b7d3732a..f23253c8f 100644 --- a/C++/similar-string-groups.cpp +++ b/C++/similar-string-groups.cpp @@ -58,3 +58,86 @@ class Solution { int size_; }; }; + +// Time: O(n*l*min(n, l^2)) +// Space: O(n*l^3) +class Solution_MLE { +public: + int numSimilarGroups(vector& A) { + const int N = A.size(), L = A[0].length(); + UnionFind union_find(A.size()); + if (N < L*L) { + for (int i = 0; i < N; ++i) { + for (int j = 0; j < i; ++j) { + if (isSimilar(A[i], A[j])) { + union_find.union_set(i, j); + } + } + } + } else { + unordered_map> buckets; + for (int i = 0; i < A.size(); ++i) { + auto word = A[i]; + buckets[word].emplace_back(i); + for (int j1 = 0; j1 < L; ++j1) { + for (int j2 = 0; j2 < j1; ++j2) { + swap(word[j1], word[j2]); + buckets[word].emplace_back(i); + swap(word[j1], word[j2]); + } + } + } + for (const auto& word : A) { + for (int i = 0; i < buckets[word].size(); ++i) { + for (int j = 0; j < i; ++j) { + union_find.union_set(buckets[word][i], buckets[word][j]); + } + } + } + } + return union_find.size(); + } + +private: + bool isSimilar(const string &a, const string &b) { + int diff = 0; + for (int i = 0; i < a.length(); ++i) { + if (a[i] != b[i]) { + ++diff; + } + } + return diff == 2; + } + + class UnionFind { + public: + UnionFind(const int n) : set_(n), size_(n) { + iota(set_.begin(), set_.end(), 0); + } + + int find_set(const int x) { + if (set_[x] != x) { + set_[x] = find_set(set_[x]); // Path compression. + } + return set_[x]; + } + + bool union_set(const int x, const int y) { + int x_root = find_set(x), y_root = find_set(y); + if (x_root == y_root) { + return false; + } + set_[min(x_root, y_root)] = max(x_root, y_root); + --size_; + return true; + } + + int size() const { + return size_; + } + + private: + vector set_; + int size_; + }; +}; From 067958b68dc7993d7113c8f429a024a00cfa85c9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 00:53:23 +0800 Subject: [PATCH 4735/4971] Update similar-string-groups.py --- Python/similar-string-groups.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/similar-string-groups.py b/Python/similar-string-groups.py index d45cbff37..a7fddd833 100644 --- a/Python/similar-string-groups.py +++ b/Python/similar-string-groups.py @@ -1,5 +1,5 @@ -# Time: O(n*l*min(n, l^2)) -# Space: O(n*l^3) +# Time: O(n * l * min(n, l^2)) +# Space: O(n * l^3) # Two strings X and Y are similar if we can swap two letters # (in different positions) of X, so that it equals Y. From 91efa8704adfed996a3c1160959ccddf1a8dd99a Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 00:53:53 +0800 Subject: [PATCH 4736/4971] Update similar-string-groups.cpp --- C++/similar-string-groups.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/similar-string-groups.cpp b/C++/similar-string-groups.cpp index f23253c8f..c04c2b1b2 100644 --- a/C++/similar-string-groups.cpp +++ b/C++/similar-string-groups.cpp @@ -59,8 +59,8 @@ class Solution { }; }; -// Time: O(n*l*min(n, l^2)) -// Space: O(n*l^3) +// Time: O(n * l * min(n, l^2)) +// Space: O(n * l^3) class Solution_MLE { public: int numSimilarGroups(vector& A) { From 6bd247c9616864144fa8c7343537c65ac3b998e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 01:02:51 +0800 Subject: [PATCH 4737/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 9e3336565..519889c85 100644 --- a/README.md +++ b/README.md @@ -223,6 +223,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 824| [Goat Latin](https://leetcode.com/problems/goat-latin/) | [C++](./C++/goat-latin.cpp) [Python](./Python/goat-latin.py) | _O(n + w^2)_ | _O(l)_ | Easy ||| 831| [Masking Personal Information](https://leetcode.com/problems/masking-personal-information/) | [C++](./C++/masking-personal-information.cpp) [Python](./Python/masking-personal-information.py) | _O(1)_ | _O(1)_ | Medium ||| 833| [Find And Replace in String](https://leetcode.com/problems/find-and-replace-in-string/) | [C++](./C++/find-and-replace-in-string.cpp) [Python](./Python/find-and-replace-in-string.py) | _O(n + m)_ | _O(n)_ | Medium ||| +839 | [Similar String Groups](https://leetcode.com/problems/similar-string-groups/) | [C++](./C++/similar-string-groups.cpp) [Python](./Python/similar-string-groups.py) | _O(n^2 * l)_ | _O(n)_ | Hard || Union Find ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -466,6 +467,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 810 | [Chalkboard XOR Game](https://leetcode.com/problems/chalkboard-xor-game/) | [C++](./C++/chalkboard-xor-game.cpp) [Python](./Python/chalkboard-xor-game.py) | _O(1)_ | _O(1)_ | Hard ||| 812 | [Largest Triangle Area](https://leetcode.com/problems/largest-triangle-area/) | [C++](./C++/largest-triangle-area.cpp) [Python](./Python/largest-triangle-area.py) | _O(n^3)_ | _O(1)_ | Easy ||| 829 | [Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/) | [C++](./C++/consecutive-numbers-sum.cpp) [Python](./Python/consecutive-numbers-sum.py) | _O(sqrt(n))_ | _O(1)_ | Medium ||| +836 | [Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap/) | [C++](./C++/rectangle-overlap.cpp) [Python](./Python/rectangle-overlap.py) | _O(1)_ | _O(1)_ | Easy ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -784,6 +786,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 813 | [Largest Sum of Averages](https://leetcode.com/problems/largest-sum-of-averages/) | [C++](./C++/largest-sum-of-averages.cpp) [Python](./Python/largest-sum-of-averages.py) | _O(k * n^2)_ | _O(n)_ | Medium || | 818 | [Race Car](https://leetcode.com/problems/race-car/) | [C++](./C++/race-car.cpp) [Python](./Python/race-car.py) | _O(nlogn)_ | _O(n)_ | Hard || | 823 | [Binary Trees With Factors](https://leetcode.com/problems/binary-trees-with-factors/) | [C++](./C++/binary-trees-with-factors.cpp) [Python](./Python/binary-trees-with-factors.py) | _O(n^2)_ | _O(n)_ | Medium || | +837 | [New 21 Game](https://leetcode.com/problems/new-21-game/) | [C++](./C++/new-21-game.cpp) [Python](./Python/new-21-game.py) | _O(n)_ | _O(n)_ | Medium || | +838 | [Push Dominoes](https://leetcode.com/problems/push-dominoes/) | [C++](./C++/push-dominoes.cpp) [Python](./Python/push-dominoes.py) | _O(n)_ | _O(n)_ | Medium || | ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 47b5bb1d3f91b24e41e8f4b567e0d9db1ba15dc4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 01:36:14 +0800 Subject: [PATCH 4738/4971] Update similar-string-groups.cpp --- C++/similar-string-groups.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/C++/similar-string-groups.cpp b/C++/similar-string-groups.cpp index c04c2b1b2..331e9b0ba 100644 --- a/C++/similar-string-groups.cpp +++ b/C++/similar-string-groups.cpp @@ -76,9 +76,13 @@ class Solution_MLE { } } else { unordered_map> buckets; + unordered_set lookup; for (int i = 0; i < A.size(); ++i) { auto word = A[i]; - buckets[word].emplace_back(i); + if (!lookup.count(word)) { + buckets[word].emplace_back(i); + lookup.emplace(word); + } for (int j1 = 0; j1 < L; ++j1) { for (int j2 = 0; j2 < j1; ++j2) { swap(word[j1], word[j2]); From 2fe62fa57a310de3bbdbc89538aef75e90875d41 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 01:42:06 +0800 Subject: [PATCH 4739/4971] Update similar-string-groups.py --- Python/similar-string-groups.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Python/similar-string-groups.py b/Python/similar-string-groups.py index a7fddd833..3d750da45 100644 --- a/Python/similar-string-groups.py +++ b/Python/similar-string-groups.py @@ -82,9 +82,12 @@ def isSimilar(a, b): union_find.union_set(i1, i2) else: buckets = collections.defaultdict(list) + lookup = set() for i in xrange(len(A)): word = list(A[i]) - buckets["".join(word)].append(i) + if A[i] not in lookup: + buckets[A[i]].append(i) + lookup.add(A[i]) for j1, j2 in itertools.combinations(xrange(L), 2): word[j1], word[j2] = word[j2], word[j1] buckets["".join(word)].append(i) From 92f6c84a47d5c71e907f284e409ff383534ff1e2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 02:08:57 +0800 Subject: [PATCH 4740/4971] Update similar-string-groups.py --- Python/similar-string-groups.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/similar-string-groups.py b/Python/similar-string-groups.py index 3d750da45..dd9a50a04 100644 --- a/Python/similar-string-groups.py +++ b/Python/similar-string-groups.py @@ -1,5 +1,5 @@ -# Time: O(n * l * min(n, l^2)) -# Space: O(n * l^3) +# Time: O(n^2 * l) ~ O(n * l^4) +# Space: O(n) ~ O(n * l^3) # Two strings X and Y are similar if we can swap two letters # (in different positions) of X, so that it equals Y. @@ -92,7 +92,7 @@ def isSimilar(a, b): word[j1], word[j2] = word[j2], word[j1] buckets["".join(word)].append(i) word[j1], word[j2] = word[j2], word[j1] - for word in A: + for word in A: # Time: O(n * l^4) for i1, i2 in itertools.combinations(buckets[word], 2): union_find.union_set(i1, i2) return union_find.size() From 1dc7a205aa2e5faa087d0f8c4da659186139934e Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 02:09:39 +0800 Subject: [PATCH 4741/4971] Update similar-string-groups.cpp --- C++/similar-string-groups.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/similar-string-groups.cpp b/C++/similar-string-groups.cpp index 331e9b0ba..258460bbc 100644 --- a/C++/similar-string-groups.cpp +++ b/C++/similar-string-groups.cpp @@ -59,8 +59,8 @@ class Solution { }; }; -// Time: O(n * l * min(n, l^2)) -// Space: O(n * l^3) +// Time: O(n^2 * l) ~ O(n * l^4) +// Space: O(n) ~ O(n * l^3) class Solution_MLE { public: int numSimilarGroups(vector& A) { From af80f68c27061f30813c3dff8ef0d90bc5afdf87 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 22:22:58 +0800 Subject: [PATCH 4742/4971] Update similar-string-groups.py --- Python/similar-string-groups.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Python/similar-string-groups.py b/Python/similar-string-groups.py index dd9a50a04..06c9a9664 100644 --- a/Python/similar-string-groups.py +++ b/Python/similar-string-groups.py @@ -71,6 +71,8 @@ def isSimilar(a, b): for x, y in itertools.izip(a, b): if x != y: diff += 1 + if diff > 2: + return False return diff == 2 N, L = len(A), len(A[0]) From 30c98076c60afe37630e71be41054fb2490a1ed4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 22 May 2018 22:25:36 +0800 Subject: [PATCH 4743/4971] Update similar-string-groups.cpp --- C++/similar-string-groups.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/C++/similar-string-groups.cpp b/C++/similar-string-groups.cpp index 258460bbc..da15f3510 100644 --- a/C++/similar-string-groups.cpp +++ b/C++/similar-string-groups.cpp @@ -20,7 +20,9 @@ class Solution { int diff = 0; for (int i = 0; i < a.length(); ++i) { if (a[i] != b[i]) { - ++diff; + if (++diff > 2) { + return false; + } } } return diff == 2; @@ -103,11 +105,13 @@ class Solution_MLE { } private: - bool isSimilar(const string &a, const string &b) { + bool isSimilar(const string& a, const string& b) { int diff = 0; for (int i = 0; i < a.length(); ++i) { if (a[i] != b[i]) { - ++diff; + if (++diff > 2) { + return false; + } } } return diff == 2; From 1a185145820c8f4f74f36ab79ac40b950cc8df91 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 May 2018 00:51:55 +0800 Subject: [PATCH 4744/4971] Update network-delay-time.py --- Python/network-delay-time.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index 347d39690..dea7c7868 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -1,4 +1,5 @@ -# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) +# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) by using binary heap, +# if we can futher to use Fibonacci heap, it would be O(|E| + |V| * log|V|) # Space: O(|E| + |V|) = O(|E|) # There are N network nodes, labelled 1 to N. From 0c01ef19cbe8f154984d40c9902b83d3552d4a68 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 May 2018 00:52:28 +0800 Subject: [PATCH 4745/4971] Update cheapest-flights-within-k-stops.py --- Python/cheapest-flights-within-k-stops.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Python/cheapest-flights-within-k-stops.py b/Python/cheapest-flights-within-k-stops.py index f3a130f1e..28c09ad8b 100644 --- a/Python/cheapest-flights-within-k-stops.py +++ b/Python/cheapest-flights-within-k-stops.py @@ -1,4 +1,5 @@ -# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) +# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|), +# if we can futher to use Fibonacci heap, it would be O(|E| + |V| * log|V|) # Space: O(|E| + |V|) = O(|E|) # There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w. From d148da7950b5d6e97414a52980a3bd962311f790 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 May 2018 00:52:56 +0800 Subject: [PATCH 4746/4971] Update cheapest-flights-within-k-stops.py --- Python/cheapest-flights-within-k-stops.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/cheapest-flights-within-k-stops.py b/Python/cheapest-flights-within-k-stops.py index 28c09ad8b..96c44cfa8 100644 --- a/Python/cheapest-flights-within-k-stops.py +++ b/Python/cheapest-flights-within-k-stops.py @@ -1,5 +1,5 @@ # Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|), -# if we can futher to use Fibonacci heap, it would be O(|E| + |V| * log|V|) +# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|) # Space: O(|E| + |V|) = O(|E|) # There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w. From dd05c4dec2211339e5a66f972179794b9c3c2ae8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 25 May 2018 00:54:38 +0800 Subject: [PATCH 4747/4971] Update network-delay-time.py --- Python/network-delay-time.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index dea7c7868..c4702142d 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -1,5 +1,5 @@ # Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) by using binary heap, -# if we can futher to use Fibonacci heap, it would be O(|E| + |V| * log|V|) +# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|) # Space: O(|E| + |V|) = O(|E|) # There are N network nodes, labelled 1 to N. From 854b62915956cd3b4070d38f6028ecc2cf38ee2c Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 27 May 2018 23:22:18 +0800 Subject: [PATCH 4748/4971] Create magic-squares-in-grid.py --- Python/magic-squares-in-grid.py | 65 +++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Python/magic-squares-in-grid.py diff --git a/Python/magic-squares-in-grid.py b/Python/magic-squares-in-grid.py new file mode 100644 index 000000000..d8dbe69b4 --- /dev/null +++ b/Python/magic-squares-in-grid.py @@ -0,0 +1,65 @@ +# Time: O(m * n) +# Space: O(1) + +# A 3 x 3 magic square is a 3 x 3 grid filled with +# distinct numbers from 1 to 9 such that each row, column, +# and both diagonals all have the same sum. +# +# Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? +# (Each subgrid is contiguous). +# +# Example 1: +# +# Input: [[4,3,8,4], +# [9,5,1,9], +# [2,7,6,2]] +# Output: 1 +# Explanation: +# The following subgrid is a 3 x 3 magic square: +# 438 +# 951 +# 276 +# +# while this one is not: +# 384 +# 519 +# 762 +# +# In total, there is only one magic square inside the given grid. +# Note: +# - 1 <= grid.length <= 10 +# - 1 <= grid[0].length <= 10 +# - 0 <= grid[i][j] <= 15 + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def numMagicSquaresInside(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + def magic(vals): + return (len(set(vals)) == 9 and + min(vals) == 1 and + vals[0]+vals[1]+vals[2] == + vals[3]+vals[4]+vals[5] == + vals[6]+vals[7]+vals[8] == + vals[0]+vals[3]+vals[6] == + vals[1]+vals[4]+vals[7] == + vals[2]+vals[5]+vals[8] == + vals[0]+vals[4]+vals[8] == + vals[2]+vals[4]+vals[6] == 15) + + result = 0 + for r in xrange(len(grid)-2): + for c in xrange(len(grid[r])-2): + if magic([grid[r][c], grid[r][c+1], grid[r][c+2], + grid[r+1][c], grid[r+1][c+1], grid[r+1][c+2], + grid[r+2][c], grid[r+2][c+1], grid[r+2][c+2]]): + result += 1 + return result From b832c3b96ba630568f074b1a8db9e65705dad93c Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 27 May 2018 23:52:03 +0800 Subject: [PATCH 4749/4971] Update magic-squares-in-grid.py --- Python/magic-squares-in-grid.py | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/Python/magic-squares-in-grid.py b/Python/magic-squares-in-grid.py index d8dbe69b4..221deca88 100644 --- a/Python/magic-squares-in-grid.py +++ b/Python/magic-squares-in-grid.py @@ -43,23 +43,28 @@ def numMagicSquaresInside(self, grid): :type grid: List[List[int]] :rtype: int """ - def magic(vals): - return (len(set(vals)) == 9 and - min(vals) == 1 and - vals[0]+vals[1]+vals[2] == - vals[3]+vals[4]+vals[5] == - vals[6]+vals[7]+vals[8] == - vals[0]+vals[3]+vals[6] == - vals[1]+vals[4]+vals[7] == - vals[2]+vals[5]+vals[8] == - vals[0]+vals[4]+vals[8] == - vals[2]+vals[4]+vals[6] == 15) + def magic(grid, r, c): + nums = set() + min_num = float("inf") + sum_diag, sum_anti = 0, 0 + for i in xrange(3): + sum_diag += grid[r+i][c+i] + sum_anti += grid[r+i][c+2-i] + sum_r, sum_c = 0, 0 + for j in xrange(3): + min_num = min(min_num, grid[r+i][c+j]) + nums.add(grid[r+i][c+j]) + sum_r += grid[r+i][c+j] + sum_c += grid[r+j][c+i] + if not (sum_r == sum_c == 15): + return False + return sum_diag == sum_anti == 15 and \ + len(nums) == 9 and \ + min_num == 1 result = 0 for r in xrange(len(grid)-2): for c in xrange(len(grid[r])-2): - if magic([grid[r][c], grid[r][c+1], grid[r][c+2], - grid[r+1][c], grid[r+1][c+1], grid[r+1][c+2], - grid[r+2][c], grid[r+2][c+1], grid[r+2][c+2]]): + if magic(grid, r, c): result += 1 return result From 4704f42f9b6de3ac6af2bbc57d1f6c78f0e6a81e Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 28 May 2018 00:02:39 +0800 Subject: [PATCH 4750/4971] Update magic-squares-in-grid.py --- Python/magic-squares-in-grid.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Python/magic-squares-in-grid.py b/Python/magic-squares-in-grid.py index 221deca88..bc59f8f41 100644 --- a/Python/magic-squares-in-grid.py +++ b/Python/magic-squares-in-grid.py @@ -44,24 +44,26 @@ def numMagicSquaresInside(self, grid): :rtype: int """ def magic(grid, r, c): + expect = k * (k**2+1) // 2 nums = set() min_num = float("inf") sum_diag, sum_anti = 0, 0 - for i in xrange(3): + for i in xrange(k): sum_diag += grid[r+i][c+i] - sum_anti += grid[r+i][c+2-i] + sum_anti += grid[r+i][c+k-1-i] sum_r, sum_c = 0, 0 - for j in xrange(3): + for j in xrange(k): min_num = min(min_num, grid[r+i][c+j]) nums.add(grid[r+i][c+j]) sum_r += grid[r+i][c+j] sum_c += grid[r+j][c+i] - if not (sum_r == sum_c == 15): + if not (sum_r == sum_c == expect): return False - return sum_diag == sum_anti == 15 and \ - len(nums) == 9 and \ + return sum_diag == sum_anti == expect and \ + len(nums) == k**2 and \ min_num == 1 + k = 3 result = 0 for r in xrange(len(grid)-2): for c in xrange(len(grid[r])-2): From a848a54c28c06918779c3e4065134471ed562df1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 00:03:30 +0800 Subject: [PATCH 4751/4971] Create magic-squares-in-grid.cpp --- C++/magic-squares-in-grid.cpp | 46 +++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 C++/magic-squares-in-grid.cpp diff --git a/C++/magic-squares-in-grid.cpp b/C++/magic-squares-in-grid.cpp new file mode 100644 index 000000000..9cc35ff71 --- /dev/null +++ b/C++/magic-squares-in-grid.cpp @@ -0,0 +1,46 @@ +// Time: O(m * n) +// Space: O(1) + +class Solution { +public: + int numMagicSquaresInside(vector>& grid) { + int result = 0; + for (int i = 0; i + k - 1 < grid.size(); ++i) { + for (int j = 0; j + k - 1 < grid[j].size(); ++j) { + if (magic(grid, i, j)) { + ++result; + } + } + } + return result; + } + +private: + static const int k = 3; + + bool magic(const vector>& grid, int r, int c) { + const int expect = k * (k * k + 1) / 2; + unordered_set nums; + int min_num = numeric_limits::max(); + int sum_diag = 0, sum_anti = 0; + for (int i = 0; i < k; ++i) { + sum_diag += grid[r + i][c + i]; + sum_anti += grid[r + i][c + k - 1 - i]; + int sum_r = 0, sum_c = 0; + for (int j = 0; j < k; ++j) { + min_num = min(min_num, grid[r + i][c + j]); + nums.emplace(grid[r + i][c + j]); + sum_r += grid[r + i][c + j]; + sum_c += grid[r + j][c + i]; + } + if (!(sum_r == sum_c && + sum_c == expect)) { + return false; + } + } + return sum_diag == sum_anti && + sum_anti == expect && + nums.size() == k * k && + min_num == 1; + } +}; From d3731f4f7b3fbd2eee95804a78ae9ac1dd9eb3ef Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 00:35:19 +0800 Subject: [PATCH 4752/4971] Create keys-and-rooms.cpp --- C++/keys-and-rooms.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/keys-and-rooms.cpp diff --git a/C++/keys-and-rooms.cpp b/C++/keys-and-rooms.cpp new file mode 100644 index 000000000..7572c880b --- /dev/null +++ b/C++/keys-and-rooms.cpp @@ -0,0 +1,23 @@ +// Time: O(n!) +// Space: O(n) + +class Solution { +public: + bool canVisitAllRooms(vector>& rooms) { + unordered_set lookup = {0}; + vector stack = {0}; + while (!stack.empty()) { + auto node = stack.back(); stack.pop_back(); + for (const auto& nei : rooms[node]) { + if (!lookup.count(nei)) { + lookup.emplace(nei); + if (lookup.size() == rooms.size()) { + return true; + } + stack.emplace_back(nei); + } + } + } + return lookup.size() == rooms.size(); + } +}; From a1586021120f23f4acda4965d2136183df583325 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 28 May 2018 00:37:31 +0800 Subject: [PATCH 4753/4971] Create keys-and-rooms.py --- Python/keys-and-rooms.py | 52 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/keys-and-rooms.py diff --git a/Python/keys-and-rooms.py b/Python/keys-and-rooms.py new file mode 100644 index 000000000..c4d2572bb --- /dev/null +++ b/Python/keys-and-rooms.py @@ -0,0 +1,52 @@ +# There are N rooms and you start in room 0. +# Each room has a distinct number in 0, 1, 2, ..., N-1, +# and each room may have some keys to access the next room. +# +# Formally, each room i has a list of keys rooms[i], +# and each key rooms[i][j] is an integer in [0, 1, ..., N-1] +# where N = rooms.length. +# A key rooms[i][j] = v opens the room with number v. +# +# Initially, all the rooms start locked (except for room 0). +# You can walk back and forth between rooms freely. +# Return true if and only if you can enter every room. +# +# Example 1: +# +# Input: [[1],[2],[3],[]] +# Output: true +# Explanation: +# We start in room 0, and pick up key 1. +# We then go to room 1, and pick up key 2. +# We then go to room 2, and pick up key 3. +# We then go to room 3. Since we were able to go to every room, +# we return true. +# Example 2: +# +# Input: [[1,3],[3,0,1],[2],[0]] +# Output: false +# Explanation: We can't enter the room with number 2. +# +# Note: +# - 1 <= rooms.length <= 1000 +# - 0 <= rooms[i].length <= 1000 +# - The number of keys in all rooms combined is at most 3000. + + +class Solution(object): + def canVisitAllRooms(self, rooms): + """ + :type rooms: List[List[int]] + :rtype: bool + """ + lookup = set([0]) + stack = [0] + while stack: + node = stack.pop() + for nei in rooms[node]: + if nei not in lookup: + lookup.add(nei) + if len(lookup) == len(rooms): + return True + stack.append(nei) + return len(lookup) == len(rooms) From 5d02e592c7d6685159b4508a0440179e36eef13d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 01:51:17 +0800 Subject: [PATCH 4754/4971] Create split-array-into-fibonacci-sequence.cpp --- C++/split-array-into-fibonacci-sequence.cpp | 52 +++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 C++/split-array-into-fibonacci-sequence.cpp diff --git a/C++/split-array-into-fibonacci-sequence.cpp b/C++/split-array-into-fibonacci-sequence.cpp new file mode 100644 index 000000000..5f4b41ee4 --- /dev/null +++ b/C++/split-array-into-fibonacci-sequence.cpp @@ -0,0 +1,52 @@ +// Time: O(n^3) +// Space: O(n) + +class Solution { +public: + vector splitIntoFibonacci(string S) { + for (int i = 0, a = 0; i + 2 < S.length(); ++i) { + a = 10 * a + S[i] - '0'; + for (int j = i + 1, b = 0; j + 1 < S.length(); ++j) { + b = 10 * b + S[j] - '0'; + vector fib = {a, b}; + int k = j + 1; + while (k < S.length()) { + if (fib[fib.size() - 2] > numeric_limits::max() - fib[fib.size() - 1]) { + break; + } + auto c = fib[fib.size() - 2] + fib[fib.size() - 1]; + auto l = startswith(S, k, c); + if (l == 0) { + break; + } + fib.emplace_back(c); + k += l; + } + if (k == S.length()) { + return fib; + } + if (b == 0) { + break; + } + } + if (a == 0) { + break; + } + } + return {}; + } + +private: + int startswith(const string& S, int k, int x) { + int y = 0; + for (int i = k; i < S.length(); ++i) { + y = 10 * y + S[i] - '0'; + if (y == x) { + return i - k + 1; + } else if (y > x) { + break; + } + } + return 0; + } +}; From 1780ea557d8b01804bf716887d820b340eff3931 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 28 May 2018 01:55:41 +0800 Subject: [PATCH 4755/4971] Create split-array-into-fibonacci-sequence.py --- Python/split-array-into-fibonacci-sequence.py | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Python/split-array-into-fibonacci-sequence.py diff --git a/Python/split-array-into-fibonacci-sequence.py b/Python/split-array-into-fibonacci-sequence.py new file mode 100644 index 000000000..c88b53308 --- /dev/null +++ b/Python/split-array-into-fibonacci-sequence.py @@ -0,0 +1,95 @@ +# Time: O(n^3) +# Space: O(n) + +# Given a string S of digits, such as S = "123456579", +# we can split it into a Fibonacci-like sequence [123, 456, 579]. +# +# Formally, a Fibonacci-like sequence is a list F of non-negative +# integers such that: +# +# 0 <= F[i] <= 2^31 - 1, +# (that is, each integer fits a 32-bit signed integer type); +# F.length >= 3; +# and F[i] + F[i+1] = F[i+2] for all 0 <= i < F.length - 2. +# Also, note that when splitting the string into pieces, +# each piece must not have extra leading zeroes, +# except if the piece is the number 0 itself. +# +# Return any Fibonacci-like sequence split from S, +# or return [] if it cannot be done. +# +# Example 1: +# +# Input: "123456579" +# Output: [123,456,579] +# Example 2: +# +# Input: "11235813" +# Output: [1,1,2,3,5,8,13] +# Example 3: +# +# Input: "112358130" +# Output: [] +# Explanation: The task is impossible. +# Example 4: +# +# Input: "0123" +# Output: [] +# Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid. +# Example 5: +# +# Input: "1101111" +# Output: [110, 1, 111] +# Explanation: The output [11, 0, 11, 11] would also be accepted. +# +# Note: +# - 1 <= S.length <= 200 +# - S contains only digits. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def splitIntoFibonacci(self, S): + """ + :type S: str + :rtype: List[int] + """ + def startswith(S, k, x): + y = 0 + for i in xrange(k, len(S)): + y = 10*y + int(S[i]) + if y == x: + return i-k+1 + elif y > x: + break + return 0 + + MAX_INT = 2**31-1 + a = 0 + for i in xrange(len(S)-2): + a = 10*a + int(S[i]) + b = 0 + for j in xrange(i+1, len(S)-1): + b = 10*b + int(S[j]) + fib = [a, b] + k = j+1 + while k < len(S): + if fib[-2] > MAX_INT-fib[-1]: + break + c = fib[-2]+fib[-1] + length = startswith(S, k, c) + if length == 0: + break + fib.append(c) + k += length + else: + return fib + if b == 0: + break + if a == 0: + break + return [] From 18f63b98bf7eefe3022dc4681e81ada9969d5228 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 28 May 2018 02:42:19 +0800 Subject: [PATCH 4756/4971] Create guess-the-word.py --- Python/guess-the-word.py | 88 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Python/guess-the-word.py diff --git a/Python/guess-the-word.py b/Python/guess-the-word.py new file mode 100644 index 000000000..b194f912a --- /dev/null +++ b/Python/guess-the-word.py @@ -0,0 +1,88 @@ +# Time: O(n^2) +# Space: O(n) + +# This problem is an interactive problem new to the LeetCode platform. +# +# We are given a word list of unique words, each word is 6 letters long, +# and one word in this list is chosen as secret. +# +# You may call master.guess(word) to guess a word. +# The guessed word should have type string and must be from the original +# list with 6 lowercase letters. +# +# This function returns an integer type, +# representing the number of exact matches (value and position) +# of your guess to the secret word. +# Also, if your guess is not in the given wordlist, it will return -1 instead. +# +# For each test case, you have 10 guesses to guess the word. +# At the end of any number of calls, if you have made 10 or +# less calls to master.guess +# and at least one of these guesses was the secret, you pass the testcase. +# +# Besides the example test case below, +# there will be 5 additional test cases, each with 100 words in the word list. +# The letters of each word in those testcases were chosen independently at +# random from 'a' to 'z', +# such that every word in the given word lists is unique. +# +# Example 1: +# Input: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"] +# +# Explanation: +# +# master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist. +# master.guess("acckzz") returns 6, because "acckzz" is secret +# and has all 6 matches. +# master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches. +# master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches. +# master.guess("abcczz") returns 4, because "abcczz" has 4 matches. +# +# We made 5 calls to master.guess and one of them was the secret, +# so we pass the test case. +# Note: Any solutions that attempt to circumvent the judge will result +# in disqualification. +# +# """ +# This is Master's API interface. +# You should not implement it, or speculate about its implementation +# """ +# class Master(object): +# def guess(self, word): +# """ +# :type word: str +# :rtype int +# """ + +import collections +import itertools + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def findSecretWord(self, wordlist, master): + """ + :type wordlist: List[Str] + :type master: Master + :rtype: None + """ + def match(a, b): + matches = 0 + for i in xrange(len(a)): + if a[i] == b[i]: + matches += 1 + return matches + + i, n = 0, 0 + while i < 10 and n < 6: + count = collections.Counter(w1 for w1, w2 in + itertools.permutations(wordlist, 2) + if match(w1, w2) == 0) + guess = min(wordlist, key=lambda w: count[w]) + n = master.guess(guess) + wordlist = [w for w in wordlist if match(w, guess) == n] + i += 1 From 78bd771d027906d7a5fee4b5cb7d3b78c757081e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 02:42:56 +0800 Subject: [PATCH 4757/4971] Create guess-the-word.cpp --- C++/guess-the-word.cpp | 52 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 C++/guess-the-word.cpp diff --git a/C++/guess-the-word.cpp b/C++/guess-the-word.cpp new file mode 100644 index 000000000..2d5359a29 --- /dev/null +++ b/C++/guess-the-word.cpp @@ -0,0 +1,52 @@ +// Time: O(n^2) +// Space: O(n) + +/** + * // This is the Master's API interface. + * // You should not implement it, or speculate about its implementation + * class Master { + * public: + * int guess(string word); + * }; + */ +class Solution { +public: + void findSecretWord(vector& wordlist, Master& master) { + for (int i = 0, n = 0; i < 10 && n < 6; ++i) { + unordered_map count; + for (const auto& w1 : wordlist) { + for (const auto& w2 : wordlist) { + if (match(w1, w2) == 0) { + ++count[w1]; + } + } + } + string guess; + for (const auto& w : wordlist) { + if (guess.empty() || + count[w] < count[guess]) { + guess = w; + } + } + n = master.guess(guess); + vector new_wordlist; + for (const auto& w : wordlist) { + if (match(w, guess) == n) { + new_wordlist.emplace_back(w); + } + } + wordlist = new_wordlist; + } + } + +private: + int match(const string& a, const string& b) { + int matches = 0; + for (int i = 0; i < a.length(); ++i) { + if (a[i] == b[i]) { + ++matches; + } + } + return matches; + } +}; From 96ce8a7d9b4997d42dcfdc992143c1b7d4c3cc14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 02:51:34 +0800 Subject: [PATCH 4758/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 519889c85..409152025 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 830 | [Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/) | [C++](./C++/positions-of-large-groups.cpp) [Python](./Python/positions-of-large-groups.py) | _O(n)_ | _O(1)_ | Easy || 832 | [Flipping an Image](https://leetcode.com/problems/flipping-an-image/) | [C++](./C++/flipping-an-image.cpp) [Python](./Python/flipping-an-image.py) | _O(n^2)_ | _O(1)_ | Easy || 835 | [Image Overlap](https://leetcode.com/problems/image-overlap/) | [C++](./C++/image-overlap.cpp) [Python](./Python/image-overlap.py) | _O(n^4)_ | _O(n^2)_ | Medium || +840 | [Magic Squares In Grid](https://leetcode.com/problems/magic-squares-in-grid/) | [C++](./C++/magic-squares-in-grid.cpp) [Python](./Python/magic-squares-in-grid.py) | _O(m * n)_ | _O(1)_ | Easy || +842 | [Split Array into Fibonacci Sequence](https://leetcode.com/problems/split-array-into-fibonacci-sequence/) | [C++](./C++/split-array-into-fibonacci-sequence.cpp) [Python](./Python/split-array-into-fibonacci-sequence.py) | _O(n^3)_ | _O(n)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -664,6 +666,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 802| [Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) | [C++](./C++/find-eventual-safe-states.cpp) [Python](./Python/find-eventual-safe-states.py) | _O(\|V\| + \|E\|)_ | _O(\|V\|)_ | Medium ||| 827| [Making A Large Island](https://leetcode.com/problems/making-a-large-island/) | [C++](./C++/making-a-large-island.cpp) [Python](./Python/making-a-large-island.py) | _O(n^2)_ | _O(n^2)_ | Hard ||| 834| [Sum of Distances in Tree](https://leetcode.com/problems/sum-of-distances-in-tree/) | [C++](./C++/sum-of-distances-in-tree.cpp) [Python](./Python/sum-of-distances-in-tree.py) | _O(n)_ | _O(n)_ | Hard ||| +841| [Keys and Rooms](https://leetcode.com/problems/keys-and-rooms/) | [C++](./C++/keys-and-rooms.cpp) [Python](./Python/keys-and-rooms.py) | _O(n!)_ | _O(n)_ | Medium ||| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -821,6 +824,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 763 | [Partition Labels](https://leetcode.com/problems/partition-labels/) | [C++](./C++/partition-labels.cpp) [Python](./Python/partition-labels.py) | _O(n)_ | _O(n)_ | Medium | | 767 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | [C++](./C++/reorganize-string.cpp) [Python](./Python/reorganize-string.py) | _O(n)_ | _O(1)_ | Medium | | 798 | [Smallest Rotation with Highest Score](https://leetcode.com/problems/smallest-rotation-with-highest-score/) | [C++](./C++/smallest-rotation-with-highest-score.cpp) [Python](./Python/smallest-rotation-with-highest-score.py) | _O(n)_ | _O(1)_ | Hard | | +843 | [Guess the Word](https://leetcode.com/problems/guess-the-word/) | [C++](./C++/guess-the-word.cpp) [Python](./Python/guess-the-word.py) | _O(n^2)_ | _O(n)_ | Hard | | ## Graph | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From d548c32bb5e802f06f7360c84e4f022758ae29f4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 02:54:02 +0800 Subject: [PATCH 4759/4971] Update magic-squares-in-grid.py --- Python/magic-squares-in-grid.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/magic-squares-in-grid.py b/Python/magic-squares-in-grid.py index bc59f8f41..6671bb251 100644 --- a/Python/magic-squares-in-grid.py +++ b/Python/magic-squares-in-grid.py @@ -65,8 +65,8 @@ def magic(grid, r, c): k = 3 result = 0 - for r in xrange(len(grid)-2): - for c in xrange(len(grid[r])-2): + for r in xrange(len(grid)-k+1): + for c in xrange(len(grid[r])-k+1): if magic(grid, r, c): result += 1 return result From d2aca979f2c8a711bbc139675cf699b6ce5ce53d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 03:00:32 +0800 Subject: [PATCH 4760/4971] Update keys-and-rooms.py --- Python/keys-and-rooms.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/keys-and-rooms.py b/Python/keys-and-rooms.py index c4d2572bb..3e562a163 100644 --- a/Python/keys-and-rooms.py +++ b/Python/keys-and-rooms.py @@ -1,3 +1,6 @@ +# Time: O(n!) +# Space: O(n) + # There are N rooms and you start in room 0. # Each room has a distinct number in 0, 1, 2, ..., N-1, # and each room may have some keys to access the next room. From e7c8d64ef4dd49e5178011f857b202c4a1cd3621 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 13:26:32 +0800 Subject: [PATCH 4761/4971] Update guess-the-word.py --- Python/guess-the-word.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Python/guess-the-word.py b/Python/guess-the-word.py index b194f912a..7ca6d5013 100644 --- a/Python/guess-the-word.py +++ b/Python/guess-the-word.py @@ -64,6 +64,40 @@ class Solution(object): + def findSecretWord(self, wordlist, master): + """ + :type wordlist: List[Str] + :type master: Master + :rtype: None + """ + def solve(possible, lookup): + min_max_size, best_guess = possible, None + for guess in xrange(len(H)): + if guess not in lookup: + groups = [[] for _ in xrange(7)] + for j in possible: + if j != guess: + groups[H[guess][j]].append(j) + max_size = max(groups, key=len) + if len(max_size) < len(min_max_size): + min_max_size, best_guess = max_size, guess + return best_guess + + H = [[sum(a == b for a, b in itertools.izip(wordlist[i], wordlist[j])) + for j in xrange(len(wordlist))] + for i in xrange(len(wordlist))] + possible, lookup = range(len(wordlist)), set() + n = 0 + while possible and n < 6: + guess = solve(possible, lookup) + n = master.guess(wordlist[guess]) + possible = [j for j in possible if H[guess][j] == n] + lookup.add(guess) + + +# Time: O(n^2) +# Space: O(n) +class Solution2(object): def findSecretWord(self, wordlist, master): """ :type wordlist: List[Str] From 25cd86c74ca4f4736d2b76ce67cdb50cccfcb2ae Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 13:38:51 +0800 Subject: [PATCH 4762/4971] Update guess-the-word.py --- Python/guess-the-word.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/guess-the-word.py b/Python/guess-the-word.py index 7ca6d5013..1b1b0fb7e 100644 --- a/Python/guess-the-word.py +++ b/Python/guess-the-word.py @@ -71,16 +71,16 @@ def findSecretWord(self, wordlist, master): :rtype: None """ def solve(possible, lookup): - min_max_size, best_guess = possible, None + min_max_group, best_guess = possible, None for guess in xrange(len(H)): if guess not in lookup: groups = [[] for _ in xrange(7)] for j in possible: if j != guess: groups[H[guess][j]].append(j) - max_size = max(groups, key=len) - if len(max_size) < len(min_max_size): - min_max_size, best_guess = max_size, guess + max_group = max(groups, key=len) + if len(max_group) < len(min_max_group): + min_max_group, best_guess = max_group, guess return best_guess H = [[sum(a == b for a, b in itertools.izip(wordlist[i], wordlist[j])) From 16b1e4598f9584973bdbef5861a407296dbabc2c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 13:45:40 +0800 Subject: [PATCH 4763/4971] Update guess-the-word.py --- Python/guess-the-word.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/guess-the-word.py b/Python/guess-the-word.py index 1b1b0fb7e..0d3bdecdd 100644 --- a/Python/guess-the-word.py +++ b/Python/guess-the-word.py @@ -70,7 +70,7 @@ def findSecretWord(self, wordlist, master): :type master: Master :rtype: None """ - def solve(possible, lookup): + def solve(H, possible, lookup): min_max_group, best_guess = possible, None for guess in xrange(len(H)): if guess not in lookup: @@ -89,7 +89,7 @@ def solve(possible, lookup): possible, lookup = range(len(wordlist)), set() n = 0 while possible and n < 6: - guess = solve(possible, lookup) + guess = solve(H, possible, lookup) n = master.guess(wordlist[guess]) possible = [j for j in possible if H[guess][j] == n] lookup.add(guess) From e05c99534ae7b124a2c51c337e2eee14feaf0c5d Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 13:59:52 +0800 Subject: [PATCH 4764/4971] Update guess-the-word.cpp --- C++/guess-the-word.cpp | 71 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/C++/guess-the-word.cpp b/C++/guess-the-word.cpp index 2d5359a29..47ca66838 100644 --- a/C++/guess-the-word.cpp +++ b/C++/guess-the-word.cpp @@ -10,6 +10,77 @@ * }; */ class Solution { +public: + void findSecretWord(vector& wordlist, Master& master) { + vector> H(wordlist.size(), vector(wordlist.size())); + for (int i = 0; i < wordlist.size(); ++i) { + for (int j = 0; j < wordlist.size(); ++j) { + H[i][j] = match(wordlist[i], wordlist[j]); + } + } + + unordered_set lookup; + vector possible(wordlist.size()); + iota(possible.begin(), possible.end(), 0); + int n = 0; + while (!possible.empty() && n < 6) { + auto guess = solve(H, possible, lookup); + n = master.guess(wordlist[guess]); + vector new_possible; + for (const auto& j : possible) { + if (H[guess][j] == n) { + new_possible.emplace_back(j); + } + } + lookup.emplace(guess); + possible = new_possible; + } + } + +private: + int solve(const vector>& H, + const vector& possible, + const unordered_set& lookup) { + + vector min_max_group = possible; + int best_guess = -1; + for (int guess = 0; guess < H.size(); ++guess) { + if (!lookup.count(guess)) { + vector> groups(7); + for (const auto& j : possible) { + if (j != guess) { + groups[H[guess][j]].emplace_back(j); + } + } + int max_group_i = 0; + for (int i = 0; i < groups.size(); ++i) { + if (groups[i].size() > groups[max_group_i].size()) { + max_group_i = i; + } + } + if (groups[max_group_i].size() < min_max_group.size()) { + min_max_group = groups[max_group_i]; + best_guess = guess; + } + } + } + return best_guess; + } + + int match(const string& a, const string& b) { + int matches = 0; + for (int i = 0; i < a.length(); ++i) { + if (a[i] == b[i]) { + ++matches; + } + } + return matches; + } +}; + +// Time: O(n^2) +// Space: O(n) +class Solution2 { public: void findSecretWord(vector& wordlist, Master& master) { for (int i = 0, n = 0; i < 10 && n < 6; ++i) { From 3702c94685045b367b87fbb0548550e8bea765cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 14:03:07 +0800 Subject: [PATCH 4765/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 409152025..bde31a1ed 100644 --- a/README.md +++ b/README.md @@ -824,7 +824,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 763 | [Partition Labels](https://leetcode.com/problems/partition-labels/) | [C++](./C++/partition-labels.cpp) [Python](./Python/partition-labels.py) | _O(n)_ | _O(n)_ | Medium | | 767 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | [C++](./C++/reorganize-string.cpp) [Python](./Python/reorganize-string.py) | _O(n)_ | _O(1)_ | Medium | | 798 | [Smallest Rotation with Highest Score](https://leetcode.com/problems/smallest-rotation-with-highest-score/) | [C++](./C++/smallest-rotation-with-highest-score.cpp) [Python](./Python/smallest-rotation-with-highest-score.py) | _O(n)_ | _O(1)_ | Hard | | -843 | [Guess the Word](https://leetcode.com/problems/guess-the-word/) | [C++](./C++/guess-the-word.cpp) [Python](./Python/guess-the-word.py) | _O(n^2)_ | _O(n)_ | Hard | | +843 | [Guess the Word](https://leetcode.com/problems/guess-the-word/) | [C++](./C++/guess-the-word.cpp) [Python](./Python/guess-the-word.py) | _O(n^2)_ | _O(n)_ | Hard | MinMax | ## Graph | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From d1bab2874ed56a1691e0faf095a22bec52365c89 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 14:03:42 +0800 Subject: [PATCH 4766/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bde31a1ed..ae104b2f9 100644 --- a/README.md +++ b/README.md @@ -824,7 +824,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 763 | [Partition Labels](https://leetcode.com/problems/partition-labels/) | [C++](./C++/partition-labels.cpp) [Python](./Python/partition-labels.py) | _O(n)_ | _O(n)_ | Medium | | 767 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | [C++](./C++/reorganize-string.cpp) [Python](./Python/reorganize-string.py) | _O(n)_ | _O(1)_ | Medium | | 798 | [Smallest Rotation with Highest Score](https://leetcode.com/problems/smallest-rotation-with-highest-score/) | [C++](./C++/smallest-rotation-with-highest-score.cpp) [Python](./Python/smallest-rotation-with-highest-score.py) | _O(n)_ | _O(1)_ | Hard | | -843 | [Guess the Word](https://leetcode.com/problems/guess-the-word/) | [C++](./C++/guess-the-word.cpp) [Python](./Python/guess-the-word.py) | _O(n^2)_ | _O(n)_ | Hard | MinMax | +843 | [Guess the Word](https://leetcode.com/problems/guess-the-word/) | [C++](./C++/guess-the-word.cpp) [Python](./Python/guess-the-word.py) | _O(n^2)_ | _O(n)_ | Hard || MinMax | ## Graph | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 4c0d47663c61d8f1fd6f812257d1680cf82c7423 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 19:39:54 +0800 Subject: [PATCH 4767/4971] Update guess-the-word.py --- Python/guess-the-word.py | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/Python/guess-the-word.py b/Python/guess-the-word.py index 0d3bdecdd..9c2abb98d 100644 --- a/Python/guess-the-word.py +++ b/Python/guess-the-word.py @@ -70,29 +70,27 @@ def findSecretWord(self, wordlist, master): :type master: Master :rtype: None """ - def solve(H, possible, lookup): + def solve(H, possible): min_max_group, best_guess = possible, None - for guess in xrange(len(H)): - if guess not in lookup: - groups = [[] for _ in xrange(7)] - for j in possible: - if j != guess: - groups[H[guess][j]].append(j) - max_group = max(groups, key=len) - if len(max_group) < len(min_max_group): - min_max_group, best_guess = max_group, guess + for guess in possible: + groups = [[] for _ in xrange(7)] + for j in possible: + if j != guess: + groups[H[guess][j]].append(j) + max_group = max(groups, key=len) + if len(max_group) < len(min_max_group): + min_max_group, best_guess = max_group, guess return best_guess H = [[sum(a == b for a, b in itertools.izip(wordlist[i], wordlist[j])) for j in xrange(len(wordlist))] for i in xrange(len(wordlist))] - possible, lookup = range(len(wordlist)), set() + possible = range(len(wordlist)) n = 0 while possible and n < 6: - guess = solve(H, possible, lookup) + guess = solve(H, possible) n = master.guess(wordlist[guess]) possible = [j for j in possible if H[guess][j] == n] - lookup.add(guess) # Time: O(n^2) From 54518cc23e4218d9ddcbe362951d6929f39ac9e1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 19:42:12 +0800 Subject: [PATCH 4768/4971] Update guess-the-word.cpp --- C++/guess-the-word.cpp | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/C++/guess-the-word.cpp b/C++/guess-the-word.cpp index 47ca66838..30ebadcb7 100644 --- a/C++/guess-the-word.cpp +++ b/C++/guess-the-word.cpp @@ -24,7 +24,7 @@ class Solution { iota(possible.begin(), possible.end(), 0); int n = 0; while (!possible.empty() && n < 6) { - auto guess = solve(H, possible, lookup); + auto guess = solve(H, possible); n = master.guess(wordlist[guess]); vector new_possible; for (const auto& j : possible) { @@ -32,37 +32,33 @@ class Solution { new_possible.emplace_back(j); } } - lookup.emplace(guess); possible = new_possible; } } private: int solve(const vector>& H, - const vector& possible, - const unordered_set& lookup) { + const vector& possible) { vector min_max_group = possible; int best_guess = -1; - for (int guess = 0; guess < H.size(); ++guess) { - if (!lookup.count(guess)) { - vector> groups(7); - for (const auto& j : possible) { - if (j != guess) { - groups[H[guess][j]].emplace_back(j); - } - } - int max_group_i = 0; - for (int i = 0; i < groups.size(); ++i) { - if (groups[i].size() > groups[max_group_i].size()) { - max_group_i = i; - } + for (const auto& guess : possible) { + vector> groups(7); + for (const auto& j : possible) { + if (j != guess) { + groups[H[guess][j]].emplace_back(j); } - if (groups[max_group_i].size() < min_max_group.size()) { - min_max_group = groups[max_group_i]; - best_guess = guess; + } + int max_group_i = 0; + for (int i = 0; i < groups.size(); ++i) { + if (groups[i].size() > groups[max_group_i].size()) { + max_group_i = i; } } + if (groups[max_group_i].size() < min_max_group.size()) { + min_max_group = groups[max_group_i]; + best_guess = guess; + } } return best_guess; } From b800070eb1b3a6864c235a31f740e1c258904ad6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 19:43:21 +0800 Subject: [PATCH 4769/4971] Update guess-the-word.cpp --- C++/guess-the-word.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/guess-the-word.cpp b/C++/guess-the-word.cpp index 30ebadcb7..62d528de4 100644 --- a/C++/guess-the-word.cpp +++ b/C++/guess-the-word.cpp @@ -19,7 +19,6 @@ class Solution { } } - unordered_set lookup; vector possible(wordlist.size()); iota(possible.begin(), possible.end(), 0); int n = 0; From 46492a74d3d04ff5c320647f95ca5a99d4a6090e Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 19:50:51 +0800 Subject: [PATCH 4770/4971] Update guess-the-word.cpp --- C++/guess-the-word.cpp | 59 +++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 21 deletions(-) diff --git a/C++/guess-the-word.cpp b/C++/guess-the-word.cpp index 62d528de4..76ab6b522 100644 --- a/C++/guess-the-word.cpp +++ b/C++/guess-the-word.cpp @@ -22,7 +22,7 @@ class Solution { vector possible(wordlist.size()); iota(possible.begin(), possible.end(), 0); int n = 0; - while (!possible.empty() && n < 6) { + while (n < 6) { auto guess = solve(H, possible); n = master.guess(wordlist[guess]); vector new_possible; @@ -78,34 +78,51 @@ class Solution { class Solution2 { public: void findSecretWord(vector& wordlist, Master& master) { - for (int i = 0, n = 0; i < 10 && n < 6; ++i) { - unordered_map count; - for (const auto& w1 : wordlist) { - for (const auto& w2 : wordlist) { - if (match(w1, w2) == 0) { - ++count[w1]; - } - } + vector> H(wordlist.size(), vector(wordlist.size())); + for (int i = 0; i < wordlist.size(); ++i) { + for (int j = 0; j < wordlist.size(); ++j) { + H[i][j] = match(wordlist[i], wordlist[j]); } - string guess; - for (const auto& w : wordlist) { - if (guess.empty() || - count[w] < count[guess]) { - guess = w; + } + + vector possible(wordlist.size()); + iota(possible.begin(), possible.end(), 0); + int n = 0; + while (n < 6) { + auto guess = solve(H, possible); + n = master.guess(wordlist[guess]); + vector new_possible; + for (const auto& j : possible) { + if (H[guess][j] == n) { + new_possible.emplace_back(j); } } - n = master.guess(guess); - vector new_wordlist; - for (const auto& w : wordlist) { - if (match(w, guess) == n) { - new_wordlist.emplace_back(w); + possible = new_possible; + } + } + +private: + int solve(const vector>& H, + const vector& possible) { + + vector min_max_group = possible; + int best_guess = -1; + for (const auto& guess : possible) { + vector> groups(7); + for (const auto& j : possible) { + if (j != guess) { + groups[H[guess][j]].emplace_back(j); } } - wordlist = new_wordlist; + int max_group_i = 0; + if (groups[max_group_i].size() < min_max_group.size()) { + min_max_group = groups[max_group_i]; + best_guess = guess; + } } + return best_guess; } -private: int match(const string& a, const string& b) { int matches = 0; for (int i = 0; i < a.length(); ++i) { From db339ce986639b03cfef4c8cac12789f8d727c52 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 28 May 2018 19:52:21 +0800 Subject: [PATCH 4771/4971] Update guess-the-word.py --- Python/guess-the-word.py | 35 ++++++++++++++++++++--------------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/Python/guess-the-word.py b/Python/guess-the-word.py index 9c2abb98d..88cd9e325 100644 --- a/Python/guess-the-word.py +++ b/Python/guess-the-word.py @@ -102,19 +102,24 @@ def findSecretWord(self, wordlist, master): :type master: Master :rtype: None """ - def match(a, b): - matches = 0 - for i in xrange(len(a)): - if a[i] == b[i]: - matches += 1 - return matches + def solve(H, possible): + min_max_group, best_guess = possible, None + for guess in possible: + groups = [[] for _ in xrange(7)] + for j in possible: + if j != guess: + groups[H[guess][j]].append(j) + max_group = groups[0] + if len(max_group) < len(min_max_group): + min_max_group, best_guess = max_group, guess + return best_guess - i, n = 0, 0 - while i < 10 and n < 6: - count = collections.Counter(w1 for w1, w2 in - itertools.permutations(wordlist, 2) - if match(w1, w2) == 0) - guess = min(wordlist, key=lambda w: count[w]) - n = master.guess(guess) - wordlist = [w for w in wordlist if match(w, guess) == n] - i += 1 + H = [[sum(a == b for a, b in itertools.izip(wordlist[i], wordlist[j])) + for j in xrange(len(wordlist))] + for i in xrange(len(wordlist))] + possible = range(len(wordlist)) + n = 0 + while possible and n < 6: + guess = solve(H, possible) + n = master.guess(wordlist[guess]) + possible = [j for j in possible if H[guess][j] == n] From c31c9f56d83497c630ac28eca72d8d448223c6c1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 30 May 2018 09:42:45 +0800 Subject: [PATCH 4772/4971] Update remove-duplicates-from-sorted-array.py --- Python/remove-duplicates-from-sorted-array.py | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/Python/remove-duplicates-from-sorted-array.py b/Python/remove-duplicates-from-sorted-array.py index b2a94cc23..c5d8cff4f 100644 --- a/Python/remove-duplicates-from-sorted-array.py +++ b/Python/remove-duplicates-from-sorted-array.py @@ -11,21 +11,17 @@ # Your function should return length = 2, and A is now [1,2]. # -class Solution: + +class Solution(object): # @param a list of integers # @return an integer def removeDuplicates(self, A): if not A: return 0 - last, i = 0, 1 - while i < len(A): + last = 0 + for i in xrange(len(A)): if A[last] != A[i]: last += 1 A[last] = A[i] - i += 1 - return last + 1 - -if __name__ == "__main__": - print Solution().removeDuplicates([1, 1, 2]) From 08f1171109320300dea0ee90a18f123fb727b05a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jun 2018 12:45:32 +0800 Subject: [PATCH 4773/4971] Create hand-of-straights.cpp --- C++/hand-of-straights.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 C++/hand-of-straights.cpp diff --git a/C++/hand-of-straights.cpp b/C++/hand-of-straights.cpp new file mode 100644 index 000000000..dfba85d6b --- /dev/null +++ b/C++/hand-of-straights.cpp @@ -0,0 +1,32 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + bool isNStraightHand(vector& hand, int W) { + if (hand.size() % W) { + return false; + } + + unordered_map counts; + for (const auto& i : hand) { + ++counts[i]; + } + + priority_queue, greater> min_heap(hand.begin(), hand.end()); + for (int i = 0; i < hand.size() / W; ++i) { + while (counts[min_heap.top()] == 0) { + min_heap.pop(); + } + int start = min_heap.top(); min_heap.pop(); + for (int j = 0; j < W; ++j) { + --counts[start]; + if (counts[start] < 0) { + return false; + } + ++start; + } + } + return true; + } +}; From 08ef2a048b8f6bdd105c3ddd7f2fba9009f08f31 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 3 Jun 2018 12:49:30 +0800 Subject: [PATCH 4774/4971] Create hand-of-straights.py --- Python/hand-of-straights.py | 62 +++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Python/hand-of-straights.py diff --git a/Python/hand-of-straights.py b/Python/hand-of-straights.py new file mode 100644 index 000000000..18edd0229 --- /dev/null +++ b/Python/hand-of-straights.py @@ -0,0 +1,62 @@ +# Time: O(nlogn) +# Space: O(n) + +# Alice has a hand of cards, given as an array of integers. +# +# Now she wants to rearrange the cards into groups +# so that each group is size W, +# and consists of W consecutive cards. +# +# Return true if and only if she can. +# +# Example 1: +# +# Input: hand = [1,2,3,6,2,3,4,7,8], W = 3 +# Output: true +# Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]. +# Example 2: +# +# Input: hand = [1,2,3,4,5], W = 4 +# Output: false +# Explanation: Alice's hand can't be rearranged into groups of 4. +# +# Note: +# - 1 <= hand.length <= 10000 +# - 0 <= hand[i] <= 10^9 +# - 1 <= W <= hand.length + +import collections +import heapq + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def isNStraightHand(self, hand, W): + """ + :type hand: List[int] + :type W: int + :rtype: bool + """ + if len(hand) % W: + return False + + counts = collections.defaultdict(int) + for i in hand: + counts[i] += 1 + + min_heap = hand[:] + heapq.heapify(min_heap) + for _ in xrange(len(min_heap)//W): + while counts[min_heap[0]] == 0: + heapq.heappop(min_heap) + start = heapq.heappop(min_heap) + for _ in xrange(W): + counts[start] -= 1 + if counts[start] < 0: + return False + start += 1 + return True From 3295aacf5bb77d8f86677ae2a943322951d98bf7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jun 2018 13:08:32 +0800 Subject: [PATCH 4775/4971] Create longest-mountain-in-array.cpp --- C++/longest-mountain-in-array.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 C++/longest-mountain-in-array.cpp diff --git a/C++/longest-mountain-in-array.cpp b/C++/longest-mountain-in-array.cpp new file mode 100644 index 000000000..efb714ce9 --- /dev/null +++ b/C++/longest-mountain-in-array.cpp @@ -0,0 +1,21 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int longestMountain(vector& A) { + int result = 0, up_len = 0, down_len = 0; + for (int i = 1; i < A.size(); ++i) { + if ((down_len && A[i - 1] < A[i]) || + A[i - 1] == A[i]) { + up_len = down_len = 0; + } + up_len += A[i - 1] < A[i]; + down_len += A[i - 1] > A[i]; + if (up_len && down_len) { + result= max(result, up_len + down_len + 1); + } + } + return result; + } +}; From e97723e09858d8b729abc940fcedcac22f11139e Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 3 Jun 2018 13:11:35 +0800 Subject: [PATCH 4776/4971] Create longest-mountain-in-array.py --- Python/longest-mountain-in-array.py | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/longest-mountain-in-array.py diff --git a/Python/longest-mountain-in-array.py b/Python/longest-mountain-in-array.py new file mode 100644 index 000000000..2fe19618d --- /dev/null +++ b/Python/longest-mountain-in-array.py @@ -0,0 +1,51 @@ +# Time: O(n) +# Space: O(1) + +# Let's call any (contiguous) subarray B (of A) a mountain +# if the following properties hold: +# +# B.length >= 3 +# There exists some 0 < i < B.length - 1 +# such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] +# (Note that B could be any subarray of A, including the entire array A.) +# +# Given an array A of integers, return the length of the longest mountain. +# +# Return 0 if there is no mountain. +# +# Example 1: +# +# Input: [2,1,4,7,3,2,5] +# Output: 5 +# Explanation: The largest mountain is [1,4,7,3,2] which has length 5. +# Example 2: +# +# Input: [2,2,2] +# Output: 0 +# Explanation: There is no mountain. +# +# Note: +# - 0 <= A.length <= 10000 +# - 0 <= A[i] <= 10000 + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def longestMountain(self, A): + """ + :type A: List[int] + :rtype: int + """ + result, up_len, down_len = 0, 0, 0 + for i in xrange(1, len(A)): + if (down_len and A[i-1] < A[i]) or A[i-1] == A[i]: + up_len, down_len = 0, 0 + up_len += A[i-1] < A[i] + down_len += A[i-1] > A[i] + if up_len and down_len: + result = max(result, up_len+down_len+1) + return result From 9c2a531d103d7733b25762c6813b7aeefd6de415 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jun 2018 13:41:30 +0800 Subject: [PATCH 4777/4971] Create shortest-path-visiting-all-nodes.cpp --- C++/shortest-path-visiting-all-nodes.cpp | 29 ++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 C++/shortest-path-visiting-all-nodes.cpp diff --git a/C++/shortest-path-visiting-all-nodes.cpp b/C++/shortest-path-visiting-all-nodes.cpp new file mode 100644 index 000000000..a99d8f8b9 --- /dev/null +++ b/C++/shortest-path-visiting-all-nodes.cpp @@ -0,0 +1,29 @@ +// Time: O(n * 2^n) +// Space: O(n * 2^n) + +class Solution { +public: + int shortestPathLength(vector>& graph) { + static const auto& INF = numeric_limits::max(); + vector> dp(1 << graph.size(), + vector(graph.size(), INF)); + queue> q; + for (int i = 0; i < graph.size(); ++i) { + dp[1 << i][i] = 0; + q.emplace(1 << i, i); + } + while (!q.empty()) { + int state, node; + tie(state, node) = q.front(); q.pop(); + auto steps = dp[state][node]; + for (const auto& nei : graph[node]) { + auto new_state = state | (1 << nei); + if (dp[new_state][nei] == INF) { + dp[new_state][nei] = steps + 1; + q.emplace(new_state, nei); + } + } + } + return *min_element(dp.back().cbegin(), dp.back().cend()); + } +}; From c86defa4462780b46d5d631b71898a994fa29c53 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 3 Jun 2018 13:45:23 +0800 Subject: [PATCH 4778/4971] Create shortest-path-visiting-all-nodes.py --- Python/shortest-path-visiting-all-nodes.py | 57 ++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Python/shortest-path-visiting-all-nodes.py diff --git a/Python/shortest-path-visiting-all-nodes.py b/Python/shortest-path-visiting-all-nodes.py new file mode 100644 index 000000000..1d3484f8d --- /dev/null +++ b/Python/shortest-path-visiting-all-nodes.py @@ -0,0 +1,57 @@ +# Time: O(n * 2^n) +# Space: O(n * 2^n) + +# An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) +# is given as graph. +# +# graph.length = N, and j != i is in the list graph[i] exactly once, +# if and only if nodes i and j are connected. +# +# Return the length of the shortest path that visits every node. +# You may start and stop at any node, you may revisit nodes multiple times, +# and you may reuse edges. +# +# Example 1: +# +# Input: [[1,2,3],[0],[0],[0]] +# Output: 4 +# Explanation: One possible path is [1,0,2,0,3] +# Example 2: +# +# Input: [[1],[0,2,4],[1,3,4],[2],[1,2]] +# Output: 4 +# Explanation: One possible path is [0,1,4,2,3] +# +# Note: +# - 1 <= graph.length <= 12 +# - 0 <= graph[i].length < graph.length + +import collections + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def shortestPathLength(self, graph): + """ + :type graph: List[List[int]] + :rtype: int + """ + dp = [[float("inf")]*(len(graph)) + for _ in xrange(1 << len(graph))] + q = collections.deque() + for i in xrange(len(graph)): + dp[1 << i][i] = 0 + q.append((1 << i, i)) + while q: + state, node = q.popleft() + steps = dp[state][node] + for nei in graph[node]: + new_state = state | (1 << nei) + if dp[new_state][nei] == float("inf"): + dp[new_state][nei] = steps+1 + q.append((new_state, nei)) + return min(dp[-1]) From d9f3348b813a88530a022c807f102a86cf04890c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jun 2018 14:07:41 +0800 Subject: [PATCH 4779/4971] Create backspace-string-compare.cpp --- C++/backspace-string-compare.cpp | 33 ++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/backspace-string-compare.cpp diff --git a/C++/backspace-string-compare.cpp b/C++/backspace-string-compare.cpp new file mode 100644 index 000000000..16516df59 --- /dev/null +++ b/C++/backspace-string-compare.cpp @@ -0,0 +1,33 @@ +// Time: O(m + n) +// Space: O(1) + +class Solution { +public: + bool backspaceCompare(string S, string T) { + int skipS = 0, skipT = 0; + for (int i = S.length() - 1, j = T.length() - 1; + i >= 0 || j >= 0; + --i, --j) { + auto x = findNextChar(S, &i, &skipS); + auto y = findNextChar(T, &j, &skipT); + if (x != y) { + return false; + } + } + return true; + } + +private: + char findNextChar(const string& s, int *i, int *skip) { + for (; *i >= 0; --(*i)) { + if (s[*i] == '#') { + ++(*skip); + } else if ((*skip) > 0) { + --(*skip); + } else { + return s[*i]; + } + } + return '\0'; + } +}; From 65009b75835748a1279a5019a08f78ffe72e0296 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 3 Jun 2018 14:11:17 +0800 Subject: [PATCH 4780/4971] Create backspace-string-compare.py --- Python/backspace-string-compare.py | 59 ++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/backspace-string-compare.py diff --git a/Python/backspace-string-compare.py b/Python/backspace-string-compare.py new file mode 100644 index 000000000..4a3e4a603 --- /dev/null +++ b/Python/backspace-string-compare.py @@ -0,0 +1,59 @@ +# Time: O(m + n) +# Space: O(1) + +# Given two strings S and T, return if they are equal +# when both are typed into empty text editors. # means a backspace character. +# +# Example 1: +# +# Input: S = "ab#c", T = "ad#c" +# Output: true +# Explanation: Both S and T become "ac". +# Example 2: +# +# Input: S = "ab##", T = "c#d#" +# Output: true +# Explanation: Both S and T become "". +# Example 3: +# +# Input: S = "a##c", T = "#a#c" +# Output: true +# Explanation: Both S and T become "c". +# Example 4: +# +# Input: S = "a#c", T = "b" +# Output: false +# Explanation: S becomes "c" while T becomes "b". +# +# Note: +# - 1 <= S.length <= 200 +# - 1 <= T.length <= 200 +# - S and T only contain lowercase letters and '#' characters. + +import itertools + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def backspaceCompare(self, S, T): + """ + :type S: str + :type T: str + :rtype: bool + """ + def findNextChar(S): + skip = 0 + for i in reversed(xrange(len(S))): + if S[i] == '#': + skip += 1 + elif skip: + skip -= 1 + else: + yield S[i] + + return all(x == y for x, y in + itertools.izip_longest(findNextChar(S), findNextChar(T))) From 6241986b0a80727c1f6b02de681771234b0fd6e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 3 Jun 2018 14:20:04 +0800 Subject: [PATCH 4781/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index ae104b2f9..87c28dc73 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 835 | [Image Overlap](https://leetcode.com/problems/image-overlap/) | [C++](./C++/image-overlap.cpp) [Python](./Python/image-overlap.py) | _O(n^4)_ | _O(n^2)_ | Medium || 840 | [Magic Squares In Grid](https://leetcode.com/problems/magic-squares-in-grid/) | [C++](./C++/magic-squares-in-grid.cpp) [Python](./Python/magic-squares-in-grid.py) | _O(m * n)_ | _O(1)_ | Easy || 842 | [Split Array into Fibonacci Sequence](https://leetcode.com/problems/split-array-into-fibonacci-sequence/) | [C++](./C++/split-array-into-fibonacci-sequence.cpp) [Python](./Python/split-array-into-fibonacci-sequence.py) | _O(n^3)_ | _O(n)_ | Medium || +845 | [Longest Mountain in Array](https://leetcode.com/problems/longest-mountain-in-array/) | [C++](./C++/longest-mountain-in-array.cpp) [Python](./Python/longest-mountain-in-array.py) | _O(n)_ | _O(1)_ | Medium || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -301,6 +302,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 378 | [Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/) | [C++](./C++/kth-smallest-element-in-a-sorted-matrix.cpp) [Python](./Python/kth-smallest-element-in-a-sorted-matrix.py) | _O(k * log(min(n, m, k)))_ | _O(min(n, m, k))_ | Medium | LintCode || 407 | [Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/) | [C++](./C++/trapping-rain-water-ii.cpp) [Python](./Python/trapping-rain-water-ii.py) | _O(m * n * (logm + logn))_ | _O(m * n)_ | Hard | LintCode || 632 | [Smallest Range](https://leetcode.com/problems/smallest-range/) | [C++](./C++/smallest-range.cpp) [Python](./Python/smallest-range.py) | _O(nlogk)_ | _O(k)_ | Hard ||| +846 | [Hand of Straights](https://leetcode.com/problems/hand-of-straights/) | [C++](./C++/hand-of-straights.cpp) [Python](./Python/hand-of-straights.py) | _O(nlogn)_ | _O(n)_ | Medium ||| ## Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -516,6 +518,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 777| [Swap Adjacent in LR String](https://leetcode.com/problems/swap-adjacent-in-lr-string/) | [C++](./C++/swap-adjacent-in-lr-string.cpp) [Python](./Python/swap-adjacent-in-lr-string.py) | _O(n)_ | _O(1)_ | Medium || 826| [Most Profit Assigning Work](https://leetcode.com/problems/most-profit-assigning-work/) | [C++](./C++/most-profit-assigning-work.cpp) [Python](./Python/most-profit-assigning-work.py) | _O(mlogm + nlogn)_ | _O(n)_ | Medium || 828| [Unique Letter String](https://leetcode.com/problems/unique-letter-string/) | [C++](./C++/unique-letter-string.cpp) [Python](./Python/unique-letter-string.py) | _O(n)_ | _O(1)_ | Hard || +844 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | [C++](./C++/backspace-string-compare.cpp) [Python](./Python/backspace-string-compare.py) | _O(m + n)_ | _O(1)_ | Easy || ## Recursion | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -791,6 +794,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 823 | [Binary Trees With Factors](https://leetcode.com/problems/binary-trees-with-factors/) | [C++](./C++/binary-trees-with-factors.cpp) [Python](./Python/binary-trees-with-factors.py) | _O(n^2)_ | _O(n)_ | Medium || | 837 | [New 21 Game](https://leetcode.com/problems/new-21-game/) | [C++](./C++/new-21-game.cpp) [Python](./Python/new-21-game.py) | _O(n)_ | _O(n)_ | Medium || | 838 | [Push Dominoes](https://leetcode.com/problems/push-dominoes/) | [C++](./C++/push-dominoes.cpp) [Python](./Python/push-dominoes.py) | _O(n)_ | _O(n)_ | Medium || | +847 | [Shortest Path Visiting All Nodes](https://leetcode.com/problems/shortest-path-visiting-all-nodes/) | [C++](./C++/shortest-path-visiting-all-nodes.cpp) [Python](./Python/shortest-path-visiting-all-nodes.py) | _O(n *2^n)_ | _O(n * 2^n)_ | Hard || BFS | ## Greedy | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 8084a3be60e35e5737047f5b2d2daf8dce0cec1a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 4 Jun 2018 21:09:59 +0800 Subject: [PATCH 4782/4971] Update sliding-window-maximum.py --- Python/sliding-window-maximum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/sliding-window-maximum.py b/Python/sliding-window-maximum.py index 1fb613e50..c55ce43b1 100644 --- a/Python/sliding-window-maximum.py +++ b/Python/sliding-window-maximum.py @@ -41,7 +41,7 @@ def maxSlidingWindow(self, nums, k): while dq and nums[i] >= nums[dq[-1]]: dq.pop() dq.append(i) - if i >= k and dq and dq[0] <= i - k: + if i >= k and dq and dq[0] == i - k: dq.popleft() if i >= k - 1: max_numbers.append(nums[dq[0]]) From f3772024750d9bfec940bc585b154d0617b0e753 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 14:34:55 +0800 Subject: [PATCH 4783/4971] Create shifting-letters.cpp --- C++/shifting-letters.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/shifting-letters.cpp diff --git a/C++/shifting-letters.cpp b/C++/shifting-letters.cpp new file mode 100644 index 000000000..939a49510 --- /dev/null +++ b/C++/shifting-letters.cpp @@ -0,0 +1,18 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string shiftingLetters(string S, vector& shifts) { + string result; + auto times = accumulate(shifts.cbegin(), shifts.cend(), 0L) % 26; + for (int i = 0; i < S.length(); ++i) { + result.push_back('a' + (S[i] - 'a' + times) % 26); + times = (times - shifts[i]) % 26; + if (times < 0) { + times += 26; + } + } + return result; + } +}; From 8061b5bf022a7c384786b9c6e154f4c1c84c5a24 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 10 Jun 2018 14:37:23 +0800 Subject: [PATCH 4784/4971] Create shifting-letters.py --- Python/shifting-letters.py | 43 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/shifting-letters.py diff --git a/Python/shifting-letters.py b/Python/shifting-letters.py new file mode 100644 index 000000000..ae87d6ddb --- /dev/null +++ b/Python/shifting-letters.py @@ -0,0 +1,43 @@ +# Time: O(n) +# Space: O(1) + +# We have a string S of lowercase letters, and an integer array shifts. +# +# Call the shift of a letter, the next letter in the alphabet, +# (wrapping around so that 'z' becomes 'a'). +# +# For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'. +# +# Now for each shifts[i] = x, +# we want to shift the first i+1 letters of S, x times. +# +# Return the final string after all such shifts to S are applied. +# +# Example 1: +# +# Input: S = "abc", shifts = [3,5,9] +# Output: "rpl" +# Explanation: +# We start with "abc". +# After shifting the first 1 letters of S by 3, we have "dbc". +# After shifting the first 2 letters of S by 5, we have "igc". +# After shifting the first 3 letters of S by 9, we have "rpl", the answer. +# Note: +# - 1 <= S.length = shifts.length <= 20000 +# - 0 <= shifts[i] <= 10 ^ 9 + + +class Solution(object): + def shiftingLetters(self, S, shifts): + """ + :type S: str + :type shifts: List[int] + :rtype: str + """ + result = [] + times = sum(shifts) % 26 + for i, c in enumerate(S): + index = ord(c) - ord('a') + result.append(chr(ord('a') + (index+times) % 26)) + times = (times-shifts[i]) % 26 + return "".join(result) From b5fb207de303d80e24fd8127ec0be7f04796d983 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 10 Jun 2018 14:55:44 +0800 Subject: [PATCH 4785/4971] Create maximize-distance-to-closest-person.py --- Python/maximize-distance-to-closest-person.py | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/maximize-distance-to-closest-person.py diff --git a/Python/maximize-distance-to-closest-person.py b/Python/maximize-distance-to-closest-person.py new file mode 100644 index 000000000..d0634a8cf --- /dev/null +++ b/Python/maximize-distance-to-closest-person.py @@ -0,0 +1,54 @@ +# Time: O(n) +# Space: O(1) + +# In a row of seats, 1 represents a person sitting in that seat, +# and 0 represents that the seat is empty. +# +# There is at least one empty seat, and at least one person sitting. +# +# Alex wants to sit in the seat such that the distance between him +# and the closest person to him is maximized. +# +# Return that maximum distance to closest person. +# +# Example 1: +# +# Input: [1,0,0,0,1,0,1] +# Output: 2 +# Explanation: +# If Alex sits in the second open seat (seats[2]), +# then the closest person has distance 2. +# If Alex sits in any other open seat, the closest person has distance 1. +# Thus, the maximum distance to the closest person is 2. +# Example 2: +# +# Input: [1,0,0,0] +# Output: 3 +# Explanation: +# If Alex sits in the last seat, the closest person is 3 seats away. +# This is the maximum distance possible, so the answer is 3. +# Note: +# - 1 <= seats.length <= 20000 +# - seats contains only 0s or 1s, at least one 0, and at least one 1. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def maxDistToClosest(self, seats): + """ + :type seats: List[int] + :rtype: int + """ + prev, result = -1, 1 + for i in xrange(len(seats)): + if seats[i]: + if prev < 0: + result = i + else: + result = max(result, (i-prev)//2) + prev = i + return max(result, len(seats)-1-prev) From d2f11c56da252a75648604eede84cb02f3a522de Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 14:56:50 +0800 Subject: [PATCH 4786/4971] Create maximize-distance-to-closest-person.cpp --- C++/maximize-distance-to-closest-person.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/maximize-distance-to-closest-person.cpp diff --git a/C++/maximize-distance-to-closest-person.cpp b/C++/maximize-distance-to-closest-person.cpp new file mode 100644 index 000000000..e5626f443 --- /dev/null +++ b/C++/maximize-distance-to-closest-person.cpp @@ -0,0 +1,20 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int maxDistToClosest(vector& seats) { + int prev = -1, result = 1; + for (int i = 0; i < seats.size(); ++i) { + if (seats[i]) { + if (prev < 0) { + result = i; + } else { + result = max(result, (i - prev) / 2); + } + prev = i; + } + } + return max(result, static_cast(seats.size()) - 1 - prev); + } +}; From 959d22739954316feb20384ec2f2f6e7ae1b2211 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 15:21:55 +0800 Subject: [PATCH 4787/4971] Create loud-and-rich.cpp --- C++/loud-and-rich.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/loud-and-rich.cpp diff --git a/C++/loud-and-rich.cpp b/C++/loud-and-rich.cpp new file mode 100644 index 000000000..e14f7c142 --- /dev/null +++ b/C++/loud-and-rich.cpp @@ -0,0 +1,33 @@ +# Time: O(q + r) +# Space: O(q) + +class Solution { +public: + vector loudAndRich(vector>& richer, vector& quiet) { + vector> graph(quiet.size()); + for (const auto& r : richer) { + graph[r[1]].emplace_back(r[0]); + } + vector result(quiet.size(), -1); + for (int i = 0; i < quiet.size(); ++i) { + dfs(graph, quiet, i, &result); + } + return result; + } + +private: + int dfs(const vector>& graph, + const vector& quiet, + int node, vector *result) { + if ((*result)[node] == -1) { + (*result)[node] = node; + for (const auto& nei : graph[node]) { + int smallest_person = dfs(graph, quiet, nei, result); + if (quiet[smallest_person] < quiet[(*result)[node]]) { + (*result)[node] = smallest_person; + } + } + } + return (*result)[node]; + } +}; From dfc0ed437749ed05089815a60e752b39a56d750d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 15:22:22 +0800 Subject: [PATCH 4788/4971] Update loud-and-rich.cpp --- C++/loud-and-rich.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/loud-and-rich.cpp b/C++/loud-and-rich.cpp index e14f7c142..0aac35796 100644 --- a/C++/loud-and-rich.cpp +++ b/C++/loud-and-rich.cpp @@ -1,5 +1,5 @@ # Time: O(q + r) -# Space: O(q) +# Space: O(q + r) class Solution { public: From be8ba56695b1b9ab137cf357be08f07476048c03 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 15:23:39 +0800 Subject: [PATCH 4789/4971] Update loud-and-rich.cpp --- C++/loud-and-rich.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/loud-and-rich.cpp b/C++/loud-and-rich.cpp index 0aac35796..534ec108d 100644 --- a/C++/loud-and-rich.cpp +++ b/C++/loud-and-rich.cpp @@ -1,5 +1,5 @@ -# Time: O(q + r) -# Space: O(q + r) +// Time: O(q + r) +// Space: O(q + r) class Solution { public: From a5e148489a10ed508ad081ab38b09d7bef7d4453 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 10 Jun 2018 15:26:49 +0800 Subject: [PATCH 4790/4971] Create loud-and-rich.py --- Python/loud-and-rich.py | 74 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Python/loud-and-rich.py diff --git a/Python/loud-and-rich.py b/Python/loud-and-rich.py new file mode 100644 index 000000000..6626a5579 --- /dev/null +++ b/Python/loud-and-rich.py @@ -0,0 +1,74 @@ +# Time: O(q + r) +# Space: O(q + r) + +# In a group of N people (labelled 0, 1, 2, ..., N-1), +# each person has different amounts of money, and different levels of +# quietness. +# +# For convenience, we'll call the person with label x, simply "person x". +# +# We'll say that richer[i] = [x, y] +# if person x definitely has more money than person y. +# Note that richer may only be a subset of valid observations. +# +# Also, we'll say quiet[x] = q if person x has quietness q. +# +# Now, return answer, where answer[x] = y if y is the least quiet person +# (that is, the person y with the smallest value of quiet[y]), +# among all people who definitely have equal to or more money than person x. +# +# Example 1: +# +# Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], +# quiet = [3,2,5,4,6,1,7,0] +# Output: [5,5,2,5,4,5,6,7] +# Explanation: +# answer[0] = 5. +# Person 5 has more money than 3, which has more money than 1, +# which has more money than 0. +# The only person who is quieter (has lower quiet[x]) is person 7, but +# it isn't clear if they have more money than person 0. +# +# answer[7] = 7. +# Among all people that definitely have equal to or more money than person 7 +# (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest +# (has lower quiet[x]) +# is person 7. +# +# The other answers can be filled out with similar reasoning. +# Note: +# - 1 <= quiet.length = N <= 500 +# - 0 <= quiet[i] < N, all quiet[i] are different. +# - 0 <= richer.length <= N * (N-1) / 2 +# - 0 <= richer[i][j] < N +# - richer[i][0] != richer[i][1] +# - richer[i]'s are all different. +# - The observations in richer are all logically consistent. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def loudAndRich(self, richer, quiet): + """ + :type richer: List[List[int]] + :type quiet: List[int] + :rtype: List[int] + """ + def dfs(graph, quiet, node, result): + if result[node] is None: + result[node] = node + for nei in graph[node]: + smallest_person = dfs(graph, quiet, nei, result) + if quiet[smallest_person] < quiet[result[node]]: + result[node] = smallest_person + return result[node] + + graph = [[] for _ in xrange(len(quiet))] + for u, v in richer: + graph[v].append(u) + result = [None]*len(quiet) + return map(lambda x: dfs(graph, quiet, x, result), xrange(len(quiet))) From f0fab425eb8d93053c3830b4565127db63dca362 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 16:16:49 +0800 Subject: [PATCH 4791/4971] Update shifting-letters.cpp --- C++/shifting-letters.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/C++/shifting-letters.cpp b/C++/shifting-letters.cpp index 939a49510..4c23b114a 100644 --- a/C++/shifting-letters.cpp +++ b/C++/shifting-letters.cpp @@ -8,10 +8,7 @@ class Solution { auto times = accumulate(shifts.cbegin(), shifts.cend(), 0L) % 26; for (int i = 0; i < S.length(); ++i) { result.push_back('a' + (S[i] - 'a' + times) % 26); - times = (times - shifts[i]) % 26; - if (times < 0) { - times += 26; - } + times = ((times - shifts[i]) % 26 + 26) % 26; } return result; } From 7776018125fce309a1ecac3cd7be1614724ed75e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 17:29:21 +0800 Subject: [PATCH 4792/4971] Create rectangle-area-ii.cpp --- C++/rectangle-area-ii.cpp | 96 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 C++/rectangle-area-ii.cpp diff --git a/C++/rectangle-area-ii.cpp b/C++/rectangle-area-ii.cpp new file mode 100644 index 000000000..d5aa02ff8 --- /dev/null +++ b/C++/rectangle-area-ii.cpp @@ -0,0 +1,96 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + enum { OPEN = 1, CLOSE = -1}; + + int rectangleArea(vector>& rectangles) { + vector> events; + set Xvals; + for (const auto& rec: rectangles) { + events.emplace_back(vector{rec[1], OPEN, rec[0], rec[2]}); + events.emplace_back(vector{rec[3], CLOSE, rec[0], rec[2]}); + Xvals.emplace(rec[0]); + Xvals.emplace(rec[2]); + } + sort(events.begin(), events.end()); + vector X(Xvals.cbegin(), Xvals.cend()); + unordered_map Xi; + for (int i = 0; i < X.size(); ++i) { + Xi[X[i]] = i; + } + + auto st = new SegmentTreeNode(0, X.size() - 1, X); + int64_t result = 0; + int64_t cur_x_sum = 0; + int cur_y = events[0][0]; + for (const auto& event: events) { + int y = event[0], type = event[1], x1 = event[2], x2 = event[3]; + result += cur_x_sum * (y - cur_y); + cur_x_sum = st->update(Xi[x1], Xi[x2], type); + cur_y = y; + } + return result % static_cast(1e9 + 7); + } + + class SegmentTreeNode { + public: + SegmentTreeNode(int start, int end, const vector& X) : + start_(start), + end_(end), + X_(X), + left_(nullptr), + right_(nullptr), + count_(0), + total_(0) { + } + + int rangeMid() const { + return start_ + (end_ - start_) / 2; + } + + SegmentTreeNode *left() { + if (left_ == nullptr) { + left_ = new SegmentTreeNode(start_, rangeMid(), X_); + } + return left_; + } + + SegmentTreeNode *right() { + if (right_ == nullptr) { + right_ = new SegmentTreeNode(rangeMid(), end_, X_); + } + return right_; + } + + int64_t total() const { + return total_; + } + + int64_t update(int i, int j, int val) { + if (i >= j) { + return 0; + } + if (start_ == i && end_ == j) { + count_ += val; + } else { + left()->update(i, min(rangeMid(), j), val); + right()->update(max(rangeMid(), i), j, val); + } + if (count_ > 0) { + total_ = X_[end_] - X_[start_]; + } else { + total_ = left()->total() + right()->total(); + } + return total_; + } + + private: + int start_, end_; + const vector& X_; + SegmentTreeNode *left_, *right_; + int count_; + int64_t total_; + }; +}; From 181099dfb21ec4d32f5bcc3d4c087f19a63df7b2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 17:33:02 +0800 Subject: [PATCH 4793/4971] Update rectangle-area-ii.cpp --- C++/rectangle-area-ii.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/C++/rectangle-area-ii.cpp b/C++/rectangle-area-ii.cpp index d5aa02ff8..7ff59dcff 100644 --- a/C++/rectangle-area-ii.cpp +++ b/C++/rectangle-area-ii.cpp @@ -46,20 +46,20 @@ class Solution { total_(0) { } - int rangeMid() const { + int mid() const { return start_ + (end_ - start_) / 2; } SegmentTreeNode *left() { if (left_ == nullptr) { - left_ = new SegmentTreeNode(start_, rangeMid(), X_); + left_ = new SegmentTreeNode(start_, mid(), X_); } return left_; } SegmentTreeNode *right() { if (right_ == nullptr) { - right_ = new SegmentTreeNode(rangeMid(), end_, X_); + right_ = new SegmentTreeNode(mid(), end_, X_); } return right_; } @@ -75,8 +75,8 @@ class Solution { if (start_ == i && end_ == j) { count_ += val; } else { - left()->update(i, min(rangeMid(), j), val); - right()->update(max(rangeMid(), i), j, val); + left()->update(i, min(mid(), j), val); + right()->update(max(mid(), i), j, val); } if (count_ > 0) { total_ = X_[end_] - X_[start_]; From f15d44f1f0ca7548a6ce66110bf20de2223e8a3c Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 10 Jun 2018 17:36:09 +0800 Subject: [PATCH 4794/4971] Create rectangle-area-ii.py --- Python/rectangle-area-ii.py | 91 +++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Python/rectangle-area-ii.py diff --git a/Python/rectangle-area-ii.py b/Python/rectangle-area-ii.py new file mode 100644 index 000000000..5900367bd --- /dev/null +++ b/Python/rectangle-area-ii.py @@ -0,0 +1,91 @@ +# Time: O(logn) +# Space: O(n) + +# We are given a list of (axis-aligned) rectangles. +# Each rectangle[i] = [x1, y1, x2, y2] , +# where (x1, y1) are the coordinates of the bottom-left corner, +# and (x2, y2) are the coordinates of the top-right corner of +# the ith rectangle. +# +# Find the total area covered by all rectangles in the plane. +# Since the answer may be too large, return it modulo 10^9 + 7. +# +# Example 1: +# +# Input: [[0,0,2,2],[1,0,2,3],[1,0,3,1]] +# Output: 6 +# Explanation: As illustrated in the picture. +# Example 2: +# +# Input: [[0,0,1000000000,1000000000]] +# Output: 49 +# Explanation: The answer is 10^18 modulo (10^9 + 7), +# which is (10^9)^2 = (-7)^2 = 49. +# +# Note: +# - 1 <= rectangles.length <= 200 +# - rectanges[i].length = 4 +# - 0 <= rectangles[i][j] <= 10^9 +# - The total area covered by all rectangles will never exceed 2^63 - 1 and +# thus will fit in a 64-bit signed integer. + + +class SegmentTreeNode(object): + def __init__(self, start, end): + self.start, self.end = start, end + self.total = self.count = 0 + self._left = self._right = None + + def mid(self): + return (self.start+self.end) // 2 + + def left(self): + self._left = self._left or SegmentTreeNode(self.start, self.mid()) + return self._left + + def right(self): + self._right = self._right or SegmentTreeNode(self.mid(), self.end) + return self._right + + def update(self, X, i, j, val): + if i >= j: + return 0 + if self.start == i and self.end == j: + self.count += val + else: + self.left().update(X, i, min(self.mid(), j), val) + self.right().update(X, max(self.mid(), i), j, val) + if self.count > 0: + self.total = X[self.end]-X[self.start] + else: + self.total = self.left().total + self.right().total + return self.total + + +class Solution(object): + def rectangleArea(self, rectangles): + """ + :type rectangles: List[List[int]] + :rtype: int + """ + OPEN, CLOSE = 1, -1 + events = [] + X = set() + for x1, y1, x2, y2 in rectangles: + events.append((y1, OPEN, x1, x2)) + events.append((y2, CLOSE, x1, x2)) + X.add(x1) + X.add(x2) + events.sort() + X = sorted(X) + Xi = {x: i for i, x in enumerate(X)} + + st = SegmentTreeNode(0, len(X)-1) + result = 0 + cur_x_sum = 0 + cur_y = events[0][0] + for y, typ, x1, x2 in events: + result += cur_x_sum * (y-cur_y) + cur_x_sum = st.update(X, Xi[x1], Xi[x2], typ) + cur_y = y + return result % (10**9+7) From 76d29e3dddd2d339d4a9bf4b04991c1a94d9a9c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 17:37:09 +0800 Subject: [PATCH 4795/4971] Update rectangle-area-ii.py --- Python/rectangle-area-ii.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/rectangle-area-ii.py b/Python/rectangle-area-ii.py index 5900367bd..b91dc6cc1 100644 --- a/Python/rectangle-area-ii.py +++ b/Python/rectangle-area-ii.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(nlogn) # Space: O(n) # We are given a list of (axis-aligned) rectangles. From 33e377d391624428970126a66fddefe829c5cae4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 17:58:25 +0800 Subject: [PATCH 4796/4971] Update README.md --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 87c28dc73..8b5901ee3 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 840 | [Magic Squares In Grid](https://leetcode.com/problems/magic-squares-in-grid/) | [C++](./C++/magic-squares-in-grid.cpp) [Python](./Python/magic-squares-in-grid.py) | _O(m * n)_ | _O(1)_ | Easy || 842 | [Split Array into Fibonacci Sequence](https://leetcode.com/problems/split-array-into-fibonacci-sequence/) | [C++](./C++/split-array-into-fibonacci-sequence.cpp) [Python](./Python/split-array-into-fibonacci-sequence.py) | _O(n^3)_ | _O(n)_ | Medium || 845 | [Longest Mountain in Array](https://leetcode.com/problems/longest-mountain-in-array/) | [C++](./C++/longest-mountain-in-array.cpp) [Python](./Python/longest-mountain-in-array.py) | _O(n)_ | _O(1)_ | Medium || +849 | [Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/) | [C++](./C++/maximize-distance-to-closest-person.cpp) [Python](./Python/maximize-distance-to-closest-person.py) | _O(n)_ | _O(1)_ | Easy || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -227,6 +228,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 831| [Masking Personal Information](https://leetcode.com/problems/masking-personal-information/) | [C++](./C++/masking-personal-information.cpp) [Python](./Python/masking-personal-information.py) | _O(1)_ | _O(1)_ | Medium ||| 833| [Find And Replace in String](https://leetcode.com/problems/find-and-replace-in-string/) | [C++](./C++/find-and-replace-in-string.cpp) [Python](./Python/find-and-replace-in-string.py) | _O(n + m)_ | _O(n)_ | Medium ||| 839 | [Similar String Groups](https://leetcode.com/problems/similar-string-groups/) | [C++](./C++/similar-string-groups.cpp) [Python](./Python/similar-string-groups.py) | _O(n^2 * l)_ | _O(n)_ | Hard || Union Find +848 | [Shifting Letters](https://leetcode.com/problems/shifting-letters/) | [C++](./C++/shifting-letters.cpp) [Python](./Python/shifting-letters.py) | _O(n)_ | _O(1)_ | Medium || ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -343,7 +345,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 687 | [Longest Univalue Path](https://leetcode.com/problems/longest-univalue-path/) | [C++](./C++/longest-univalue-path.cpp) [Python](./Python/longest-univalue-path.py) | _O(n)_ | _O(h)_ | Easy || 699 | [Falling Squares](https://leetcode.com/problems/falling-squares/) | [C++](./C++/falling-squares.cpp) [Python](./Python/falling-squares.py) | _O(nlogn)_ | _O(n)_ | Hard || Segment Tree | 814 | [Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning/) | [C++](./C++/binary-tree-pruning.cpp) [Python](./Python/binary-tree-pruning.py) | _O(n)_ | _O(h)_ | Medium || DFS | - +850 | [Rectangle Area II](https://leetcode.com/problems/rectangle-area-ii/) | [C++](./C++/rectangle-area-ii.cpp) [Python](./Python/rectangle-area-ii.py) | _O(nlogn)_ | _O(n)_ | Hard || Segment Tree | ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| @@ -670,6 +672,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 827| [Making A Large Island](https://leetcode.com/problems/making-a-large-island/) | [C++](./C++/making-a-large-island.cpp) [Python](./Python/making-a-large-island.py) | _O(n^2)_ | _O(n^2)_ | Hard ||| 834| [Sum of Distances in Tree](https://leetcode.com/problems/sum-of-distances-in-tree/) | [C++](./C++/sum-of-distances-in-tree.cpp) [Python](./Python/sum-of-distances-in-tree.py) | _O(n)_ | _O(n)_ | Hard ||| 841| [Keys and Rooms](https://leetcode.com/problems/keys-and-rooms/) | [C++](./C++/keys-and-rooms.cpp) [Python](./Python/keys-and-rooms.py) | _O(n!)_ | _O(n)_ | Medium ||| +851| [Loud and Rich](https://leetcode.com/problems/loud-and-rich/) | [C++](./C++/loud-and-rich.cpp) [Python](./Python/loud-and-rich.py) | _O(q + r)_ | _O(q + r)_ | Medium ||| ## Backtracking | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 50ddb9fc01a8181e63d9ee90c5d1a45145a670ee Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 19:26:31 +0800 Subject: [PATCH 4797/4971] Update falling-squares.cpp --- C++/falling-squares.cpp | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/C++/falling-squares.cpp b/C++/falling-squares.cpp index 0232da1da..16645c73a 100644 --- a/C++/falling-squares.cpp +++ b/C++/falling-squares.cpp @@ -1,8 +1,34 @@ // Time: O(nlogn) // Space: O(n) -// Segment Tree solution. class Solution { +public: + vector fallingSquares(vector>& positions) { + vector result; + map heights; + int maxH = heights[-1] = 0; + for (const auto& p : positions) { + auto it0 = heights.upper_bound(p.first); + auto it1 = heights.lower_bound(p.first + p.second); + int h0 = prev(it0)->second; + int h1 = (it1->first == p.first + p.second) ? it1->second : prev(it1)->second; + for (auto it = it0; it != it1; ++it) { + h0 = max(h0, it->second); + } + heights.erase(it0, it1); + heights[p.first] = h0 + p.second; + heights[p.first + p.second] = h1; + maxH = max(maxH, h0 + p.second); + result.emplace_back(maxH); + } + return result; + } +}; + +// Time: O(nlogn) +// Space: O(n) +// Segment Tree solution. +class Solution2 { public: vector fallingSquares(vector>& positions) { set index; @@ -104,7 +130,7 @@ class Solution { // Time: O(n * sqrt(n)) // Space: O(n) -class Solution2 { +class Solution3 { public: vector fallingSquares(vector>& positions) { set index; @@ -176,7 +202,7 @@ class Solution2 { // Time: O(n^2) // Space: O(n) -class Solution3 { +class Solution4 { public: vector fallingSquares(vector>& positions) { vector heights(positions.size()); From 5c1c272cced52b05fc8a17bd3654372122ed0a2a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 19:29:11 +0800 Subject: [PATCH 4798/4971] Update falling-squares.cpp --- C++/falling-squares.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/C++/falling-squares.cpp b/C++/falling-squares.cpp index 16645c73a..339d25fee 100644 --- a/C++/falling-squares.cpp +++ b/C++/falling-squares.cpp @@ -7,21 +7,21 @@ class Solution { vector result; map heights; int maxH = heights[-1] = 0; - for (const auto& p : positions) { - auto it0 = heights.upper_bound(p.first); + for (const auto& p : positions) { + auto it0 = heights.upper_bound(p.first); auto it1 = heights.lower_bound(p.first + p.second); - int h0 = prev(it0)->second; + int h0 = prev(it0)->second; int h1 = (it1->first == p.first + p.second) ? it1->second : prev(it1)->second; - for (auto it = it0; it != it1; ++it) { + for (auto it = it0; it != it1; ++it) { h0 = max(h0, it->second); } - heights.erase(it0, it1); - heights[p.first] = h0 + p.second; - heights[p.first + p.second] = h1; - maxH = max(maxH, h0 + p.second); - result.emplace_back(maxH); - } - return result; + heights.erase(it0, it1); + heights[p.first] = h0 + p.second; + heights[p.first + p.second] = h1; + maxH = max(maxH, h0 + p.second); + result.emplace_back(maxH); + } + return result; } }; From 713e66624d08792c6a39a1c2e8147bd05fa452fd Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 19:32:52 +0800 Subject: [PATCH 4799/4971] Update falling-squares.cpp --- C++/falling-squares.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/falling-squares.cpp b/C++/falling-squares.cpp index 339d25fee..ea0e0ba35 100644 --- a/C++/falling-squares.cpp +++ b/C++/falling-squares.cpp @@ -11,7 +11,7 @@ class Solution { auto it0 = heights.upper_bound(p.first); auto it1 = heights.lower_bound(p.first + p.second); int h0 = prev(it0)->second; - int h1 = (it1->first == p.first + p.second) ? it1->second : prev(it1)->second; + int h1 = prev(it1)->second; for (auto it = it0; it != it1; ++it) { h0 = max(h0, it->second); } From 2101b4acc2014a056fd15ccc1d4d03010ed517bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 19:49:03 +0800 Subject: [PATCH 4800/4971] Update falling-squares.py --- Python/falling-squares.py | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/Python/falling-squares.py b/Python/falling-squares.py index d834723fd..53dbd9ba4 100644 --- a/Python/falling-squares.py +++ b/Python/falling-squares.py @@ -65,6 +65,25 @@ # 1 <= positions[0] <= 10^8. # 1 <= positions[1] <= 10^6. +# Time: O(nlogn) ~ O(n^2) +# Space: O(n) +class Solution(object): + def fallingSquares(self, positions): + result = [] + pos = [-1] + heights = [0] + maxH = 0 + for left, side in positions: + l = bisect.bisect_right(pos, left) + r = bisect.bisect_left(pos, left+side) + high = max(heights[l-1:r] or [0]) + side + pos[l:r] = [left, left+side] # Time: O(n) + heights[l:r] = [high, heights[r-1]] # Time: O(n) + maxH = max(maxH, high) + result.append(maxH) + return result + + import bisect @@ -130,8 +149,10 @@ def query(self, L, R): return result +# Time: O(nlogn) +# Space: O(n) # Segment Tree solution. -class Solution(object): +class Solution2(object): def fallingSquares(self, positions): index = set() for left, size in positions: @@ -152,7 +173,7 @@ def fallingSquares(self, positions): # Time: O(n * sqrt(n)) # Space: O(n) -class Solution2(object): +class Solution3(object): def fallingSquares(self, positions): def query(heights, left, right, B, blocks, blocks_read): result = 0 @@ -204,7 +225,7 @@ def update(heights, left, right, B, blocks, blocks_read, h): # Time: O(n^2) # Space: O(n) -class Solution3(object): +class Solution4(object): def fallingSquares(self, positions): """ :type positions: List[List[int]] From 24686864b2cb3a7e0a0dd6423c8891be7a3310bb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 10 Jun 2018 22:37:07 +0800 Subject: [PATCH 4801/4971] Update falling-squares.py --- Python/falling-squares.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/falling-squares.py b/Python/falling-squares.py index 53dbd9ba4..9d76976cb 100644 --- a/Python/falling-squares.py +++ b/Python/falling-squares.py @@ -67,6 +67,9 @@ # Time: O(nlogn) ~ O(n^2) # Space: O(n) +import bisect + + class Solution(object): def fallingSquares(self, positions): result = [] @@ -84,9 +87,6 @@ def fallingSquares(self, positions): return result -import bisect - - class SegmentTree(object): def __init__(self, N, update_fn, query_fn): self.N = N From d7cc3d6590d1d6d46bdf780b93e76ea6aa50334d Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 18 Jun 2018 12:22:27 +0800 Subject: [PATCH 4802/4971] Create peak-index-in-a-mountain-array.py --- Python/peak-index-in-a-mountain-array.py | 41 ++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Python/peak-index-in-a-mountain-array.py diff --git a/Python/peak-index-in-a-mountain-array.py b/Python/peak-index-in-a-mountain-array.py new file mode 100644 index 000000000..388f3d153 --- /dev/null +++ b/Python/peak-index-in-a-mountain-array.py @@ -0,0 +1,41 @@ +# Time: O(logn) +# Space: O(1) + +# Let's call an array A a mountain if the following properties hold: +# +# A.length >= 3 +# There exists some 0 < i < A.length - 1 +# such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] +# Given an array that is definitely a mountain, +# return any i such that +# A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. +# +# Example 1: +# +# Input: [0,1,0] +# Output: 1 +# Example 2: +# +# Input: [0,2,1,0] +# Output: 1 +# Note: +# +# 3 <= A.length <= 10000 +# 0 <= A[i] <= 10^6 +# A is a mountain, as defined above. + + +class Solution(object): + def peakIndexInMountainArray(self, A): + """ + :type A: List[int] + :rtype: int + """ + left, right = 0, len(A) + while left < right: + mid = left + (right-left)//2 + if A[mid] > A[mid+1]: + right = mid + else: + left = mid+1 + return left From 8abb3c0e134d813d99616b127dd235aed12df0d6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 12:23:37 +0800 Subject: [PATCH 4803/4971] Create peak-index-in-a-mountain-array.cpp --- C++/peak-index-in-a-mountain-array.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 C++/peak-index-in-a-mountain-array.cpp diff --git a/C++/peak-index-in-a-mountain-array.cpp b/C++/peak-index-in-a-mountain-array.cpp new file mode 100644 index 000000000..2425f8459 --- /dev/null +++ b/C++/peak-index-in-a-mountain-array.cpp @@ -0,0 +1,18 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int peakIndexInMountainArray(vector& A) { + int left = 0, right = A.size(); + while (left < right) { + const auto mid = left + (right - left) / 2; + if (A[mid] > A[mid + 1]) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } +}; From dc4a5cabf5e0b26f8164eea0c312a64c2b70b340 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 12:39:56 +0800 Subject: [PATCH 4804/4971] Create car-fleet.cpp --- C++/car-fleet.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 C++/car-fleet.cpp diff --git a/C++/car-fleet.cpp b/C++/car-fleet.cpp new file mode 100644 index 000000000..003eba1e7 --- /dev/null +++ b/C++/car-fleet.cpp @@ -0,0 +1,23 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + int carFleet(int target, vector& position, vector& speed) { + vector> cars; + for (int i = 0; i < position.size(); ++i) { + cars.emplace_back(position[i], + static_cast(target - position[i]) / speed[i]); + } + sort(cars.begin(), cars.end()); + int result = 0; + double curr = 0; + for (int i = position.size() - 1; i >= 0 ; --i) { + if (cars[i].second > curr) { + curr = cars[i].second; + ++result; + } + } + return result; + } +}; From 151a5a64aa5d0e3a2b4e63c7f07916efa087b8a2 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 18 Jun 2018 12:43:32 +0800 Subject: [PATCH 4805/4971] Create car-fleet.py --- Python/car-fleet.py | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/car-fleet.py diff --git a/Python/car-fleet.py b/Python/car-fleet.py new file mode 100644 index 000000000..85d5619c5 --- /dev/null +++ b/Python/car-fleet.py @@ -0,0 +1,59 @@ +# Time: O(nlogn) +# Space: O(n) + +# N cars are going to the same destination along a one lane road. +# The destination is target miles away. +# +# Each car i has a constant speed speed[i] (in miles per hour), +# and initial position position[i] miles towards the target along the road. +# +# A car can never pass another car ahead of it, +# but it can catch up to it, and drive bumper to bumper at the same speed. +# +# The distance between these two cars is ignored - they are assumed to +# have the same position. +# +# A car fleet is some non-empty set of cars driving at the same position +# and same speed. +# Note that a single car is also a car fleet. +# +# If a car catches up to a car fleet right at the destination point, +# it will still be considered as one car fleet. +# +# How many car fleets will arrive at the destination? +# +# Example 1: +# +# Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3] +# Output: 3 +# Explanation: +# The cars starting at 10 and 8 become a fleet, meeting each other at 12. +# The car starting at 0 doesn't catch up to any other car, so it is a fleet +# by itself. +# The cars starting at 5 and 3 become a fleet, meeting each other at 6. +# Note that no other cars meet these fleets before the destination, +# so the answer is 3. +# +# Note: +# - 0 <= N <= 10 ^ 4 +# - 0 < target <= 10 ^ 6 +# - 0 < speed[i] <= 10 ^ 6 +# - 0 <= position[i] < target +# - All initial positions are different. + + +class Solution(object): + def carFleet(self, target, position, speed): + """ + :type target: int + :type position: List[int] + :type speed: List[int] + :rtype: int + """ + times = [float(target-p)/s for p, s in sorted(zip(position, speed))] + result, curr = 0, 0 + for t in reversed(times): + if t > curr: + result += 1 + curr = t + return result From f688652003953026c4995141c505eea397828dec Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 14:47:35 +0800 Subject: [PATCH 4806/4971] Create exam-room.cpp --- C++/exam-room.cpp | 116 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 C++/exam-room.cpp diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp new file mode 100644 index 000000000..934dc3fc0 --- /dev/null +++ b/C++/exam-room.cpp @@ -0,0 +1,116 @@ +// Time: seat: O(logn), +// leave: O(logn) +// Space: O(n) + +class ExamRoom { +public: + ExamRoom(int N) : num_(N) { + max_heap.emplace(new Segment(-1, num_, num_, 0)); + neighbors[-1] = make_pair(-1, num_); + neighbors[num_] = make_pair(-1, num_); + } + + int seat() { + while (!neighbors.count(max_heap.top()->l) || + !neighbors.count(max_heap.top()->r) || + neighbors.count(max_heap.top()->pos)) { + max_heap.pop(); // lazy deletion + } + const auto curr = max_heap.top(); max_heap.pop(); + if (curr->l == -1 && curr->r == num_) { + max_heap.emplace( + new Segment(curr->l + 1, curr->r, + curr->r - 1, + curr->r - 1)); + neighbors[curr->l + 1] = make_pair(curr->l, curr->r); + } else if (curr->l == -1) { + max_heap.emplace( + new Segment(curr->l + 1, curr->r, + curr->r / 2, + curr->r / 2)); + neighbors[curr->l + 1] = make_pair(curr->l, curr->r); + neighbors[curr->r].first = curr->l + 1; + } else if (curr->r == num_) { + max_heap.emplace( + new Segment(curr->l, curr->r - 1, + (curr->r - 1 - curr->l) / 2, + (curr->r - 1 - curr->l) / 2 + curr->l)); + neighbors[curr->r - 1] = make_pair(curr->l, curr->r); + neighbors[curr->l].second = curr->r - 1; + } else { + max_heap.emplace( + new Segment(curr->l, curr->pos, + (curr->pos - curr->l) / 2, + (curr->pos - curr->l) / 2 + curr->l)); + max_heap.emplace( + new Segment(curr->pos, curr->r, + (curr->r - curr->pos) / 2, + (curr->r - curr->pos) / 2 + curr->pos)); + neighbors[curr->pos] = make_pair(curr->l, curr->r); + neighbors[curr->l].second = curr->pos; + neighbors[curr->r].first = curr->pos; + } + return curr->pos; + } + + void leave(int p) { + const auto nei = neighbors[p]; + neighbors.erase(p); + if (nei.first == -1 && nei.second == num_) { + max_heap.emplace( + new Segment(nei.first, nei.second, + nei.second, + nei.first + 1)); + } else if (nei.first == -1) { + max_heap.emplace( + new Segment(nei.first, nei.second, + nei.second, + nei.first + 1)); + neighbors[nei.second].first = -1; + } else if (nei.second == num_) { + max_heap.emplace( + new Segment(nei.first, nei.second, + nei.second - 1 - nei.first, + nei.second - 1)); + neighbors[nei.first].second = nei.second; + } else { + max_heap.emplace( + new Segment(nei.first, nei.second, + (nei.second - nei.first) / 2, + (nei.second - nei.first) / 2 + nei.first)); + neighbors[nei.first].second = nei.second; + neighbors[nei.second].first = nei.first; + } + } + +private: + struct Segment { + int l; + int r; + int dis; + int pos; + Segment(int l, int r, int dis, int pos) : + l(l), r(r), dis(dis), pos(pos) { + } + }; + + using S = shared_ptr; + struct Compare { + bool operator()(const S& a, const S& b) { + return a->dis == b->dis ? + greater()(a->l, b->l) : + less()(a->dis, b->dis); + } + }; + + int num_; + priority_queue, Compare> max_heap; + unordered_map> neighbors; +}; + +/** + * Your ExamRoom object will be instantiated and called as such: + * ExamRoom obj = new ExamRoom(N); + * int param_1 = obj.seat(); + * obj.leave(p); + */ From 36ab66d8469a3d76bfc8fef661dd82e4f07855e9 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 14:50:30 +0800 Subject: [PATCH 4807/4971] Update exam-room.cpp --- C++/exam-room.cpp | 56 +++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index 934dc3fc0..2260237e2 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -5,7 +5,7 @@ class ExamRoom { public: ExamRoom(int N) : num_(N) { - max_heap.emplace(new Segment(-1, num_, num_, 0)); + max_heap.emplace(make_shared(-1, num_, num_, 0)); neighbors[-1] = make_pair(-1, num_); neighbors[num_] = make_pair(-1, num_); } @@ -19,33 +19,33 @@ class ExamRoom { const auto curr = max_heap.top(); max_heap.pop(); if (curr->l == -1 && curr->r == num_) { max_heap.emplace( - new Segment(curr->l + 1, curr->r, - curr->r - 1, - curr->r - 1)); + make_shared(curr->l + 1, curr->r, + curr->r - 1, + curr->r - 1)); neighbors[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->l == -1) { max_heap.emplace( - new Segment(curr->l + 1, curr->r, - curr->r / 2, - curr->r / 2)); + make_shared(curr->l + 1, curr->r, + curr->r / 2, + curr->r / 2)); neighbors[curr->l + 1] = make_pair(curr->l, curr->r); neighbors[curr->r].first = curr->l + 1; } else if (curr->r == num_) { max_heap.emplace( - new Segment(curr->l, curr->r - 1, - (curr->r - 1 - curr->l) / 2, - (curr->r - 1 - curr->l) / 2 + curr->l)); + make_shared(curr->l, curr->r - 1, + (curr->r - 1 - curr->l) / 2, + (curr->r - 1 - curr->l) / 2 + curr->l)); neighbors[curr->r - 1] = make_pair(curr->l, curr->r); neighbors[curr->l].second = curr->r - 1; } else { max_heap.emplace( - new Segment(curr->l, curr->pos, - (curr->pos - curr->l) / 2, - (curr->pos - curr->l) / 2 + curr->l)); + make_shared(curr->l, curr->pos, + (curr->pos - curr->l) / 2, + (curr->pos - curr->l) / 2 + curr->l)); max_heap.emplace( - new Segment(curr->pos, curr->r, - (curr->r - curr->pos) / 2, - (curr->r - curr->pos) / 2 + curr->pos)); + make_shared(curr->pos, curr->r, + (curr->r - curr->pos) / 2, + (curr->r - curr->pos) / 2 + curr->pos)); neighbors[curr->pos] = make_pair(curr->l, curr->r); neighbors[curr->l].second = curr->pos; neighbors[curr->r].first = curr->pos; @@ -58,26 +58,26 @@ class ExamRoom { neighbors.erase(p); if (nei.first == -1 && nei.second == num_) { max_heap.emplace( - new Segment(nei.first, nei.second, - nei.second, - nei.first + 1)); + make_shared(nei.first, nei.second, + nei.second, + nei.first + 1)); } else if (nei.first == -1) { max_heap.emplace( - new Segment(nei.first, nei.second, - nei.second, - nei.first + 1)); + make_shared(nei.first, nei.second, + nei.second, + nei.first + 1)); neighbors[nei.second].first = -1; } else if (nei.second == num_) { max_heap.emplace( - new Segment(nei.first, nei.second, - nei.second - 1 - nei.first, - nei.second - 1)); + make_shared(nei.first, nei.second, + nei.second - 1 - nei.first, + nei.second - 1)); neighbors[nei.first].second = nei.second; } else { max_heap.emplace( - new Segment(nei.first, nei.second, - (nei.second - nei.first) / 2, - (nei.second - nei.first) / 2 + nei.first)); + make_shared(nei.first, nei.second, + (nei.second - nei.first) / 2, + (nei.second - nei.first) / 2 + nei.first)); neighbors[nei.first].second = nei.second; neighbors[nei.second].first = nei.first; } From 1f9862842ca715ef3b39c76384cd4dee87cd8442 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 14:51:39 +0800 Subject: [PATCH 4808/4971] Update exam-room.cpp --- C++/exam-room.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index 2260237e2..270e96f59 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -26,26 +26,26 @@ class ExamRoom { } else if (curr->l == -1) { max_heap.emplace( make_shared(curr->l + 1, curr->r, - curr->r / 2, - curr->r / 2)); + curr->r / 2, + curr->r / 2)); neighbors[curr->l + 1] = make_pair(curr->l, curr->r); neighbors[curr->r].first = curr->l + 1; } else if (curr->r == num_) { max_heap.emplace( make_shared(curr->l, curr->r - 1, - (curr->r - 1 - curr->l) / 2, - (curr->r - 1 - curr->l) / 2 + curr->l)); + (curr->r - 1 - curr->l) / 2, + (curr->r - 1 - curr->l) / 2 + curr->l)); neighbors[curr->r - 1] = make_pair(curr->l, curr->r); neighbors[curr->l].second = curr->r - 1; } else { max_heap.emplace( make_shared(curr->l, curr->pos, - (curr->pos - curr->l) / 2, - (curr->pos - curr->l) / 2 + curr->l)); + (curr->pos - curr->l) / 2, + (curr->pos - curr->l) / 2 + curr->l)); max_heap.emplace( make_shared(curr->pos, curr->r, - (curr->r - curr->pos) / 2, - (curr->r - curr->pos) / 2 + curr->pos)); + (curr->r - curr->pos) / 2, + (curr->r - curr->pos) / 2 + curr->pos)); neighbors[curr->pos] = make_pair(curr->l, curr->r); neighbors[curr->l].second = curr->pos; neighbors[curr->r].first = curr->pos; From f018478a203dc5fb0a0f91c64049eaa73b8d1beb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 14:54:01 +0800 Subject: [PATCH 4809/4971] Update exam-room.cpp --- C++/exam-room.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index 270e96f59..9101d3733 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -94,9 +94,9 @@ class ExamRoom { } }; - using S = shared_ptr; + template struct Compare { - bool operator()(const S& a, const S& b) { + bool operator()(const T& a, const T& b) { return a->dis == b->dis ? greater()(a->l, b->l) : less()(a->dis, b->dis); @@ -104,7 +104,8 @@ class ExamRoom { }; int num_; - priority_queue, Compare> max_heap; + using S = shared_ptr; + priority_queue, Compare> max_heap; unordered_map> neighbors; }; From 19aa553782f5fc608c4281bfdfcec68649ae2955 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 15:31:23 +0800 Subject: [PATCH 4810/4971] Update exam-room.cpp --- C++/exam-room.cpp | 70 +++++++++++++++++++++++------------------------ 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index 9101d3733..6b053466d 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -6,14 +6,14 @@ class ExamRoom { public: ExamRoom(int N) : num_(N) { max_heap.emplace(make_shared(-1, num_, num_, 0)); - neighbors[-1] = make_pair(-1, num_); - neighbors[num_] = make_pair(-1, num_); + seats[-1] = make_pair(-1, num_); + seats[num_] = make_pair(-1, num_); } int seat() { - while (!neighbors.count(max_heap.top()->l) || - !neighbors.count(max_heap.top()->r) || - neighbors.count(max_heap.top()->pos)) { + while (!seats.count(max_heap.top()->l) || + !seats.count(max_heap.top()->r) || + seats.count(max_heap.top()->pos)) { max_heap.pop(); // lazy deletion } const auto curr = max_heap.top(); max_heap.pop(); @@ -22,21 +22,21 @@ class ExamRoom { make_shared(curr->l + 1, curr->r, curr->r - 1, curr->r - 1)); - neighbors[curr->l + 1] = make_pair(curr->l, curr->r); + seats[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->l == -1) { max_heap.emplace( make_shared(curr->l + 1, curr->r, curr->r / 2, curr->r / 2)); - neighbors[curr->l + 1] = make_pair(curr->l, curr->r); - neighbors[curr->r].first = curr->l + 1; + seats[curr->l + 1] = make_pair(curr->l, curr->r); + seats[curr->r].first = curr->l + 1; } else if (curr->r == num_) { max_heap.emplace( make_shared(curr->l, curr->r - 1, (curr->r - 1 - curr->l) / 2, (curr->r - 1 - curr->l) / 2 + curr->l)); - neighbors[curr->r - 1] = make_pair(curr->l, curr->r); - neighbors[curr->l].second = curr->r - 1; + seats[curr->r - 1] = make_pair(curr->l, curr->r); + seats[curr->l].second = curr->r - 1; } else { max_heap.emplace( make_shared(curr->l, curr->pos, @@ -46,40 +46,40 @@ class ExamRoom { make_shared(curr->pos, curr->r, (curr->r - curr->pos) / 2, (curr->r - curr->pos) / 2 + curr->pos)); - neighbors[curr->pos] = make_pair(curr->l, curr->r); - neighbors[curr->l].second = curr->pos; - neighbors[curr->r].first = curr->pos; + seats[curr->pos] = make_pair(curr->l, curr->r); + seats[curr->l].second = curr->pos; + seats[curr->r].first = curr->pos; } return curr->pos; } void leave(int p) { - const auto nei = neighbors[p]; - neighbors.erase(p); - if (nei.first == -1 && nei.second == num_) { + const auto neighbors = seats[p]; + seats.erase(p); + if (neighbors.first == -1 && neighbors.second == num_) { max_heap.emplace( - make_shared(nei.first, nei.second, - nei.second, - nei.first + 1)); - } else if (nei.first == -1) { + make_shared(neighbors.first, neighbors.second, + neighbors.second, + neighbors.first + 1)); + } else if (neighbors.first == -1) { max_heap.emplace( - make_shared(nei.first, nei.second, - nei.second, - nei.first + 1)); - neighbors[nei.second].first = -1; - } else if (nei.second == num_) { + make_shared(neighbors.first, neighbors.second, + neighbors.second, + neighbors.first + 1)); + seats[neighbors.second].first = -1; + } else if (neighbors.second == num_) { max_heap.emplace( - make_shared(nei.first, nei.second, - nei.second - 1 - nei.first, - nei.second - 1)); - neighbors[nei.first].second = nei.second; + make_shared(neighbors.first, neighbors.second, + neighbors.second - 1 - neighbors.first, + neighbors.second - 1)); + seats[neighbors.first].second = neighbors.second; } else { max_heap.emplace( - make_shared(nei.first, nei.second, - (nei.second - nei.first) / 2, - (nei.second - nei.first) / 2 + nei.first)); - neighbors[nei.first].second = nei.second; - neighbors[nei.second].first = nei.first; + make_shared(neighbors.first, neighbors.second, + (neighbors.second - neighbors.first) / 2, + (neighbors.second - neighbors.first) / 2 + neighbors.first)); + seats[neighbors.first].second = neighbors.second; + seats[neighbors.second].first = neighbors.first; } } @@ -106,7 +106,7 @@ class ExamRoom { int num_; using S = shared_ptr; priority_queue, Compare> max_heap; - unordered_map> neighbors; + unordered_map> seats; }; /** From 3a62536435e89ceb3289647261c50a23b33b503c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 15:36:42 +0800 Subject: [PATCH 4811/4971] Update exam-room.cpp --- C++/exam-room.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index 6b053466d..f479dfd2c 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -66,7 +66,7 @@ class ExamRoom { make_shared(neighbors.first, neighbors.second, neighbors.second, neighbors.first + 1)); - seats[neighbors.second].first = -1; + seats[neighbors.second].first = neighbors.first; } else if (neighbors.second == num_) { max_heap.emplace( make_shared(neighbors.first, neighbors.second, From 22db1f0cfaab0775d81e6b2b8fa3544d80d9f1b7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 15:53:42 +0800 Subject: [PATCH 4812/4971] Update exam-room.cpp --- C++/exam-room.cpp | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index f479dfd2c..033ef7b9c 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -13,9 +13,11 @@ class ExamRoom { int seat() { while (!seats.count(max_heap.top()->l) || !seats.count(max_heap.top()->r) || - seats.count(max_heap.top()->pos)) { + seats[max_heap.top()->l].second != max_heap.top()->r || + seats[max_heap.top()->r].first != max_heap.top()->l) { max_heap.pop(); // lazy deletion } + const auto curr = max_heap.top(); max_heap.pop(); if (curr->l == -1 && curr->r == num_) { max_heap.emplace( @@ -29,14 +31,12 @@ class ExamRoom { curr->r / 2, curr->r / 2)); seats[curr->l + 1] = make_pair(curr->l, curr->r); - seats[curr->r].first = curr->l + 1; } else if (curr->r == num_) { max_heap.emplace( make_shared(curr->l, curr->r - 1, (curr->r - 1 - curr->l) / 2, (curr->r - 1 - curr->l) / 2 + curr->l)); seats[curr->r - 1] = make_pair(curr->l, curr->r); - seats[curr->l].second = curr->r - 1; } else { max_heap.emplace( make_shared(curr->l, curr->pos, @@ -47,9 +47,9 @@ class ExamRoom { (curr->r - curr->pos) / 2, (curr->r - curr->pos) / 2 + curr->pos)); seats[curr->pos] = make_pair(curr->l, curr->r); - seats[curr->l].second = curr->pos; - seats[curr->r].first = curr->pos; } + seats[curr->l].second = curr->pos; + seats[curr->r].first = curr->pos; return curr->pos; } @@ -66,21 +66,19 @@ class ExamRoom { make_shared(neighbors.first, neighbors.second, neighbors.second, neighbors.first + 1)); - seats[neighbors.second].first = neighbors.first; } else if (neighbors.second == num_) { max_heap.emplace( make_shared(neighbors.first, neighbors.second, neighbors.second - 1 - neighbors.first, neighbors.second - 1)); - seats[neighbors.first].second = neighbors.second; } else { max_heap.emplace( make_shared(neighbors.first, neighbors.second, (neighbors.second - neighbors.first) / 2, (neighbors.second - neighbors.first) / 2 + neighbors.first)); - seats[neighbors.first].second = neighbors.second; - seats[neighbors.second].first = neighbors.first; } + seats[neighbors.first].second = neighbors.second; + seats[neighbors.second].first = neighbors.first; } private: From 40e1570775add64a396ac436c3e200f32d1dc7f6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 15:58:10 +0800 Subject: [PATCH 4813/4971] Update exam-room.cpp --- C++/exam-room.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index 033ef7b9c..c2a7a9313 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -1,4 +1,4 @@ -// Time: seat: O(logn), +// Time: seat: O(logn) on average, // leave: O(logn) // Space: O(n) From c06a16ad1c4730a48a1e246579838a0bb0db2a91 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 16:41:07 +0800 Subject: [PATCH 4814/4971] Create k-similar-strings.cpp --- C++/k-similar-strings.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 C++/k-similar-strings.cpp diff --git a/C++/k-similar-strings.cpp b/C++/k-similar-strings.cpp new file mode 100644 index 000000000..e6984fc40 --- /dev/null +++ b/C++/k-similar-strings.cpp @@ -0,0 +1,38 @@ +// Time: O(s * s!/(a!*...*z!)), s is the length of A, B, +// a...z is the count of each alphabet, sum(a...z) = s +// Space: O(s * s!/(a!*...*z!)) + +class Solution { +public: + int kSimilarity(string A, string B) { + queue q; + unordered_set lookup; + + lookup.emplace(A); + q.emplace(A); + int result = 0; + while (!q.empty()) { + for (int size = q.size() - 1; size >= 0; --size) { + auto s = q.front(); q.pop(); + if (s == B) { + return result; + } + int i; + for (i = 0; s[i] == B[i]; ++i); + for (int j = i + 1; j < s.length(); ++j){ + if (s[j] == B[j] || s[i] != B[j]) { + continue; + } + swap(s[i], s[j]); + if (!lookup.count(s)) { + lookup.emplace(s); + q.emplace(s); + } + swap(s[i], s[j]); + } + } + ++result; + } + return result; + } +}; From f2144d7c9d01fa6c4e794b2c293a70f60cf1b189 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 18 Jun 2018 17:03:44 +0800 Subject: [PATCH 4815/4971] Create k-similar-strings.py --- Python/k-similar-strings.py | 72 +++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Python/k-similar-strings.py diff --git a/Python/k-similar-strings.py b/Python/k-similar-strings.py new file mode 100644 index 000000000..c67b2a383 --- /dev/null +++ b/Python/k-similar-strings.py @@ -0,0 +1,72 @@ +# Time: O(s * s!/(a!*...*z!)), s is the length of A, B, +# a...z is the count of each alphabet, +# sum(a...z) = s +# Space: O(s * s!/(a!*...*z!)) + +# Strings A and B are K-similar (for some non-negative integer K) +# if we can swap the positions of two letters +# in A exactly K times so that the resulting string equals B. +# +# Given two anagrams A and B, return the smallest K for which A and B are +# K-similar. +# +# Example 1: +# +# Input: A = "ab", B = "ba" +# Output: 1 +# Example 2: +# +# Input: A = "abc", B = "bca" +# Output: 2 +# Example 3: +# +# Input: A = "abac", B = "baca" +# Output: 2 +# Example 4: +# +# Input: A = "aabc", B = "abca" +# Output: 2 +# Note: +# - 1 <= A.length == B.length <= 20 +# - A and B contain only lowercase letters from +# the set {'a', 'b', 'c', 'd', 'e', 'f'} + +import collections + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def kSimilarity(self, A, B): + """ + :type A: str + :type B: str + :rtype: int + """ + def neighbors(s, B): + for i, c in enumerate(s): + if c != B[i]: + break + t = list(s) + for j in xrange(i+1, len(s)): + if t[j] == B[i]: + t[i], t[j] = t[j], t[i] + yield "".join(t) + t[j], t[i] = t[i], t[j] + + q = collections.deque([A]) + lookup = set() + result = 0 + while q: + for _ in xrange(len(q)): + s = q.popleft() + if s == B: + return result + for t in neighbors(s, B): + if t not in lookup: + lookup.add(t) + q.append(t) + result += 1 From 8ce0dbc6da017b9f5adc9fce50669db1cf6f73f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 17:29:04 +0800 Subject: [PATCH 4816/4971] Update exam-room.cpp --- C++/exam-room.cpp | 108 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index c2a7a9313..076f4e1b2 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -3,6 +3,114 @@ // Space: O(n) class ExamRoom { +public: + ExamRoom(int N) : num_(N) { + max_bst.emplace(make_shared(-1, num_, num_, 0)); + seats[-1] = make_pair(-1, num_); + seats[num_] = make_pair(-1, num_); + } + + int seat() { + while (!seats.count((*max_bst.cbegin())->l) || + !seats.count((*max_bst.cbegin())->r) || + seats[(*max_bst.cbegin())->l].second != (*max_bst.cbegin())->r || + seats[(*max_bst.cbegin())->r].first != (*max_bst.cbegin())->l) { + max_bst.erase(max_bst.begin()); // lazy deletion + } + + const auto curr = *max_bst.begin(); max_bst.erase(max_bst.begin()); + if (curr->l == -1 && curr->r == num_) { + max_bst.emplace( + make_shared(curr->l + 1, curr->r, + curr->r - 1, + curr->r - 1)); + seats[curr->l + 1] = make_pair(curr->l, curr->r); + } else if (curr->l == -1) { + max_bst.emplace( + make_shared(curr->l + 1, curr->r, + curr->r / 2, + curr->r / 2)); + seats[curr->l + 1] = make_pair(curr->l, curr->r); + } else if (curr->r == num_) { + max_bst.emplace( + make_shared(curr->l, curr->r - 1, + (curr->r - 1 - curr->l) / 2, + (curr->r - 1 - curr->l) / 2 + curr->l)); + seats[curr->r - 1] = make_pair(curr->l, curr->r); + } else { + max_bst.emplace( + make_shared(curr->l, curr->pos, + (curr->pos - curr->l) / 2, + (curr->pos - curr->l) / 2 + curr->l)); + max_bst.emplace( + make_shared(curr->pos, curr->r, + (curr->r - curr->pos) / 2, + (curr->r - curr->pos) / 2 + curr->pos)); + seats[curr->pos] = make_pair(curr->l, curr->r); + } + seats[curr->l].second = curr->pos; + seats[curr->r].first = curr->pos; + return curr->pos; + } + + void leave(int p) { + const auto neighbors = seats[p]; + seats.erase(p); + if (neighbors.first == -1 && neighbors.second == num_) { + max_bst.emplace( + make_shared(neighbors.first, neighbors.second, + neighbors.second, + neighbors.first + 1)); + } else if (neighbors.first == -1) { + max_bst.emplace( + make_shared(neighbors.first, neighbors.second, + neighbors.second, + neighbors.first + 1)); + } else if (neighbors.second == num_) { + max_bst.emplace( + make_shared(neighbors.first, neighbors.second, + neighbors.second - 1 - neighbors.first, + neighbors.second - 1)); + } else { + max_bst.emplace( + make_shared(neighbors.first, neighbors.second, + (neighbors.second - neighbors.first) / 2, + (neighbors.second - neighbors.first) / 2 + neighbors.first)); + } + seats[neighbors.first].second = neighbors.second; + seats[neighbors.second].first = neighbors.first; + } + +private: + struct Segment { + int l; + int r; + int dis; + int pos; + Segment(int l, int r, int dis, int pos) : + l(l), r(r), dis(dis), pos(pos) { + } + }; + + template + struct Compare { + bool operator()(const T& a, const T& b) { + return a->dis == b->dis ? + less()(a->l, b->l) : + greater()(a->dis, b->dis); + } + }; + + int num_; + using S = shared_ptr; + multiset> max_bst; + unordered_map> seats; +}; + +// Time: seat: O(logn) on average, +// leave: O(logn) +// Space: O(n) +class ExamRoom2 { public: ExamRoom(int N) : num_(N) { max_heap.emplace(make_shared(-1, num_, num_, 0)); From efd0e783ecd1c9a51c789dbf28436610a8957bdb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 17:39:36 +0800 Subject: [PATCH 4817/4971] Update exam-room.cpp --- C++/exam-room.cpp | 120 +++++++++++++++++++++++----------------------- 1 file changed, 60 insertions(+), 60 deletions(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index 076f4e1b2..313312aea 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -5,80 +5,80 @@ class ExamRoom { public: ExamRoom(int N) : num_(N) { - max_bst.emplace(make_shared(-1, num_, num_, 0)); - seats[-1] = make_pair(-1, num_); - seats[num_] = make_pair(-1, num_); + max_bst_.emplace(make_shared(-1, num_, num_, 0)); + seats_[-1] = make_pair(-1, num_); + seats_[num_] = make_pair(-1, num_); } int seat() { - while (!seats.count((*max_bst.cbegin())->l) || - !seats.count((*max_bst.cbegin())->r) || - seats[(*max_bst.cbegin())->l].second != (*max_bst.cbegin())->r || - seats[(*max_bst.cbegin())->r].first != (*max_bst.cbegin())->l) { - max_bst.erase(max_bst.begin()); // lazy deletion + while (!seats_.count((*max_bst_.cbegin())->l) || + !seats_.count((*max_bst_.cbegin())->r) || + seats_[(*max_bst_.cbegin())->l].second != (*max_bst_.cbegin())->r || + seats_[(*max_bst_.cbegin())->r].first != (*max_bst_.cbegin())->l) { + max_bst_.erase(max_bst_.begin()); // lazy deletion } - const auto curr = *max_bst.begin(); max_bst.erase(max_bst.begin()); + const auto curr = *max_bst_.begin(); max_bst_.erase(max_bst_.begin()); if (curr->l == -1 && curr->r == num_) { - max_bst.emplace( + max_bst_.emplace( make_shared(curr->l + 1, curr->r, curr->r - 1, curr->r - 1)); - seats[curr->l + 1] = make_pair(curr->l, curr->r); + seats_[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->l == -1) { - max_bst.emplace( + max_bst_.emplace( make_shared(curr->l + 1, curr->r, curr->r / 2, curr->r / 2)); - seats[curr->l + 1] = make_pair(curr->l, curr->r); + seats_[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->r == num_) { - max_bst.emplace( + max_bst_.emplace( make_shared(curr->l, curr->r - 1, (curr->r - 1 - curr->l) / 2, (curr->r - 1 - curr->l) / 2 + curr->l)); - seats[curr->r - 1] = make_pair(curr->l, curr->r); + seats_[curr->r - 1] = make_pair(curr->l, curr->r); } else { - max_bst.emplace( + max_bst_.emplace( make_shared(curr->l, curr->pos, (curr->pos - curr->l) / 2, (curr->pos - curr->l) / 2 + curr->l)); - max_bst.emplace( + max_bst_.emplace( make_shared(curr->pos, curr->r, (curr->r - curr->pos) / 2, (curr->r - curr->pos) / 2 + curr->pos)); - seats[curr->pos] = make_pair(curr->l, curr->r); + seats_[curr->pos] = make_pair(curr->l, curr->r); } - seats[curr->l].second = curr->pos; - seats[curr->r].first = curr->pos; + seats_[curr->l].second = curr->pos; + seats_[curr->r].first = curr->pos; return curr->pos; } void leave(int p) { - const auto neighbors = seats[p]; - seats.erase(p); + const auto neighbors = seats_[p]; + seats_.erase(p); if (neighbors.first == -1 && neighbors.second == num_) { - max_bst.emplace( + max_bst_.emplace( make_shared(neighbors.first, neighbors.second, neighbors.second, neighbors.first + 1)); } else if (neighbors.first == -1) { - max_bst.emplace( + max_bst_.emplace( make_shared(neighbors.first, neighbors.second, neighbors.second, neighbors.first + 1)); } else if (neighbors.second == num_) { - max_bst.emplace( + max_bst_.emplace( make_shared(neighbors.first, neighbors.second, neighbors.second - 1 - neighbors.first, neighbors.second - 1)); } else { - max_bst.emplace( + max_bst_.emplace( make_shared(neighbors.first, neighbors.second, (neighbors.second - neighbors.first) / 2, (neighbors.second - neighbors.first) / 2 + neighbors.first)); } - seats[neighbors.first].second = neighbors.second; - seats[neighbors.second].first = neighbors.first; + seats_[neighbors.first].second = neighbors.second; + seats_[neighbors.second].first = neighbors.first; } private: @@ -103,8 +103,8 @@ class ExamRoom { int num_; using S = shared_ptr; - multiset> max_bst; - unordered_map> seats; + multiset> max_bst_; + unordered_map> seats_; }; // Time: seat: O(logn) on average, @@ -113,80 +113,80 @@ class ExamRoom { class ExamRoom2 { public: ExamRoom(int N) : num_(N) { - max_heap.emplace(make_shared(-1, num_, num_, 0)); - seats[-1] = make_pair(-1, num_); - seats[num_] = make_pair(-1, num_); + max_heap_.emplace(make_shared(-1, num_, num_, 0)); + seats_[-1] = make_pair(-1, num_); + seats_[num_] = make_pair(-1, num_); } int seat() { - while (!seats.count(max_heap.top()->l) || - !seats.count(max_heap.top()->r) || - seats[max_heap.top()->l].second != max_heap.top()->r || - seats[max_heap.top()->r].first != max_heap.top()->l) { - max_heap.pop(); // lazy deletion + while (!seats_.count(max_heap_.top()->l) || + !seats_.count(max_heap_.top()->r) || + seats_[max_heap_.top()->l].second != max_heap_.top()->r || + seats_[max_heap_.top()->r].first != max_heap_.top()->l) { + max_heap_.pop(); // lazy deletion } - const auto curr = max_heap.top(); max_heap.pop(); + const auto curr = max_heap_.top(); max_heap_.pop(); if (curr->l == -1 && curr->r == num_) { - max_heap.emplace( + max_heap_.emplace( make_shared(curr->l + 1, curr->r, curr->r - 1, curr->r - 1)); - seats[curr->l + 1] = make_pair(curr->l, curr->r); + seats_[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->l == -1) { - max_heap.emplace( + max_heap_.emplace( make_shared(curr->l + 1, curr->r, curr->r / 2, curr->r / 2)); - seats[curr->l + 1] = make_pair(curr->l, curr->r); + seats_[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->r == num_) { - max_heap.emplace( + max_heap_.emplace( make_shared(curr->l, curr->r - 1, (curr->r - 1 - curr->l) / 2, (curr->r - 1 - curr->l) / 2 + curr->l)); - seats[curr->r - 1] = make_pair(curr->l, curr->r); + seats_[curr->r - 1] = make_pair(curr->l, curr->r); } else { - max_heap.emplace( + max_heap_.emplace( make_shared(curr->l, curr->pos, (curr->pos - curr->l) / 2, (curr->pos - curr->l) / 2 + curr->l)); - max_heap.emplace( + max_heap_.emplace( make_shared(curr->pos, curr->r, (curr->r - curr->pos) / 2, (curr->r - curr->pos) / 2 + curr->pos)); - seats[curr->pos] = make_pair(curr->l, curr->r); + seats_[curr->pos] = make_pair(curr->l, curr->r); } - seats[curr->l].second = curr->pos; - seats[curr->r].first = curr->pos; + seats_[curr->l].second = curr->pos; + seats_[curr->r].first = curr->pos; return curr->pos; } void leave(int p) { - const auto neighbors = seats[p]; - seats.erase(p); + const auto neighbors = seats_[p]; + seats_.erase(p); if (neighbors.first == -1 && neighbors.second == num_) { - max_heap.emplace( + max_heap_.emplace( make_shared(neighbors.first, neighbors.second, neighbors.second, neighbors.first + 1)); } else if (neighbors.first == -1) { - max_heap.emplace( + max_heap_.emplace( make_shared(neighbors.first, neighbors.second, neighbors.second, neighbors.first + 1)); } else if (neighbors.second == num_) { - max_heap.emplace( + max_heap_.emplace( make_shared(neighbors.first, neighbors.second, neighbors.second - 1 - neighbors.first, neighbors.second - 1)); } else { - max_heap.emplace( + max_heap_.emplace( make_shared(neighbors.first, neighbors.second, (neighbors.second - neighbors.first) / 2, (neighbors.second - neighbors.first) / 2 + neighbors.first)); } - seats[neighbors.first].second = neighbors.second; - seats[neighbors.second].first = neighbors.first; + seats_[neighbors.first].second = neighbors.second; + seats_[neighbors.second].first = neighbors.first; } private: @@ -211,8 +211,8 @@ class ExamRoom2 { int num_; using S = shared_ptr; - priority_queue, Compare> max_heap; - unordered_map> seats; + priority_queue, Compare> max_heap_; + unordered_map> seats_; }; /** From 5e16df584c4e0c24a004545cc065a4a0d59e0f22 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 17:40:11 +0800 Subject: [PATCH 4818/4971] Update exam-room.cpp --- C++/exam-room.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index 313312aea..a49d68c77 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -112,7 +112,7 @@ class ExamRoom { // Space: O(n) class ExamRoom2 { public: - ExamRoom(int N) : num_(N) { + ExamRoom2(int N) : num_(N) { max_heap_.emplace(make_shared(-1, num_, num_, 0)); seats_[-1] = make_pair(-1, num_); seats_[num_] = make_pair(-1, num_); From 0db7f3511ddc00f2c373bdd43a531fcc8b68dbdb Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 18:06:03 +0800 Subject: [PATCH 4819/4971] Update exam-room.cpp --- C++/exam-room.cpp | 129 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 126 insertions(+), 3 deletions(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index a49d68c77..fa0ca7098 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -1,10 +1,133 @@ -// Time: seat: O(logn) on average, +// Time: seat: O(logn), // leave: O(logn) // Space: O(n) class ExamRoom { public: ExamRoom(int N) : num_(N) { + segment_iters_[make_pair(-1, num_)] = + max_bst_.emplace(make_shared(-1, num_, num_, 0)); + seats_[-1] = make_pair(-1, num_); + seats_[num_] = make_pair(-1, num_); + } + + int seat() { + const auto curr = *max_bst_.begin(); max_bst_.erase(max_bst_.begin()); + segment_iters_.erase(make_pair(curr->l, curr->r)); + if (curr->l == -1 && curr->r == num_) { + segment_iters_[make_pair(curr->l + 1, curr->r)] = max_bst_.emplace( + make_shared(curr->l + 1, curr->r, + curr->r - 1, + curr->r - 1)); + seats_[curr->l + 1] = make_pair(curr->l, curr->r); + } else if (curr->l == -1) { + segment_iters_[make_pair(curr->l + 1, curr->r)] = max_bst_.emplace( + make_shared(curr->l + 1, curr->r, + curr->r / 2, + curr->r / 2)); + seats_[curr->l + 1] = make_pair(curr->l, curr->r); + } else if (curr->r == num_) { + segment_iters_[make_pair(curr->l, curr->r - 1)] = max_bst_.emplace( + make_shared(curr->l, curr->r - 1, + (curr->r - 1 - curr->l) / 2, + (curr->r - 1 - curr->l) / 2 + curr->l)); + seats_[curr->r - 1] = make_pair(curr->l, curr->r); + } else { + segment_iters_[make_pair(curr->l, curr->pos)] = max_bst_.emplace( + make_shared(curr->l, curr->pos, + (curr->pos - curr->l) / 2, + (curr->pos - curr->l) / 2 + curr->l)); + segment_iters_[make_pair(curr->pos, curr->r)] = max_bst_.emplace( + make_shared(curr->pos, curr->r, + (curr->r - curr->pos) / 2, + (curr->r - curr->pos) / 2 + curr->pos)); + seats_[curr->pos] = make_pair(curr->l, curr->r); + } + seats_[curr->l].second = curr->pos; + seats_[curr->r].first = curr->pos; + return curr->pos; + } + + void leave(int p) { + const auto neighbors = seats_[p]; + seats_.erase(p); + const auto& left_segment = make_pair(neighbors.first, p); + const auto& right_segment = make_pair(p, neighbors.second); + if (segment_iters_.count(left_segment)) { + max_bst_.erase(segment_iters_[left_segment]); segment_iters_.erase(left_segment); + } + if (segment_iters_.count(right_segment)) { + max_bst_.erase(segment_iters_[right_segment]); segment_iters_.erase(right_segment); + } + + if (neighbors.first == -1 && neighbors.second == num_) { + segment_iters_[neighbors] = max_bst_.emplace( + make_shared(neighbors.first, neighbors.second, + neighbors.second, + neighbors.first + 1)); + } else if (neighbors.first == -1) { + segment_iters_[neighbors] = max_bst_.emplace( + make_shared(neighbors.first, neighbors.second, + neighbors.second, + neighbors.first + 1)); + } else if (neighbors.second == num_) { + segment_iters_[neighbors] = max_bst_.emplace( + make_shared(neighbors.first, neighbors.second, + neighbors.second - 1 - neighbors.first, + neighbors.second - 1)); + } else { + segment_iters_[neighbors] = max_bst_.emplace( + make_shared(neighbors.first, neighbors.second, + (neighbors.second - neighbors.first) / 2, + (neighbors.second - neighbors.first) / 2 + neighbors.first)); + } + seats_[neighbors.first].second = neighbors.second; + seats_[neighbors.second].first = neighbors.first; + } + +private: + struct Segment { + int l; + int r; + int dis; + int pos; + Segment(int l, int r, int dis, int pos) : + l(l), r(r), dis(dis), pos(pos) { + } + }; + + template + struct Compare { + bool operator()(const T& a, const T& b) { + return a->dis == b->dis ? + less()(a->l, b->l) : + greater()(a->dis, b->dis); + } + }; + + template + struct PairHash { + size_t operator()(const pair& p) const { + size_t seed = 0; + seed ^= std::hash{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2); + seed ^= std::hash{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2); + return seed; + } + }; + + int num_; + using S = shared_ptr; + multiset> max_bst_; + unordered_map> seats_; + unordered_map, multiset>::iterator, PairHash> segment_iters_; +}; + +// Time: seat: O(logn) on average, +// leave: O(logn) +// Space: O(n) +class ExamRoom2 { +public: + ExamRoom2(int N) : num_(N) { max_bst_.emplace(make_shared(-1, num_, num_, 0)); seats_[-1] = make_pair(-1, num_); seats_[num_] = make_pair(-1, num_); @@ -110,9 +233,9 @@ class ExamRoom { // Time: seat: O(logn) on average, // leave: O(logn) // Space: O(n) -class ExamRoom2 { +class ExamRoom3 { public: - ExamRoom2(int N) : num_(N) { + ExamRoom3(int N) : num_(N) { max_heap_.emplace(make_shared(-1, num_, num_, 0)); seats_[-1] = make_pair(-1, num_); seats_[num_] = make_pair(-1, num_); From 3cc2604ed258eb6a79a5847786eeb979b9a70803 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 18:13:34 +0800 Subject: [PATCH 4820/4971] Update exam-room.cpp --- C++/exam-room.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index fa0ca7098..642dff8a5 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -52,10 +52,10 @@ class ExamRoom { const auto neighbors = seats_[p]; seats_.erase(p); const auto& left_segment = make_pair(neighbors.first, p); - const auto& right_segment = make_pair(p, neighbors.second); if (segment_iters_.count(left_segment)) { max_bst_.erase(segment_iters_[left_segment]); segment_iters_.erase(left_segment); } + const auto& right_segment = make_pair(p, neighbors.second); if (segment_iters_.count(right_segment)) { max_bst_.erase(segment_iters_[right_segment]); segment_iters_.erase(right_segment); } From d9d6d842bbce022fe23040b4544294b6ecdc2656 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 18:31:09 +0800 Subject: [PATCH 4821/4971] Update exam-room.cpp --- C++/exam-room.cpp | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index 642dff8a5..41af8c3e1 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -19,19 +19,17 @@ class ExamRoom { make_shared(curr->l + 1, curr->r, curr->r - 1, curr->r - 1)); - seats_[curr->l + 1] = make_pair(curr->l, curr->r); + } else if (curr->l == -1) { segment_iters_[make_pair(curr->l + 1, curr->r)] = max_bst_.emplace( make_shared(curr->l + 1, curr->r, curr->r / 2, curr->r / 2)); - seats_[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->r == num_) { segment_iters_[make_pair(curr->l, curr->r - 1)] = max_bst_.emplace( make_shared(curr->l, curr->r - 1, (curr->r - 1 - curr->l) / 2, (curr->r - 1 - curr->l) / 2 + curr->l)); - seats_[curr->r - 1] = make_pair(curr->l, curr->r); } else { segment_iters_[make_pair(curr->l, curr->pos)] = max_bst_.emplace( make_shared(curr->l, curr->pos, @@ -41,8 +39,8 @@ class ExamRoom { make_shared(curr->pos, curr->r, (curr->r - curr->pos) / 2, (curr->r - curr->pos) / 2 + curr->pos)); - seats_[curr->pos] = make_pair(curr->l, curr->r); } + seats_[curr->pos] = make_pair(curr->l, curr->r); seats_[curr->l].second = curr->pos; seats_[curr->r].first = curr->pos; return curr->pos; @@ -147,19 +145,16 @@ class ExamRoom2 { make_shared(curr->l + 1, curr->r, curr->r - 1, curr->r - 1)); - seats_[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->l == -1) { max_bst_.emplace( make_shared(curr->l + 1, curr->r, curr->r / 2, curr->r / 2)); - seats_[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->r == num_) { max_bst_.emplace( make_shared(curr->l, curr->r - 1, (curr->r - 1 - curr->l) / 2, (curr->r - 1 - curr->l) / 2 + curr->l)); - seats_[curr->r - 1] = make_pair(curr->l, curr->r); } else { max_bst_.emplace( make_shared(curr->l, curr->pos, @@ -169,8 +164,8 @@ class ExamRoom2 { make_shared(curr->pos, curr->r, (curr->r - curr->pos) / 2, (curr->r - curr->pos) / 2 + curr->pos)); - seats_[curr->pos] = make_pair(curr->l, curr->r); } + seats_[curr->pos] = make_pair(curr->l, curr->r); seats_[curr->l].second = curr->pos; seats_[curr->r].first = curr->pos; return curr->pos; @@ -255,19 +250,16 @@ class ExamRoom3 { make_shared(curr->l + 1, curr->r, curr->r - 1, curr->r - 1)); - seats_[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->l == -1) { max_heap_.emplace( make_shared(curr->l + 1, curr->r, curr->r / 2, curr->r / 2)); - seats_[curr->l + 1] = make_pair(curr->l, curr->r); } else if (curr->r == num_) { max_heap_.emplace( make_shared(curr->l, curr->r - 1, (curr->r - 1 - curr->l) / 2, (curr->r - 1 - curr->l) / 2 + curr->l)); - seats_[curr->r - 1] = make_pair(curr->l, curr->r); } else { max_heap_.emplace( make_shared(curr->l, curr->pos, @@ -277,8 +269,8 @@ class ExamRoom3 { make_shared(curr->pos, curr->r, (curr->r - curr->pos) / 2, (curr->r - curr->pos) / 2 + curr->pos)); - seats_[curr->pos] = make_pair(curr->l, curr->r); } + seats_[curr->pos] = make_pair(curr->l, curr->r); seats_[curr->l].second = curr->pos; seats_[curr->r].first = curr->pos; return curr->pos; From b44f79537edc4909bfd335d9418aaaf567c1b15a Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 18:34:55 +0800 Subject: [PATCH 4822/4971] Update exam-room.cpp --- C++/exam-room.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index 41af8c3e1..c6832d80d 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -19,7 +19,6 @@ class ExamRoom { make_shared(curr->l + 1, curr->r, curr->r - 1, curr->r - 1)); - } else if (curr->l == -1) { segment_iters_[make_pair(curr->l + 1, curr->r)] = max_bst_.emplace( make_shared(curr->l + 1, curr->r, From 4f0e82c8f95815ce197d7ce9e58c3f30422d1fa7 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 18 Jun 2018 19:07:20 +0800 Subject: [PATCH 4823/4971] Create exam-room.py --- Python/exam-room.py | 133 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 Python/exam-room.py diff --git a/Python/exam-room.py b/Python/exam-room.py new file mode 100644 index 000000000..74be3b964 --- /dev/null +++ b/Python/exam-room.py @@ -0,0 +1,133 @@ +# Time: seat: O(logn) on average, +# leave: O(logn) +# Space: O(n) + +# In an exam room, there are N seats in a single row, +# numbered 0, 1, 2, ..., N-1. +# +# When a student enters the room, +# they must sit in the seat that maximizes the distance to the closest person. +# If there are multiple such seats, they sit in the seat with +# the lowest number. +# (Also, if no one is in the room, then the student sits at seat number 0.) +# +# Return a class ExamRoom(int N) that exposes two functions: +# ExamRoom.seat() returning an int representing what seat the student sat in, +# and ExamRoom.leave(int p) representing that the student in seat number p now +# leaves the room. +# It is guaranteed that any calls to ExamRoom.leave(p) have a student sitting +# in seat p. +# +# Example 1: +# +# Input: ["ExamRoom","seat","seat","seat","seat","leave","seat"], +# [[10],[],[],[],[],[4],[]] +# Output: [null,0,9,4,2,null,5] +# Explanation: +# ExamRoom(10) -> null +# seat() -> 0, no one is in the room, then the student sits at seat number 0. +# seat() -> 9, the student sits at the last seat number 9. +# seat() -> 4, the student sits at the last seat number 4. +# seat() -> 2, the student sits at the last seat number 2. +# leave(4) -> null +# seat() -> 5, the student sits at the last seat number 5. +# +# Note: +# - 1 <= N <= 10^9 +# - ExamRoom.seat() and ExamRoom.leave() will be called at most 10^4 times +# across all test cases. +# - Calls to ExamRoom.leave(p) are guaranteed to have a student currently +# sitting in seat number p. + + +import heapq + +LEN, POS, L, R = range(4) +LEFT, RIGHT = range(2) + + +class ExamRoom(object): + + def __init__(self, N): + """ + :type N: int + """ + self.__num = N + self.__max_heap = [(-self.__num, 0, -1, self.__num)] + self.__seats = {} + self.__seats[-1] = [-1, self.__num] + self.__seats[self.__num] = [-1, self.__num] + + def seat(self): + """ + :rtype: int + """ + while self.__max_heap[0][L] not in self.__seats or \ + self.__max_heap[0][R] not in self.__seats or \ + self.__seats[self.__max_heap[0][L]][RIGHT] != \ + self.__max_heap[0][R] or \ + self.__seats[self.__max_heap[0][R]][LEFT] != \ + self.__max_heap[0][L]: + heapq.heappop(self.__max_heap) # lazy deletion + + curr = heapq.heappop(self.__max_heap) + if curr[L] == -1 and curr[R] == self.__num: + heapq.heappush(self.__max_heap, (-(curr[R]-1), + curr[R]-1, + curr[L]+1, curr[R])) + elif curr[L] == -1: + heapq.heappush(self.__max_heap, (-(curr[R]//2), + curr[R]//2, + curr[L]+1, curr[R])) + elif curr[R] == self.__num: + heapq.heappush(self.__max_heap, (-((curr[R]-1-curr[L])//2), + (curr[R]-1-curr[L])//2+curr[L], + curr[L], curr[R]-1)) + else: + heapq.heappush(self.__max_heap, (-((curr[POS]-curr[L])//2), + (curr[POS]-curr[L])//2+curr[L], + curr[L], curr[POS])) + heapq.heappush(self.__max_heap, (-((curr[R]-curr[POS])//2), + (curr[R]-curr[POS])//2+curr[POS], + curr[POS], curr[R])) + self.__seats[curr[POS]] = [curr[L], curr[R]] + self.__seats[curr[L]][RIGHT] = curr[POS] + self.__seats[curr[R]][LEFT] = curr[POS] + return curr[POS] + + def leave(self, p): + """ + :type p: int + :rtype: void + """ + neighbors = self.__seats[p] + self.__seats.pop(p) + if neighbors[LEFT] == -1 and neighbors[RIGHT] == self.__num: + heapq.heappush(self.__max_heap, + (-neighbors[RIGHT], + neighbors[LEFT]+1, + neighbors[LEFT], neighbors[RIGHT])) + elif neighbors[LEFT] == -1: + heapq.heappush(self.__max_heap, + (-neighbors[RIGHT], + neighbors[LEFT]+1, + neighbors[LEFT], neighbors[RIGHT])) + elif neighbors[RIGHT] == self.__num: + heapq.heappush(self.__max_heap, + (-(neighbors[RIGHT]-1-neighbors[LEFT]), + neighbors[RIGHT]-1, + neighbors[LEFT], neighbors[RIGHT])) + else: + heapq.heappush(self.__max_heap, + (-((neighbors[RIGHT]-neighbors[LEFT])//2), + (neighbors[RIGHT]-neighbors[LEFT])//2 + + neighbors[LEFT], + neighbors[LEFT], neighbors[RIGHT])) + self.__seats[neighbors[LEFT]][RIGHT] = neighbors[RIGHT] + self.__seats[neighbors[RIGHT]][LEFT] = neighbors[LEFT] + + +# Your ExamRoom object will be instantiated and called as such: +# obj = ExamRoom(N) +# param_1 = obj.seat() +# obj.leave(p) From 3f87c53317d3eb9332062596dc92ddf06866fb09 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 19:20:50 +0800 Subject: [PATCH 4824/4971] Update exam-room.cpp --- C++/exam-room.cpp | 180 +++++++++++++++++++++++----------------------- 1 file changed, 90 insertions(+), 90 deletions(-) diff --git a/C++/exam-room.cpp b/C++/exam-room.cpp index c6832d80d..91ef117a4 100644 --- a/C++/exam-room.cpp +++ b/C++/exam-room.cpp @@ -6,7 +6,7 @@ class ExamRoom { public: ExamRoom(int N) : num_(N) { segment_iters_[make_pair(-1, num_)] = - max_bst_.emplace(make_shared(-1, num_, num_, 0)); + max_bst_.emplace(make_shared(num_, 0, -1, num_)); seats_[-1] = make_pair(-1, num_); seats_[num_] = make_pair(-1, num_); } @@ -16,28 +16,28 @@ class ExamRoom { segment_iters_.erase(make_pair(curr->l, curr->r)); if (curr->l == -1 && curr->r == num_) { segment_iters_[make_pair(curr->l + 1, curr->r)] = max_bst_.emplace( - make_shared(curr->l + 1, curr->r, + make_shared(curr->r - 1, curr->r - 1, - curr->r - 1)); + curr->l + 1, curr->r)); } else if (curr->l == -1) { segment_iters_[make_pair(curr->l + 1, curr->r)] = max_bst_.emplace( - make_shared(curr->l + 1, curr->r, + make_shared(curr->r / 2, curr->r / 2, - curr->r / 2)); + curr->l + 1, curr->r)); } else if (curr->r == num_) { segment_iters_[make_pair(curr->l, curr->r - 1)] = max_bst_.emplace( - make_shared(curr->l, curr->r - 1, - (curr->r - 1 - curr->l) / 2, - (curr->r - 1 - curr->l) / 2 + curr->l)); + make_shared((curr->r - 1 - curr->l) / 2, + (curr->r - 1 - curr->l) / 2 + curr->l, + curr->l, curr->r - 1)); } else { segment_iters_[make_pair(curr->l, curr->pos)] = max_bst_.emplace( - make_shared(curr->l, curr->pos, - (curr->pos - curr->l) / 2, - (curr->pos - curr->l) / 2 + curr->l)); + make_shared((curr->pos - curr->l) / 2, + (curr->pos - curr->l) / 2 + curr->l, + curr->l, curr->pos)); segment_iters_[make_pair(curr->pos, curr->r)] = max_bst_.emplace( - make_shared(curr->pos, curr->r, - (curr->r - curr->pos) / 2, - (curr->r - curr->pos) / 2 + curr->pos)); + make_shared((curr->r - curr->pos) / 2, + (curr->r - curr->pos) / 2 + curr->pos, + curr->pos, curr->r)); } seats_[curr->pos] = make_pair(curr->l, curr->r); seats_[curr->l].second = curr->pos; @@ -59,24 +59,24 @@ class ExamRoom { if (neighbors.first == -1 && neighbors.second == num_) { segment_iters_[neighbors] = max_bst_.emplace( - make_shared(neighbors.first, neighbors.second, - neighbors.second, - neighbors.first + 1)); + make_shared(neighbors.second, + neighbors.first + 1, + neighbors.first, neighbors.second)); } else if (neighbors.first == -1) { segment_iters_[neighbors] = max_bst_.emplace( - make_shared(neighbors.first, neighbors.second, - neighbors.second, - neighbors.first + 1)); + make_shared(neighbors.second, + neighbors.first + 1, + neighbors.first, neighbors.second)); } else if (neighbors.second == num_) { segment_iters_[neighbors] = max_bst_.emplace( - make_shared(neighbors.first, neighbors.second, - neighbors.second - 1 - neighbors.first, - neighbors.second - 1)); + make_shared(neighbors.second - 1 - neighbors.first, + neighbors.second - 1, + neighbors.first, neighbors.second)); } else { segment_iters_[neighbors] = max_bst_.emplace( - make_shared(neighbors.first, neighbors.second, - (neighbors.second - neighbors.first) / 2, - (neighbors.second - neighbors.first) / 2 + neighbors.first)); + make_shared((neighbors.second - neighbors.first) / 2, + (neighbors.second - neighbors.first) / 2 + neighbors.first, + neighbors.first, neighbors.second)); } seats_[neighbors.first].second = neighbors.second; seats_[neighbors.second].first = neighbors.first; @@ -84,12 +84,12 @@ class ExamRoom { private: struct Segment { - int l; - int r; int dis; int pos; - Segment(int l, int r, int dis, int pos) : - l(l), r(r), dis(dis), pos(pos) { + int l; + int r; + Segment(int dis, int pos, int l, int r) : + dis(dis), pos(pos), l(l), r(r) { } }; @@ -125,7 +125,7 @@ class ExamRoom { class ExamRoom2 { public: ExamRoom2(int N) : num_(N) { - max_bst_.emplace(make_shared(-1, num_, num_, 0)); + max_bst_.emplace(make_shared(num_, 0, -1, num_)); seats_[-1] = make_pair(-1, num_); seats_[num_] = make_pair(-1, num_); } @@ -141,28 +141,28 @@ class ExamRoom2 { const auto curr = *max_bst_.begin(); max_bst_.erase(max_bst_.begin()); if (curr->l == -1 && curr->r == num_) { max_bst_.emplace( - make_shared(curr->l + 1, curr->r, + make_shared(curr->r - 1, curr->r - 1, - curr->r - 1)); + curr->l + 1, curr->r)); } else if (curr->l == -1) { max_bst_.emplace( - make_shared(curr->l + 1, curr->r, + make_shared(curr->r / 2, curr->r / 2, - curr->r / 2)); + curr->l + 1, curr->r)); } else if (curr->r == num_) { max_bst_.emplace( - make_shared(curr->l, curr->r - 1, - (curr->r - 1 - curr->l) / 2, - (curr->r - 1 - curr->l) / 2 + curr->l)); + make_shared((curr->r - 1 - curr->l) / 2, + (curr->r - 1 - curr->l) / 2 + curr->l, + curr->l, curr->r - 1)); } else { max_bst_.emplace( - make_shared(curr->l, curr->pos, - (curr->pos - curr->l) / 2, - (curr->pos - curr->l) / 2 + curr->l)); + make_shared((curr->pos - curr->l) / 2, + (curr->pos - curr->l) / 2 + curr->l, + curr->l, curr->pos)); max_bst_.emplace( - make_shared(curr->pos, curr->r, - (curr->r - curr->pos) / 2, - (curr->r - curr->pos) / 2 + curr->pos)); + make_shared((curr->r - curr->pos) / 2, + (curr->r - curr->pos) / 2 + curr->pos, + curr->pos, curr->r)); } seats_[curr->pos] = make_pair(curr->l, curr->r); seats_[curr->l].second = curr->pos; @@ -175,24 +175,24 @@ class ExamRoom2 { seats_.erase(p); if (neighbors.first == -1 && neighbors.second == num_) { max_bst_.emplace( - make_shared(neighbors.first, neighbors.second, - neighbors.second, - neighbors.first + 1)); + make_shared(neighbors.second, + neighbors.first + 1, + neighbors.first, neighbors.second)); } else if (neighbors.first == -1) { max_bst_.emplace( - make_shared(neighbors.first, neighbors.second, - neighbors.second, - neighbors.first + 1)); + make_shared(neighbors.second, + neighbors.first + 1, + neighbors.first, neighbors.second)); } else if (neighbors.second == num_) { max_bst_.emplace( - make_shared(neighbors.first, neighbors.second, - neighbors.second - 1 - neighbors.first, - neighbors.second - 1)); + make_shared(neighbors.second - 1 - neighbors.first, + neighbors.second - 1, + neighbors.first, neighbors.second)); } else { max_bst_.emplace( - make_shared(neighbors.first, neighbors.second, - (neighbors.second - neighbors.first) / 2, - (neighbors.second - neighbors.first) / 2 + neighbors.first)); + make_shared((neighbors.second - neighbors.first) / 2, + (neighbors.second - neighbors.first) / 2 + neighbors.first, + neighbors.first, neighbors.second)); } seats_[neighbors.first].second = neighbors.second; seats_[neighbors.second].first = neighbors.first; @@ -200,12 +200,12 @@ class ExamRoom2 { private: struct Segment { - int l; - int r; int dis; int pos; - Segment(int l, int r, int dis, int pos) : - l(l), r(r), dis(dis), pos(pos) { + int l; + int r; + Segment(int dis, int pos, int l, int r) : + dis(dis), pos(pos), l(l), r(r) { } }; @@ -230,7 +230,7 @@ class ExamRoom2 { class ExamRoom3 { public: ExamRoom3(int N) : num_(N) { - max_heap_.emplace(make_shared(-1, num_, num_, 0)); + max_heap_.emplace(make_shared(num_, 0, -1, num_)); seats_[-1] = make_pair(-1, num_); seats_[num_] = make_pair(-1, num_); } @@ -246,28 +246,28 @@ class ExamRoom3 { const auto curr = max_heap_.top(); max_heap_.pop(); if (curr->l == -1 && curr->r == num_) { max_heap_.emplace( - make_shared(curr->l + 1, curr->r, + make_shared(curr->r - 1, curr->r - 1, - curr->r - 1)); + curr->l + 1, curr->r)); } else if (curr->l == -1) { max_heap_.emplace( - make_shared(curr->l + 1, curr->r, + make_shared(curr->r / 2, curr->r / 2, - curr->r / 2)); + curr->l + 1, curr->r)); } else if (curr->r == num_) { max_heap_.emplace( - make_shared(curr->l, curr->r - 1, - (curr->r - 1 - curr->l) / 2, - (curr->r - 1 - curr->l) / 2 + curr->l)); + make_shared((curr->r - 1 - curr->l) / 2, + (curr->r - 1 - curr->l) / 2 + curr->l, + curr->l, curr->r - 1)); } else { max_heap_.emplace( - make_shared(curr->l, curr->pos, - (curr->pos - curr->l) / 2, - (curr->pos - curr->l) / 2 + curr->l)); + make_shared((curr->pos - curr->l) / 2, + (curr->pos - curr->l) / 2 + curr->l, + curr->l, curr->pos)); max_heap_.emplace( - make_shared(curr->pos, curr->r, - (curr->r - curr->pos) / 2, - (curr->r - curr->pos) / 2 + curr->pos)); + make_shared((curr->r - curr->pos) / 2, + (curr->r - curr->pos) / 2 + curr->pos, + curr->pos, curr->r)); } seats_[curr->pos] = make_pair(curr->l, curr->r); seats_[curr->l].second = curr->pos; @@ -280,24 +280,24 @@ class ExamRoom3 { seats_.erase(p); if (neighbors.first == -1 && neighbors.second == num_) { max_heap_.emplace( - make_shared(neighbors.first, neighbors.second, - neighbors.second, - neighbors.first + 1)); + make_shared(neighbors.second, + neighbors.first + 1, + neighbors.first, neighbors.second)); } else if (neighbors.first == -1) { max_heap_.emplace( - make_shared(neighbors.first, neighbors.second, - neighbors.second, - neighbors.first + 1)); + make_shared(neighbors.second, + neighbors.first + 1, + neighbors.first, neighbors.second)); } else if (neighbors.second == num_) { max_heap_.emplace( - make_shared(neighbors.first, neighbors.second, - neighbors.second - 1 - neighbors.first, - neighbors.second - 1)); + make_shared(neighbors.second - 1 - neighbors.first, + neighbors.second - 1, + neighbors.first, neighbors.second)); } else { max_heap_.emplace( - make_shared(neighbors.first, neighbors.second, - (neighbors.second - neighbors.first) / 2, - (neighbors.second - neighbors.first) / 2 + neighbors.first)); + make_shared((neighbors.second - neighbors.first) / 2, + (neighbors.second - neighbors.first) / 2 + neighbors.first, + neighbors.first, neighbors.second)); } seats_[neighbors.first].second = neighbors.second; seats_[neighbors.second].first = neighbors.first; @@ -305,12 +305,12 @@ class ExamRoom3 { private: struct Segment { - int l; - int r; int dis; int pos; - Segment(int l, int r, int dis, int pos) : - l(l), r(r), dis(dis), pos(pos) { + int l; + int r; + Segment(int dis, int pos, int l, int r) : + dis(dis), pos(pos), l(l), r(r) { } }; From ef5f1ab87ede6b9965655f608b32fa321a83ed80 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 19:30:29 +0800 Subject: [PATCH 4825/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 8b5901ee3..9265dbcaa 100644 --- a/README.md +++ b/README.md @@ -285,6 +285,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 739| [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) | [C++](./C++/daily-temperatures.cpp) [Python](./Python/daily-temperatures.py) | _O(n)_ | _O(n)_ | Medium || 770| [Basic Calculator IV](https://leetcode.com/problems/basic-calculator-iv/) | [C++](./C++/basic-calculator-iv.cpp) [Python](./Python/basic-calculator-iv.py) | add: _O(d * t)_
sub: _O(d * t)_
mul: _O(d * t^2)_
eval: _O(d * t)_
to_list: _O(d * tlogt)_ | _O(e + d * t)_ | Hard || 772| [Basic Calculator III](https://leetcode.com/problems/basic-calculator-iii/) | [C++](./C++/basic-calculator-iii.cpp) [Python](./Python/basic-calculator-iii.py) | _O(n)_ | _O(n)_ | Hard || +853| [Car Fleet](https://leetcode.com/problems/car-fleet/) | [C++](./C++/car-fleet.cpp) [Python](./Python/car-fleet.py) | _O(nlogn)_ | _O(n)_ | Medium || ## Queue | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -305,6 +306,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 407 | [Trapping Rain Water II](https://leetcode.com/problems/trapping-rain-water-ii/) | [C++](./C++/trapping-rain-water-ii.cpp) [Python](./Python/trapping-rain-water-ii.py) | _O(m * n * (logm + logn))_ | _O(m * n)_ | Hard | LintCode || 632 | [Smallest Range](https://leetcode.com/problems/smallest-range/) | [C++](./C++/smallest-range.cpp) [Python](./Python/smallest-range.py) | _O(nlogk)_ | _O(k)_ | Hard ||| 846 | [Hand of Straights](https://leetcode.com/problems/hand-of-straights/) | [C++](./C++/hand-of-straights.cpp) [Python](./Python/hand-of-straights.py) | _O(nlogn)_ | _O(n)_ | Medium ||| +855 | [Exam Room](https://leetcode.com/problems/exam-room/) | [C++](./C++/exam-room.cpp) [Python](./Python/exam-room.py) | seat: _O(logn)_
leave: _O(logn)_ | _O(n)_ | Medium || BST, Hash | ## Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -587,6 +589,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 774 | [Minimize Max Distance to Gas Station](https://leetcode.com/problems/minimize-max-distance-to-gas-station/) | [C++](./C++/minimize-max-distance-to-gas-station.cpp) [Python](./Python/minimize-max-distance-to-gas-station.py) | _O(nlogr)_ | _O(1)_ | Hard | | 786 | [K-th Smallest Prime Fraction](https://leetcode.com/problems/k-th-smallest-prime-fraction/) | [C++](./C++/k-th-smallest-prime-fraction.cpp) [Python](./Python/k-th-smallest-prime-fraction.py) | _O(nlogr)_ | _O(1)_ | Hard | | 793 | [Preimage Size of Factorial Zeroes Function](https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/) | [C++](./C++/preimage-size-of-factorial-zeroes-function.cpp) [Python](./Python/preimage-size-of-factorial-zeroes-function.py) | _O((logn)^2)_ | _O(1)_ | Hard | | +852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [C++](./C++/peak-index-in-a-mountain-array.cpp) [Python](./Python/peak-index-in-a-mountain-array.py) | _O(logn)_ | _O(1)_ | Easy | | ## Binary Search Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -631,6 +634,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 773|[Sliding Puzzle](https://leetcode.com/problems/sliding-puzzle/)| [C++](./C++/sliding-puzzle.cpp) [Python](./Python/sliding-puzzle.py)| _O((m * n) * (m * n)!)_ | _O((m * n) * (m * n)!)_ | Hard | | `A* Search Algorithm` | 787|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| [C++](./C++/cheapest-flights-within-k-stops.cpp) [Python](./Python/cheapest-flights-within-k-stops.py)| _O(\|E\| * log\|V\|)_ | _O(\|E\|)_ | Medium | | `Dijkstra's algorithm` | 815|[Bus Routes](https://leetcode.com/problems/bus-routes/)| [C++](./C++/bus-routes.cpp) [Python](./Python/bus-routes.py)| _O(\|E\| + \|V\|)_ | _O(\|E\| + \|V\|)_ | Hard | | | +854|[ K-Similar Strings](https://leetcode.com/problems/k-similar-strings/)| [C++](./C++/k-similar-strings.cpp) [Python](./Python/k-similar-strings.py)| _O(n * n!/(c_a!*...*c_z!))_ | _O(n * n!/(c_a!*...*c_z!))_ | Hard | | | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From bcea009f0d04ab168037c0ff509ba281d99cd3cc Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 19:32:48 +0800 Subject: [PATCH 4826/4971] Update k-similar-strings.py --- Python/k-similar-strings.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/k-similar-strings.py b/Python/k-similar-strings.py index c67b2a383..e662050ad 100644 --- a/Python/k-similar-strings.py +++ b/Python/k-similar-strings.py @@ -1,7 +1,7 @@ -# Time: O(s * s!/(a!*...*z!)), s is the length of A, B, -# a...z is the count of each alphabet, -# sum(a...z) = s -# Space: O(s * s!/(a!*...*z!)) +# Time: O(n * n!/(c_a!*...*c_z!), n is the length of A, B, +# c_a...c_z is the count of each alphabet, +# n = sum(c_a...c_z) +# Space: O(n * n!/(c_a!*...*c_z!) # Strings A and B are K-similar (for some non-negative integer K) # if we can swap the positions of two letters From f5dac471a64d564483e55460e700919a2fbd166c Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 19:32:52 +0800 Subject: [PATCH 4827/4971] Update k-similar-strings.cpp --- C++/k-similar-strings.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/C++/k-similar-strings.cpp b/C++/k-similar-strings.cpp index e6984fc40..f19d7af0e 100644 --- a/C++/k-similar-strings.cpp +++ b/C++/k-similar-strings.cpp @@ -1,6 +1,8 @@ -// Time: O(s * s!/(a!*...*z!)), s is the length of A, B, -// a...z is the count of each alphabet, sum(a...z) = s -// Space: O(s * s!/(a!*...*z!)) +// Time: O(n * n!/(c_a!*...*c_z!), n is the length of A, B, +// c_a...c_z is the count of each alphabet, +// n = sum(c_a...c_z) +// Space: O(n * n!/(c_a!*...*c_z!) + class Solution { public: From bb485549120cad5606ba1cf2bb4b3e0c2c538023 Mon Sep 17 00:00:00 2001 From: kamyu Date: Mon, 18 Jun 2018 19:33:08 +0800 Subject: [PATCH 4828/4971] Update k-similar-strings.cpp --- C++/k-similar-strings.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/C++/k-similar-strings.cpp b/C++/k-similar-strings.cpp index f19d7af0e..f56a2ca92 100644 --- a/C++/k-similar-strings.cpp +++ b/C++/k-similar-strings.cpp @@ -3,7 +3,6 @@ // n = sum(c_a...c_z) // Space: O(n * n!/(c_a!*...*c_z!) - class Solution { public: int kSimilarity(string A, string B) { From 16a20c967b3db0c4940f42adb1bc14c131367792 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Mon, 18 Jun 2018 22:34:46 +0800 Subject: [PATCH 4829/4971] Update exam-room.py --- Python/exam-room.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Python/exam-room.py b/Python/exam-room.py index 74be3b964..03fcba211 100644 --- a/Python/exam-room.py +++ b/Python/exam-room.py @@ -54,9 +54,8 @@ def __init__(self, N): """ self.__num = N self.__max_heap = [(-self.__num, 0, -1, self.__num)] - self.__seats = {} - self.__seats[-1] = [-1, self.__num] - self.__seats[self.__num] = [-1, self.__num] + self.__seats = {-1: [-1, self.__num], + self.__num: [-1, self.__num]} def seat(self): """ From 43fb9676517a8371deb3be2b4a2900897039d7d4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jun 2018 12:43:42 +0800 Subject: [PATCH 4830/4971] Create minimum-cost-to-hire-k-workers.cpp --- C++/minimum-cost-to-hire-k-workers.cpp | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 C++/minimum-cost-to-hire-k-workers.cpp diff --git a/C++/minimum-cost-to-hire-k-workers.cpp b/C++/minimum-cost-to-hire-k-workers.cpp new file mode 100644 index 000000000..82ab1eca4 --- /dev/null +++ b/C++/minimum-cost-to-hire-k-workers.cpp @@ -0,0 +1,28 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + double mincostToHireWorkers(vector& quality, vector& wage, int K) { + vector> workers; + for (int i = 0; i < quality.size(); ++i) { + workers.emplace_back(static_cast(wage[i]) / quality[i], + quality[i]); + } + sort(workers.begin(), workers.end()); + auto result = numeric_limits::max(); + auto sum = 0.0; + priority_queue max_heap; + for (const auto& worker: workers) { + sum += worker.second; + max_heap.emplace(worker.second); + if (max_heap.size() > K) { + sum -= max_heap.top(), max_heap.pop(); + } + if (max_heap.size() == K) { + result = min(result, sum * worker.first); + } + } + return result; + } +}; From db80a59407040b208542647856600435cb90cb2d Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 24 Jun 2018 12:51:39 +0800 Subject: [PATCH 4831/4971] Create minimum-cost-to-hire-k-workers.py --- Python/minimum-cost-to-hire-k-workers.py | 60 ++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Python/minimum-cost-to-hire-k-workers.py diff --git a/Python/minimum-cost-to-hire-k-workers.py b/Python/minimum-cost-to-hire-k-workers.py new file mode 100644 index 000000000..c43b0fe9d --- /dev/null +++ b/Python/minimum-cost-to-hire-k-workers.py @@ -0,0 +1,60 @@ +# Time: O(nlogn) +# Space : O(n) + +# There are N workers. +# The i-th worker has a quality[i] and a minimum wage expectation wage[i]. +# +# Now we want to hire exactly K workers to form a paid group. +# When hiring a group of K workers, we must pay them according to +# the following rules: +# +# Every worker in the paid group should be paid in the ratio of +# their quality compared to other workers in the paid group. +# Every worker in the paid group must be paid at least their minimum wage +# expectation. +# Return the least amount of money needed to form a paid group satisfying +# the above conditions. +# +# Example 1: +# +# Input: quality = [10,20,5], wage = [70,50,30], K = 2 +# Output: 105.00000 +# Explanation: We pay 70 to 0-th worker and 35 to 2-th worker. +# Example 2: +# +# Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3 +# Output: 30.66667 +# Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers +# seperately. +# +# Note: +# - 1 <= K <= N <= 10000, where N = quality.length = wage.length +# - 1 <= quality[i] <= 10000 +# - 1 <= wage[i] <= 10000 +# - Answers within 10^-5 of the correct answer will be considered correct. + +import itertools +import heapq + + +class Solution(object): + def mincostToHireWorkers(self, quality, wage, K): + """ + :type quality: List[int] + :type wage: List[int] + :type K: int + :rtype: float + """ + workers = [[float(w)/q, q] for w, q in itertools.izip(wage, quality)] + workers.sort() + result = float("inf") + qsum = 0 + max_heap = [] + for r, q in workers: + qsum += q + heapq.heappush(max_heap, -q) + if len(max_heap) > K: + qsum -= -heapq.heappop(max_heap) + if len(max_heap) == K: + result = min(result, qsum*r) + return result From 7f916990040187dc00fb48be5569745255df1e12 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jun 2018 13:10:35 +0800 Subject: [PATCH 4832/4971] Create score-of-parentheses.cpp --- C++/score-of-parentheses.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 C++/score-of-parentheses.cpp diff --git a/C++/score-of-parentheses.cpp b/C++/score-of-parentheses.cpp new file mode 100644 index 000000000..e0a750352 --- /dev/null +++ b/C++/score-of-parentheses.cpp @@ -0,0 +1,34 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + int scoreOfParentheses(string S) { + int result = 0, depth = 0; + for (int i = 0; i < S.length(); ++i) { + (S[i] == '(') ? ++depth : --depth; + if (S[i] == '(' && S[i + 1] == ')') { + result += 1 << (depth - 1); + } + } + return result; + } +}; + +// Time: O(n) +// Space: O(h) +class Solution2 { +public: + int scoreOfParentheses(string S) { + vector stack(1, 0); + for (const auto& c : S) { + if (c == '(') { + stack.emplace_back(0); + } else { + const auto last = stack.back(); stack.pop_back(); + stack.back() += (last == 0) ? 1 : 2 * last; + } + } + return stack.front(); + } +}; From 2c6d80d77dac7d79f56935a9c2f480529bc504bc Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jun 2018 13:16:58 +0800 Subject: [PATCH 4833/4971] Update score-of-parentheses.cpp --- C++/score-of-parentheses.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/score-of-parentheses.cpp b/C++/score-of-parentheses.cpp index e0a750352..c37ad4554 100644 --- a/C++/score-of-parentheses.cpp +++ b/C++/score-of-parentheses.cpp @@ -26,7 +26,7 @@ class Solution2 { stack.emplace_back(0); } else { const auto last = stack.back(); stack.pop_back(); - stack.back() += (last == 0) ? 1 : 2 * last; + stack.back() += max(1, 2 * last); } } return stack.front(); From 05a21d1944f161376ac6ccb152ad268c30cb50ae Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 24 Jun 2018 13:20:10 +0800 Subject: [PATCH 4834/4971] Create score-of-parentheses.py --- Python/score-of-parentheses.py | 70 ++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Python/score-of-parentheses.py diff --git a/Python/score-of-parentheses.py b/Python/score-of-parentheses.py new file mode 100644 index 000000000..89dcc34f8 --- /dev/null +++ b/Python/score-of-parentheses.py @@ -0,0 +1,70 @@ +# Time: O(n) +# Space: O(1) + +# Given a balanced parentheses string S, +# compute the score of the string based on the following rule: +# +# () has score 1 +# AB has score A + B, where A and B are balanced parentheses strings. +# (A) has score 2 * A, where A is a balanced parentheses string. +# +# Example 1: +# +# Input: "()" +# Output: 1 +# Example 2: +# +# Input: "(())" +# Output: 2 +# Example 3: +# +# Input: "()()" +# Output: 2 +# Example 4: +# +# Input: "(()(()))" +# Output: 6 +# +# Note: +# - S is a balanced parentheses string, containing only ( and ). +# - 2 <= S.length <= 50 + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def scoreOfParentheses(self, S): + """ + :type S: str + :rtype: int + """ + result, depth = 0, 0 + for i in xrange(len(S)): + if S[i] == '(': + depth += 1 + else: + depth -= 1 + if S[i] == '(' and S[i+1] == ')': + result += 2**(depth-1) + return result + + +# Time: O(n) +# Space: O(h) +class Solution2(object): + def scoreOfParentheses(self, S): + """ + :type S: str + :rtype: int + """ + stack = [0] + for c in S: + if c == '(': + stack.append(0) + else: + last = stack.pop() + stack[-1] += max(1, 2*last) + return stack[0] From 6f66259968e03d3ec25c020b316130dfb3d84f44 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jun 2018 14:40:19 +0800 Subject: [PATCH 4835/4971] Create mirror-reflection.cpp --- C++/mirror-reflection.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 C++/mirror-reflection.cpp diff --git a/C++/mirror-reflection.cpp b/C++/mirror-reflection.cpp new file mode 100644 index 000000000..614f64bbf --- /dev/null +++ b/C++/mirror-reflection.cpp @@ -0,0 +1,37 @@ +// Time: O(1) +// Space: O(1) + +class Solution { +public: + int mirrorReflection(int p, int q) { + return (p & -p) > (q & -q) ? 2 : (p & -p) < (q & -q) ? 0 : 1; + } +}; + + +// Time: O(log(max(p, q))) = O(1) due to 32-bit integer +// Space: O(1) +class Solution2 { +public: + int mirrorReflection(int p, int q) { + const auto lcm = p * q / gcd(p, q); + // let a = lcm / p, b = lcm / q + if (lcm / p % 2 == 1) { + if (lcm / q % 2 == 1) { // a is odd, b is odd <=> (p & -p) == (q & -q) + return 1; + } + return 2; // a is odd, b is even <=> (p & -p) > (q & -q) + } + return 0; // a is even, b is odd <=> (p & -p) < (q & -q) + } + +private: + int gcd(int a, int b) { + while (b != 0) { + int tmp = b; + b = a % b; + a = tmp; + } + return a; + } +}; From 4d29f538bde2b68e0d66a94c846a6e5e4152d072 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jun 2018 14:48:01 +0800 Subject: [PATCH 4836/4971] Update mirror-reflection.cpp --- C++/mirror-reflection.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/C++/mirror-reflection.cpp b/C++/mirror-reflection.cpp index 614f64bbf..ad3165ae7 100644 --- a/C++/mirror-reflection.cpp +++ b/C++/mirror-reflection.cpp @@ -4,6 +4,7 @@ class Solution { public: int mirrorReflection(int p, int q) { + // explanation commented in the following solution return (p & -p) > (q & -q) ? 2 : (p & -p) < (q & -q) ? 0 : 1; } }; @@ -17,8 +18,8 @@ class Solution2 { const auto lcm = p * q / gcd(p, q); // let a = lcm / p, b = lcm / q if (lcm / p % 2 == 1) { - if (lcm / q % 2 == 1) { // a is odd, b is odd <=> (p & -p) == (q & -q) - return 1; + if (lcm / q % 2 == 1) { + return 1; // a is odd, b is odd <=> (p & -p) == (q & -q) } return 2; // a is odd, b is even <=> (p & -p) > (q & -q) } From d44c33f9730f3ef0c3540fbf5e127bf156759a00 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 24 Jun 2018 14:48:29 +0800 Subject: [PATCH 4837/4971] add --- Python/mirror-reflection.py | 59 +++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/mirror-reflection.py diff --git a/Python/mirror-reflection.py b/Python/mirror-reflection.py new file mode 100644 index 000000000..ee52f7e64 --- /dev/null +++ b/Python/mirror-reflection.py @@ -0,0 +1,59 @@ +# Time: O(1) +# Space: O(1) + +# There is a special square room with mirrors on each of the four walls. +# Except for the southwest corner, there are receptors on each of +# the remaining corners, +# numbered 0, 1, and 2. +# +# The square room has walls of length p, +# and a laser ray from the southwest corner first meets +# the east wall at a distance q from the 0th receptor. +# +# Return the number of the receptor that the ray meets first. +# (It is guaranteed that the ray will meet a receptor eventually.) +# +# Example 1: +# +# Input: p = 2, q = 1 +# Output: 2 +# Explanation: The ray meets receptor 2 the first time it gets reflected back +# to the left wall. +# +# Note: +# - 1 <= p <= 1000 +# - 0 <= q <= p + + +class Solution(object): + def mirrorReflection(self, p, q): + """ + :type p: int + :type q: int + :rtype: int + """ + # explanation commented in the following solution + return 2 if (p & -p) > (q & -q) else 0 if (p & -p) < (q & -q) else 1 + + +# Time: O(log(max(p, q))) = O(1) due to 32-bit integer +# Space: O(1) +class Solution2(object): + def mirrorReflection(self, p, q): + """ + :type p: int + :type q: int + :rtype: int + """ + def gcd(a, b): + while b: + a, b = b, a % b + return a + + lcm = p*q // gcd(p, q) + # let a = lcm / p, b = lcm / q + if lcm // p % 2 == 1: + if lcm // q % 2 == 1: + return 1 # a is odd, b is odd <=> (p & -p) == (q & -q) + return 2 # a is odd, b is even <=> (p & -p) > (q & -q) + return 0 # a is even, b is odd <=> (p & -p) < (q & -q) From f291916f7b5e7ebdbf289168f64d514749747407 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 24 Jun 2018 14:49:02 +0800 Subject: [PATCH 4838/4971] add --- Python/mirror-reflection.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/mirror-reflection.py b/Python/mirror-reflection.py index ee52f7e64..a7de7a1aa 100644 --- a/Python/mirror-reflection.py +++ b/Python/mirror-reflection.py @@ -49,7 +49,7 @@ def gcd(a, b): while b: a, b = b, a % b return a - + lcm = p*q // gcd(p, q) # let a = lcm / p, b = lcm / q if lcm // p % 2 == 1: From d9b07db0feb97420ff33ad8098e6ae3550f1adad Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jun 2018 14:57:59 +0800 Subject: [PATCH 4839/4971] Create buddy-strings.cpp --- C++/buddy-strings.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 C++/buddy-strings.cpp diff --git a/C++/buddy-strings.cpp b/C++/buddy-strings.cpp new file mode 100644 index 000000000..003d70f70 --- /dev/null +++ b/C++/buddy-strings.cpp @@ -0,0 +1,22 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool buddyStrings(string A, string B) { + if (A.length() != B.length()) { + return false; + } + vector diff; + for (int i = 0; i < A.length(); ++i) { + if (A[i] != B[i]) { + diff.emplace_back(i); + if (diff.size() > 2) { + return false; + } + } + } + return (diff.empty() && unordered_set(A.begin(), A.end()).size() < A.size()) || + (diff.size() == 2 && A[diff[0]] == B[diff[1]] && A[diff[1]] == B[diff[0]]); + } +}; From 24ec4e8f0e20b8b7f0641f7e179a4328423f0e27 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 24 Jun 2018 15:02:03 +0800 Subject: [PATCH 4840/4971] Create buddy-strings.py --- Python/buddy-strings.py | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/buddy-strings.py diff --git a/Python/buddy-strings.py b/Python/buddy-strings.py new file mode 100644 index 000000000..7819c6f99 --- /dev/null +++ b/Python/buddy-strings.py @@ -0,0 +1,48 @@ +# Time: O(n) +# Space: O(1) + +# Given two strings A and B of lowercase letters, +# return true if and only if we can swap two letters in A +# so that the result equals B. +# +# Example 1: +# +# Input: A = "ab", B = "ba" +# Output: true +# Example 2: +# +# Input: A = "ab", B = "ab" +# Output: false +# Example 3: +# +# Input: A = "aa", B = "aa" +# Output: true +# Example 4: +# +# Input: A = "aaaaaaabc", B = "aaaaaaacb" +# Output: true +# Example 5: +# +# Input: A = "", B = "aa" +# Output: false +# +# Note: +# - 0 <= A.length <= 20000 +# - 0 <= B.length <= 20000 +# - A and B consist only of lowercase letters. + +import itertools + + +class Solution(object): + def buddyStrings(self, A, B): + """ + :type A: str + :type B: str + :rtype: bool + """ + if len(A) != len(B): + return False + diff = [(a, b) for a, b in itertools.izip(A, B) if a != b] + return (not diff and len(set(A)) < len(A)) or \ + (len(diff) == 2 and diff[0] == diff[1][::-1]) From ffe3c4307358672c3b079b6b0a613e647789bf1d Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 24 Jun 2018 15:04:03 +0800 Subject: [PATCH 4841/4971] Update buddy-strings.py --- Python/buddy-strings.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Python/buddy-strings.py b/Python/buddy-strings.py index 7819c6f99..f4810a478 100644 --- a/Python/buddy-strings.py +++ b/Python/buddy-strings.py @@ -43,6 +43,11 @@ def buddyStrings(self, A, B): """ if len(A) != len(B): return False - diff = [(a, b) for a, b in itertools.izip(A, B) if a != b] + diff = [] + for a, b in itertools.izip(A, B): + if a != b: + diff.append((a, b)) + if len(diff) > 2: + return False return (not diff and len(set(A)) < len(A)) or \ (len(diff) == 2 and diff[0] == diff[1][::-1]) From a05c5eae6c9ef8a481b60014601a39a0b3d01cb2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jun 2018 15:45:21 +0800 Subject: [PATCH 4842/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 9265dbcaa..e9d215493 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 833| [Find And Replace in String](https://leetcode.com/problems/find-and-replace-in-string/) | [C++](./C++/find-and-replace-in-string.cpp) [Python](./Python/find-and-replace-in-string.py) | _O(n + m)_ | _O(n)_ | Medium ||| 839 | [Similar String Groups](https://leetcode.com/problems/similar-string-groups/) | [C++](./C++/similar-string-groups.cpp) [Python](./Python/similar-string-groups.py) | _O(n^2 * l)_ | _O(n)_ | Hard || Union Find 848 | [Shifting Letters](https://leetcode.com/problems/shifting-letters/) | [C++](./C++/shifting-letters.cpp) [Python](./Python/shifting-letters.py) | _O(n)_ | _O(1)_ | Medium || +859 | [Buddy Strings](https://leetcode.com/problems/buddy-strings/) | [C++](./C++/buddy-strings.cpp) [Python](./Python/buddy-strings.py) | _O(n)_ | _O(1)_ | Easy || ## Linked List | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -286,6 +287,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 770| [Basic Calculator IV](https://leetcode.com/problems/basic-calculator-iv/) | [C++](./C++/basic-calculator-iv.cpp) [Python](./Python/basic-calculator-iv.py) | add: _O(d * t)_
sub: _O(d * t)_
mul: _O(d * t^2)_
eval: _O(d * t)_
to_list: _O(d * tlogt)_ | _O(e + d * t)_ | Hard || 772| [Basic Calculator III](https://leetcode.com/problems/basic-calculator-iii/) | [C++](./C++/basic-calculator-iii.cpp) [Python](./Python/basic-calculator-iii.py) | _O(n)_ | _O(n)_ | Hard || 853| [Car Fleet](https://leetcode.com/problems/car-fleet/) | [C++](./C++/car-fleet.cpp) [Python](./Python/car-fleet.py) | _O(nlogn)_ | _O(n)_ | Medium || +856| [Score of Parentheses](https://leetcode.com/problems/score-of-parentheses/) | [C++](./C++/score-of-parentheses.cpp) [Python](./Python/score-of-parentheses.py) | _O(n)_ | _O(1)_ | Medium || ## Queue | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -307,6 +309,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 632 | [Smallest Range](https://leetcode.com/problems/smallest-range/) | [C++](./C++/smallest-range.cpp) [Python](./Python/smallest-range.py) | _O(nlogk)_ | _O(k)_ | Hard ||| 846 | [Hand of Straights](https://leetcode.com/problems/hand-of-straights/) | [C++](./C++/hand-of-straights.cpp) [Python](./Python/hand-of-straights.py) | _O(nlogn)_ | _O(n)_ | Medium ||| 855 | [Exam Room](https://leetcode.com/problems/exam-room/) | [C++](./C++/exam-room.cpp) [Python](./Python/exam-room.py) | seat: _O(logn)_
leave: _O(logn)_ | _O(n)_ | Medium || BST, Hash | +857 | [Minimum Cost to Hire K Workers](https://leetcode.com/problems/minimum-cost-to-hire-k-workers/) | [C++](./C++/minimum-cost-to-hire-k-workers.cpp) [Python](./Python/minimum-cost-to-hire-k-workers.py) | _O(nlogn)_ | _O(n)_ | Hard || Sort | ## Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -476,6 +479,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 812 | [Largest Triangle Area](https://leetcode.com/problems/largest-triangle-area/) | [C++](./C++/largest-triangle-area.cpp) [Python](./Python/largest-triangle-area.py) | _O(n^3)_ | _O(1)_ | Easy ||| 829 | [Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/) | [C++](./C++/consecutive-numbers-sum.cpp) [Python](./Python/consecutive-numbers-sum.py) | _O(sqrt(n))_ | _O(1)_ | Medium ||| 836 | [Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap/) | [C++](./C++/rectangle-overlap.cpp) [Python](./Python/rectangle-overlap.py) | _O(1)_ | _O(1)_ | Easy ||| +858 | [Mirror Reflection](https://leetcode.com/problems/mirror-reflection/) | [C++](./C++/mirror-reflection.cpp) [Python](./Python/mirror-reflection.py) | _O(1)_ | _O(1)_ | Medium ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From b3301ee0a53d06815df686dc792047f80ec8adb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jun 2018 15:48:47 +0800 Subject: [PATCH 4843/4971] Update buddy-strings.cpp --- C++/buddy-strings.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/buddy-strings.cpp b/C++/buddy-strings.cpp index 003d70f70..738d07a66 100644 --- a/C++/buddy-strings.cpp +++ b/C++/buddy-strings.cpp @@ -16,7 +16,7 @@ class Solution { } } } - return (diff.empty() && unordered_set(A.begin(), A.end()).size() < A.size()) || - (diff.size() == 2 && A[diff[0]] == B[diff[1]] && A[diff[1]] == B[diff[0]]); + return (diff.empty() && unordered_set(A.begin(), A.end()).size() < A.size()) || + (diff.size() == 2 && A[diff[0]] == B[diff[1]] && A[diff[1]] == B[diff[0]]); } }; From cffdd95dc2056ef008d086c65aeb7bc94592559f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jun 2018 21:22:35 +0800 Subject: [PATCH 4844/4971] Update score-of-parentheses.py --- Python/score-of-parentheses.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/score-of-parentheses.py b/Python/score-of-parentheses.py index 89dcc34f8..6eecf01b1 100644 --- a/Python/score-of-parentheses.py +++ b/Python/score-of-parentheses.py @@ -47,8 +47,8 @@ def scoreOfParentheses(self, S): depth += 1 else: depth -= 1 - if S[i] == '(' and S[i+1] == ')': - result += 2**(depth-1) + if S[i-1] == '(': + result += 2**depth return result From 672ca999de833f966cab6146eda4c92061a4d3a1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 24 Jun 2018 21:23:29 +0800 Subject: [PATCH 4845/4971] Update score-of-parentheses.cpp --- C++/score-of-parentheses.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/C++/score-of-parentheses.cpp b/C++/score-of-parentheses.cpp index c37ad4554..4cf6c8a9e 100644 --- a/C++/score-of-parentheses.cpp +++ b/C++/score-of-parentheses.cpp @@ -6,9 +6,13 @@ class Solution { int scoreOfParentheses(string S) { int result = 0, depth = 0; for (int i = 0; i < S.length(); ++i) { - (S[i] == '(') ? ++depth : --depth; - if (S[i] == '(' && S[i + 1] == ')') { - result += 1 << (depth - 1); + if (S[i] == '(') { + ++depth; + } else { + --depth; + if (S[i - 1] == '(') { + result += 1 << depth; + } } } return result; From 943e97884bf673d6e8387c56cba288bbabab0d5e Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 1 Jul 2018 19:15:59 +0800 Subject: [PATCH 4846/4971] Create shortest-subarray-with-sum-at-least-k.py --- .../shortest-subarray-with-sum-at-least-k.py | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Python/shortest-subarray-with-sum-at-least-k.py diff --git a/Python/shortest-subarray-with-sum-at-least-k.py b/Python/shortest-subarray-with-sum-at-least-k.py new file mode 100644 index 000000000..db63a9dce --- /dev/null +++ b/Python/shortest-subarray-with-sum-at-least-k.py @@ -0,0 +1,55 @@ +# Time: O(n) +# Space: O(n) + +# Return the length of the shortest, non-empty, +# contiguous subarray of A with sum at least K. +# If there is no non-empty subarray with sum at least K, return -1. +# +# Example 1: +# +# Input: A = [1], K = 1 +# Output: 1 +# Example 2: +# +# Input: A = [1,2], K = 4 +# Output: -1 +# Example 3: +# +# Input: A = [2,-1,2], K = 3 +# Output: 3 +# +# Note: +# - 1 <= A.length <= 50000 +# - -10 ^ 5 <= A[i] <= 10 ^ 5 +# - 1 <= K <= 10 ^ 9 + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + +import collections + + +class Solution(object): + def shortestSubarray(self, A, K): + """ + :type A: List[int] + :type K: int + :rtype: int + """ + accumulated_sum = [0]*(len(A)+1) + for i in xrange(len(A)): + accumulated_sum[i+1] = accumulated_sum[i]+A[i] + + result = float("inf") + mono_increasing_q = collections.deque() + for i, curr in enumerate(accumulated_sum): + while mono_increasing_q and curr <= \ + accumulated_sum[mono_increasing_q[-1]]: + mono_increasing_q.pop() + while mono_increasing_q and \ + curr-accumulated_sum[mono_increasing_q[0]] >= K: + result = min(result, i-mono_increasing_q.popleft()) + mono_increasing_q.append(i) + return result if result != float("inf") else -1 From 9ee4219591fe7d9ff161d585f8d56416cfe8519e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Jul 2018 19:24:31 +0800 Subject: [PATCH 4847/4971] Create shortest-subarray-with-sum-at-least-k.cpp --- C++/shortest-subarray-with-sum-at-least-k.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/shortest-subarray-with-sum-at-least-k.cpp diff --git a/C++/shortest-subarray-with-sum-at-least-k.cpp b/C++/shortest-subarray-with-sum-at-least-k.cpp new file mode 100644 index 000000000..5d8628e7e --- /dev/null +++ b/C++/shortest-subarray-with-sum-at-least-k.cpp @@ -0,0 +1,26 @@ +// Time: O(n) +// Space: O(n) + +class Solution { +public: + int shortestSubarray(vector& A, int K) { + vector accumulated_sum(A.size() + 1, 0); + partial_sum(A.cbegin(), A.cend(), next(accumulated_sum.begin()), plus()); + + int result = numeric_limits::max(); + deque mono_increasing_q; + for (int i = 0; i < accumulated_sum.size(); ++i) { + while (!mono_increasing_q.empty() && + accumulated_sum[i] <= accumulated_sum[mono_increasing_q.back()]) { + mono_increasing_q.pop_back(); + } + while (!mono_increasing_q.empty() && + accumulated_sum[i] - accumulated_sum[mono_increasing_q.front()] >= K) { + result = min(result, i - mono_increasing_q.front()); + mono_increasing_q.pop_front(); + } + mono_increasing_q.emplace_back(i); + } + return result != numeric_limits::max() ? result : -1; + } +}; From 1ff6b92b0f477d301a9fdf2c52ed897b4115e277 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 1 Jul 2018 19:44:11 +0800 Subject: [PATCH 4848/4971] Create all-nodes-distance-k-in-binary-tree.py --- Python/all-nodes-distance-k-in-binary-tree.py | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Python/all-nodes-distance-k-in-binary-tree.py diff --git a/Python/all-nodes-distance-k-in-binary-tree.py b/Python/all-nodes-distance-k-in-binary-tree.py new file mode 100644 index 000000000..7ca349ecd --- /dev/null +++ b/Python/all-nodes-distance-k-in-binary-tree.py @@ -0,0 +1,69 @@ +# Time: O(n) +# Space: O(n) + +# We are given a binary tree (with root node root), a target node, +# and an integer value `K`. +# +# Return a list of the values of all nodes that have a distance K +# from the target node. The answer can be returned in any order. +# +# Example 1: +# +# Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2 +# Output: [7,4,1] +# Explanation: +# The nodes that are a distance 2 from the target node (with value 5) +# have values 7, 4, and 1. +# +# Note that the inputs "root" and "target" are actually TreeNodes. +# The descriptions of the inputs above are +# just serializations of these objects. +# +# Note: +# - The given tree is non-empty. +# - Each node in the tree has unique values 0 <= node.val <= 500. +# - The target node is a node in the tree. +# - 0 <= K <= 1000. +# +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +import collections + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def distanceK(self, root, target, K): + """ + :type root: TreeNode + :type target: TreeNode + :type K: int + :rtype: List[int] + """ + def dfs(parent, child, neighbors): + if not child: + return + if parent: + neighbors[parent.val].append(child.val) + neighbors[child.val].append(parent.val) + dfs(child, child.left, neighbors) + dfs(child, child.right, neighbors) + + neighbors = collections.defaultdict(list) + dfs(None, root, neighbors) + bfs = [target.val] + lookup = set(bfs) + for _ in xrange(K): + bfs = [nei for node in bfs + for nei in neighbors[node] + if nei not in lookup] + lookup |= set(bfs) + return bfs From 40ab3dcd691231934b6f5adf5348e2685f05d5c6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Jul 2018 19:53:08 +0800 Subject: [PATCH 4849/4971] Create all-nodes-distance-k-in-binary-tree.cpp --- C++/all-nodes-distance-k-in-binary-tree.cpp | 49 +++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 C++/all-nodes-distance-k-in-binary-tree.cpp diff --git a/C++/all-nodes-distance-k-in-binary-tree.cpp b/C++/all-nodes-distance-k-in-binary-tree.cpp new file mode 100644 index 000000000..5fac4dc05 --- /dev/null +++ b/C++/all-nodes-distance-k-in-binary-tree.cpp @@ -0,0 +1,49 @@ +// 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 distanceK(TreeNode* root, TreeNode* target, int K) { + unordered_map> neighbors; + dfs(nullptr, root, &neighbors); + + vector bfs{target->val}; + unordered_set lookup{target->val}; + for (int i = 0; i < K; ++i) { + vector curr; + for (const auto& node : bfs) { + for (const auto& nei : neighbors[node]) { + if (!lookup.count(nei)) { + curr.emplace_back(nei); + lookup.emplace(nei); + } + } + } + swap(bfs, curr); + } + return bfs; + } + +private: + void dfs(TreeNode *parent, TreeNode *child, + unordered_map> *neighbors) { + if (!child) { + return; + } + if (parent) { + (*neighbors)[parent->val].emplace_back(child->val); + (*neighbors)[child->val].emplace_back(parent->val); + } + dfs(child, child->left, neighbors); + dfs(child, child->right, neighbors); + } +}; From c8e38143c927eea5b77da05c3efe4a095184d41f Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 1 Jul 2018 20:38:02 +0800 Subject: [PATCH 4850/4971] Create score-after-flipping-matrix.py --- Python/score-after-flipping-matrix.py | 48 +++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/score-after-flipping-matrix.py diff --git a/Python/score-after-flipping-matrix.py b/Python/score-after-flipping-matrix.py new file mode 100644 index 000000000..9e832f8c1 --- /dev/null +++ b/Python/score-after-flipping-matrix.py @@ -0,0 +1,48 @@ +# Time: O(r * c) +# Space: O(1) + +# We have a two dimensional matrix A where each value is 0 or 1. +# +# A move consists of choosing any row or column, +# and toggling each value in that row or column: +# changing all 0s to 1s, and all 1s to 0s. +# +# After making any number of moves, every row of this matrix +# is interpreted as a binary number, and the score of the matrix +# is the sum of these numbers. +# +# Return the highest possible score. +# +# Example 1: +# +# Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]] +# Output: 39 +# Explanation: +# Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]]. +# 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39 +# +# Note: +# - 1 <= A.length <= 20 +# - 1 <= A[0].length <= 20 +# - A[i][j] is 0 or 1. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def matrixScore(self, A): + """ + :type A: List[List[int]] + :rtype: int + """ + R, C = len(A), len(A[0]) + result = 0 + for c in xrange(C): + col = 0 + for r in xrange(R): + col += A[r][c] ^ A[r][0] + result += max(col, R-col) * 2**(C-1-c) + return result From 989d5a98ce01339a2f746ce2942b44cf0a2d4bb1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Jul 2018 20:40:45 +0800 Subject: [PATCH 4851/4971] Create score-after-flipping-matrix.cpp --- C++/score-after-flipping-matrix.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/score-after-flipping-matrix.cpp diff --git a/C++/score-after-flipping-matrix.cpp b/C++/score-after-flipping-matrix.cpp new file mode 100644 index 000000000..dc2ce59ac --- /dev/null +++ b/C++/score-after-flipping-matrix.cpp @@ -0,0 +1,19 @@ +// Time: O(r * c) +// Space: O(1) + +class Solution { +public: + int matrixScore(vector>& A) { + int R = A.size(); + int C = A[0].size(); + int result = 0; + for (int c = 0; c < C; ++c) { + int col = 0; + for (int r = 0; r < R; ++r) { + col += A[r][c] ^ A[r][0]; + } + result += max(col, R - col) * (1 << (C - 1 - c)); + } + return result; + } +}; From 10b97df342ff0d0a9d66ceb045158b8c538cc66d Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 1 Jul 2018 20:49:36 +0800 Subject: [PATCH 4852/4971] Create lemonade-change.py --- Python/lemonade-change.py | 75 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Python/lemonade-change.py diff --git a/Python/lemonade-change.py b/Python/lemonade-change.py new file mode 100644 index 000000000..7f00e3d8b --- /dev/null +++ b/Python/lemonade-change.py @@ -0,0 +1,75 @@ +# Time: O(n) +# Space: O(1) + +# At a lemonade stand, each lemonade costs $5. +# +# Customers are standing in a queue to buy from you, +# and order one at a time (in the order specified by bills). +# +# Each customer will only buy one lemonade and pay with either a $5, $10, +# or $20 bill. You must provide the correct change to each customer, +# so that the net transaction is that the customer pays $5. +# +# Note that you don't have any change in hand at first. +# +# Return true if and only if you can provide every customer +# with correct change. +# +# Example 1: +# +# Input: [5,5,5,10,20] +# Output: true +# Explanation: +# From the first 3 customers, we collect three $5 bills in order. +# From the fourth customer, we collect a $10 bill and give back a $5. +# From the fifth customer, we give a $10 bill and a $5 bill. +# Since all customers got correct change, we output true. +# Example 2: +# +# Input: [5,5,10] +# Output: true +# Example 3: +# +# Input: [10,10] +# Output: false +# Example 4: +# +# Input: [5,5,10,10,20] +# Output: false +# Explanation: +# From the first two customers in order, we collect two $5 bills. +# For the next two customers in order, we collect a $10 bill and +# give back a $5 bill. +# For the last customer, we can't give change of $15 back +# because we only have two $10 bills. +# Since not every customer received correct change, the answer is false. +# +# Note: +# - 0 <= bills.length <= 10000 +# - bills[i] will be either 5, 10, or 20. + + +class Solution(object): + def lemonadeChange(self, bills): + """ + :type bills: List[int] + :rtype: bool + """ + five, ten = 0, 0 + for bill in bills: + if bill == 5: + five += 1 + elif bill == 10: + if not five: + return False + five -= 1 + ten += 1 + else: + if ten and five: + ten -= 1 + five -= 1 + elif five >= 3: + five -= 3 + else: + return False + return True From 72468d04366aaad402dd255c03f1a4f7c1a9e5d7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Jul 2018 20:53:00 +0800 Subject: [PATCH 4853/4971] Create lemonade-change.cpp --- C++/lemonade-change.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 C++/lemonade-change.cpp diff --git a/C++/lemonade-change.cpp b/C++/lemonade-change.cpp new file mode 100644 index 000000000..1823c122a --- /dev/null +++ b/C++/lemonade-change.cpp @@ -0,0 +1,30 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + bool lemonadeChange(vector& bills) { + int five = 0, ten = 0; + for (const auto& bill : bills) { + if (bill == 5) { + ++five; + } else if (bill == 10) { + if (!five) { + return false; + } + --five; + ++ten; + } else { + if (five && ten) { + --five; + --ten; + } else if (five >= 3) { + five -= 3; + } else { + return false; + } + } + } + return true; + } +}; From 107b5d91def808d9c21b8907e1fb2b01372d303a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 Jul 2018 20:59:03 +0800 Subject: [PATCH 4854/4971] Update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index e9d215493..a8494d486 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 842 | [Split Array into Fibonacci Sequence](https://leetcode.com/problems/split-array-into-fibonacci-sequence/) | [C++](./C++/split-array-into-fibonacci-sequence.cpp) [Python](./Python/split-array-into-fibonacci-sequence.py) | _O(n^3)_ | _O(n)_ | Medium || 845 | [Longest Mountain in Array](https://leetcode.com/problems/longest-mountain-in-array/) | [C++](./C++/longest-mountain-in-array.cpp) [Python](./Python/longest-mountain-in-array.py) | _O(n)_ | _O(1)_ | Medium || 849 | [Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/) | [C++](./C++/maximize-distance-to-closest-person.cpp) [Python](./Python/maximize-distance-to-closest-person.py) | _O(n)_ | _O(1)_ | Easy || +860 | [Lemonade Change](https://leetcode.com/problems/lemonade-change/) | [C++](./C++/lemonade-change.cpp) [Python](./Python/lemonade-change.py) | _O(n)_ | _O(1)_ | Easy || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -295,6 +296,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 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 |📖|| 346| [Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream/)| [C++](./C++/moving-average-from-data-stream.cpp) [Python](./Python/moving-average-from-data-stream.py) | _O(1)_ | _O(w)_ | Easy |📖|| +862| [Shortest Subarray with Sum at Least K](https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/)| [C++](./C++/shortest-subarray-with-sum-at-least-k.cpp) [Python](./Python/shortest-subarray-with-sum-at-least-k.py) | _O(n)_ | _O(n)_ | Hard ||| ## Heap | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -351,6 +353,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 699 | [Falling Squares](https://leetcode.com/problems/falling-squares/) | [C++](./C++/falling-squares.cpp) [Python](./Python/falling-squares.py) | _O(nlogn)_ | _O(n)_ | Hard || Segment Tree | 814 | [Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning/) | [C++](./C++/binary-tree-pruning.cpp) [Python](./Python/binary-tree-pruning.py) | _O(n)_ | _O(h)_ | Medium || DFS | 850 | [Rectangle Area II](https://leetcode.com/problems/rectangle-area-ii/) | [C++](./C++/rectangle-area-ii.cpp) [Python](./Python/rectangle-area-ii.py) | _O(nlogn)_ | _O(n)_ | Hard || Segment Tree | +863 | [All Nodes Distance K in Binary Tree](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/) | [C++](./C++/all-nodes-distance-k-in-binary-tree.cpp) [Python](./Python/all-nodes-distance-k-in-binary-tree.py) | _O(n)_ | _O(n)_ | Medium || DFS + BFS | + ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| @@ -840,6 +844,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 767 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | [C++](./C++/reorganize-string.cpp) [Python](./Python/reorganize-string.py) | _O(n)_ | _O(1)_ | Medium | | 798 | [Smallest Rotation with Highest Score](https://leetcode.com/problems/smallest-rotation-with-highest-score/) | [C++](./C++/smallest-rotation-with-highest-score.cpp) [Python](./Python/smallest-rotation-with-highest-score.py) | _O(n)_ | _O(1)_ | Hard | | 843 | [Guess the Word](https://leetcode.com/problems/guess-the-word/) | [C++](./C++/guess-the-word.cpp) [Python](./Python/guess-the-word.py) | _O(n^2)_ | _O(n)_ | Hard || MinMax | +861 | [Score After Flipping Matrix](https://leetcode.com/problems/score-after-flipping-matrix/) | [C++](./C++/score-after-flipping-matrix.cpp) [Python](./Python/score-after-flipping-matrix.py) | _O(r * c)_ | _O(1)_ | Medium || ## Graph | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 0fcd94d97c176a80b2f0f02349b4f5f4ba059153 Mon Sep 17 00:00:00 2001 From: kamyu Date: Tue, 3 Jul 2018 23:51:29 +0800 Subject: [PATCH 4855/4971] Create random-pick-with-blacklist.cpp --- C++/random-pick-with-blacklist.cpp | 52 ++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 C++/random-pick-with-blacklist.cpp diff --git a/C++/random-pick-with-blacklist.cpp b/C++/random-pick-with-blacklist.cpp new file mode 100644 index 000000000..288ad67d8 --- /dev/null +++ b/C++/random-pick-with-blacklist.cpp @@ -0,0 +1,52 @@ +// Time: ctor: O(nlogn) +// pick: O(logn) +// Space: O(n) + +class Solution { +public: + Solution(int N, vector blacklist) { + _n = N - blacklist.size(); + sort(blacklist.begin(), blacklist.end()); + int prev = 0, count = 0; + for (const auto& black : blacklist) { + if (prev != black) { + _intervals.push_back({prev, black - 1, count}); + count += black - prev; + } + prev = black + 1; + } + _intervals.push_back({prev, N - 1, count}); + } + + int pick() { + int index = rand() % _n; + int left = 0, right = _intervals.size() - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + Interval cur = _intervals[mid]; + if (index < cur.accu_count + cur.right - cur.left + 1) { + right = mid - 1; + } else { + left = mid + 1; + } + } + Interval cur = _intervals[left]; + return cur.left + index - cur.accu_count; + } + +private: + struct Interval { + int left; + int right; + int accu_count; + }; + + int _n; + vector _intervals; +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(N, blacklist); + * int param_1 = obj.pick(); + */ From 8aefec658a7b43a592102b08bf067426e69642cf Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Jul 2018 00:02:48 +0800 Subject: [PATCH 4856/4971] Update random-pick-with-blacklist.cpp --- C++/random-pick-with-blacklist.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/C++/random-pick-with-blacklist.cpp b/C++/random-pick-with-blacklist.cpp index 288ad67d8..347c0e630 100644 --- a/C++/random-pick-with-blacklist.cpp +++ b/C++/random-pick-with-blacklist.cpp @@ -4,8 +4,9 @@ class Solution { public: - Solution(int N, vector blacklist) { - _n = N - blacklist.size(); + Solution(int N, vector blacklist) : + _n(N - blacklist.size()) { + sort(blacklist.begin(), blacklist.end()); int prev = 0, count = 0; for (const auto& black : blacklist) { @@ -23,7 +24,7 @@ class Solution { int left = 0, right = _intervals.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; - Interval cur = _intervals[mid]; + const auto& cur = _intervals[mid]; if (index < cur.accu_count + cur.right - cur.left + 1) { right = mid - 1; } else { From 62d5c5ab90d286011e62206b7aa6180dbe3b2c1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Jul 2018 00:27:05 +0800 Subject: [PATCH 4857/4971] Update random-pick-with-blacklist.cpp --- C++/random-pick-with-blacklist.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/random-pick-with-blacklist.cpp b/C++/random-pick-with-blacklist.cpp index 347c0e630..10720babd 100644 --- a/C++/random-pick-with-blacklist.cpp +++ b/C++/random-pick-with-blacklist.cpp @@ -11,12 +11,12 @@ class Solution { int prev = 0, count = 0; for (const auto& black : blacklist) { if (prev != black) { - _intervals.push_back({prev, black - 1, count}); + _intervals.push_back({prev, black, count}); count += black - prev; } prev = black + 1; } - _intervals.push_back({prev, N - 1, count}); + _intervals.push_back({prev, N, count}); } int pick() { @@ -25,7 +25,7 @@ class Solution { while (left <= right) { int mid = left + (right - left) / 2; const auto& cur = _intervals[mid]; - if (index < cur.accu_count + cur.right - cur.left + 1) { + if (index < cur.accu_count + cur.right - cur.left) { right = mid - 1; } else { left = mid + 1; From 124f49124927f03a228179fc09ee15ca22a1e8cb Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Wed, 4 Jul 2018 00:29:48 +0800 Subject: [PATCH 4858/4971] Create random-pick-with-blacklist.py --- Python/random-pick-with-blacklist.py | 91 ++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Python/random-pick-with-blacklist.py diff --git a/Python/random-pick-with-blacklist.py b/Python/random-pick-with-blacklist.py new file mode 100644 index 000000000..ef698c87e --- /dev/null +++ b/Python/random-pick-with-blacklist.py @@ -0,0 +1,91 @@ +# Time: ctor: O(nlogn) +# pick: O(logn) +# Space: O(n) + +# Given a blacklist B containing unique integers from [0, N), +# write a function to return a uniform random integer from +# [0, N) which is NOT in B. +# +# Optimize it such that it minimizes the call to system’s Math.random(). +# +# Note: +# +# 1 <= N <= 1000000000 +# 0 <= B.length < min(100000, N) +# [0, N) does NOT include N. See interval notation. +# Example 1: +# +# Input: +# ["Solution","pick","pick","pick"] +# [[1,[]],[],[],[]] +# Output: [null,0,0,0] +# Example 2: +# +# Input: +# ["Solution","pick","pick","pick"] +# [[2,[]],[],[],[]] +# Output: [null,1,1,1] +# Example 3: +# +# Input: +# ["Solution","pick","pick","pick"] +# [[3,[1]],[],[],[]] +# Output: [null,0,0,2] +# Example 4: +# +# Input: +# ["Solution","pick","pick","pick"] +# [[4,[2]],[],[],[]] +# Output: [null,1,3,1] +# Explanation of Input Syntax: +# +# The input is two lists: the subroutines called and +# their arguments. Solution's constructor has two arguments, +# N and the blacklist B. +# pick has no arguments. +# Arguments are always wrapped with a list, +# even if there aren't any. + +import random + +LEFT, RIGHT, ACCU_COUNT = range(3) + + +class Solution(object): + + def __init__(self, N, blacklist): + """ + :type N: int + :type blacklist: List[int] + """ + self.__n = N-len(blacklist) + self.__intervals = [] + blacklist.sort() + prev, count = 0, 0 + for black in blacklist: + if prev != black: + self.__intervals.append((prev, black, count)) + count += black-prev + prev = black+1 + self.__intervals.append((prev, N, count)) + + def pick(self): + """ + :rtype: int + """ + index = random.randint(0, self.__n-1) + left, right = 0, len(self.__intervals)-1 + while left <= right: + mid = left+(right-left) // 2 + cur = self.__intervals[mid] + if index < cur[ACCU_COUNT]+cur[RIGHT]-cur[LEFT]: + right = mid-1 + else: + left = mid+1 + return self.__intervals[left][LEFT] + \ + index - self.__intervals[left][ACCU_COUNT] + + +# Your Solution object will be instantiated and called as such: +# obj = Solution(N, blacklist) +# param_1 = obj.pick() From 9f809266a1dcc0e59c91d5227ca5baff99bcfb69 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Jul 2018 00:32:28 +0800 Subject: [PATCH 4859/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a8494d486..f7934a1e7 100644 --- a/README.md +++ b/README.md @@ -598,6 +598,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 786 | [K-th Smallest Prime Fraction](https://leetcode.com/problems/k-th-smallest-prime-fraction/) | [C++](./C++/k-th-smallest-prime-fraction.cpp) [Python](./Python/k-th-smallest-prime-fraction.py) | _O(nlogr)_ | _O(1)_ | Hard | | 793 | [Preimage Size of Factorial Zeroes Function](https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/) | [C++](./C++/preimage-size-of-factorial-zeroes-function.cpp) [Python](./Python/preimage-size-of-factorial-zeroes-function.py) | _O((logn)^2)_ | _O(1)_ | Hard | | 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [C++](./C++/peak-index-in-a-mountain-array.cpp) [Python](./Python/peak-index-in-a-mountain-array.py) | _O(logn)_ | _O(1)_ | Easy | | +864 | [Random Pick with Blacklist](https://leetcode.com/problems/random-pick-with-blacklist/) | [C++](./C++/random-pick-with-blacklist.cpp) [Python](./Python/random-pick-with-blacklist.py) | ctor: _O(nlogn)_
pick: _O(logn)_ | _O(n)_ | Hard | | ## Binary Search Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From d90c9741bfa91569e5191532b105a8692cd6136d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Jul 2018 00:33:33 +0800 Subject: [PATCH 4860/4971] Update random-pick-with-blacklist.py --- Python/random-pick-with-blacklist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/random-pick-with-blacklist.py b/Python/random-pick-with-blacklist.py index ef698c87e..cd06f5243 100644 --- a/Python/random-pick-with-blacklist.py +++ b/Python/random-pick-with-blacklist.py @@ -83,7 +83,7 @@ def pick(self): else: left = mid+1 return self.__intervals[left][LEFT] + \ - index - self.__intervals[left][ACCU_COUNT] + index-self.__intervals[left][ACCU_COUNT] # Your Solution object will be instantiated and called as such: From e511b3e07dc4663760e425c2ced1b57f8380e84b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Jul 2018 00:33:50 +0800 Subject: [PATCH 4861/4971] Update random-pick-with-blacklist.py --- Python/random-pick-with-blacklist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/random-pick-with-blacklist.py b/Python/random-pick-with-blacklist.py index cd06f5243..f41aa4078 100644 --- a/Python/random-pick-with-blacklist.py +++ b/Python/random-pick-with-blacklist.py @@ -76,7 +76,7 @@ def pick(self): index = random.randint(0, self.__n-1) left, right = 0, len(self.__intervals)-1 while left <= right: - mid = left+(right-left) // 2 + mid = left+(right-left)//2 cur = self.__intervals[mid] if index < cur[ACCU_COUNT]+cur[RIGHT]-cur[LEFT]: right = mid-1 From a355305fc9305242791cacbeb5fcfa02db328b87 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 4 Jul 2018 00:49:31 +0800 Subject: [PATCH 4862/4971] Update random-pick-with-blacklist.cpp --- C++/random-pick-with-blacklist.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/C++/random-pick-with-blacklist.cpp b/C++/random-pick-with-blacklist.cpp index 10720babd..b5b76cfdf 100644 --- a/C++/random-pick-with-blacklist.cpp +++ b/C++/random-pick-with-blacklist.cpp @@ -5,33 +5,33 @@ class Solution { public: Solution(int N, vector blacklist) : - _n(N - blacklist.size()) { + n_(N - blacklist.size()) { sort(blacklist.begin(), blacklist.end()); int prev = 0, count = 0; for (const auto& black : blacklist) { if (prev != black) { - _intervals.push_back({prev, black, count}); + intervals_.push_back({prev, black, count}); count += black - prev; } prev = black + 1; } - _intervals.push_back({prev, N, count}); + intervals_.push_back({prev, N, count}); } int pick() { - int index = rand() % _n; - int left = 0, right = _intervals.size() - 1; + int index = rand() % n_; + int left = 0, right = intervals_.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; - const auto& cur = _intervals[mid]; + const auto& cur = intervals_[mid]; if (index < cur.accu_count + cur.right - cur.left) { right = mid - 1; } else { left = mid + 1; } } - Interval cur = _intervals[left]; + Interval cur = intervals_[left]; return cur.left + index - cur.accu_count; } @@ -42,8 +42,8 @@ class Solution { int accu_count; }; - int _n; - vector _intervals; + int n_; + vector intervals_; }; /** From ab113c5ab00b0465bd84b12e95614fe99fa6df9a Mon Sep 17 00:00:00 2001 From: Sergey Sudakovich Date: Sat, 7 Jul 2018 13:11:20 -0700 Subject: [PATCH 4863/4971] Make find-bottom-left-value less terse Appending to a list that is being looped over and having a loop variable being used after loop context is done just rubs me the wrong way. Made this look look more like level traversal with the left node added last. --- Python/find-bottom-left-tree-value.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Python/find-bottom-left-tree-value.py b/Python/find-bottom-left-tree-value.py index 15dbde147..696f0bae9 100644 --- a/Python/find-bottom-left-tree-value.py +++ b/Python/find-bottom-left-tree-value.py @@ -61,7 +61,8 @@ def findBottomLeftValue(self, root): :type root: TreeNode :rtype: int """ - queue = [root] - for node in queue: - queue += filter(None, (node.right, node.left)) - return node.val + last_node, queue = None, [root] + while queue: + last_node = queue.pop(0) + queue.extend([n for n in [last_node.right, last_node.left] if n]) + return last_node.value From 292f7c2b3b39a670244ba3791ceb5eb758b9ed01 Mon Sep 17 00:00:00 2001 From: Sergey Sudakovich Date: Sat, 7 Jul 2018 13:46:33 -0700 Subject: [PATCH 4864/4971] Fix import errors This should address https://github.com/kamyu104/LeetCode/issues/122 Flake8 will still fail with these: ./Python/find-the-celebrity.py:20:16: F821 undefined name 'knows' if knows(candidate, i): # All candidates < i are not celebrity candidates. ^ ./Python/find-the-celebrity.py:24:36: F821 undefined name 'knows' if i != candidate and (knows(candidate, i) \ ^ ./Python/find-the-celebrity.py:25:24: F821 undefined name 'knows' or not knows(i, candidate)): ^ 27 F821 undefined name 'TreeNode' ./Python/first-bad-version.py:34:16: F821 undefined name 'isBadVersion' if isBadVersion(mid): ^ ./Python/guess-number-higher-or-lower.py:28:16: F821 undefined name 'guess' if guess(mid) <= 0: ^ ./Python/find-the-celebrity.py:20:16: F821 undefined name 'knows' if knows(candidate, i): # All candidates < i are not celebrity candidates. ^ ./Python/find-the-celebrity.py:24:36: F821 undefined name 'knows' if i != candidate and (knows(candidate, i) \ ^ ./Python/find-the-celebrity.py:25:24: F821 undefined name 'knows' or not knows(i, candidate)): ^ 5 F821 undefined name 'knows' --- Python/construct-binary-tree-from-string.py | 10 +-- Python/data-stream-as-disjoint-intervals.py | 9 ++- Python/delete-node-in-a-bst.py | 6 +- Python/employee-free-time.py | 10 ++- Python/maximum-binary-tree.py | 11 +-- Python/maximum-length-of-repeated-subarray.py | 6 +- Python/mini-parser.py | 76 +++++++++---------- Python/plus-one-linked-list.py | 9 ++- Python/remove-linked-list-elements.py | 9 ++- .../serialize-and-deserialize-binary-tree.py | 12 +-- Python/serialize-and-deserialize-bst.py | 12 +-- Python/top-k-frequent-elements.py | 4 +- 12 files changed, 92 insertions(+), 82 deletions(-) diff --git a/Python/construct-binary-tree-from-string.py b/Python/construct-binary-tree-from-string.py index c7bcaafab..d8d085036 100644 --- a/Python/construct-binary-tree-from-string.py +++ b/Python/construct-binary-tree-from-string.py @@ -2,11 +2,11 @@ # 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 TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None class Solution(object): def str2tree(self, s): diff --git a/Python/data-stream-as-disjoint-intervals.py b/Python/data-stream-as-disjoint-intervals.py index 48b6188a8..7c3b3285a 100644 --- a/Python/data-stream-as-disjoint-intervals.py +++ b/Python/data-stream-as-disjoint-intervals.py @@ -18,10 +18,11 @@ # are small compared to the data stream's size? # Definition for an interval. -# class Interval(object): -# def __init__(self, s=0, e=0): -# self.start = s -# self.end = e +class Interval(object): + def __init__(self, s=0, e=0): + self.start = s + self.end = e + class SummaryRanges(object): diff --git a/Python/delete-node-in-a-bst.py b/Python/delete-node-in-a-bst.py index 04dd96f59..09b64141a 100644 --- a/Python/delete-node-in-a-bst.py +++ b/Python/delete-node-in-a-bst.py @@ -19,9 +19,9 @@ def deleteNode(self, root, key): return root if root.val > key: - root.left = deleteNode(root.left, key) + root.left = self.deleteNode(root.left, key) elif root.val < key: - root.right = deleteNode(root.right, key) + root.right = self.deleteNode(root.right, key) else: if not root.left: right = root.right @@ -37,6 +37,6 @@ def deleteNode(self, root, key): successor = successor.left root.val = successor.val - root.right = deleteNode(root.right, successor.val) + root.right = self.deleteNode(root.right, successor.val) return root diff --git a/Python/employee-free-time.py b/Python/employee-free-time.py index 6fe120844..bbd3f6abe 100644 --- a/Python/employee-free-time.py +++ b/Python/employee-free-time.py @@ -28,14 +28,16 @@ # - 0 <= schedule[i].start < schedule[i].end <= 10^8. # Definition for an interval. -# class Interval(object): -# def __init__(self, s=0, e=0): -# self.start = s -# self.end = e import heapq +class Interval(object): + def __init__(self, s=0, e=0): + self.start = s + self.end = e + + class Solution(object): def employeeFreeTime(self, schedule): """ diff --git a/Python/maximum-binary-tree.py b/Python/maximum-binary-tree.py index c95d5ff82..be1c46f71 100644 --- a/Python/maximum-binary-tree.py +++ b/Python/maximum-binary-tree.py @@ -25,11 +25,12 @@ # Definition for a binary tree node. -# class TreeNode(object): -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + class Solution(object): def constructMaximumBinaryTree(self, nums): diff --git a/Python/maximum-length-of-repeated-subarray.py b/Python/maximum-length-of-repeated-subarray.py index e633ed608..563ee2608 100644 --- a/Python/maximum-length-of-repeated-subarray.py +++ b/Python/maximum-length-of-repeated-subarray.py @@ -27,7 +27,7 @@ def findLength(self, A, B): :type B: List[int] :rtype: int """ - if len(A) < len(B): return findLength(B, A) + if len(A) < len(B): return self.findLength(B, A) result = 0 dp = [[0] * (len(B)+1) for _ in xrange(2)] for i in xrange(len(A)): @@ -50,7 +50,7 @@ def findLength(self, A, B): :type B: List[int] :rtype: int """ - if len(A) > len(B): return findLength(B, A) + if len(A) > len(B): return self.findLength(B, A) M, p = 10**9+7, 113 p_inv = pow(p, M-2, M) def check(guess): @@ -96,7 +96,7 @@ def findLength(self, A, B): :type B: List[int] :rtype: int """ - if len(A) > len(B): return findLength(B, A) + if len(A) > len(B): return self.findLength(B, A) def check(length): lookup = set(A[i:i+length] \ diff --git a/Python/mini-parser.py b/Python/mini-parser.py index fadf39f66..b4f724978 100644 --- a/Python/mini-parser.py +++ b/Python/mini-parser.py @@ -31,44 +31,44 @@ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ -#class NestedInteger(object): -# def __init__(self, value=None): -# """ -# If value is not specified, initializes an empty list. -# Otherwise initializes a single integer equal to value. -# """ -# -# def isInteger(self): -# """ -# @return True if this NestedInteger holds a single integer, rather than a nested list. -# :rtype bool -# """ -# -# def add(self, elem): -# """ -# Set this NestedInteger to hold a nested list and adds a nested integer elem to it. -# :rtype void -# """ -# -# def setInteger(self, value): -# """ -# Set this NestedInteger to hold a single integer equal to value. -# :rtype void -# """ -# -# def getInteger(self): -# """ -# @return the single integer that this NestedInteger holds, if it holds a single integer -# Return None if this NestedInteger holds a nested list -# :rtype int -# """ -# -# def getList(self): -# """ -# @return the nested list that this NestedInteger holds, if it holds a nested list -# Return None if this NestedInteger holds a single integer -# :rtype List[NestedInteger] -# """ +class NestedInteger(object): + def __init__(self, value=None): + """ + If value is not specified, initializes an empty list. + Otherwise initializes a single integer equal to value. + """ + + def isInteger(self): + """ + @return True if this NestedInteger holds a single integer, rather than a nested list. + :rtype bool + """ + + def add(self, elem): + """ + Set this NestedInteger to hold a nested list and adds a nested integer elem to it. + :rtype void + """ + + def setInteger(self, value): + """ + Set this NestedInteger to hold a single integer equal to value. + :rtype void + """ + + def getInteger(self): + """ + @return the single integer that this NestedInteger holds, if it holds a single integer + Return None if this NestedInteger holds a nested list + :rtype int + """ + + def getList(self): + """ + @return the nested list that this NestedInteger holds, if it holds a nested list + Return None if this NestedInteger holds a single integer + :rtype List[NestedInteger] + """ class Solution(object): diff --git a/Python/plus-one-linked-list.py b/Python/plus-one-linked-list.py index 1d7e2c352..faa54d5ee 100644 --- a/Python/plus-one-linked-list.py +++ b/Python/plus-one-linked-list.py @@ -2,10 +2,11 @@ # Space: O(1) # Definition for singly-linked list. -# class ListNode(object): -# def __init__(self, x): -# self.val = x -# self.next = None +class ListNode(object): + def __init__(self, x): + self.val = x + self.next = None + # Two pointers solution. class Solution(object): diff --git a/Python/remove-linked-list-elements.py b/Python/remove-linked-list-elements.py index 316f1d6de..9e6226968 100644 --- a/Python/remove-linked-list-elements.py +++ b/Python/remove-linked-list-elements.py @@ -8,10 +8,11 @@ # Return: 1 --> 2 --> 3 --> 4 --> 5 # # 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 + class Solution: # @param {ListNode} head diff --git a/Python/serialize-and-deserialize-binary-tree.py b/Python/serialize-and-deserialize-binary-tree.py index 1806df30f..89c2ddfa0 100644 --- a/Python/serialize-and-deserialize-binary-tree.py +++ b/Python/serialize-and-deserialize-binary-tree.py @@ -27,11 +27,13 @@ # # Definition for a binary tree node. -# class TreeNode(object): -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + class Codec: def serialize(self, root): diff --git a/Python/serialize-and-deserialize-bst.py b/Python/serialize-and-deserialize-bst.py index 7ab9837df..cf993194f 100644 --- a/Python/serialize-and-deserialize-bst.py +++ b/Python/serialize-and-deserialize-bst.py @@ -17,15 +17,17 @@ # 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 import collections +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + class Codec: def serialize(self, root): diff --git a/Python/top-k-frequent-elements.py b/Python/top-k-frequent-elements.py index 386c7dc11..4789fa8f2 100644 --- a/Python/top-k-frequent-elements.py +++ b/Python/top-k-frequent-elements.py @@ -30,7 +30,7 @@ def topKFrequent(self, nums, k): :type k: int :rtype: List[int] """ - counts = collections.Counter(words) + counts = collections.Counter(nums) buckets = [[] for _ in xrange(len(nums)+1)] for i, count in counts.iteritems(): buckets[count].append(i) @@ -55,7 +55,7 @@ def topKFrequent(self, nums, k): :type k: int :rtype: List[int] """ - counts = collections.Counter(words) + counts = collections.Counter(nums) p = [] for key, val in counts.iteritems(): p.append((-val, key)) From 02589e4fae948e56b907f36d5d9ddac35bb1c972 Mon Sep 17 00:00:00 2001 From: Sergey Sudakovich Date: Sat, 7 Jul 2018 13:56:16 -0700 Subject: [PATCH 4865/4971] Make flake8 happy for Python2.7 --- Python/find-the-celebrity.py | 10 ++++++---- Python/first-bad-version.py | 2 +- Python/guess-number-higher-or-lower.py | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Python/find-the-celebrity.py b/Python/find-the-celebrity.py index da013af89..103354840 100644 --- a/Python/find-the-celebrity.py +++ b/Python/find-the-celebrity.py @@ -17,11 +17,13 @@ def findCelebrity(self, n): candidate = 0 # Find the candidate. for i in xrange(1, n): - if knows(candidate, i): # All candidates < i are not celebrity candidates. - candidate = i + if knows(candidate, i): # noqa + candidate = i # All candidates < i are not celebrity candidates. # Verify the candidate. for i in xrange(n): - if i != candidate and (knows(candidate, i) \ - or not knows(i, candidate)): + candidate_knows_i = knows(candidate, i) # noqa + i_knows_candidate = knows(i, candidate) # noqa + if i != candidate and (candidate_knows_i or + not i_knows_candidate): return -1 return candidate diff --git a/Python/first-bad-version.py b/Python/first-bad-version.py index 32ff42d2b..9a46a2d39 100644 --- a/Python/first-bad-version.py +++ b/Python/first-bad-version.py @@ -31,7 +31,7 @@ def firstBadVersion(self, n): left, right = 1, n while left <= right: mid = left + (right - left) / 2 - if isBadVersion(mid): + if isBadVersion(mid): # noqa right = mid - 1 else: left = mid + 1 diff --git a/Python/guess-number-higher-or-lower.py b/Python/guess-number-higher-or-lower.py index 14f6bb46a..600f58c23 100644 --- a/Python/guess-number-higher-or-lower.py +++ b/Python/guess-number-higher-or-lower.py @@ -25,7 +25,7 @@ def guessNumber(self, n): left, right = 1, n while left <= right: mid = left + (right - left) / 2 - if guess(mid) <= 0: + if guess(mid) <= 0: # noqa right = mid - 1 else: left = mid + 1 From e4c6e80da41f63c18f9b097f7097f8504afba26b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 12:47:20 +0800 Subject: [PATCH 4866/4971] Update random-pick-with-blacklist.cpp --- C++/random-pick-with-blacklist.cpp | 49 +++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/C++/random-pick-with-blacklist.cpp b/C++/random-pick-with-blacklist.cpp index b5b76cfdf..f44f45b98 100644 --- a/C++/random-pick-with-blacklist.cpp +++ b/C++/random-pick-with-blacklist.cpp @@ -1,8 +1,47 @@ +// Time: ctor: O(b) +// pick: O(1) +// Space: O(b) + +class Solution { +public: + Solution(int N, vector blacklist) : + n_(N - blacklist.size()) { + unordered_set whitelist; + for (int i = n_; i < N; ++i) { + whitelist.emplace(i); + } + for (const auto& black : blacklist) { + whitelist.erase(black); + } + auto white = whitelist.cbegin(); + for (const auto& black : blacklist) { + if (black < n_) { + lookup_[black] = *(white++); + } + } + } + + int pick() { + int index = rand() % n_; + return lookup_.count(index) ? lookup_[index] : index; + } + +private: + int n_; + unordered_map lookup_; +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(N, blacklist); + * int param_1 = obj.pick(); + */ + + // Time: ctor: O(nlogn) // pick: O(logn) // Space: O(n) - -class Solution { +class Solution2 { public: Solution(int N, vector blacklist) : n_(N - blacklist.size()) { @@ -45,9 +84,3 @@ class Solution { int n_; vector intervals_; }; - -/** - * Your Solution object will be instantiated and called as such: - * Solution obj = new Solution(N, blacklist); - * int param_1 = obj.pick(); - */ From ddbd863cf33063f582eafd269bdea2fcac4b8885 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 12:47:56 +0800 Subject: [PATCH 4867/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f7934a1e7..83cb6a1c4 100644 --- a/README.md +++ b/README.md @@ -598,7 +598,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 786 | [K-th Smallest Prime Fraction](https://leetcode.com/problems/k-th-smallest-prime-fraction/) | [C++](./C++/k-th-smallest-prime-fraction.cpp) [Python](./Python/k-th-smallest-prime-fraction.py) | _O(nlogr)_ | _O(1)_ | Hard | | 793 | [Preimage Size of Factorial Zeroes Function](https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/) | [C++](./C++/preimage-size-of-factorial-zeroes-function.cpp) [Python](./Python/preimage-size-of-factorial-zeroes-function.py) | _O((logn)^2)_ | _O(1)_ | Hard | | 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [C++](./C++/peak-index-in-a-mountain-array.cpp) [Python](./Python/peak-index-in-a-mountain-array.py) | _O(logn)_ | _O(1)_ | Easy | | -864 | [Random Pick with Blacklist](https://leetcode.com/problems/random-pick-with-blacklist/) | [C++](./C++/random-pick-with-blacklist.cpp) [Python](./Python/random-pick-with-blacklist.py) | ctor: _O(nlogn)_
pick: _O(logn)_ | _O(n)_ | Hard | | +864 | [Random Pick with Blacklist](https://leetcode.com/problems/random-pick-with-blacklist/) | [C++](./C++/random-pick-with-blacklist.cpp) [Python](./Python/random-pick-with-blacklist.py) | ctor: _O(b)_
pick: _O(1)_ | _O(b)_ | Hard | | ## Binary Search Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From e0d1ffb2061b82d9e87c59a44efbf27a93df8b65 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 13:26:05 +0800 Subject: [PATCH 4868/4971] Update random-pick-with-blacklist.cpp --- C++/random-pick-with-blacklist.cpp | 39 +++++++++--------------------- 1 file changed, 11 insertions(+), 28 deletions(-) diff --git a/C++/random-pick-with-blacklist.cpp b/C++/random-pick-with-blacklist.cpp index f44f45b98..4fcdcd8ae 100644 --- a/C++/random-pick-with-blacklist.cpp +++ b/C++/random-pick-with-blacklist.cpp @@ -44,43 +44,26 @@ class Solution { class Solution2 { public: Solution(int N, vector blacklist) : - n_(N - blacklist.size()) { - - sort(blacklist.begin(), blacklist.end()); - int prev = 0, count = 0; - for (const auto& black : blacklist) { - if (prev != black) { - intervals_.push_back({prev, black, count}); - count += black - prev; - } - prev = black + 1; - } - intervals_.push_back({prev, N, count}); - } - + n_(N - blacklist.size()), + blacklist_(blacklist) { + sort(blacklist_.begin(), blacklist_.end()); + } + int pick() { int index = rand() % n_; - int left = 0, right = intervals_.size() - 1; + int left = 0, right = blacklist_.size() - 1; while (left <= right) { - int mid = left + (right - left) / 2; - const auto& cur = intervals_[mid]; - if (index < cur.accu_count + cur.right - cur.left) { + auto mid = left + (right - left) / 2; + if (index + mid < blacklist_[mid]) { right = mid - 1; } else { left = mid + 1; } } - Interval cur = intervals_[left]; - return cur.left + index - cur.accu_count; + return index + left; } -private: - struct Interval { - int left; - int right; - int accu_count; - }; - +private: int n_; - vector intervals_; + vector blacklist_; }; From 7c6f3d80bf752accc250511c8535797250e8eb3c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 13:26:40 +0800 Subject: [PATCH 4869/4971] Update random-pick-with-blacklist.cpp --- C++/random-pick-with-blacklist.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/C++/random-pick-with-blacklist.cpp b/C++/random-pick-with-blacklist.cpp index 4fcdcd8ae..7d4f3f1bc 100644 --- a/C++/random-pick-with-blacklist.cpp +++ b/C++/random-pick-with-blacklist.cpp @@ -46,8 +46,9 @@ class Solution2 { Solution(int N, vector blacklist) : n_(N - blacklist.size()), blacklist_(blacklist) { - sort(blacklist_.begin(), blacklist_.end()); - } + + sort(blacklist_.begin(), blacklist_.end()); + } int pick() { int index = rand() % n_; From 4d6cf4fdfe7a16353626896e196dee9488924c30 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 13:40:54 +0800 Subject: [PATCH 4870/4971] Update random-pick-with-blacklist.cpp --- C++/random-pick-with-blacklist.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/random-pick-with-blacklist.cpp b/C++/random-pick-with-blacklist.cpp index 7d4f3f1bc..8afa1f3c6 100644 --- a/C++/random-pick-with-blacklist.cpp +++ b/C++/random-pick-with-blacklist.cpp @@ -19,7 +19,7 @@ class Solution { lookup_[black] = *(white++); } } - } + } int pick() { int index = rand() % n_; From 2f51e0bc6e330ad0ff53be9966aa3b341cf70520 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 13:43:50 +0800 Subject: [PATCH 4871/4971] Update random-pick-with-blacklist.py --- Python/random-pick-with-blacklist.py | 55 ++++++++++++++++++---------- 1 file changed, 36 insertions(+), 19 deletions(-) diff --git a/Python/random-pick-with-blacklist.py b/Python/random-pick-with-blacklist.py index f41aa4078..7bb534dc1 100644 --- a/Python/random-pick-with-blacklist.py +++ b/Python/random-pick-with-blacklist.py @@ -1,6 +1,6 @@ -# Time: ctor: O(nlogn) -# pick: O(logn) -# Space: O(n) +# Time: ctor: O(b) +# pick: O(1) +# Space: O(b) # Given a blacklist B containing unique integers from [0, N), # write a function to return a uniform random integer from @@ -48,42 +48,59 @@ import random -LEFT, RIGHT, ACCU_COUNT = range(3) - class Solution(object): - + def __init__(self, N, blacklist): """ :type N: int :type blacklist: List[int] """ self.__n = N-len(blacklist) - self.__intervals = [] - blacklist.sort() - prev, count = 0, 0 + self.__lookup = {} + white = iter(set(range(self.__n, N))-set(blacklist)) for black in blacklist: - if prev != black: - self.__intervals.append((prev, black, count)) - count += black-prev - prev = black+1 - self.__intervals.append((prev, N, count)) + if black < self.__n: + self.__lookup[black] = next(white) + + + def pick(self): + """ + :rtype: int + """ + index = random.randint(0, self.__n-1) + return self.__lookup[index] if index in self.__lookup else index + +# Time: ctor: O(nlogn) +# pick: O(logn) +# Space: O(n) +import random + +class Solution2(object): + + def __init__(self, N, blacklist): + """ + :type N: int + :type blacklist: List[int] + """ + self.__n = N-len(blacklist) + blacklist.sort() + self.__blacklist = blacklist + def pick(self): """ :rtype: int """ index = random.randint(0, self.__n-1) - left, right = 0, len(self.__intervals)-1 + left, right = 0, len(self.__blacklist)-1 while left <= right: mid = left+(right-left)//2 - cur = self.__intervals[mid] - if index < cur[ACCU_COUNT]+cur[RIGHT]-cur[LEFT]: + if index+mid < self.__blacklist[mid]: right = mid-1 else: left = mid+1 - return self.__intervals[left][LEFT] + \ - index-self.__intervals[left][ACCU_COUNT] + return index+left # Your Solution object will be instantiated and called as such: From 231f77ab9f0f05e3034ad92e66599edbd35f1255 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 13:44:07 +0800 Subject: [PATCH 4872/4971] Update random-pick-with-blacklist.cpp --- C++/random-pick-with-blacklist.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/C++/random-pick-with-blacklist.cpp b/C++/random-pick-with-blacklist.cpp index 8afa1f3c6..10e419654 100644 --- a/C++/random-pick-with-blacklist.cpp +++ b/C++/random-pick-with-blacklist.cpp @@ -31,13 +31,6 @@ class Solution { unordered_map lookup_; }; -/** - * Your Solution object will be instantiated and called as such: - * Solution obj = new Solution(N, blacklist); - * int param_1 = obj.pick(); - */ - - // Time: ctor: O(nlogn) // pick: O(logn) // Space: O(n) @@ -68,3 +61,9 @@ class Solution2 { int n_; vector blacklist_; }; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(N, blacklist); + * int param_1 = obj.pick(); + */ From f982c6e1980db5f9234db69bcc8ea0e5fb153324 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 13:49:02 +0800 Subject: [PATCH 4873/4971] Update random-pick-with-blacklist.cpp --- C++/random-pick-with-blacklist.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/C++/random-pick-with-blacklist.cpp b/C++/random-pick-with-blacklist.cpp index 10e419654..5bc64a9c6 100644 --- a/C++/random-pick-with-blacklist.cpp +++ b/C++/random-pick-with-blacklist.cpp @@ -31,9 +31,9 @@ class Solution { unordered_map lookup_; }; -// Time: ctor: O(nlogn) -// pick: O(logn) -// Space: O(n) +// Time: ctor: O(blogb) +// pick: O(logb) +// Space: O(b) class Solution2 { public: Solution(int N, vector blacklist) : From a0d8e03bfac2b25714a1350c4729a5a33fd13222 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 13:49:24 +0800 Subject: [PATCH 4874/4971] Update random-pick-with-blacklist.py --- Python/random-pick-with-blacklist.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/random-pick-with-blacklist.py b/Python/random-pick-with-blacklist.py index 7bb534dc1..f1a270548 100644 --- a/Python/random-pick-with-blacklist.py +++ b/Python/random-pick-with-blacklist.py @@ -72,9 +72,9 @@ def pick(self): return self.__lookup[index] if index in self.__lookup else index -# Time: ctor: O(nlogn) -# pick: O(logn) -# Space: O(n) +# Time: ctor: O(blogb) +# pick: O(logb) +# Space: O(b) import random class Solution2(object): From 0d5e5ccf8496276bd0f12225cc725615a6f466c0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 15:58:36 +0800 Subject: [PATCH 4875/4971] Update cheapest-flights-within-k-stops.py --- Python/cheapest-flights-within-k-stops.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Python/cheapest-flights-within-k-stops.py b/Python/cheapest-flights-within-k-stops.py index 96c44cfa8..bd739de50 100644 --- a/Python/cheapest-flights-within-k-stops.py +++ b/Python/cheapest-flights-within-k-stops.py @@ -49,12 +49,16 @@ def findCheapestPrice(self, n, flights, src, dst, K): adj = collections.defaultdict(list) for u, v, w in flights: adj[u].append((v, w)) + best = collections.defaultdict(lambda: collections.defaultdict(lambda: float("inf"))) min_heap = [(0, src, K+1)] while min_heap: result, u, k = heapq.heappop(min_heap) + if k < 0 or best[k][u] < result: + continue if u == dst: return result - if k > 0: - for v, w in adj[u]: + for v, w in adj[u]: + if result+w < best[k-1][v]: + best[k-1][v] = result+w heapq.heappush(min_heap, (result+w, v, k-1)) return -1 From e0bc459d6d2c5f686faa977c2ba83b3a4adda311 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 16:06:56 +0800 Subject: [PATCH 4876/4971] Update cheapest-flights-within-k-stops.py --- Python/cheapest-flights-within-k-stops.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/cheapest-flights-within-k-stops.py b/Python/cheapest-flights-within-k-stops.py index bd739de50..55117e37b 100644 --- a/Python/cheapest-flights-within-k-stops.py +++ b/Python/cheapest-flights-within-k-stops.py @@ -50,9 +50,9 @@ def findCheapestPrice(self, n, flights, src, dst, K): for u, v, w in flights: adj[u].append((v, w)) best = collections.defaultdict(lambda: collections.defaultdict(lambda: float("inf"))) - min_heap = [(0, src, K+1)] + min_heap = [(0, K+1, src)] while min_heap: - result, u, k = heapq.heappop(min_heap) + result, k, u = heapq.heappop(min_heap) if k < 0 or best[k][u] < result: continue if u == dst: @@ -60,5 +60,5 @@ def findCheapestPrice(self, n, flights, src, dst, K): for v, w in adj[u]: if result+w < best[k-1][v]: best[k-1][v] = result+w - heapq.heappush(min_heap, (result+w, v, k-1)) + heapq.heappush(min_heap, (result+w, k-1, v)) return -1 From 039468667441f83b8d787240799d9c6602f57c71 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 16:19:47 +0800 Subject: [PATCH 4877/4971] Update cheapest-flights-within-k-stops.cpp --- C++/cheapest-flights-within-k-stops.cpp | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/C++/cheapest-flights-within-k-stops.cpp b/C++/cheapest-flights-within-k-stops.cpp index cd2eada48..1dc7d3fac 100644 --- a/C++/cheapest-flights-within-k-stops.cpp +++ b/C++/cheapest-flights-within-k-stops.cpp @@ -12,20 +12,28 @@ class Solution { adj[u].emplace_back(v, w); } + unordered_map> best; using T = tuple; priority_queue, greater> min_heap; - min_heap.emplace(0, src, K + 1); + min_heap.emplace(0, K + 1, src); while (!min_heap.empty()) { - int result, u, k; - tie(result, u, k) = min_heap.top(); min_heap.pop(); + int result, k, u; + tie(result, k, u) = min_heap.top(); min_heap.pop(); + if (k < 0 || + (best.count(k) && best[k].count(u) && best[k][u] < result)) { + continue; + } if (u == dst) { return result; } - if (k > 0) { - for (const auto& kvp : adj[u]) { - int v, w; - tie(v, w) = kvp; - min_heap.emplace(result + w, v, k - 1); + for (const auto& kvp : adj[u]) { + int v, w; + tie(v, w) = kvp; + if (!best.count(k - 1) || + !best[k - 1].count(v) || + result + w < best[k - 1][v]) { + best[k - 1][v] = result + w; + min_heap.emplace(result + w, k - 1, v); } } } From ca8bf1fe64e67bccd58978dc64bbbe91ae73c0f2 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 16:28:07 +0800 Subject: [PATCH 4878/4971] Update network-delay-time.py --- Python/network-delay-time.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index c4702142d..0be4d38f8 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -35,11 +35,17 @@ def networkDelayTime(self, times, N, K): result = 0 lookup = set() + best = collections.defaultdict(lambda: float("inf")) min_heap = [(0, K-1)] while min_heap and len(lookup) != N: result, u = heapq.heappop(min_heap) + if best[u] < result: + continue lookup.add(u) for v, w in adj[u]: if v in lookup: continue - heapq.heappush(min_heap, (result+w, v)) + if result+w < best[v]: + best[v] = result+w + heapq.heappush(min_heap, (result+w, v)) return result if len(lookup) == N else -1 + From 0e84580eed37ecb7fa11cbb7065b31e1b014889f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 16:31:27 +0800 Subject: [PATCH 4879/4971] Update network-delay-time.py --- Python/network-delay-time.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index 0be4d38f8..12bec072e 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -39,13 +39,12 @@ def networkDelayTime(self, times, N, K): min_heap = [(0, K-1)] while min_heap and len(lookup) != N: result, u = heapq.heappop(min_heap) + lookup.add(u) if best[u] < result: continue - lookup.add(u) for v, w in adj[u]: if v in lookup: continue if result+w < best[v]: best[v] = result+w heapq.heappush(min_heap, (result+w, v)) return result if len(lookup) == N else -1 - From b216945d9b034c9d4faecfa0669deb3ea2425cec Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 16:32:34 +0800 Subject: [PATCH 4880/4971] Update network-delay-time.cpp --- C++/network-delay-time.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/C++/network-delay-time.cpp b/C++/network-delay-time.cpp index f3489d721..7496cd87e 100644 --- a/C++/network-delay-time.cpp +++ b/C++/network-delay-time.cpp @@ -15,17 +15,26 @@ class Solution { int result = 0; unordered_set lookup; + unordered_map best; priority_queue, greater

> min_heap; min_heap.emplace(0, K - 1); while (!min_heap.empty() && lookup.size() != N) { int u; tie(result, u) = min_heap.top(); min_heap.pop(); lookup.emplace(u); + if (best.count(u) && + best[u] < result) { + continue; + } for (const auto& kvp : adj[u]) { int v, w; tie(v, w) = kvp; if (lookup.count(v)) continue; - min_heap.emplace(result + w, v); + if (!best.count(v) || + result + w < best[v]) { + best[v] = result + w; + min_heap.emplace(result + w, v); + } } } return lookup.size() == N ? result : -1; From 53382a011b0ffd959e00a1b1ee496a43e9484843 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 16:37:15 +0800 Subject: [PATCH 4881/4971] Update cheapest-flights-within-k-stops.py --- Python/cheapest-flights-within-k-stops.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Python/cheapest-flights-within-k-stops.py b/Python/cheapest-flights-within-k-stops.py index 55117e37b..02acd7898 100644 --- a/Python/cheapest-flights-within-k-stops.py +++ b/Python/cheapest-flights-within-k-stops.py @@ -50,15 +50,15 @@ def findCheapestPrice(self, n, flights, src, dst, K): for u, v, w in flights: adj[u].append((v, w)) best = collections.defaultdict(lambda: collections.defaultdict(lambda: float("inf"))) - min_heap = [(0, K+1, src)] + min_heap = [(0, src, K+1)] while min_heap: - result, k, u = heapq.heappop(min_heap) - if k < 0 or best[k][u] < result: + result, u, k = heapq.heappop(min_heap) + if k < 0 or best[u][k] < result: continue if u == dst: return result for v, w in adj[u]: - if result+w < best[k-1][v]: - best[k-1][v] = result+w - heapq.heappush(min_heap, (result+w, k-1, v)) + if result+w < best[v][k-1]: + best[v][k-1] = result+w + heapq.heappush(min_heap, (result+w, v, k-1)) return -1 From 27535845226f83adcb01fa0cd7b56c7102aa33e8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 16:37:45 +0800 Subject: [PATCH 4882/4971] Update cheapest-flights-within-k-stops.cpp --- C++/cheapest-flights-within-k-stops.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/C++/cheapest-flights-within-k-stops.cpp b/C++/cheapest-flights-within-k-stops.cpp index 1dc7d3fac..985bf3b87 100644 --- a/C++/cheapest-flights-within-k-stops.cpp +++ b/C++/cheapest-flights-within-k-stops.cpp @@ -15,12 +15,12 @@ class Solution { unordered_map> best; using T = tuple; priority_queue, greater> min_heap; - min_heap.emplace(0, K + 1, src); + min_heap.emplace(0, src, K + 1); while (!min_heap.empty()) { - int result, k, u; - tie(result, k, u) = min_heap.top(); min_heap.pop(); + int result, u, k; + tie(result, u, k) = min_heap.top(); min_heap.pop(); if (k < 0 || - (best.count(k) && best[k].count(u) && best[k][u] < result)) { + (best.count(u) && best[u].count(k) && best[u][k] < result)) { continue; } if (u == dst) { @@ -29,11 +29,11 @@ class Solution { for (const auto& kvp : adj[u]) { int v, w; tie(v, w) = kvp; - if (!best.count(k - 1) || - !best[k - 1].count(v) || - result + w < best[k - 1][v]) { - best[k - 1][v] = result + w; - min_heap.emplace(result + w, k - 1, v); + if (!best.count(v) || + !best[v].count(k - 1) || + result + w < best[v][k - 1]) { + best[v][k - 1] = result + w; + min_heap.emplace(result + w, v, k - 1); } } } From 837a1ce39110a3e00d2ef4bbab96031499931f1e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 17:32:58 +0800 Subject: [PATCH 4883/4971] Create shortest-path-to-get-all-keys.cpp --- C++/shortest-path-to-get-all-keys.cpp | 105 ++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 C++/shortest-path-to-get-all-keys.cpp diff --git a/C++/shortest-path-to-get-all-keys.cpp b/C++/shortest-path-to-get-all-keys.cpp new file mode 100644 index 000000000..8e256a0d1 --- /dev/null +++ b/C++/shortest-path-to-get-all-keys.cpp @@ -0,0 +1,105 @@ +// Time: O(k*r*c + |E|log|V|) = O(k*r*c + (k*|V|)*log|V|) +// = O(k*r*c + (k*(k*2^k))*log(k*2^k)) +// = O(k*r*c + (k*(k*2^k))*(logk + k*log2)) +// = O(k*r*c + (k*(k*2^k))*k) +// = O(k*r*c + k^3*2^k) +// Space: O(|V|) = O(k*2^k) + +class Solution { +public: + int shortestPathAllKeys(vector& grid) { + unordered_map> locations; + for (int r = 0; r < grid.size(); ++r) { + for (int c = 0; c < grid[0].size(); ++c) { + if (string(".#").find(grid[r][c]) == string::npos) { + locations[grid[r][c]] = make_pair(r, c); + } + } + } + unordered_map> dists; + for (const auto& kvp : locations) { + dists[kvp.first] = bfs(grid, kvp.first, locations); + } + + // Dijkstra's algorithm + using T = tuple; + priority_queue, greater> min_heap; + min_heap.emplace(0, '@', 0); + unordered_map> best; + best['@'][0] = 0; + int count = 0; + for (const auto& kvp : locations) { + if (islower(kvp.first)) { + ++count; + } + } + uint32_t target_state = (1 << count) - 1; + while (!min_heap.empty()) { + int cur_d, state; + char place; + tie(cur_d, place, state) = min_heap.top(); min_heap.pop(); + if (best.count(place) && + best[place].count(state) && + best[place][state] < cur_d) { + continue; + } + if (state == target_state) { + return cur_d; + } + for (const auto& kvp : dists[place]) { + int dest, d; + tie(dest, d) = kvp; + auto next_state = state; + if (islower(dest)) { + next_state |= (1 << (dest - 'a')); + } else if (isupper(dest)) { + if (!(state & (1 << (dest - 'A')))) { + continue; + } + } + if (!best.count(dest) || + !best[dest].count(next_state) || + cur_d + d < best[dest][next_state]) { + best[dest][next_state] = cur_d + d; + min_heap.emplace(cur_d + d, dest, next_state); + } + } + } + return -1; + } + +private: + unordered_map bfs(const vector&grid, + char source, + const unordered_map>& locations) { + static const vector> directions{{0, -1}, {0, 1}, + {-1, 0}, {1, 0}}; + int r, c; + tie(r, c) = locations.at(source); + vector> lookup(grid.size(), vector(grid[0].size())); + lookup[r][c] = true; + queue> q; + q.emplace(r, c, 0); + unordered_map dist; + while (!q.empty()) { + int r, c, d; + tie(r, c, d) = q.front(); q.pop(); + if (source != grid[r][c] && grid[r][c] != '.') { + dist[grid[r][c]] = d; + continue; + } + for (const auto& dir : directions) { + int cr = r + dir.first, cc = c + dir.second; + if (!((0 <= cr && cr < grid.size()) && + (0 <= cc && cc < grid[0].size()))) { + continue; + } + if (grid[cr][cc] != '#' && !lookup[cr][cc]) { + lookup[cr][cc] = true; + q.emplace(cr, cc, d + 1); + } + } + } + return dist ; + } +}; From d7d4b799fdf12ff44d4a8c9ea02cf0c5ca30b1da Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 8 Jul 2018 17:41:04 +0800 Subject: [PATCH 4884/4971] Create shortest-path-to-get-all-keys.py --- Python/shortest-path-to-get-all-keys.py | 109 ++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 Python/shortest-path-to-get-all-keys.py diff --git a/Python/shortest-path-to-get-all-keys.py b/Python/shortest-path-to-get-all-keys.py new file mode 100644 index 000000000..b4663d534 --- /dev/null +++ b/Python/shortest-path-to-get-all-keys.py @@ -0,0 +1,109 @@ +# Time: O(k*r*c + |E|log|V|) = O(k*r*c + (k*|V|)*log|V|) +# = O(k*r*c + (k*(k*2^k))*log(k*2^k)) +# = O(k*r*c + (k*(k*2^k))*(logk + k*log2)) +# = O(k*r*c + (k*(k*2^k))*k) +# = O(k*r*c + k^3*2^k) +# Space: O(|V|) = O(k*2^k) + +# We are given a 2-dimensional grid. "." is an empty cell, +# "#" is a wall, "@" is the starting point, ("a", "b", ...) are keys, +# and ("A", "B", ...) are locks. +# +# We start at the starting point, and one move consists of walking one space +# in one of the 4 cardinal directions. We cannot walk outside the grid, +# or walk into a wall. If we walk over a key, we pick it up. +# We can't walk over a lock unless we have the corresponding key. +# +# For some 1 <= K <= 6, there is exactly one lowercase and one uppercase +# letter of the first K letters of the English alphabet in the grid. +# This means that there is exactly one key for each lock, and one lock for +# each key; +# and also that the letters used to represent the keys and locks were chosen +# in the same order as the English alphabet. +# +# Return the lowest number of moves to acquire all keys. If it's impossible, +# return -1. +# +# Example 1: +# +# Input: ["@.a.#","###.#","b.A.B"] +# Output: 8 +# Example 2: +# +# Input: ["@..aA","..B#.","....b"] +# Output: 6 +# +# Note: +# - 1 <= grid.length <= 30 +# - 1 <= grid[0].length <= 30 +# - grid[i][j] contains only '.', '#', '@', 'a'-'f' and 'A'-'F' +# - The number of keys is in [1, 6]. Each key has a different letter and +# opens exactly one lock. + +import collections +import heapq + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def shortestPathAllKeys(self, grid): + """ + :type grid: List[str] + :rtype: int + """ + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + + def bfs(grid, source, locations): + r, c = locations[source] + lookup = [[False]*(len(grid[0])) for _ in xrange(len(grid))] + lookup[r][c] = True + q = collections.deque([(r, c, 0)]) + dist = {} + while q: + r, c, d = q.popleft() + if source != grid[r][c] != '.': + dist[grid[r][c]] = d + continue + for direction in directions: + cr, cc = r+direction[0], c+direction[1] + if not ((0 <= cr < len(grid)) and + (0 <= cc < len(grid[cr]))): + continue + if grid[cr][cc] != '#' and not lookup[cr][cc]: + lookup[cr][cc] = True + q.append((cr, cc, d+1)) + return dist + + locations = {place: (r, c) + for r, row in enumerate(grid) + for c, place in enumerate(row) + if place not in '.#'} + dists = {place: bfs(grid, place, locations) for place in locations} + + # Dijkstra's algorithm + min_heap = [(0, '@', 0)] + best = collections.defaultdict(lambda: collections.defaultdict( + lambda: float("inf"))) + best['@'][0] = 0 + target_state = 2**sum(place.islower() for place in locations)-1 + while min_heap: + cur_d, place, state = heapq.heappop(min_heap) + if best[place][state] < cur_d: + continue + if state == target_state: + return cur_d + for dest, d in dists[place].iteritems(): + next_state = state + if dest.islower(): + next_state |= (1 << (ord(dest)-ord('a'))) + elif dest.isupper(): + if not (state & (1 << (ord(dest)-ord('A')))): + continue + if cur_d+d < best[dest][next_state]: + best[dest][next_state] = cur_d+d + heapq.heappush(min_heap, (cur_d+d, dest, next_state)) + return -1 From 85c93296da6c8c38f3792bffa8032e765dfdaaa4 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 17:52:25 +0800 Subject: [PATCH 4885/4971] Create smallest-subtree-with-all-the-deepest-nodes.cpp --- ...est-subtree-with-all-the-deepest-nodes.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/smallest-subtree-with-all-the-deepest-nodes.cpp diff --git a/C++/smallest-subtree-with-all-the-deepest-nodes.cpp b/C++/smallest-subtree-with-all-the-deepest-nodes.cpp new file mode 100644 index 000000000..b29a24187 --- /dev/null +++ b/C++/smallest-subtree-with-all-the-deepest-nodes.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: + TreeNode* subtreeWithAllDeepest(TreeNode* root) { + return dfs(root).node; + } + +private: + struct Result { + TreeNode *node; + int depth; + }; + + Result dfs(TreeNode *node) { + if (!node) { + return {nullptr, 0}; + } + auto left = dfs(node->left); + auto right = dfs(node->right); + if (left.depth > right.depth) { + return {left.node, left.depth + 1}; + } + if (left.depth < right.depth) { + return {right.node, right.depth + 1}; + } + return {node, left.depth + 1}; + } +}; From fda8a0816c1a6bca0e2dd097ec2dd9b1a6dcc769 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 8 Jul 2018 17:54:51 +0800 Subject: [PATCH 4886/4971] Create smallest-subtree-with-all-the-deepest-nodes --- ...lest-subtree-with-all-the-deepest-nodes.py | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/smallest-subtree-with-all-the-deepest-nodes.py diff --git a/Python/smallest-subtree-with-all-the-deepest-nodes.py b/Python/smallest-subtree-with-all-the-deepest-nodes.py new file mode 100644 index 000000000..e0957e805 --- /dev/null +++ b/Python/smallest-subtree-with-all-the-deepest-nodes.py @@ -0,0 +1,59 @@ +# Time: O(n) +# Space: O(h) + +# Given a binary tree rooted at root, the depth of each node is +# the shortest distance to the root. +# A node is deepest if it has the largest depth possible among +# any node in the entire tree. +# The subtree of a node is that node, plus the set of all descendants +# of that node. +# Return the node with the largest depth such that it contains +# all the deepest nodes in it's subtree. +# +# Example 1: +# +# Input: [3,5,1,6,2,0,8,null,null,7,4] +# Output: [2,7,4] +# Explanation: +# +# We return the node with value 2, colored in yellow in the diagram. +# The nodes colored in blue are the deepest nodes of the tree. +# The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is +# a serialization of the given tree. +# The output "[2, 7, 4]" is a serialization of the subtree +# rooted at the node with value 2. +# Both the input and output have TreeNode type. +# +# Note: +# - The number of nodes in the tree will be between 1 and 500. +# - The values of each node are unique. +# +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +import collections + + +class Solution(object): + def subtreeWithAllDeepest(self, root): + """ + :type root: TreeNode + :rtype: TreeNode + """ + Result = collections.namedtuple("Result", ("node", "depth")) + + def dfs(node): + if not node: + return Result(None, 0) + left, right = dfs(node.left), dfs(node.right) + if left.depth > right.depth: + return Result(left.node, left.depth+1) + if left.depth < right.depth: + return Result(right.node, right.depth+1) + return Result(node, left.depth+1) + + return dfs(root).node From b431285f2a8857e96b598e99216e2b84e780d9c7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 18:33:25 +0800 Subject: [PATCH 4887/4971] Create prime-palindrome.cpp --- C++/prime-palindrome.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 C++/prime-palindrome.cpp diff --git a/C++/prime-palindrome.cpp b/C++/prime-palindrome.cpp new file mode 100644 index 000000000..c869a3942 --- /dev/null +++ b/C++/prime-palindrome.cpp @@ -0,0 +1,33 @@ +// Time: O(n^(3/2)) +// Space: O(logn) + +class Solution { +public: + int primePalindrome(int N) { + if (8 <= N && N <= 11) { + // any palindrome with even digits is multiple of 11 + return 11; + } + for (int i = to_string(N).length() / 2; i < 100000; ++i) { + const string s = to_string(i), rev_s(s.rbegin(), s.rend()); + int j = stoi(s + rev_s.substr(1)); + if (j >= N && isPrime(j)) { + return j; + } + } + return -1; + } + +private: + bool isPrime(int num) { + if (num < 2 || num % 2 == 0) { + return num == 2; + } + for (int i = 3; i * i <= num; i += 2) { + if (num % i == 0) { + return false; + } + } + return true; + } +}; From bc541ce35ae3357328c6a6ba9747d7688bfdd267 Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 8 Jul 2018 18:35:56 +0800 Subject: [PATCH 4888/4971] Create prime-palindrome.py --- Python/prime-palindrome.py | 54 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/prime-palindrome.py diff --git a/Python/prime-palindrome.py b/Python/prime-palindrome.py new file mode 100644 index 000000000..c93690413 --- /dev/null +++ b/Python/prime-palindrome.py @@ -0,0 +1,54 @@ +# Time: O(n^(3/2)) +# Space: O(logn) + +# Find the smallest prime palindrome greater than or equal to N. +# Recall that a number is prime if it's only divisors are 1 and itself, +# and it is greater than 1. +# +# For example, 2,3,5,7,11 and 13 are primes. +# +# Recall that a number is a palindrome if it reads the same from +# left to right as it does from right to left. +# +# For example, 12321 is a palindrome. +# +# Example 1: +# +# Input: 6 +# Output: 7 +# Example 2: +# +# Input: 8 +# Output: 11 +# Example 3: +# +# Input: 13 +# Output: 101 +# +# Note: +# - 1 <= N <= 10^8 +# - The answer is guaranteed to exist and be less than 2 * 10^8. + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + +class Solution(object): + def primePalindrome(self, N): + """ + :type N: int + :rtype: int + """ + def is_prime(n): + if n < 2 or n % 2 == 0: + return n == 2 + return all(n % d for d in xrange(3, int(n**.5) + 1, 2)) + + if 8 <= N <= 11: + return 11 + for i in xrange(10**(len(str(N))//2), 10**5): + j = int(str(i) + str(i)[-2::-1]) + if j >= N and is_prime(j): + return j From c344f8cfe60438730fb5fd36d28661dfbed89034 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 18:42:04 +0800 Subject: [PATCH 4889/4971] Create transpose-matrix.cpp --- C++/transpose-matrix.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 C++/transpose-matrix.cpp diff --git a/C++/transpose-matrix.cpp b/C++/transpose-matrix.cpp new file mode 100644 index 000000000..c6b259607 --- /dev/null +++ b/C++/transpose-matrix.cpp @@ -0,0 +1,15 @@ +// Time: O(r * c) +// Space: O(1) + +class Solution { +public: + vector> transpose(vector>& A) { + vector> result(A[0].size(), vector(A.size())); + for (int r = 0; r < A.size(); ++r) { + for (int c = 0; c < A[0].size(); ++c) { + result[c][r] = A[r][c]; + } + } + return result; + } +}; From bc94796d0e86d2d125f316963f3401932e6330d0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 18:42:35 +0800 Subject: [PATCH 4890/4971] Create transpose-matrix.py --- Python/transpose-matrix.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/transpose-matrix.py diff --git a/Python/transpose-matrix.py b/Python/transpose-matrix.py new file mode 100644 index 000000000..1653eb016 --- /dev/null +++ b/Python/transpose-matrix.py @@ -0,0 +1,32 @@ +# Time: O(r * c) +# Space: O(1) + +# Given a matrix A, return the transpose of A. +# +# The transpose of a matrix is the matrix flipped over it's main diagonal, +# switching the row and column indices of the matrix. +# +# Example 1: +# +# Input: [[1,2,3],[4,5,6],[7,8,9]] +# Output: [[1,4,7],[2,5,8],[3,6,9]] +# Example 2: +# +# Input: [[1,2,3],[4,5,6]] +# Output: [[1,4],[2,5],[3,6]] +# +# Note: +# - 1 <= A.length <= 1000 +# - 1 <= A[0].length <= 1000 + +class Solution(object): + def transpose(self, A): + """ + :type A: List[List[int]] + :rtype: List[List[int]] + """ + result = [[None] * len(A) for _ in xrange(len(A[0]))] + for r, row in enumerate(A): + for c, val in enumerate(row): + result[c][r] = val + return result From 5a582557ec7368224d81998a2e73f689412ca80b Mon Sep 17 00:00:00 2001 From: Allen Liu Date: Sun, 8 Jul 2018 18:43:58 +0800 Subject: [PATCH 4891/4971] update --- Python/transpose-matrix.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Python/transpose-matrix.py b/Python/transpose-matrix.py index 1653eb016..aafe88758 100644 --- a/Python/transpose-matrix.py +++ b/Python/transpose-matrix.py @@ -19,6 +19,12 @@ # - 1 <= A.length <= 1000 # - 1 <= A[0].length <= 1000 +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + + class Solution(object): def transpose(self, A): """ From 25a618556f2faeeae9cdaf7ea808c048ba9b728e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 19:09:48 +0800 Subject: [PATCH 4892/4971] Update README.md --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 83cb6a1c4..527215fac 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 845 | [Longest Mountain in Array](https://leetcode.com/problems/longest-mountain-in-array/) | [C++](./C++/longest-mountain-in-array.cpp) [Python](./Python/longest-mountain-in-array.py) | _O(n)_ | _O(1)_ | Medium || 849 | [Maximize Distance to Closest Person](https://leetcode.com/problems/maximize-distance-to-closest-person/) | [C++](./C++/maximize-distance-to-closest-person.cpp) [Python](./Python/maximize-distance-to-closest-person.py) | _O(n)_ | _O(1)_ | Easy || 860 | [Lemonade Change](https://leetcode.com/problems/lemonade-change/) | [C++](./C++/lemonade-change.cpp) [Python](./Python/lemonade-change.py) | _O(n)_ | _O(1)_ | Easy || +868 | [Transpose Matrix](https://leetcode.com/problems/transpose-matrix/) | [C++](./C++/transpose-matrix.cpp) [Python](./Python/transpose-matrix.py) | _O(r * c)_ | _O(1)_ | Easy || ## String | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -354,6 +355,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 814 | [Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning/) | [C++](./C++/binary-tree-pruning.cpp) [Python](./Python/binary-tree-pruning.py) | _O(n)_ | _O(h)_ | Medium || DFS | 850 | [Rectangle Area II](https://leetcode.com/problems/rectangle-area-ii/) | [C++](./C++/rectangle-area-ii.cpp) [Python](./Python/rectangle-area-ii.py) | _O(nlogn)_ | _O(n)_ | Hard || Segment Tree | 863 | [All Nodes Distance K in Binary Tree](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/) | [C++](./C++/all-nodes-distance-k-in-binary-tree.cpp) [Python](./Python/all-nodes-distance-k-in-binary-tree.py) | _O(n)_ | _O(n)_ | Medium || DFS + BFS | +866 | [Smallest Subtree with all the Deepest Nodes](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/) | [C++](./C++/smallest-subtree-with-all-the-deepest-nodes.cpp) [Python](./Python/smallest-subtree-with-all-the-deepest-nodes.py) | _O(n)_ | _O(h)_ | Medium || DFS | ## Hash Table | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -484,6 +486,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 829 | [Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/) | [C++](./C++/consecutive-numbers-sum.cpp) [Python](./Python/consecutive-numbers-sum.py) | _O(sqrt(n))_ | _O(1)_ | Medium ||| 836 | [Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap/) | [C++](./C++/rectangle-overlap.cpp) [Python](./Python/rectangle-overlap.py) | _O(1)_ | _O(1)_ | Easy ||| 858 | [Mirror Reflection](https://leetcode.com/problems/mirror-reflection/) | [C++](./C++/mirror-reflection.cpp) [Python](./Python/mirror-reflection.py) | _O(1)_ | _O(1)_ | Medium ||| +867 | [Prime Palindrome](https://leetcode.com/problems/prime-palindrome/) | [C++](./C++/prime-palindrome.cpp) [Python](./Python/prime-palindrome.py) | _O(1)_ | _O(1)_ | Medium ||| ## Sort | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -643,7 +646,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 773|[Sliding Puzzle](https://leetcode.com/problems/sliding-puzzle/)| [C++](./C++/sliding-puzzle.cpp) [Python](./Python/sliding-puzzle.py)| _O((m * n) * (m * n)!)_ | _O((m * n) * (m * n)!)_ | Hard | | `A* Search Algorithm` | 787|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| [C++](./C++/cheapest-flights-within-k-stops.cpp) [Python](./Python/cheapest-flights-within-k-stops.py)| _O(\|E\| * log\|V\|)_ | _O(\|E\|)_ | Medium | | `Dijkstra's algorithm` | 815|[Bus Routes](https://leetcode.com/problems/bus-routes/)| [C++](./C++/bus-routes.cpp) [Python](./Python/bus-routes.py)| _O(\|E\| + \|V\|)_ | _O(\|E\| + \|V\|)_ | Hard | | | -854|[ K-Similar Strings](https://leetcode.com/problems/k-similar-strings/)| [C++](./C++/k-similar-strings.cpp) [Python](./Python/k-similar-strings.py)| _O(n * n!/(c_a!*...*c_z!))_ | _O(n * n!/(c_a!*...*c_z!))_ | Hard | | | +854|[K-Similar Strings](https://leetcode.com/problems/k-similar-strings/)| [C++](./C++/k-similar-strings.cpp) [Python](./Python/k-similar-strings.py)| _O(n * n!/(c_a!*...*c_z!))_ | _O(n * n!/(c_a!*...*c_z!))_ | Hard | | | +865|[Shortest Path to Get All Keys](https://leetcode.com/problems/shortest-path-to-get-all-keys/)| [C++](./C++/shortest-path-to-get-all-keys.cpp) [Python](./Python/shortest-path-to-get-all-keys.py)| _O(k*r*c + k^3*2^k)_ | _O(k*2^k)_ | Hard | | `Dijkstra's algorithm` | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 197c32e0f1e075b33e169a3964ba5bcab5e9bc91 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 19:10:45 +0800 Subject: [PATCH 4893/4971] Update transpose-matrix.py --- Python/transpose-matrix.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Python/transpose-matrix.py b/Python/transpose-matrix.py index aafe88758..3d00e1fde 100644 --- a/Python/transpose-matrix.py +++ b/Python/transpose-matrix.py @@ -36,3 +36,14 @@ def transpose(self, A): for c, val in enumerate(row): result[c][r] = val return result + + +# Time: O(r * c) +# Space: O(1) +class Solution2(object): + def transpose(self, A): + """ + :type A: List[List[int]] + :rtype: List[List[int]] + """ + return zip(*A) From fa6d780182614d8dd92e12d01b6f344bdb26b1d8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 8 Jul 2018 19:12:30 +0800 Subject: [PATCH 4894/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 527215fac..627ed9ab6 100644 --- a/README.md +++ b/README.md @@ -647,7 +647,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 787|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| [C++](./C++/cheapest-flights-within-k-stops.cpp) [Python](./Python/cheapest-flights-within-k-stops.py)| _O(\|E\| * log\|V\|)_ | _O(\|E\|)_ | Medium | | `Dijkstra's algorithm` | 815|[Bus Routes](https://leetcode.com/problems/bus-routes/)| [C++](./C++/bus-routes.cpp) [Python](./Python/bus-routes.py)| _O(\|E\| + \|V\|)_ | _O(\|E\| + \|V\|)_ | Hard | | | 854|[K-Similar Strings](https://leetcode.com/problems/k-similar-strings/)| [C++](./C++/k-similar-strings.cpp) [Python](./Python/k-similar-strings.py)| _O(n * n!/(c_a!*...*c_z!))_ | _O(n * n!/(c_a!*...*c_z!))_ | Hard | | | -865|[Shortest Path to Get All Keys](https://leetcode.com/problems/shortest-path-to-get-all-keys/)| [C++](./C++/shortest-path-to-get-all-keys.cpp) [Python](./Python/shortest-path-to-get-all-keys.py)| _O(k*r*c + k^3*2^k)_ | _O(k*2^k)_ | Hard | | `Dijkstra's algorithm` | +865|[Shortest Path to Get All Keys](https://leetcode.com/problems/shortest-path-to-get-all-keys/)| [C++](./C++/shortest-path-to-get-all-keys.cpp) [Python](./Python/shortest-path-to-get-all-keys.py)| _O(k * r * c + k^3*2^k)_ | _O(k*2^k)_ | Hard | | `Dijkstra's algorithm` | ## Depth-First Search | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From f893b3da28d041baf2969717ab6d256fa316b216 Mon Sep 17 00:00:00 2001 From: Zitong Guo Date: Tue, 10 Jul 2018 16:55:13 +0800 Subject: [PATCH 4895/4971] Add new solution for rotate-array.py --- Python/rotate-array.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Python/rotate-array.py b/Python/rotate-array.py index 7e5484fca..10738f32f 100644 --- a/Python/rotate-array.py +++ b/Python/rotate-array.py @@ -83,6 +83,16 @@ def rotate(self, nums, k): break start += 1 +class Solution4: + """ + :type nums: List[int] + :type k: int + :rtype: void Do not return anything, modify nums in-place instead. + """ + def rotate(self, nums, k): + while k > 0: + nums.insert(0, nums.pop()) + k -= 1 if __name__ == '__main__': nums = [1, 2, 3, 4, 5, 6, 7] From f76642d67b9d54024291f8be3dd9730d6244cc90 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Jul 2018 22:20:54 +0800 Subject: [PATCH 4896/4971] Update rotate-array.py --- Python/rotate-array.py | 58 +++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 21 deletions(-) diff --git a/Python/rotate-array.py b/Python/rotate-array.py index 10738f32f..f1f33f6c2 100644 --- a/Python/rotate-array.py +++ b/Python/rotate-array.py @@ -1,15 +1,14 @@ # 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: +class Solution(object): """ :type nums: List[int] :type k: int @@ -28,19 +27,13 @@ def reverse(self, nums, start, end): start += 1 end -= 1 - def rotate2(self, nums, k): - """ - :type nums: List[int] - :type k: int - :rtype: void Do not return anything, modify nums in-place instead. - """ - nums[:] = nums[len(nums) - k:] + nums[:len(nums) - k] - +# Time: O(n) +# Space: O(1) from fractions import gcd -class Solution2: +class Solution2(object): """ :type nums: List[int] :type k: int @@ -48,20 +41,22 @@ class Solution2: """ def rotate(self, nums, k): + def apply_cycle_permutation(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 + 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 + apply_cycle_permutation(k, i, cycle_len, nums) -class Solution3: +# Time: O(n) +# Space: O(1) +class Solution3(object): """ :type nums: List[int] :type k: int @@ -83,7 +78,27 @@ def rotate(self, nums, k): break start += 1 -class Solution4: + +# Time: O(n) +# Space: O(n) +class Solution4(object): + """ + :type nums: List[int] + :type k: int + :rtype: void Do not return anything, modify nums in-place instead. + """ + def rotate(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: void Do not return anything, modify nums in-place instead. + """ + nums[:] = nums[len(nums) - k:] + nums[:len(nums) - k] + + +# Time: O(n^2) +# Space: O(1) +class Solution5(object): """ :type nums: List[int] :type k: int @@ -94,6 +109,7 @@ def rotate(self, nums, k): nums.insert(0, nums.pop()) k -= 1 + if __name__ == '__main__': nums = [1, 2, 3, 4, 5, 6, 7] Solution().rotate(nums, 3) From d599d775b5a36da2505176255e2b9ba4533ced1b Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Jul 2018 23:27:39 +0800 Subject: [PATCH 4897/4971] Update network-delay-time.py --- Python/network-delay-time.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/network-delay-time.py b/Python/network-delay-time.py index 12bec072e..a78da2f02 100644 --- a/Python/network-delay-time.py +++ b/Python/network-delay-time.py @@ -17,9 +17,9 @@ # - The length of times will be in the range [1, 6000]. # - All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 1 <= w <= 100. +import collections import heapq - # Dijkstra's algorithm class Solution(object): def networkDelayTime(self, times, N, K): From ffc91ffad249ee10f2a28cdaab7ede84dadaf96d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Jul 2018 23:33:43 +0800 Subject: [PATCH 4898/4971] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 627ed9ab6..95b601625 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%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) [![SayThanks](https://img.shields.io/badge/say-thanks-ff69b4.svg)](https://saythanks.io/to/kamyu104) +# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.md) [![SayThanks](https://img.shields.io/badge/say-thanks-ff69b4.svg)](https://saythanks.io/to/kamyu104) ![Travis](https://travis-ci.org/kamyu104/LeetCode.svg?branch=master) The number of LeetCode questions is increasing every week. For more questions and solutions, you can see my [LintCode](https://github.com/kamyu104/LintCode) repository. From 2252fe88729a981fd45bd6688e3c3ab7ec612d1d Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Jul 2018 23:48:22 +0800 Subject: [PATCH 4899/4971] Update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 95b601625..c3e73f059 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,11 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates * [Shell Script](https://github.com/kamyu104/LeetCode#shell-script) +## Reference + +* [C++ STL Time Complexity](http://john-ahlgren.blogspot.com/2013/10/stl-container-performance.html) +* [Python Time Complexity](https://wiki.python.org/moin/TimeComplexity) + ## Bit Manipulation | # | Title | Solution | Time | Space | Difficulty | Tag | Note| |-----|---------------- | --------------- | --------------- | --------------- | ------------- |--------------|-----| From bf2c7c3cbd4c80b8bf3e7f850d82f8e972a25bc1 Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Jul 2018 23:52:09 +0800 Subject: [PATCH 4900/4971] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c3e73f059..12ad2863b 100644 --- a/README.md +++ b/README.md @@ -43,8 +43,11 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Reference -* [C++ STL Time Complexity](http://john-ahlgren.blogspot.com/2013/10/stl-container-performance.html) -* [Python Time Complexity](https://wiki.python.org/moin/TimeComplexity) +* C++ + * [STL Time Complexity](http://www.cplusplus.com/reference/stl/) + * [STL Time Complexity](http://john-ahlgren.blogspot.com/2013/10/stl-container-performance.html) +* Python + * [Time Complexity](https://wiki.python.org/moin/TimeComplexity) ## Bit Manipulation | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From f54283f24cf1de986e03320c244e0ee52443143c Mon Sep 17 00:00:00 2001 From: kamyu Date: Wed, 11 Jul 2018 23:53:00 +0800 Subject: [PATCH 4901/4971] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 12ad2863b..c96dd1c2d 100644 --- a/README.md +++ b/README.md @@ -44,8 +44,8 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates ## Reference * C++ - * [STL Time Complexity](http://www.cplusplus.com/reference/stl/) - * [STL Time Complexity](http://john-ahlgren.blogspot.com/2013/10/stl-container-performance.html) + * [STL Time Complexity (Detailed)](http://www.cplusplus.com/reference/stl/) + * [STL Time Complexity (Summary)](http://john-ahlgren.blogspot.com/2013/10/stl-container-performance.html) * Python * [Time Complexity](https://wiki.python.org/moin/TimeComplexity) From daea75fbe4dffa87ce30f1f5d68e5c527d75cc6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Jul 2018 00:01:54 +0800 Subject: [PATCH 4902/4971] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c96dd1c2d..5518265c4 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates * C++ * [STL Time Complexity (Detailed)](http://www.cplusplus.com/reference/stl/) * [STL Time Complexity (Summary)](http://john-ahlgren.blogspot.com/2013/10/stl-container-performance.html) + * [Data Structure and Algorithms Cheat Sheet](https://github.com/gibsjose/cpp-cheat-sheet/blob/master/Data%20Structures%20and%20Algorithms.md) * Python * [Time Complexity](https://wiki.python.org/moin/TimeComplexity) From deff278c2f33eeed647ba624b2b69143813f8f02 Mon Sep 17 00:00:00 2001 From: kamyu Date: Thu, 12 Jul 2018 02:05:40 +0800 Subject: [PATCH 4903/4971] Update rotate-array.py --- Python/rotate-array.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/rotate-array.py b/Python/rotate-array.py index f1f33f6c2..8e43bff0c 100644 --- a/Python/rotate-array.py +++ b/Python/rotate-array.py @@ -96,7 +96,7 @@ def rotate(self, nums, k): nums[:] = nums[len(nums) - k:] + nums[:len(nums) - k] -# Time: O(n^2) +# Time: O(k * n) # Space: O(1) class Solution5(object): """ From 6b3ac9d53c53d132c969c873b5c5a3b190a83c1c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 00:41:38 +0800 Subject: [PATCH 4904/4971] Create insert-into-a-binary-search-tree.cpp --- C++/insert-into-a-binary-search-tree.cpp | 53 ++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 C++/insert-into-a-binary-search-tree.cpp diff --git a/C++/insert-into-a-binary-search-tree.cpp b/C++/insert-into-a-binary-search-tree.cpp new file mode 100644 index 000000000..cbf16a683 --- /dev/null +++ b/C++/insert-into-a-binary-search-tree.cpp @@ -0,0 +1,53 @@ +// Time: O(h) +// 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* insertIntoBST(TreeNode* root, int val) { + TreeNode *curr = root, *parent = nullptr; + while (curr) { + parent = curr; + if (val <= curr->val) { + curr = curr->left; + } else { + curr = curr->right; + } + } + if (!parent) { + root = new TreeNode(val); + } else if (val <= parent->val) { + parent->left = new TreeNode(val); + } else { + parent->right = new TreeNode(val); + } + return root; + } +}; + + +// Time: O(h) +// Space: O(h) +class Solution2 { +public: + TreeNode* insertIntoBST(TreeNode* root, int val) { + if (!root) { + root = new TreeNode(val); + } else { + if (val <= root->val) { + root->left = insertIntoBST(root->left, val); + } else { + root->right = insertIntoBST(root->right, val); + } + } + return root; + } +}; From 866c9de39a9d14c6805d4ec3f2d0364afd05d11f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 00:49:36 +0800 Subject: [PATCH 4905/4971] Create insert-into-a-binary-search-tree.py --- Python/insert-into-a-binary-search-tree.py | 86 ++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Python/insert-into-a-binary-search-tree.py diff --git a/Python/insert-into-a-binary-search-tree.py b/Python/insert-into-a-binary-search-tree.py new file mode 100644 index 000000000..c2ae3738d --- /dev/null +++ b/Python/insert-into-a-binary-search-tree.py @@ -0,0 +1,86 @@ +# Time: O(h) +# Space: O(1) + +# Given the root node of a binary search tree (BST) and +# a value to be inserted into the tree, insert the value into the BST. +# Return the root node of the BST after the insertion. It is guaranteed +# that the new value does not exist in the original BST. +# +# Note that there may exist multiple valid ways for the insertion, +# as long as the tree remains a BST after insertion. You can return any of them. +# +# For example, +# +# Given the tree: +# 4 +# / \ +# 2 7 +# / \ +# 1 3 +# And the value to insert: 5 +# You can return this binary search tree: +# +# 4 +# / \ +# 2 7 +# / \ / +# 1 3 5 +# This tree is also valid: +# +# 5 +# / \ +# 2 7 +# / \ +# 1 3 +# \ +# 4 + + +# 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 insertIntoBST(self, root, val): + """ + :type root: TreeNode + :type val: int + :rtype: TreeNode + """ + curr, parent = root, None + while curr: + parent = curr + if val <= curr.val: + curr = curr.left + else: + curr = curr.right + if not parent: + root = TreeNode(val) + elif val <= parent.val: + parent.left = TreeNode(val) + else: + parent.right = TreeNode(val) + return root + + +# Time: O(h) +# Space: O(h) +class Solution2(object): + def insertIntoBST(self, root, val): + """ + :type root: TreeNode + :type val: int + :rtype: TreeNode + """ + if not root: + root = TreeNode(val) + else: + if val <= root.val: + root.left = self.insertIntoBST(root.left, val) + else: + root.right = self.insertIntoBST(root.right, val) + return root From 7331e1d1061a7a1ac9abc583d45746facfde9180 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 10:10:30 +0800 Subject: [PATCH 4906/4971] Create search-in-a-binary-search-tree.py --- Python/search-in-a-binary-search-tree.py | 48 ++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Python/search-in-a-binary-search-tree.py diff --git a/Python/search-in-a-binary-search-tree.py b/Python/search-in-a-binary-search-tree.py new file mode 100644 index 000000000..755970f77 --- /dev/null +++ b/Python/search-in-a-binary-search-tree.py @@ -0,0 +1,48 @@ +# Time: O(h) +# Space: O(1) + +# Given the root node of a binary search tree (BST) and a value. +# You need to find the node in the BST that the node's value equals the given value. +# Return the subtree rooted with that node. +# If such node doesn't exist, you should return NULL. +# +# For example, +# +# Given the tree: +# 4 +# / \ +# 2 7 +# / \ +# 1 3 +# +# And the value to search: 2 +# You should return this subtree: +# +# 2 +# / \ +# 1 3 +# In the example above, +# if we want to search the value 5, +# since there is no node with value 5, we should return NULL. + +# 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 searchBST(self, root, val): + """ + :type root: TreeNode + :type val: int + :rtype: TreeNode + """ + while root and val != root.val: + if val < root.val: + root = root.left + else: + root = root.right + return root From 2a38b25229fad982e680847ba72f02352169a440 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 10:12:05 +0800 Subject: [PATCH 4907/4971] Create search-in-a-binary-search-tree.cpp --- C++/search-in-a-binary-search-tree.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/search-in-a-binary-search-tree.cpp diff --git a/C++/search-in-a-binary-search-tree.cpp b/C++/search-in-a-binary-search-tree.cpp new file mode 100644 index 000000000..e4fa5b4bc --- /dev/null +++ b/C++/search-in-a-binary-search-tree.cpp @@ -0,0 +1,25 @@ +// Time: O(h) +// 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* searchBST(TreeNode* root, int val) { + while (root && val != root->val) { + if (val < root->val) { + root = root->left; + } else { + root = root->right; + } + } + return root; + } +}; From f408a6fb41a63f1cb879c1d96d149efcc3751605 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 10:50:54 +0800 Subject: [PATCH 4908/4971] Create robot-room-cleaner.cpp --- C++/robot-room-cleaner.cpp | 67 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 C++/robot-room-cleaner.cpp diff --git a/C++/robot-room-cleaner.cpp b/C++/robot-room-cleaner.cpp new file mode 100644 index 000000000..d9ee22296 --- /dev/null +++ b/C++/robot-room-cleaner.cpp @@ -0,0 +1,67 @@ +// Time: O(n), n is the number of cells +// Space: O(n) + +/** + * // This is the robot's control interface. + * // You should not implement it, or speculate about its implementation + * class Robot { + * public: + * // Returns true if the cell in front is open and robot moves into the cell. + * // Returns false if the cell in front is blocked and robot stays in the current cell. + * bool move(); + * + * // Robot will stay in the same cell after calling turnLeft/turnRight. + * // Each turn will be 90 degrees. + * void turnLeft(); + * void turnRight(); + * + * // Clean the current cell. + * void clean(); + * }; + */ +class Solution { +public: + template + struct PairHash { + size_t operator()(const pair& p) const { + size_t seed = 0; + seed ^= std::hash{}(p.first) + 0x9e3779b9 + (seed<<6) + (seed>>2); + seed ^= std::hash{}(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2); + return seed; + } + }; + + void cleanRoom(Robot& robot) { + unordered_set, PairHash> lookup; + dfs({0, 0}, robot, 0, &lookup); + } + +private: + void dfs(const pair& pos, Robot& robot, int dir, + unordered_set, PairHash> *lookup) { + if (lookup->count(pos)) { + return; + } + lookup->emplace(pos); + + robot.clean(); + static const vector> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + for (int i = 0; i < directions.size(); ++i, dir = (dir + 1) % 4) { + if (robot.move()) { + dfs({pos.first + directions[dir].first, + pos.second + directions[dir].second}, + robot, dir, lookup); + goBack(robot); + } + robot.turnRight(); + } + } + + void goBack(Robot& robot) { + robot.turnLeft(); + robot.turnLeft(); + robot.move(); + robot.turnRight(); + robot.turnRight(); + } +}; From d9ec585ec51a0f85939eba15d94c4f20316459e6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 15:43:37 +0800 Subject: [PATCH 4909/4971] Update robot-room-cleaner.cpp --- C++/robot-room-cleaner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/robot-room-cleaner.cpp b/C++/robot-room-cleaner.cpp index d9ee22296..b8a029231 100644 --- a/C++/robot-room-cleaner.cpp +++ b/C++/robot-room-cleaner.cpp @@ -46,7 +46,7 @@ class Solution { robot.clean(); static const vector> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; - for (int i = 0; i < directions.size(); ++i, dir = (dir + 1) % 4) { + for (int i = 0; i < directions.size(); ++i, dir = (dir + 1) % directions.size()) { if (robot.move()) { dfs({pos.first + directions[dir].first, pos.second + directions[dir].second}, From 9e3129a80ecfe7177b09e3a279d3d91b7f9fe56e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 16:06:43 +0800 Subject: [PATCH 4910/4971] Create robot-room-cleaner.py --- Python/robot-room-cleaner.py | 66 ++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Python/robot-room-cleaner.py diff --git a/Python/robot-room-cleaner.py b/Python/robot-room-cleaner.py new file mode 100644 index 000000000..c772c58e2 --- /dev/null +++ b/Python/robot-room-cleaner.py @@ -0,0 +1,66 @@ +# Time: O(n), n is the number of cells +# Space: O(n) + +# """ +# This is the robot's control interface. +# You should not implement it, or speculate about its implementation +# """ +#class Robot(object): +# def move(self): +# """ +# Returns true if the cell in front is open and robot moves into the cell. +# Returns false if the cell in front is blocked and robot stays in the current cell. +# :rtype bool +# """ +# +# def turnLeft(self): +# """ +# Robot will stay in the same cell after calling turnLeft/turnRight. +# Each turn will be 90 degrees. +# :rtype void +# """ +# +# def turnRight(self): +# """ +# Robot will stay in the same cell after calling turnLeft/turnRight. +# Each turn will be 90 degrees. +# :rtype void +# """ +# +# def clean(self): +# """ +# Clean the current cell. +# :rtype void +# """ + +class Solution(object): + def cleanRoom(self, robot): + """ + :type robot: Robot + :rtype: None + """ + directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] + + def goBack(robot): + robot.turnLeft() + robot.turnLeft() + robot.move() + robot.turnRight() + robot.turnRight() + + def dfs(pos, robot, d, lookup): + if pos in lookup: + return + lookup.add(pos) + + robot.clean() + for _ in directions: + if robot.move(): + dfs((pos[0]+directions[d][0], + pos[1]+directions[d][1]), + robot, d, lookup) + goBack(robot) + robot.turnRight() + d = (d+1) % len(directions) + + dfs((0, 0), robot, 0, set()) From d1f6949381acaf497a91390d7ddd2acd26771c9f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 16:37:36 +0800 Subject: [PATCH 4911/4971] Create serialize-and-deserialize-n-ary-tree.py --- .../serialize-and-deserialize-n-ary-tree.py | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Python/serialize-and-deserialize-n-ary-tree.py diff --git a/Python/serialize-and-deserialize-n-ary-tree.py b/Python/serialize-and-deserialize-n-ary-tree.py new file mode 100644 index 000000000..7a135ce84 --- /dev/null +++ b/Python/serialize-and-deserialize-n-ary-tree.py @@ -0,0 +1,67 @@ +# Time: O(n) +# Space: O(h) + +""" +# Definition for a Node. +class Node(object): + def __init__(self, val, children): + self.val = val + self.children = children +""" +class Codec: + + def serialize(self, root): + """Encodes a tree to a single string. + + :type root: Node + :rtype: str + """ + def dfs(node, vals): + if not node: + return + vals.append(str(node.val)) + for child in node.children: + dfs(child, vals) + vals.append("#") + + vals = [] + dfs(root, vals) + return " ".join(vals) + + + def deserialize(self, data): + """Decodes your encoded data to tree. + + :type data: str + :rtype: Node + """ + 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 + + if not data: + return None + + vals = iter(isplit(data, ' ')) + root = Node(int(next(vals)), []) + stack = [root] + for val in vals: + if val == "#": + stack.pop() + else: + node = Node(int(val), []) + stack[-1].children.append(node) + stack.append(node) + return root + + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.deserialize(codec.serialize(root)) From 710fa04b7c11c0e70629d27b515017f12bcec985 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 16:51:53 +0800 Subject: [PATCH 4912/4971] Update serialize-and-deserialize-n-ary-tree.py --- .../serialize-and-deserialize-n-ary-tree.py | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/Python/serialize-and-deserialize-n-ary-tree.py b/Python/serialize-and-deserialize-n-ary-tree.py index 7a135ce84..b580ea7ea 100644 --- a/Python/serialize-and-deserialize-n-ary-tree.py +++ b/Python/serialize-and-deserialize-n-ary-tree.py @@ -45,21 +45,22 @@ def isplit(source, sep): return yield source[start:idx] start = idx + sepsize - + + def dfs(vals): + val = next(vals) + if val == "#": + return None + root = Node(int(val), []) + child = dfs(vals) + while child: + root.children.append(child) + child = dfs(vals) + return root + if not data: return None - vals = iter(isplit(data, ' ')) - root = Node(int(next(vals)), []) - stack = [root] - for val in vals: - if val == "#": - stack.pop() - else: - node = Node(int(val), []) - stack[-1].children.append(node) - stack.append(node) - return root + return dfs(iter(isplit(data, ' '))) # Your Codec object will be instantiated and called as such: From a2bee25ae8040b25ede44c989490f6d50fa7fb21 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 16:53:10 +0800 Subject: [PATCH 4913/4971] Update serialize-and-deserialize-n-ary-tree.py --- Python/serialize-and-deserialize-n-ary-tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/serialize-and-deserialize-n-ary-tree.py b/Python/serialize-and-deserialize-n-ary-tree.py index b580ea7ea..e1bc83f1c 100644 --- a/Python/serialize-and-deserialize-n-ary-tree.py +++ b/Python/serialize-and-deserialize-n-ary-tree.py @@ -1,13 +1,13 @@ # Time: O(n) # Space: O(h) -""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children -""" + + class Codec: def serialize(self, root): From 0e28ea9e41c7940680f33d25ee4d355dd00f4636 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 17:13:03 +0800 Subject: [PATCH 4914/4971] Create serialize-and-deserialize-n-ary-tree.cpp --- C++/serialize-and-deserialize-n-ary-tree.cpp | 137 +++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 C++/serialize-and-deserialize-n-ary-tree.cpp diff --git a/C++/serialize-and-deserialize-n-ary-tree.cpp b/C++/serialize-and-deserialize-n-ary-tree.cpp new file mode 100644 index 000000000..76bd46986 --- /dev/null +++ b/C++/serialize-and-deserialize-n-ary-tree.cpp @@ -0,0 +1,137 @@ +// Time: O(n) +// Space: O(h) + +/* +// Definition for a Node. +class Node { +public: + int val = NULL; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ +class Codec { +public: + + // Encodes a tree to a single string. + string serialize(Node* root) { + ostringstream out; + serializeHelper(root, out); + return out.str(); + } + + // Decodes your encoded data to tree. + Node* deserialize(string data) { + if (data.empty()) { + return nullptr; + } + int start = 0; + return deserializeHelper(data, &start); + } + +private: + void serializeHelper(const Node *root, ostringstream& out) { + if (!root) { + return; + } + + out << root->val << " "; + for (const auto& child : root->children) { + serializeHelper(child, out); + } + out << "# "; + } + + Node *deserializeHelper(const string& data, int *start) { + int num; + if (!getNumber(data, start, &num)) { + return nullptr; + } + auto root = new Node(num); + for (auto child = deserializeHelper(data, start); + child != nullptr; + child = deserializeHelper(data, start)) { + root->children.emplace_back(child); + } + return root; + } + + 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; + } +}; + +// Time: O(n) +// Space: O(n) +class Codec2 { +public: + + // Encodes a tree to a single string. + string serialize(Node* root) { + ostringstream out; + serializeHelper(root, out); + return out.str(); + } + + // Decodes your encoded data to tree. + Node* deserialize(string data) { + if (data.empty()) { + return nullptr; + } + istringstream in(data); // Space: O(n) + return deserializeHelper(in); + } + +private: + void serializeHelper(const Node *root, ostringstream& out) { + if (!root) { + return; + } + + out << root->val << " "; + for (const auto& child : root->children) { + serializeHelper(child, out); + } + out << "# "; + } + + Node *deserializeHelper(istringstream& in) { + string val; + in >> val; + if (val == "#") { + return nullptr; + } + auto root = new Node(stoi(val)); + for (auto child = deserializeHelper(in); + child != nullptr; + child = deserializeHelper(in)) { + root->children.emplace_back(child); + } + return root; + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.deserialize(codec.serialize(root)); From 73f1169ad6a194dcc3a4b5234476a756477d7de8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 18:00:22 +0800 Subject: [PATCH 4915/4971] Create encode-n-ary-tree-to-binary-tree.py --- Python/encode-n-ary-tree-to-binary-tree.py | 69 ++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Python/encode-n-ary-tree-to-binary-tree.py diff --git a/Python/encode-n-ary-tree-to-binary-tree.py b/Python/encode-n-ary-tree-to-binary-tree.py new file mode 100644 index 000000000..864514a6a --- /dev/null +++ b/Python/encode-n-ary-tree-to-binary-tree.py @@ -0,0 +1,69 @@ +# Time: O(n) +# Space: O(h) + +""" +# Definition for a Node. +class Node(object): + def __init__(self, val, children): + self.val = val + self.children = children +""" +""" +# 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 encode(self, root): + """Encodes an n-ary tree to a binary tree. + + :type root: Node + :rtype: TreeNode + """ + def encodeHelper(root, parent, index): + if not root: + return None + node = TreeNode(root.val); + if index+1 < len(parent.children): + node.left = encodeHelper(parent.children[index+1], parent, index+1) + if root.children: + node.right = encodeHelper(root.children[0], root, 0); + return node + + if not root: + return None + node = TreeNode(root.val); + if root.children: + node.right = encodeHelper(root.children[0], root, 0) + return node + + def decode(self, data): + """Decodes your binary tree to an n-ary tree. + + :type data: TreeNode + :rtype: Node + """ + def decodeHelper(root, parent): + if not root: + return + children = [] + node = Node(root.val, children) + decodeHelper(root.right, node) + parent.children.append(node) + decodeHelper(root.left, parent) + + if not data: + return None + children = [] + node = Node(data.val, children) + decodeHelper(data.right, node) + return node + + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.decode(codec.encode(root)) From 3e7cc66e0c9c2ce56d46c43d2925ea40ef7b1f14 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 18:01:03 +0800 Subject: [PATCH 4916/4971] Create encode-n-ary-tree-to-binary-tree.cpp --- C++/encode-n-ary-tree-to-binary-tree.cpp | 83 ++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 C++/encode-n-ary-tree-to-binary-tree.cpp diff --git a/C++/encode-n-ary-tree-to-binary-tree.cpp b/C++/encode-n-ary-tree-to-binary-tree.cpp new file mode 100644 index 000000000..b6dc5c03a --- /dev/null +++ b/C++/encode-n-ary-tree-to-binary-tree.cpp @@ -0,0 +1,83 @@ +// Time: O(n) +// Space: O(h) + +/* +// Definition for a Node. +class Node { +public: + int val = NULL; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ +/** + * 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 an n-ary tree to a binary tree. + TreeNode* encode(Node* root) { + if (root == nullptr) { + return nullptr; + } + auto node = new TreeNode(root->val); + if (!root->children.empty()) { + node->right = encodeHelper(root->children[0], root, 0); + } + return node; + } + + // Decodes your binary tree to an n-ary tree. + Node* decode(TreeNode* root) { + if (root == nullptr) { + return nullptr; + } + vector children; + auto node = new Node(root->val, children); + decodeHelper(root->right, node); + return node; + } + +private: + TreeNode *encodeHelper(Node *root, Node *parent, int index) { + if (root == nullptr) { + return nullptr; + } + auto node = new TreeNode(root->val); + if (index + 1 < parent->children.size()) { + node->left = encodeHelper(parent->children[index + 1], parent, index + 1); + } + if (!root->children.empty()) { + node->right = encodeHelper(root->children[0], root, 0); + } + return node; + } + + void decodeHelper(TreeNode* root, Node* parent) { + if (!root) { + return; + } + vector children; + auto node = new Node(root->val, children); + decodeHelper(root->right, node); + parent->children.push_back(node); + decodeHelper(root->left, parent); + } +}; + +// Your Codec object will be instantiated and called as such: +// Codec codec; +// codec.decode(codec.encode(root)); From bd0bf8add54efb32321b84fd06f4261d31231d01 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 18:19:52 +0800 Subject: [PATCH 4917/4971] Create insert-into-a-cyclic-sorted-list.py --- Python/insert-into-a-cyclic-sorted-list.py | 43 ++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/insert-into-a-cyclic-sorted-list.py diff --git a/Python/insert-into-a-cyclic-sorted-list.py b/Python/insert-into-a-cyclic-sorted-list.py new file mode 100644 index 000000000..fde54700d --- /dev/null +++ b/Python/insert-into-a-cyclic-sorted-list.py @@ -0,0 +1,43 @@ +# Time: O(n) +# Space: O(1) + +""" +# Definition for a Node. +class Node(object): + def __init__(self, val, next): + self.val = val + self.next = next +""" +class Solution(object): + def insert(self, head, insertVal): + """ + :type head: Node + :type insertVal: int + :rtype: Node + """ + def insertAfter(node, val): + node.next = Node(val, node.next) + + if not head: + node = Node(insertVal, None) + node.next = node + return node + + curr = head + while True: + if curr.val < curr.next.val: + if curr.val <= insertVal and \ + insertVal <= curr.next.val: + insertAfter(curr, insertVal) + break + elif curr.val > curr.next.val: + if curr.val <= insertVal or \ + insertVal <= curr.next.val: + insertAfter(curr, insertVal) + break; + else: + if curr.next == head: + insertAfter(curr, insertVal) + break + curr = curr.next + return head From 6634fcba7e8590e11fcbe79756a16c7086e80a2a Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 18:20:23 +0800 Subject: [PATCH 4918/4971] Update insert-into-a-cyclic-sorted-list.py --- Python/insert-into-a-cyclic-sorted-list.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/insert-into-a-cyclic-sorted-list.py b/Python/insert-into-a-cyclic-sorted-list.py index fde54700d..66e38c058 100644 --- a/Python/insert-into-a-cyclic-sorted-list.py +++ b/Python/insert-into-a-cyclic-sorted-list.py @@ -34,7 +34,7 @@ def insertAfter(node, val): if curr.val <= insertVal or \ insertVal <= curr.next.val: insertAfter(curr, insertVal) - break; + break else: if curr.next == head: insertAfter(curr, insertVal) From c9c3fbe37f69258ff797443141904fee240caeaa Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 18:20:52 +0800 Subject: [PATCH 4919/4971] Update insert-into-a-cyclic-sorted-list.py --- Python/insert-into-a-cyclic-sorted-list.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/insert-into-a-cyclic-sorted-list.py b/Python/insert-into-a-cyclic-sorted-list.py index 66e38c058..b1f6e7a0c 100644 --- a/Python/insert-into-a-cyclic-sorted-list.py +++ b/Python/insert-into-a-cyclic-sorted-list.py @@ -1,13 +1,13 @@ # Time: O(n) # Space: O(1) -""" # Definition for a Node. class Node(object): def __init__(self, val, next): self.val = val self.next = next -""" + + class Solution(object): def insert(self, head, insertVal): """ From 9b8e66d4a6ae219d6b39255415ad761de943e061 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 18:21:20 +0800 Subject: [PATCH 4920/4971] Create insert-into-a-cyclic-sorted-list.cpp --- C++/insert-into-a-cyclic-sorted-list.cpp | 56 ++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 C++/insert-into-a-cyclic-sorted-list.cpp diff --git a/C++/insert-into-a-cyclic-sorted-list.cpp b/C++/insert-into-a-cyclic-sorted-list.cpp new file mode 100644 index 000000000..40644c85c --- /dev/null +++ b/C++/insert-into-a-cyclic-sorted-list.cpp @@ -0,0 +1,56 @@ +// Time: O(n) +// Space: O(1) + +/* +// Definition for a Node. +class Node { +public: + int val; + Node* next; + + Node() {} + + Node(int _val, Node* _next) { + val = _val; + next = _next; + } +}; +*/ +class Solution { +public: + Node* insert(Node* head, int insertVal) { + if (head == nullptr) { + auto node = new Node(insertVal, nullptr); + node->next = node; + return node; + } + auto curr = head; + while (true) { + if (curr->val < curr->next->val) { + if (curr->val <= insertVal && + insertVal <= curr->next->val) { + insertAfter(curr, insertVal); + break; + } + } else if (curr->val > curr->next->val) { + if (curr->val <= insertVal || + insertVal <= curr->next->val) { + insertAfter(curr, insertVal); + break; + } + } else { + if (curr->next == head) { + insertAfter(curr, insertVal); + break; + } + } + curr = curr->next; + } + return head; + } + +private: + void insertAfter(Node *node, int val) { + node->next = new Node(val, node->next); + } +}; From 63c815a4d541cb6326a9b73a11ffed5fe16d2b8e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 19:05:01 +0800 Subject: [PATCH 4921/4971] Create convert-binary-search-tree-to-sorted-doubly-linked-list.cpp --- ...arch-tree-to-sorted-doubly-linked-list.cpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 C++/convert-binary-search-tree-to-sorted-doubly-linked-list.cpp diff --git a/C++/convert-binary-search-tree-to-sorted-doubly-linked-list.cpp b/C++/convert-binary-search-tree-to-sorted-doubly-linked-list.cpp new file mode 100644 index 000000000..e635b36ab --- /dev/null +++ b/C++/convert-binary-search-tree-to-sorted-doubly-linked-list.cpp @@ -0,0 +1,42 @@ +// Time: O(n) +// Space: O(h) + +/* +// Definition for a Node. +class Node { +public: + int val; + Node* left; + Node* right; + + Node() {} + + Node(int _val, Node* _left, Node* _right) { + val = _val; + left = _left; + right = _right; + } +}; +*/ +class Solution { +public: + Node* treeToDoublyList(Node* root) { + if (!root) { + return nullptr; + } + Node *left_head = root, *left_tail = root; + Node *right_head = root, *right_tail = root; + if (root->left) { + left_head = treeToDoublyList(root->left); + left_tail = left_head->left; + } + if (root->right) { + right_head = treeToDoublyList(root->right); + right_tail = right_head->left; + } + left_tail->right = root, right_head->left = root; + root->left = left_tail, root->right = right_head; + left_head->left = right_tail, right_tail->right = left_head; + return left_head; + } +}; From a8c13b1710001b104956c4b0efa8a82fa6778f02 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 19:05:39 +0800 Subject: [PATCH 4922/4971] Create convert-binary-search-tree-to-sorted-doubly-linked-list.py --- ...earch-tree-to-sorted-doubly-linked-list.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Python/convert-binary-search-tree-to-sorted-doubly-linked-list.py diff --git a/Python/convert-binary-search-tree-to-sorted-doubly-linked-list.py b/Python/convert-binary-search-tree-to-sorted-doubly-linked-list.py new file mode 100644 index 000000000..6838ffae3 --- /dev/null +++ b/Python/convert-binary-search-tree-to-sorted-doubly-linked-list.py @@ -0,0 +1,30 @@ +# Time: O(n) +# Space: O(h) + +""" +# Definition for a Node. +class Node(object): + def __init__(self, val, left, right): + self.val = val + self.left = left + self.right = right +""" +class Solution(object): + def treeToDoublyList(self, root): + """ + :type root: Node + :rtype: Node + """ + if not root: + return None + left_head, left_tail, right_head, right_tail = root, root, root, root + if root.left: + left_head = self.treeToDoublyList(root.left) + left_tail = left_head.left + if root.right: + right_head = self.treeToDoublyList(root.right) + right_tail = right_head.left + left_tail.right, right_head.left = root, root + root.left, root.right = left_tail, right_head + left_head.left, right_tail.right = right_tail, left_head + return left_head From d65165cb098e1a30981498f7eef5ef33d0eebe89 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 19:18:01 +0800 Subject: [PATCH 4923/4971] Create flatten-a-multilevel-doubly-linked-list.cpp --- ...latten-a-multilevel-doubly-linked-list.cpp | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 C++/flatten-a-multilevel-doubly-linked-list.cpp diff --git a/C++/flatten-a-multilevel-doubly-linked-list.cpp b/C++/flatten-a-multilevel-doubly-linked-list.cpp new file mode 100644 index 000000000..5cc969f35 --- /dev/null +++ b/C++/flatten-a-multilevel-doubly-linked-list.cpp @@ -0,0 +1,45 @@ +// Time: O(n) +// Space: O(1) + +/* +// Definition for a Node. +class Node { +public: + int val = NULL; + Node* prev = NULL; + Node* next = NULL; + Node* child = NULL; + + Node() {} + + Node(int _val, Node* _prev, Node* _next, Node* _child) { + val = _val; + prev = _prev; + next = _next; + child = _child; + } +}; +*/ +class Solution { +public: + Node* flatten(Node* head) { + for (auto curr = head; curr; curr = curr->next) { + if (!curr->child) { + continue; + } + auto curr_next = curr->next; + curr->child->prev = curr; + curr->next = curr->child; + auto last_child = curr; + while (last_child->next) { + last_child = last_child->next; + } + if (curr_next) { + last_child->next = curr_next; + curr_next->prev = last_child; + } + curr->child = nullptr; + } + return head; + } +}; From 671a9e0e9cb7b0a4e6d5b90a669c6e5479aebf20 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 19:18:49 +0800 Subject: [PATCH 4924/4971] Create flatten-a-multilevel-doubly-linked-list.py --- ...flatten-a-multilevel-doubly-linked-list.py | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Python/flatten-a-multilevel-doubly-linked-list.py diff --git a/Python/flatten-a-multilevel-doubly-linked-list.py b/Python/flatten-a-multilevel-doubly-linked-list.py new file mode 100644 index 000000000..ff2dc661b --- /dev/null +++ b/Python/flatten-a-multilevel-doubly-linked-list.py @@ -0,0 +1,33 @@ +# Time: O(n) +# Space: O(1) + +# Definition for a Node. +class Node(object): + def __init__(self, val, prev, next, child): + self.val = val + self.prev = prev + self.next = next + self.child = child + + +class Solution(object): + def flatten(self, head): + """ + :type head: Node + :rtype: Node + """ + curr = head + while curr: + if curr.child: + curr_next = curr.next + curr.child.prev = curr + curr.next = curr.child + last_child = curr + while last_child.next: + last_child = last_child.next + if curr_next: + last_child.next = curr_next + curr_next.prev = last_child + curr.child = None + curr = curr.next + return head From d9f25772d4c34de069f0beb716050ee0becfcad7 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 19:28:56 +0800 Subject: [PATCH 4925/4971] Create search-in-a-sorted-array-of-unknown-size.cpp --- ...arch-in-a-sorted-array-of-unknown-size.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/search-in-a-sorted-array-of-unknown-size.cpp diff --git a/C++/search-in-a-sorted-array-of-unknown-size.cpp b/C++/search-in-a-sorted-array-of-unknown-size.cpp new file mode 100644 index 000000000..d30a7f7c5 --- /dev/null +++ b/C++/search-in-a-sorted-array-of-unknown-size.cpp @@ -0,0 +1,24 @@ +// Time: O(logn) +// Space: O(1) + +// Forward declaration of ArrayReader class. +class ArrayReader; + +class Solution { +public: + int search(const ArrayReader& reader, int target) { + int left = 0, right = 19999; + while (left <= right) { + auto mid = left + (right-left) / 2; + auto response = reader.get(mid); + if (response > target) { + right = mid - 1; + } else if (response < target) { + left = mid + 1; + } else { + return mid; + } + } + return -1; + } +}; From 4bc715be98aa5dc9d4981f92483083afededcc76 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 19:29:57 +0800 Subject: [PATCH 4926/4971] Create search-in-a-sorted-array-of-unknown-size.py --- ...earch-in-a-sorted-array-of-unknown-size.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/search-in-a-sorted-array-of-unknown-size.py diff --git a/Python/search-in-a-sorted-array-of-unknown-size.py b/Python/search-in-a-sorted-array-of-unknown-size.py new file mode 100644 index 000000000..9300a9e22 --- /dev/null +++ b/Python/search-in-a-sorted-array-of-unknown-size.py @@ -0,0 +1,21 @@ +# Time: O(logn) +# Space: O(1) + +class Solution(object): + def search(self, reader, target): + """ + :type reader: ArrayReader + :type target: int + :rtype: int + """ + left, right = 0, 19999 + while left <= right: + mid = left + (right-left)//2 + response = reader.get(mid) + if response > target: + right = mid-1 + elif response < target: + left = mid+1 + else: + return mid + return -1 From fb0e64b15db8da5a6ee40dd4a58e9c6fcc5c8009 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 19:31:43 +0800 Subject: [PATCH 4927/4971] Update convert-binary-search-tree-to-sorted-doubly-linked-list.py --- ...convert-binary-search-tree-to-sorted-doubly-linked-list.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/convert-binary-search-tree-to-sorted-doubly-linked-list.py b/Python/convert-binary-search-tree-to-sorted-doubly-linked-list.py index 6838ffae3..95748c003 100644 --- a/Python/convert-binary-search-tree-to-sorted-doubly-linked-list.py +++ b/Python/convert-binary-search-tree-to-sorted-doubly-linked-list.py @@ -1,14 +1,14 @@ # Time: O(n) # Space: O(h) -""" # Definition for a Node. class Node(object): def __init__(self, val, left, right): self.val = val self.left = left self.right = right -""" + + class Solution(object): def treeToDoublyList(self, root): """ From 148f4ec4f2f4a7b03373c5d1803568b21ab76000 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 19:32:56 +0800 Subject: [PATCH 4928/4971] Update encode-n-ary-tree-to-binary-tree.py --- Python/encode-n-ary-tree-to-binary-tree.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/encode-n-ary-tree-to-binary-tree.py b/Python/encode-n-ary-tree-to-binary-tree.py index 864514a6a..c0842bbee 100644 --- a/Python/encode-n-ary-tree-to-binary-tree.py +++ b/Python/encode-n-ary-tree-to-binary-tree.py @@ -1,21 +1,21 @@ # Time: O(n) # Space: O(h) -""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children -""" -""" + + # 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 encode(self, root): From 05b0a28eb7c090c9ae0a6a775cc52cdd26515af0 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 19:40:29 +0800 Subject: [PATCH 4929/4971] Create binary-search.cpp --- C++/binary-search.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/binary-search.cpp diff --git a/C++/binary-search.cpp b/C++/binary-search.cpp new file mode 100644 index 000000000..53b02fe7a --- /dev/null +++ b/C++/binary-search.cpp @@ -0,0 +1,20 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int search(vector& nums, int target) { + int left = 0, right = nums.size() - 1; + while (left <= right) { + auto mid = left + (right-left) / 2; + if (nums[mid] > target) { + right = mid - 1; + } else if (nums[mid] < target) { + left = mid + 1; + } else { + return mid; + } + } + return -1; + } +}; From b70bdf6fc728391885c4c68e1c198623eb801486 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 19:41:59 +0800 Subject: [PATCH 4930/4971] Create binary-search.py --- Python/binary-search.py | 42 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/binary-search.py diff --git a/Python/binary-search.py b/Python/binary-search.py new file mode 100644 index 000000000..315b30ec7 --- /dev/null +++ b/Python/binary-search.py @@ -0,0 +1,42 @@ +# Time: O(logn) +# Space: O(1) + +# Given a sorted (in ascending order) integer array nums of n elements +# and a target value, write a function to search target in nums. +# If target exists, then return its index, otherwise return -1. +# +# Example 1: +# +# Input: nums = [-1,0,3,5,9,12], target = 9 +# Output: 4 +# Explanation: 9 exists in nums and its index is 4 +# +# Example 2: +# +# Input: nums = [-1,0,3,5,9,12], target = 2 +# Output: -1 +# Explanation: 2 does not exist in nums so return -1 +# +# Note: +# - You may assume that all elements in nums are unique. +# - n will be in the range [1, 10000]. +# - The value of each element in nums will be in the range [-9999, 9999]. + + +class Solution(object): + def search(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + left, right = 0, len(nums)-1 + while left <= right: + mid = left + (right-left)//2 + if nums[mid] > target: + right = mid-1 + elif nums[mid] < target: + left = mid+1 + else: + return mid + return -1 From a2377fb8bed4e1e28a38930f54fe87c172c2631c Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 22:14:32 +0800 Subject: [PATCH 4931/4971] Create kth-largest-element-in-a-stream.cpp --- C++/kth-largest-element-in-a-stream.cpp | 31 +++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/kth-largest-element-in-a-stream.cpp diff --git a/C++/kth-largest-element-in-a-stream.cpp b/C++/kth-largest-element-in-a-stream.cpp new file mode 100644 index 000000000..1b1d69cfe --- /dev/null +++ b/C++/kth-largest-element-in-a-stream.cpp @@ -0,0 +1,31 @@ +// Time: O(nlogk) +// Space: O(k) + +class KthLargest { +public: + KthLargest(int k, vector nums) : + k_(k) { + for (const auto& num : nums) { + add(num); + } + } + + int add(int val) { + min_heap_.emplace(val); + if (min_heap_.size() > k_) { + min_heap_.pop(); + } + return min_heap_.top(); + } + +private: + const int k_; + priority_queue, greater> min_heap_; +}; + +/** + * Your KthLargest object will be instantiated and called as such: + * KthLargest obj = new KthLargest(k, nums); + * int param_1 = obj.add(val); + */ + From 75e7c19d57ac5b0598fc4f809de40d0e0db82bad Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 22:16:01 +0800 Subject: [PATCH 4932/4971] Create kth-largest-element-in-a-stream.py --- Python/kth-largest-element-in-a-stream.py | 56 +++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/kth-largest-element-in-a-stream.py diff --git a/Python/kth-largest-element-in-a-stream.py b/Python/kth-largest-element-in-a-stream.py new file mode 100644 index 000000000..27e57d241 --- /dev/null +++ b/Python/kth-largest-element-in-a-stream.py @@ -0,0 +1,56 @@ +# Time: O(nlogk) +# Space: O(k) + +# Design a class to find the kth largest element in a stream. +# Note that it is the kth largest element in the sorted order, +# not the kth distinct element. +# +# Your KthLargest class will have a constructor +# which accepts an integer k and an integer array nums, +# which contains initial elements from the stream. +# For each call to the method KthLargest.add, +# return the element representing the kth largest element in the stream. +# +# Example: +# +# int k = 3; +# int[] arr = [4,5,8,2]; +# KthLargest kthLargest = new KthLargest(3, arr); +# kthLargest.add(3); // returns 4 +# kthLargest.add(5); // returns 5 +# kthLargest.add(10); // returns 5 +# kthLargest.add(9); // returns 8 +# kthLargest.add(4); // returns 8 +# Note: +# - You may assume that nums' length ≥ k-1 and k ≥ 1. + +import heapq + + +class KthLargest(object): + + def __init__(self, k, nums): + """ + :type k: int + :type nums: List[int] + """ + self.__k = k + self.__min_heap = [] + for n in nums: + self.add(n) + + + def add(self, val): + """ + :type val: int + :rtype: int + """ + heapq.heappush(self.__min_heap, val) + if len(self.__min_heap) > self.__k: + heapq.heappop(self.__min_heap) + return self.__min_heap[0] + + +# Your KthLargest object will be instantiated and called as such: +# obj = KthLargest(k, nums) +# param_1 = obj.add(val) From 9194edfbd7542381de832be53972997d78a38e1b Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 23:03:18 +0800 Subject: [PATCH 4933/4971] Create construct-quad-tree.cpp --- C++/construct-quad-tree.cpp | 56 +++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 C++/construct-quad-tree.cpp diff --git a/C++/construct-quad-tree.cpp b/C++/construct-quad-tree.cpp new file mode 100644 index 000000000..cfe3f6888 --- /dev/null +++ b/C++/construct-quad-tree.cpp @@ -0,0 +1,56 @@ +// Time: O(n) +// Space: O(h) + +/* +// Definition for a QuadTree node. +class Node { +public: + bool val; + bool isLeaf; + Node* topLeft; + Node* topRight; + Node* bottomLeft; + Node* bottomRight; + + Node() {} + + Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { + val = _val; + isLeaf = _isLeaf; + topLeft = _topLeft; + topRight = _topRight; + bottomLeft = _bottomLeft; + bottomRight = _bottomRight; + } +}; +*/ +class Solution { +public: + Node* construct(vector>& grid) { + if (grid.empty()) { + return nullptr; + } + return dfs(grid, 0, 0, grid.size()); + } + +private: + Node* dfs(const vector>& grid, + int x, int y, int l) { + if (l == 1) { + return new Node(grid[x][y] == 1, true, nullptr, nullptr, nullptr, nullptr); + } + int half = l / 2; + auto topLeftNode = dfs(grid, x, y, half); + auto topRightNode = dfs(grid, x, y + half, half); + auto bottomLeftNode = dfs(grid, x + half, y, half); + auto bottomRightNode = dfs(grid, x + half, y + half, half); + if (topLeftNode->isLeaf && topRightNode->isLeaf && + bottomLeftNode->isLeaf && bottomRightNode->isLeaf && + topLeftNode->val == topRightNode->val && + topRightNode->val == bottomLeftNode->val && + bottomLeftNode->val == bottomRightNode->val) { + return new Node(topLeftNode->val, true, nullptr, nullptr, nullptr, nullptr); + } + return new Node(true, false, topLeftNode, topRightNode, bottomLeftNode, bottomRightNode); + } +}; From 843d9ebf654a8d475329c6884ed6ebaff50b802e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 23:05:30 +0800 Subject: [PATCH 4934/4971] Create construct-quad-tree.py --- Python/construct-quad-tree.py | 62 +++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Python/construct-quad-tree.py diff --git a/Python/construct-quad-tree.py b/Python/construct-quad-tree.py new file mode 100644 index 000000000..39e4204a8 --- /dev/null +++ b/Python/construct-quad-tree.py @@ -0,0 +1,62 @@ +# Time: O(n) +# Space: O(h) + +# We want to use quad trees to store an N x N boolean grid. +# Each cell in the grid can only be true or false. +# The root node represents the whole grid. For each node, +# it will be subdivided into four children nodes until the values +# in the region it represents are all the same. +# +# Each node has another two boolean attributes : isLeaf and val. isLeaf is true +# if and only if the node is a leaf node. +# The val attribute for a leaf node contains the value of the region it represents. +# +# Your task is to use a quad tree to represent a given grid. +# The following example may help you understand the problem better: +# +# Given the 8 x 8 grid below, we want to construct the corresponding quad tree: +# It can be divided according to the definition above: +# +# The corresponding quad tree should be as following, +# where each node is represented as a (isLeaf, val) pair. +# +# For the non-leaf nodes, val can be arbitrary, so it is represented as *. +# +# Note: +# - N is less than 1000 and guaranteened to be a power of 2. +# - If you want to know more about the quad tree, you can refer to its wiki. + +# Definition for a QuadTree node. +class Node(object): + def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): + self.val = val + self.isLeaf = isLeaf + self.topLeft = topLeft + self.topRight = topRight + self.bottomLeft = bottomLeft + self.bottomRight = bottomRight + + +class Solution(object): + def construct(self, grid): + """ + :type grid: List[List[int]] + :rtype: Node + """ + def dfs(grid, x, y, l): + if l == 1: + return Node(grid[x][y] == 1, True, None, None, None, None) + half = l // 2 + topLeftNode = dfs(grid, x, y, half) + topRightNode = dfs(grid, x, y+half, half) + bottomLeftNode = dfs(grid, x+half, y, half) + bottomRightNode = dfs(grid, x+half, y+half, half) + if topLeftNode.isLeaf and topRightNode.isLeaf and \ + bottomLeftNode.isLeaf and bottomRightNode.isLeaf and \ + topLeftNode.val == topRightNode.val == bottomLeftNode.val == bottomRightNode.val: + return Node(topLeftNode.val, True, None, None, None, None) + return Node(True, False, topLeftNode, topRightNode, bottomLeftNode, bottomRightNode) + + if not grid: + return None + return dfs(grid, 0, 0, len(grid)) From 28ebcfb1101b363352a422b2b5e212e2f156a2e3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 23:12:18 +0800 Subject: [PATCH 4935/4971] Create maximum-depth-of-n-ary-tree.cpp --- C++/maximum-depth-of-n-ary-tree.cpp | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/maximum-depth-of-n-ary-tree.cpp diff --git a/C++/maximum-depth-of-n-ary-tree.cpp b/C++/maximum-depth-of-n-ary-tree.cpp new file mode 100644 index 000000000..48fd5d13b --- /dev/null +++ b/C++/maximum-depth-of-n-ary-tree.cpp @@ -0,0 +1,31 @@ +// Time: O(n) +// Space: O(h) + +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ +class Solution { +public: + int maxDepth(Node* root) { + if (root == nullptr) { + return 0; + } + int depth = 0; + for (const auto& child : root->children) { + depth = max(depth, maxDepth(child)); + } + return 1 + depth; + } +}; From 0dc2c75307bf6b4257373cf2c14b98bd932f0ace Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 23:14:03 +0800 Subject: [PATCH 4936/4971] Create maximum-depth-of-n-ary-tree.py --- Python/maximum-depth-of-n-ary-tree.py | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Python/maximum-depth-of-n-ary-tree.py diff --git a/Python/maximum-depth-of-n-ary-tree.py b/Python/maximum-depth-of-n-ary-tree.py new file mode 100644 index 000000000..088901eef --- /dev/null +++ b/Python/maximum-depth-of-n-ary-tree.py @@ -0,0 +1,35 @@ +# Time: O(n) +# Space: O(h) + +# Given a n-ary tree, find its maximum depth. +# +# The maximum depth is the number of nodes along the longest path +# from the root node down to the farthest leaf node. +# +# For example, given a 3-ary tree: +# +# We should return its max depth, which is 3. +# +# Note: +# - The depth of the tree is at most 1000. +# - The total number of nodes is at most 5000. + +# Definition for a Node. +class Node(object): + def __init__(self, val, children): + self.val = val + self.children = children + + +class Solution(object): + def maxDepth(self, root): + """ + :type root: Node + :rtype: int + """ + if not root: + return 0 + depth = 0 + for child in root.children: + depth = max(depth, self.maxDepth(child)) + return 1+depth From 58ffc83e6d6b4bad58266840bdead32013880069 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 23:22:31 +0800 Subject: [PATCH 4937/4971] Create to-lower-case.cpp --- C++/to-lower-case.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 C++/to-lower-case.cpp diff --git a/C++/to-lower-case.cpp b/C++/to-lower-case.cpp new file mode 100644 index 000000000..73e99af33 --- /dev/null +++ b/C++/to-lower-case.cpp @@ -0,0 +1,17 @@ +// Time: O(n) +// Space: O(1) + +class Solution { +public: + string toLowerCase(string str) { + string result; + for (const auto c : str) { + if ('A' <= c && c <= 'Z') { + result.push_back('a' + c - 'A'); + } else { + result.push_back(c); + } + } + return result; + } +}; From 1926289a8cad1107f9bd4e0d66a36afee3fd1017 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 23:24:00 +0800 Subject: [PATCH 4938/4971] Create to-lower-case.py --- Python/to-lower-case.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Python/to-lower-case.py diff --git a/Python/to-lower-case.py b/Python/to-lower-case.py new file mode 100644 index 000000000..7e2cee950 --- /dev/null +++ b/Python/to-lower-case.py @@ -0,0 +1,14 @@ +# Time: O(n) +# Space: O(1) + +# Implement function ToLowerCase() that has a string parameter str, +# and returns the same string in lowercase. + +class Solution(object): + def toLowerCase(self, str): + """ + :type str: str + :rtype: str + """ + return "".join([chr(ord('a')+ord(c)-ord('A')) + if 'A' <= c <= 'Z' else c for c in str]) From b4a932d00772387a5a89c55bfddc134d82c8c4df Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 23:41:21 +0800 Subject: [PATCH 4939/4971] Create n-ary-tree-postorder-traversal.py --- Python/n-ary-tree-postorder-traversal.py | 49 ++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Python/n-ary-tree-postorder-traversal.py diff --git a/Python/n-ary-tree-postorder-traversal.py b/Python/n-ary-tree-postorder-traversal.py new file mode 100644 index 000000000..e972ba569 --- /dev/null +++ b/Python/n-ary-tree-postorder-traversal.py @@ -0,0 +1,49 @@ +# Time: O(n) +# Space: O(h) + +# Given an n-ary tree, return the postorder traversal of its nodes' values. +# For example, given a 3-ary tree: +# Return its postorder traversal as: [5,6,3,2,4,1]. +# Note: Recursive solution is trivial, could you do it iteratively? + +# Definition for a Node. +class Node(object): + def __init__(self, val, children): + self.val = val + self.children = children + + +class Solution(object): + def postorder(self, root): + """ + :type root: Node + :rtype: List[int] + """ + if not root: + return [] + result, stack = [], [root] + while stack: + node = stack.pop() + result.append(node.val) + for child in node.children: + if child: + stack.append(child) + return result[::-1] + + +class Solution2(object): + def postorder(self, root): + """ + :type root: Node + :rtype: List[int] + """ + def dfs(root, result): + for child in root.children: + if child: + dfs(child, result) + result.append(root.val) + + result = [] + if root: + dfs(root, result) + return result From 7bca7855cb2bd424b139d0e62fb39a60a294da7e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 23:43:12 +0800 Subject: [PATCH 4940/4971] Create n-ary-tree-preorder-traversal.py --- Python/n-ary-tree-preorder-traversal.py | 51 +++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Python/n-ary-tree-preorder-traversal.py diff --git a/Python/n-ary-tree-preorder-traversal.py b/Python/n-ary-tree-preorder-traversal.py new file mode 100644 index 000000000..6ad99cdd7 --- /dev/null +++ b/Python/n-ary-tree-preorder-traversal.py @@ -0,0 +1,51 @@ +# Time: O(n) +# Space: O(h) + +# Given an n-ary tree, return the preorder traversal of its nodes' values. +# +# For example, given a 3-ary tree: +# Return its preorder traversal as: [1,3,5,6,2,4]. +# +# Note: Recursive solution is trivial, could you do it iteratively? + +# Definition for a Node. +class Node(object): + def __init__(self, val, children): + self.val = val + self.children = children + + +class Solution(object): + def preorder(self, root): + """ + :type root: Node + :rtype: List[int] + """ + if not root: + return [] + result, stack = [], [root] + while stack: + node = stack.pop() + result.append(node.val) + for child in reversed(node.children): + if child: + stack.append(child) + return result + + +class Solution2(object): + def preorder(self, root): + """ + :type root: Node + :rtype: List[int] + """ + def dfs(root, result): + result.append(root.val) + for child in root.children: + if child: + dfs(child, result) + + result = [] + if root: + dfs(root, result) + return result From 5a22fcd826d5546dcf9ba629ed1266292601f38d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 23:50:00 +0800 Subject: [PATCH 4941/4971] Create n-ary-tree-preorder-traversal.cpp --- C++/n-ary-tree-preorder-traversal.cpp | 40 +++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/n-ary-tree-preorder-traversal.cpp diff --git a/C++/n-ary-tree-preorder-traversal.cpp b/C++/n-ary-tree-preorder-traversal.cpp new file mode 100644 index 000000000..923a62455 --- /dev/null +++ b/C++/n-ary-tree-preorder-traversal.cpp @@ -0,0 +1,40 @@ +// Time: O(n) +// Space: O(h) + +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ +class Solution { +public: + vector preorder(Node* root) { + if (!root) { + return {}; + } + vector result; + vector stack{root}; + while (!stack.empty()) { + auto node = stack.back(); stack.pop_back(); + result.emplace_back(node->val); + for (auto rit = node->children.rbegin(); + rit != node->children.rend(); + ++rit) { + if (*rit) { + stack.emplace_back(*rit); + } + } + } + return result; + } +}; From 6a797cbedc6b72c89328bcf052efac485e3520be Mon Sep 17 00:00:00 2001 From: kamyu Date: Sat, 14 Jul 2018 23:50:35 +0800 Subject: [PATCH 4942/4971] Create n-ary-tree-postorder-traversal.cpp --- C++/n-ary-tree-postorder-traversal.cpp | 39 ++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 C++/n-ary-tree-postorder-traversal.cpp diff --git a/C++/n-ary-tree-postorder-traversal.cpp b/C++/n-ary-tree-postorder-traversal.cpp new file mode 100644 index 000000000..31981e6b6 --- /dev/null +++ b/C++/n-ary-tree-postorder-traversal.cpp @@ -0,0 +1,39 @@ +// Time: O(n) +// Space: O(h) + +/* +// Definition for a Node. +class Node { +public: + int val; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ +class Solution { +public: + vector postorder(Node* root) { + if (!root) { + return {}; + } + vector result; + vector stack{root}; + while (!stack.empty()) { + auto node = stack.back(); stack.pop_back(); + result.emplace_back(node->val); + for (const auto& child : node->children) { + if (child) { + stack.emplace_back(child); + } + } + } + reverse(result.begin(), result.end()); + return result; + } +}; From 63f92cab8fceb50df04f51623bf33543e1972c43 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 00:03:12 +0800 Subject: [PATCH 4943/4971] Create n-ary-tree-level-order-traversal.cpp --- C++/n-ary-tree-level-order-traversal.cpp | 43 ++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 C++/n-ary-tree-level-order-traversal.cpp diff --git a/C++/n-ary-tree-level-order-traversal.cpp b/C++/n-ary-tree-level-order-traversal.cpp new file mode 100644 index 000000000..222aa6b7a --- /dev/null +++ b/C++/n-ary-tree-level-order-traversal.cpp @@ -0,0 +1,43 @@ +// Time: O(n) +// Space: O(w) + +/* +// Definition for a Node. +class Node { +public: + int val = NULL; + vector children; + + Node() {} + + Node(int _val, vector _children) { + val = _val; + children = _children; + } +}; +*/ +class Solution { +public: + vector> levelOrder(Node* root) { + if (!root) { + return {}; + } + vector> result; + vector q{root}; + while (!q.empty()) { + vector curr; + vector next_q; + for (const auto& node : q) { + for (const auto& child : node->children) { + if (child) { + next_q.emplace_back(child); + } + } + curr.emplace_back(node->val); + } + result.emplace_back(move(curr)); + q = move(next_q); + } + return result; + } +}; From 14025758fddf6b16aeb00fa72933155f6e005a17 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 00:04:41 +0800 Subject: [PATCH 4944/4971] Create n-ary-tree-level-order-traversal.py --- Python/n-ary-tree-level-order-traversal.py | 40 ++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Python/n-ary-tree-level-order-traversal.py diff --git a/Python/n-ary-tree-level-order-traversal.py b/Python/n-ary-tree-level-order-traversal.py new file mode 100644 index 000000000..1765b3f70 --- /dev/null +++ b/Python/n-ary-tree-level-order-traversal.py @@ -0,0 +1,40 @@ +# Time: O(n) +# Space: O(w) + +# Given an n-ary tree, return the level order traversal of +# its nodes' values. (ie, from left to right, level by level). +# +# For example, given a 3-ary tree: +# +# We should return its level order traversal: +# [ +# [1], +# [3,2,4], +# [5,6] +# ] +# +# Note: +# - The depth of the tree is at most 1000. +# - The total number of nodes is at most 5000. + + +# Definition for a Node. +class Node(object): + def __init__(self, val, children): + self.val = val + self.children = children + + +class Solution(object): + def levelOrder(self, root): + """ + :type root: Node + :rtype: List[List[int]] + """ + if not root: + return [] + result, q = [], [root] + while q: + result.append([node.val for node in q]) + q = [child for node in q for child in node.children if child] + return result From 6c8876fe9da0b80ef0ae2b73e648d8a2102cad6d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 12:08:01 +0800 Subject: [PATCH 4945/4971] Create design-linked-list.cpp --- C++/design-linked-list.cpp | 110 +++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 C++/design-linked-list.cpp diff --git a/C++/design-linked-list.cpp b/C++/design-linked-list.cpp new file mode 100644 index 000000000..3b9408906 --- /dev/null +++ b/C++/design-linked-list.cpp @@ -0,0 +1,110 @@ +// Time: O(n) +// Space: O(n) + +struct Node { + Node(int value) : + val(value), + next(nullptr), + prev(nullptr) {} + int val; + Node *next; + Node *prev; +}; + +class MyLinkedList { +public: + /** Initialize your data structure here. */ + MyLinkedList() : size_(0) { + head_ = tail_ = new Node(-1); + head_->next = tail_; + tail_->prev = head_; + } + + /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ + int get(int index) { + if (0 <= index && index <= size_ / 2) { + return forward(0, index, head_->next)->val; + } else if (size_ / 2 < index && index < size_) { + return backward(size_, index, tail_)->val; + } + return -1; + } + + /** Add a node of value val before the first element of the linked list. + After the insertion, the new node will be the first node of the linked list. */ + void addAtHead(int val) { + add(head_, val); + } + + /** Append a node of value val to the last element of the linked list. */ + void addAtTail(int val) { + add(tail_->prev, val); + } + + /** Add a node of value val before the index-th node in the linked list. + If index equals to the length of linked list, + the node will be appended to the end of linked list. + If index is greater than the length, the node will not be inserted. */ + void addAtIndex(int index, int val) { + if (0 <= index && index <= size_ / 2) { + add(forward(0, index, head_->next)->prev, val); + } else if (size_ / 2 < index && index <= size_) { + add(backward(size_, index, tail_)->prev, val); + } + } + + /** Delete the index-th node in the linked list, if the index is valid. */ + void deleteAtIndex(int index) { + if (0 <= index && index <= size_ / 2) { + remove(forward(0, index, head_->next)); + } else if (size_ / 2 < index && index < size_) { + remove(backward(size_, index, tail_)); + } + } + +private: + void add(Node *preNode, int val) { + auto node = new Node(val); + node->prev = preNode; + node->next = preNode->next; + node->prev->next = node->next->prev = node; + ++size_; + } + + void remove(Node *node) { + node->prev->next = node->next; + node->next->prev = node->prev; + --size_; + } + + Node *forward(int start, int end, Node *curr) { + while (start != end) { + ++start; + curr = curr->next; + } + return curr; + } + + Node *backward(int start, int end, Node *curr) { + while (start != end) { + --start; + curr = curr->prev; + } + return curr; + } + + Node *head_; + Node *tail_; + int size_; +}; + +/** + * Your MyLinkedList object will be instantiated and called as such: + * MyLinkedList obj = new MyLinkedList(); + * int param_1 = obj.get(index); + * obj.addAtHead(val); + * obj.addAtTail(val); + * obj.addAtIndex(index,val); + * obj.deleteAtIndex(index); + */ + From 39ce8f3668d73c82fc29d5e7ee4638b47c6116c3 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 12:08:37 +0800 Subject: [PATCH 4946/4971] Create design-linked-list.py --- Python/design-linked-list.py | 107 +++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 Python/design-linked-list.py diff --git a/Python/design-linked-list.py b/Python/design-linked-list.py new file mode 100644 index 000000000..94d48d082 --- /dev/null +++ b/Python/design-linked-list.py @@ -0,0 +1,107 @@ +# Time: O(n) +# Space: O(n) + +class Node: + def __init__(self, value): + self.val = value + self.next = self.prev = None + + +class MyLinkedList(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.__head = self.__tail = Node(-1) + self.__head.next = self.__tail + self.__tail.prev = self.__head + self.__size = 0 + + def get(self, index): + """ + Get the value of the index-th node in the linked list. If the index is invalid, return -1. + :type index: int + :rtype: int + """ + if 0 <= index <= self.__size // 2: + return self.__forward(0, index, self.__head.next).val + elif self.__size // 2 < index < self.__size: + return self.__backward(self.__size, index, self.__tail).val + return -1 + + def addAtHead(self, val): + """ + Add a node of value val before the first element of the linked list. + After the insertion, the new node will be the first node of the linked list. + :type val: int + :rtype: void + """ + self.__add(self.__head, val) + + def addAtTail(self, val): + """ + Append a node of value val to the last element of the linked list. + :type val: int + :rtype: void + """ + self.__add(self.__tail.prev, val) + + def addAtIndex(self, index, val): + """ + Add a node of value val before the index-th node in the linked list. + If index equals to the length of linked list, + the node will be appended to the end of linked list. + If index is greater than the length, the node will not be inserted. + :type index: int + :type val: int + :rtype: void + """ + if 0 <= index <= self.__size // 2: + self.__add(self.__forward(0, index, self.__head.next).prev, val) + elif self.__size // 2 < index <= self.__size: + self.__add(self.__backward(self.__size, index, self.__tail).prev, val) + + def deleteAtIndex(self, index): + """ + Delete the index-th node in the linked list, if the index is valid. + :type index: int + :rtype: void + """ + if 0 <= index <= self.__size // 2: + self.__remove(self.__forward(0, index, self.__head.next)) + elif self.__size // 2 < index < self.__size: + self.__remove(self.__backward(self.__size, index, self.__tail)) + + def __add(self, preNode, val): + node = Node(val) + node.prev = preNode + node.next = preNode.next + node.prev.next = node.next.prev = node + self.__size += 1 + + def __remove(self, node): + node.prev.next = node.next + node.next.prev = node.prev + self.__size -= 1 + + def __forward(self, start, end, curr): + while start != end: + start += 1 + curr = curr.next + return curr + + def __backward(self, start, end, curr): + while start != end: + start -= 1 + curr = curr.prev + return curr + + +# Your MyLinkedList object will be instantiated and called as such: +# obj = MyLinkedList() +# param_1 = obj.get(index) +# obj.addAtHead(val) +# obj.addAtTail(val) +# obj.addAtIndex(index,val) +# obj.deleteAtIndex(index) From 2c8772237465739bac85e6c97721dc1188ae0840 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 13:55:17 +0800 Subject: [PATCH 4947/4971] Create minimum-number-of-refueling-stops.cpp --- C++/minimum-number-of-refueling-stops.cpp | 25 +++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 C++/minimum-number-of-refueling-stops.cpp diff --git a/C++/minimum-number-of-refueling-stops.cpp b/C++/minimum-number-of-refueling-stops.cpp new file mode 100644 index 000000000..94e4b2e5e --- /dev/null +++ b/C++/minimum-number-of-refueling-stops.cpp @@ -0,0 +1,25 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + int minRefuelStops(int target, int startFuel, vector>& stations) { + priority_queue max_heap; + stations.push_back(vector{target, numeric_limits::min()}); + + int result = 0, prev = 0; + for (const auto& station : stations) { + startFuel -= station[0] - prev; + while (!max_heap.empty() && startFuel < 0) { + startFuel += max_heap.top(); max_heap.pop(); + ++result; + } + if (startFuel < 0) { + return -1; + } + max_heap.emplace(station[1]); + prev = station[0]; + } + return result; + } +}; From 64135c180c68b6d413baadcd4ad5b646faad4beb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 13:57:54 +0800 Subject: [PATCH 4948/4971] Create minimum-number-of-refueling-stops.py --- Python/minimum-number-of-refueling-stops.py | 73 +++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Python/minimum-number-of-refueling-stops.py diff --git a/Python/minimum-number-of-refueling-stops.py b/Python/minimum-number-of-refueling-stops.py new file mode 100644 index 000000000..19ce7cf0a --- /dev/null +++ b/Python/minimum-number-of-refueling-stops.py @@ -0,0 +1,73 @@ +# Time: O(nlogn) +# Space: O(n) + +# A car travels from a starting position to a destination +# which is target miles east of the starting position. +# +# Along the way, there are gas stations. +# Each station[i] represents a gas station that is station[i][0] miles +# east of the starting position, and has station[i][1] liters of gas. +# +# The car starts with an infinite tank of gas, which initially has startFuel +# liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives. +# +# When the car reaches a gas station, it may stop and refuel, +# transferring all the gas from the station into the car. +# +# What is the least number of refueling stops the car must make +# in order to reach its destination? If it cannot reach the destination, return -1. +# +# Note that if the car reaches a gas station with 0 fuel left, +# the car can still refuel there. +# If the car reaches the destination with 0 fuel left, +# it is still considered to have arrived. +# +# Example 1: +# +# Input: target = 1, startFuel = 1, stations = [] +# Output: 0 +# Explanation: We can reach the target without refueling. +# Example 2: +# +# Input: target = 100, startFuel = 1, stations = [[10,100]] +# Output: -1 +# Explanation: We can't reach the target (or even the first gas station). +# Example 3: +# +# Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]] +# Output: 2 +# Explanation: +# We start with 10 liters of fuel. +# We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas. +# Then, we drive from position 10 to position 60 (expending 50 liters of fuel), +# and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target. +# We made 2 refueling stops along the way, so we return 2. +# +# Note: +# - 1 <= target, startFuel, stations[i][1] <= 10^9 +# - 0 <= stations.length <= 500 +# - 0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target + +class Solution(object): + def minRefuelStops(self, target, startFuel, stations): + """ + :type target: int + :type startFuel: int + :type stations: List[List[int]] + :rtype: int + """ + max_heap = [] + stations.append((target, float("inf"))) + + result = prev = 0 + for location, capacity in stations: + startFuel -= location - prev + while max_heap and startFuel < 0: + startFuel += -heapq.heappop(max_heap) + result += 1 + if startFuel < 0: + return -1 + heapq.heappush(max_heap, -capacity) + prev = location + + return result From f705ea13226be01b457dd22555122b3e06641386 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 14:15:39 +0800 Subject: [PATCH 4949/4971] Create advantage-shuffle.cpp --- C++/advantage-shuffle.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 C++/advantage-shuffle.cpp diff --git a/C++/advantage-shuffle.cpp b/C++/advantage-shuffle.cpp new file mode 100644 index 000000000..96cb01fad --- /dev/null +++ b/C++/advantage-shuffle.cpp @@ -0,0 +1,35 @@ +// Time: O(nlogn) +// Space: O(n) + +class Solution { +public: + vector advantageCount(vector& A, vector& B) { + vector sortedA(A.cbegin(), A.cend()); + sort(sortedA.begin(), sortedA.end()); + vector sortedB(B.cbegin(), B.cend()); + sort(sortedB.begin(), sortedB.end()); + + unordered_map> candidates; + vector others; + int j = 0; + for (const auto& a : sortedA) { + if (a > sortedB[j]) { + candidates[sortedB[j]].emplace_back(a); + ++j; + } else { + others.emplace_back(a); + } + } + vector result; + for (const auto& b : B) { + if (!candidates[b].empty()) { + result.emplace_back(candidates[b].back()); + candidates[b].pop_back(); + } else { + result.emplace_back(others.back()); + others.pop_back(); + } + } + return result; + } +}; From b704d6118b0cfd2ab6a9a25e9515abcd5665b867 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 14:16:59 +0800 Subject: [PATCH 4950/4971] Create advantage-shuffle.py --- Python/advantage-shuffle.py | 43 +++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/advantage-shuffle.py diff --git a/Python/advantage-shuffle.py b/Python/advantage-shuffle.py new file mode 100644 index 000000000..3935a4675 --- /dev/null +++ b/Python/advantage-shuffle.py @@ -0,0 +1,43 @@ +# Time: O(nlogn) +# Space: O(n) + +# Given two arrays A and B of equal size, the advantage of A with respect to B +# is the number of indices i for which A[i] > B[i]. +# +# Return any permutation of A that maximizes its advantage with respect to B. +# +# Example 1: +# +# Input: A = [2,7,11,15], B = [1,10,4,11] +# Output: [2,11,7,15] +# Example 2: +# +# Input: A = [12,24,8,32], B = [13,25,32,11] +# Output: [24,32,8,12] +# +# Note: +# - 1 <= A.length = B.length <= 10000 +# - 0 <= A[i] <= 10^9 +# - 0 <= B[i] <= 10^9 + +class Solution(object): + def advantageCount(self, A, B): + """ + :type A: List[int] + :type B: List[int] + :rtype: List[int] + """ + sortedA = sorted(A) + sortedB = sorted(B) + + candidates = {b: [] for b in B} + others = [] + j = 0 + for a in sortedA: + if a > sortedB[j]: + candidates[sortedB[j]].append(a) + j += 1 + else: + others.append(a) + return [candidates[b].pop() if candidates[b] else others.pop() + for b in B] From 82c303311dae518eed37e8f25b10ea1323cfbd42 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 14:31:20 +0800 Subject: [PATCH 4951/4971] Create reordered-power-of-2.cpp --- C++/reordered-power-of-2.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 C++/reordered-power-of-2.cpp diff --git a/C++/reordered-power-of-2.cpp b/C++/reordered-power-of-2.cpp new file mode 100644 index 000000000..3f4d56cc2 --- /dev/null +++ b/C++/reordered-power-of-2.cpp @@ -0,0 +1,24 @@ +// Time: O((logn)^2) +// Space: O(logn) + +class Solution { +public: + bool reorderedPowerOf2(int N) { + vector count = counter(N); + for (int i = 0; i < 31; ++i) { + if (count == counter(1 << i)) { + return true; + } + } + return false; + } + +private: + vector counter(int N) { + vector result(10, 0); + for (; N; N /= 10) { + ++result[N % 10]; + } + return result; + } +}; From a4d144f3d83d8f3a82a88a687be08aeea71d9796 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 14:32:55 +0800 Subject: [PATCH 4952/4971] Create reordered-power-of-2.py --- Python/reordered-power-of-2.py | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Python/reordered-power-of-2.py diff --git a/Python/reordered-power-of-2.py b/Python/reordered-power-of-2.py new file mode 100644 index 000000000..f889dfbe7 --- /dev/null +++ b/Python/reordered-power-of-2.py @@ -0,0 +1,43 @@ +# Time: O((logn)^2) +# Space: O(logn) + +# Starting with a positive integer N, +# we reorder the digits in any order (including the original order) +# such that the leading digit is not zero. +# +# Return true if and only if we can do this in a way +# such that the resulting number is a power of 2. +# +# Example 1: +# +# Input: 1 +# Output: true +# Example 2: +# +# Input: 10 +# Output: false +# Example 3: +# +# Input: 16 +# Output: true +# Example 4: +# +# Input: 24 +# Output: false +# Example 5: +# +# Input: 46 +# Output: true +# +# Note: +# - 1 <= N <= 10^9 + +class Solution(object): + def reorderedPowerOf2(self, N): + """ + :type N: int + :rtype: bool + """ + count = collections.Counter(str(N)) + return any(count == collections.Counter(str(1 << i)) + for i in xrange(31)) From e2c8465540988c155f5b1ae6d9a3d05cd8bec424 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 14:36:43 +0800 Subject: [PATCH 4953/4971] Create binary-gap.cpp --- C++/binary-gap.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 C++/binary-gap.cpp diff --git a/C++/binary-gap.cpp b/C++/binary-gap.cpp new file mode 100644 index 000000000..97a9affaa --- /dev/null +++ b/C++/binary-gap.cpp @@ -0,0 +1,19 @@ +// Time: O(logn) +// Space: O(1) + +class Solution { +public: + int binaryGap(int N) { + int result = 0; + int last = -1; + for (int i = 0; i < 32; ++i) { + if ((N >> i) & 1) { + if (last != -1) { + result = max(result, i - last); + } + last = i; + } + } + return result; + } +}; From 50c11dd425175806821f4b9f19bdb41fddf4f09f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 14:38:30 +0800 Subject: [PATCH 4954/4971] Create binary-gap.py --- Python/binary-gap.py | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Python/binary-gap.py diff --git a/Python/binary-gap.py b/Python/binary-gap.py new file mode 100644 index 000000000..74067559c --- /dev/null +++ b/Python/binary-gap.py @@ -0,0 +1,57 @@ +# Time: O(logn) +# Space: O(1) + +# Given a positive integer N, find and return the longest distance +# between two consecutive 1's in the binary representation of N. +# +# If there aren't two consecutive 1's, return 0. +# +# Example 1: +# +# Input: 22 +# Output: 2 +# Explanation: +# 22 in binary is 0b10110. +# In the binary representation of 22, there are three ones, +# and two consecutive pairs of 1's. +# The first consecutive pair of 1's have distance 2. +# The second consecutive pair of 1's have distance 1. +# The answer is the largest of these two distances, which is 2. +# Example 2: +# +# Input: 5 +# Output: 2 +# Explanation: +# 5 in binary is 0b101. +# Example 3: +# +# Input: 6 +# Output: 1 +# Explanation: +# 6 in binary is 0b110. +# Example 4: +# +# Input: 8 +# Output: 0 +# Explanation: +# 8 in binary is 0b1000. +# There aren't any consecutive pairs of 1's +# in the binary representation of 8, so we return 0. +# +# Note: +# - 1 <= N <= 10^9 + +class Solution(object): + def binaryGap(self, N): + """ + :type N: int + :rtype: int + """ + result = 0 + last = None + for i in xrange(32): + if (N >> i) & 1: + if last is not None: + result = max(result, i-last) + last = i + return result From 81be8ae86fc4a9ae2c4e69dbb3a75132fd067fbb Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 15:09:57 +0800 Subject: [PATCH 4955/4971] Create design-hashmap.cpp --- C++/design-hashmap.cpp | 55 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 C++/design-hashmap.cpp diff --git a/C++/design-hashmap.cpp b/C++/design-hashmap.cpp new file mode 100644 index 000000000..6327a9b10 --- /dev/null +++ b/C++/design-hashmap.cpp @@ -0,0 +1,55 @@ +// Time: O(1) +// Space: O(n) + +class MyHashMap { +public: + /** Initialize your data structure here. */ + MyHashMap() : data_(10000) { + + } + + /** value will always be positive. */ + void put(int key, int value) { + auto& list = data_[key % data_.size()]; + auto it = find_if(list.begin(), list.end(), + [&](const pair& i) { return i.first == key; } ); + if (it != list.end()) { + it->second = value; + } else { + list.emplace_back(key, value); + } + } + + /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ + int get(int key) { + auto& list = data_[key % data_.size()]; + auto it = find_if(list.begin(), list.end(), + [&](const pair& i) { return i.first == key; } ); + if (it != list.end()) { + return it->second; + } else { + return -1; + } + } + + /** Removes the mapping of the specified value key if this map contains a mapping for the key */ + void remove(int key) { + auto& list = data_[key % data_.size()]; + auto it = find_if(list.begin(), list.end(), + [&](const pair& i) { return i.first == key; } ); + if (it != list.end()) { + list.erase(it); + } + } + +private: + vector>> data_; +}; + +/** + * Your MyHashMap object will be instantiated and called as such: + * MyHashMap obj = new MyHashMap(); + * obj.put(key,value); + * int param_2 = obj.get(key); + * obj.remove(key); + */ From dc6e09cf8daf7845a35beb5f8d416f97c623520f Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 15:13:56 +0800 Subject: [PATCH 4956/4971] Create design-hashset.cpp --- C++/design-hashset.cpp | 45 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 C++/design-hashset.cpp diff --git a/C++/design-hashset.cpp b/C++/design-hashset.cpp new file mode 100644 index 000000000..c0d824f67 --- /dev/null +++ b/C++/design-hashset.cpp @@ -0,0 +1,45 @@ +// Time: O(1) +// Space: O(n) + +class MyHashSet { +public: + /** Initialize your data structure here. */ + MyHashSet() : data_(10000) { + + } + + void add(int key) { + auto& list = data_[key % data_.size()]; + auto it = find(list.begin(), list.end(), key); + if (it == list.end()) { + list.emplace_back(key); + } + } + + void remove(int key) { + auto& list = data_[key % data_.size()]; + auto it = find(list.begin(), list.end(), key); + if (it != list.end()) { + list.erase(it); + } + } + + /** Returns true if this set did not already contain the specified element */ + bool contains(int key) { + auto& list = data_[key % data_.size()]; + auto it = find(list.begin(), list.end(), key); + return it != list.end(); + } + +private: + vector> data_; +}; + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet obj = new MyHashSet(); + * obj.add(key); + * obj.remove(key); + * bool param_3 = obj.contains(key); + */ + From c68094031edc4a7516ce19df8ca92d715d784682 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 15:27:17 +0800 Subject: [PATCH 4957/4971] Create design-hashmap.py --- Python/design-hashmap.py | 125 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 Python/design-hashmap.py diff --git a/Python/design-hashmap.py b/Python/design-hashmap.py new file mode 100644 index 000000000..0b9c6e75f --- /dev/null +++ b/Python/design-hashmap.py @@ -0,0 +1,125 @@ +# Time: O(1) +# Space: O(n) + +# Design a HashMap without using any built-in hash table libraries. +# +# To be specific, your design should include these two functions: +# +# put(key, value) : Insert a (key, value) pair into the HashMap. +# If the value already exists in the HashMap, update the value. +# get(key): Returns the value to which the specified key is mapped, +# or -1 if this map contains no mapping for the key. +# remove(key) : Remove the mapping for the value key if this map contains the mapping for the key. +# +# Example: +# +# MyHashMap hashMap = new MyHashMap(); +# hashMap.put(1, 1); +# hashMap.put(2, 2); +# hashMap.get(1); // returns 1 +# hashMap.get(3); // returns -1 (not found) +# hashMap.put(2, 1); // update the existing value +# hashMap.get(2); // returns 1 +# hashMap.remove(2); // remove the mapping for 2 +# hashMap.get(2); // returns -1 (not found) +# +# Note: +# - All values will be in the range of [1, 1000000]. +# - The number of operations will be in the range of [1, 10000]. +# - Please do not use the built-in HashMap library. + + +class ListNode(object): + def __init__(self, key, val): + self.val = val + self.key = key + self.next = None + self.prev = None + + +class LinkedList(object): + def __init__(self): + self.head = None + self.tail = None + + def insert(self, node): + node.next, node.prev = None, None # avoid dirty node + if self.head is None: + self.head = node + else: + self.tail.next = node + node.prev = self.tail + self.tail = node + + def delete(self, node): + if node.prev: + node.prev.next = node.next + else: + self.head = node.next + if node.next: + node.next.prev = node.prev + else: + self.tail = node.prev + node.next, node.prev = None, None # make node clean + + def find(self, key): + curr = self.head + while curr: + if curr.key == key: + break + curr = curr.next + return curr + + +class MyHashMap(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.__data = [LinkedList() for _ in xrange(10000)] + + def put(self, key, value): + """ + value will always be positive. + :type key: int + :type value: int + :rtype: void + """ + l = self.__data[key % len(self.__data)] + node = l.find(key) + if node: + node.val = value + else: + l.insert(ListNode(key, value)) + + def get(self, key): + """ + Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key + :type key: int + :rtype: int + """ + l = self.__data[key % len(self.__data)] + node = l.find(key) + if node: + return node.val + else: + return -1 + + def remove(self, key): + """ + Removes the mapping of the specified value key if this map contains a mapping for the key + :type key: int + :rtype: void + """ + l = self.__data[key % len(self.__data)] + node = l.find(key) + if node: + l.delete(node) + + +# Your MyHashMap object will be instantiated and called as such: +# obj = MyHashMap() +# obj.put(key,value) +# param_2 = obj.get(key) +# obj.remove(key) From ed09f85f78e9766875728e5d88b051d508398ee5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 15:28:31 +0800 Subject: [PATCH 4958/4971] Create design-hashset.py --- Python/design-hashset.py | 115 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 Python/design-hashset.py diff --git a/Python/design-hashset.py b/Python/design-hashset.py new file mode 100644 index 000000000..00f94e37f --- /dev/null +++ b/Python/design-hashset.py @@ -0,0 +1,115 @@ +# Time: O(1) +# Space: O(n) + +# Design a HashSet without using any built-in hash table libraries. +# +# To be specific, your design should include these two functions: +# +# add(value): Insert a value into the HashSet. +# contains(value) : Return whether the value exists in the HashSet or not. +# remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing. +# +# Example: +# +# MyHashSet hashSet = new MyHashSet(); +# hashSet.add(1); +# hashSet.add(2); +# hashSet.contains(1); // returns true +# hashSet.contains(3); // returns false (not found) +# hashSet.add(2); +# hashSet.contains(2); // returns true +# hashSet.remove(2); +# hashSet.contains(2); // returns false (already removed) +# +# Note: +# - All values will be in the range of [1, 1000000]. +# - The number of operations will be in the range of [1, 10000]. +# - Please do not use the built-in HashSet library. + + +class ListNode(object): + def __init__(self, key, val): + self.val = val + self.key = key + self.next = None + self.prev = None + + +class LinkedList(object): + def __init__(self): + self.head = None + self.tail = None + + def insert(self, node): + node.next, node.prev = None, None # avoid dirty node + if self.head is None: + self.head = node + else: + self.tail.next = node + node.prev = self.tail + self.tail = node + + def delete(self, node): + if node.prev: + node.prev.next = node.next + else: + self.head = node.next + if node.next: + node.next.prev = node.prev + else: + self.tail = node.prev + node.next, node.prev = None, None # make node clean + + def find(self, key): + curr = self.head + while curr: + if curr.key == key: + break + curr = curr.next + return curr + + +class MyHashSet(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.__data = [LinkedList() for _ in xrange(10000)] + + def add(self, key): + """ + :type key: int + :rtype: void + """ + l = self.__data[key % len(self.__data)] + node = l.find(key) + if not node: + l.insert(ListNode(key, 0)) + + def remove(self, key): + """ + :type key: int + :rtype: void + """ + l = self.__data[key % len(self.__data)] + node = l.find(key) + if node: + l.delete(node) + + def contains(self, key): + """ + Returns true if this set did not already contain the specified element + :type key: int + :rtype: bool + """ + l = self.__data[key % len(self.__data)] + node = l.find(key) + return node is not None + + +# Your MyHashSet object will be instantiated and called as such: +# obj = MyHashSet() +# obj.add(key) +# obj.remove(key) +# param_3 = obj.contains(key) From ce7ffc47d57ea977e6c8701d5af499c84112dd06 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:13:17 +0800 Subject: [PATCH 4959/4971] Create design-circular-deque.cpp --- C++/design-circular-deque.cpp | 92 +++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 C++/design-circular-deque.cpp diff --git a/C++/design-circular-deque.cpp b/C++/design-circular-deque.cpp new file mode 100644 index 000000000..b92954285 --- /dev/null +++ b/C++/design-circular-deque.cpp @@ -0,0 +1,92 @@ +// Time: O(1) +// Space: O(k) + +class MyCircularDeque { +public: + /** Initialize your data structure here. Set the size of the deque to be k. */ + MyCircularDeque(int k) : + start_(0), + size_(0), + buffer_(k, 0) { + + } + + /** Adds an item at the front of Deque. Return true if the operation is successful. */ + bool insertFront(int value) { + if (isFull()) { + return false; + } + start_ = (start_ - 1 + buffer_.size()) % buffer_.size(); + buffer_[start_] = value; + ++size_; + return true; + } + + /** Adds an item at the rear of Deque. Return true if the operation is successful. */ + bool insertLast(int value) { + if (isFull()) { + return false; + } + buffer_[(start_ + size_) % buffer_.size()] = value; + ++size_; + return true; + } + + /** Deletes an item from the front of Deque. Return true if the operation is successful. */ + bool deleteFront() { + if (isEmpty()) { + return false; + } + start_ = (start_ + 1) % buffer_.size(); + --size_; + return true; + } + + /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ + bool deleteLast() { + if (isEmpty()) { + return false; + } + --size_; + return true; + } + + /** Get the front item from the deque. */ + int getFront() { + return isEmpty() ? -1 : buffer_[start_]; + } + + /** Get the last item from the deque. */ + int getRear() { + return isEmpty() ? -1 : buffer_[(start_ + size_ - 1) % buffer_.size()]; + } + + /** Checks whether the circular deque is empty or not. */ + bool isEmpty() { + return size_ == 0; + } + + /** Checks whether the circular deque is full or not. */ + bool isFull() { + return size_ == buffer_.size(); + } + +private: + int start_; + int size_; + vector buffer_; +}; + +/** + * Your MyCircularDeque object will be instantiated and called as such: + * MyCircularDeque obj = new MyCircularDeque(k); + * bool param_1 = obj.insertFront(value); + * bool param_2 = obj.insertLast(value); + * bool param_3 = obj.deleteFront(); + * bool param_4 = obj.deleteLast(); + * int param_5 = obj.getFront(); + * int param_6 = obj.getRear(); + * bool param_7 = obj.isEmpty(); + * bool param_8 = obj.isFull(); + */ + From 7b7be7991a46413514866d9dc34932ee6ca6658d Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:13:40 +0800 Subject: [PATCH 4960/4971] Create design-circular-queue.cpp --- C++/design-circular-queue.cpp | 70 +++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 C++/design-circular-queue.cpp diff --git a/C++/design-circular-queue.cpp b/C++/design-circular-queue.cpp new file mode 100644 index 000000000..4b10e11f9 --- /dev/null +++ b/C++/design-circular-queue.cpp @@ -0,0 +1,70 @@ +// Time: O(1) +// Space: O(k) + +class MyCircularQueue { +public: + /** Initialize your data structure here. Set the size of the queue to be k. */ + MyCircularQueue(int k) : + start_(0), + size_(0), + buffer_(k, 0) { + + } + + /** Insert an element into the circular queue. Return true if the operation is successful. */ + bool enQueue(int value) { + if (isFull()) { + return false; + } + buffer_[(start_ + size_) % buffer_.size()] = value; + ++size_; + return true; + } + + /** Delete an element from the circular queue. Return true if the operation is successful. */ + bool deQueue() { + if (isEmpty()) { + return false; + } + start_ = (start_ + 1) % buffer_.size(); + --size_; + return true; + } + + /** Get the front item from the queue. */ + int Front() { + return isEmpty() ? -1 : buffer_[start_]; + } + + /** Get the last item from the queue. */ + int Rear() { + return isEmpty() ? -1 : buffer_[(start_ + size_ - 1) % buffer_.size()]; + } + + /** Checks whether the circular queue is empty or not. */ + bool isEmpty() { + return size_ == 0; + } + + /** Checks whether the circular queue is full or not. */ + bool isFull() { + return size_ == buffer_.size(); + } + +private: + int start_; + int size_; + vector buffer_; +}; + +/** + * Your MyCircularQueue object will be instantiated and called as such: + * MyCircularQueue obj = new MyCircularQueue(k); + * bool param_1 = obj.enQueue(value); + * bool param_2 = obj.deQueue(); + * int param_3 = obj.Front(); + * int param_4 = obj.Rear(); + * bool param_5 = obj.isEmpty(); + * bool param_6 = obj.isFull(); + */ + From 573530465bde80ae8fb612f8e79ef036d50b6691 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:26:46 +0800 Subject: [PATCH 4961/4971] Create design-circular-queue.py --- Python/design-circular-queue.py | 111 ++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 Python/design-circular-queue.py diff --git a/Python/design-circular-queue.py b/Python/design-circular-queue.py new file mode 100644 index 000000000..1c4051508 --- /dev/null +++ b/Python/design-circular-queue.py @@ -0,0 +1,111 @@ +# Time: O(1) +# Space: O(k) + +# Design your implementation of the circular queue. +# The circular queue is a linear data structure in which +# the operations are performed based on FIFO (First In First Out) +# principle and the last position is connected back to +# the first position to make a circle. It is also called ‘Ring Buffer’. +# One of the Benefits of the circular queue is that +# we can make use of the spaces in front of the queue. +# In a normal queue, once the queue becomes full, +# we can not insert the next element even if there is a space in front of the queue. +# But using the circular queue, we can use the space to store new values. +# Your implementation should support following operations: +# +# MyCircularQueue(k): Constructor, set the size of the queue to be k. +# Front: Get the front item from the queue. If the queue is empty, return -1. +# Rear: Get the last item from the queue. If the queue is empty, return -1. +# enQueue(value): Insert an element into the circular queue. Return true if the operation is successful. +# deQueue(): Delete an element from the circular queue. Return true if the operation is successful. +# isEmpty(): Checks whether the circular queue is empty or not. +# isFull(): Checks whether the circular queue is full or not. +# Example: +# +# MyCircularQueue circularQueue = new MycircularQueue(3); // set the size to be 3 +# circularQueue.enQueue(1); // return true +# circularQueue.enQueue(2); // return true +# circularQueue.enQueue(3); // return true +# circularQueue.enQueue(4); // return false, the queue is full +# circularQueue.Rear(); // return 3 +# circularQueue.isFull(); // return true +# circularQueue.deQueue(); // return true +# circularQueue.enQueue(4); // return true +# circularQueue.Rear(); // return 4 +# +# Note: +# - All values will be in the range of [1, 1000]. +# - The number of operations will be in the range of [1, 1000]. +# - Please do not use the built-in Queue library. + +class MyCircularQueue(object): + + def __init__(self, k): + """ + Initialize your data structure here. Set the size of the queue to be k. + :type k: int + """ + self.__start = 0 + self.__size = 0 + self.__buffer = [0] * k + + def enQueue(self, value): + """ + Insert an element into the circular queue. Return true if the operation is successful. + :type value: int + :rtype: bool + """ + if self.isFull(): + return False + self.__buffer[(self.__start+self.__size) % len(self.__buffer)] = value + self.__size += 1 + return True + + def deQueue(self): + """ + Delete an element from the circular queue. Return true if the operation is successful. + :rtype: bool + """ + if self.isEmpty(): + return False + self.__start = (self.__start+1) % len(self.__buffer) + self.__size -= 1 + return True + + def Front(self): + """ + Get the front item from the queue. + :rtype: int + """ + return -1 if self.isEmpty() else self.__buffer[self.__start] + + def Rear(self): + """ + Get the last item from the queue. + :rtype: int + """ + return -1 if self.isEmpty() else self.__buffer[(self.__start+self.__size-1) % len(self.__buffer)] + + def isEmpty(self): + """ + Checks whether the circular queue is empty or not. + :rtype: bool + """ + return self.__size == 0 + + def isFull(self): + """ + Checks whether the circular queue is full or not. + :rtype: bool + """ + return self.__size == len(self.__buffer) + + +# Your MyCircularQueue object will be instantiated and called as such: +# obj = MyCircularQueue(k) +# param_1 = obj.enQueue(value) +# param_2 = obj.deQueue() +# param_3 = obj.Front() +# param_4 = obj.Rear() +# param_5 = obj.isEmpty() +# param_6 = obj.isFull() From a53d69a2dafec900893ee650d7b3c51e2d7895ad Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:27:43 +0800 Subject: [PATCH 4962/4971] Create design-circular-deque.py --- Python/design-circular-deque.py | 129 ++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 Python/design-circular-deque.py diff --git a/Python/design-circular-deque.py b/Python/design-circular-deque.py new file mode 100644 index 000000000..9802eb08a --- /dev/null +++ b/Python/design-circular-deque.py @@ -0,0 +1,129 @@ +# Time: O(1) +# Space: O(k) + +# Design your implementation of the circular double-ended queue (deque). +# Your implementation should support following operations: +# +# MyCircularDeque(k): Constructor, set the size of the deque to be k. +# insertFront(): Adds an item at the front of Deque. Return true if the operation is successful. +# insertLast(): Adds an item at the rear of Deque. Return true if the operation is successful. +# deleteFront(): Deletes an item from the front of Deque. Return true if the operation is successful. +# deleteLast(): Deletes an item from the rear of Deque. Return true if the operation is successful. +# getFront(): Gets the front item from the Deque. If the deque is empty, return -1. +# getRear(): Gets the last item from Deque. If the deque is empty, return -1. +# isEmpty(): Checks whether Deque is empty or not. +# isFull(): Checks whether Deque is full or not. +# Example: +# +# MyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be 3 +# circularDeque.insertLast(1); // return true +# circularDeque.insertLast(2); // return true +# circularDeque.insertFront(3); // return true +# circularDeque.insertFront(4); // return false, the queue is full +# circularDeque.getRear(); // return 32 +# circularDeque.isFull(); // return true +# circularDeque.deleteLast(); // return true +# circularDeque.insertFront(4); // return true +# circularDeque.getFront(); // return 4 +# +# Note: +# - All values will be in the range of [1, 1000]. +# - The number of operations will be in the range of [1, 1000]. +# - Please do not use the built-in Deque library. + +class MyCircularDeque(object): + + def __init__(self, k): + """ + Initialize your data structure here. Set the size of the deque to be k. + :type k: int + """ + self.__start = 0 + self.__size = 0 + self.__buffer = [0] * k + + def insertFront(self, value): + """ + Adds an item at the front of Deque. Return true if the operation is successful. + :type value: int + :rtype: bool + """ + if self.isFull(): + return False + self.__start = (self.__start-1) % len(self.__buffer) + self.__buffer[self.__start] = value + self.__size += 1 + return True + + def insertLast(self, value): + """ + Adds an item at the rear of Deque. Return true if the operation is successful. + :type value: int + :rtype: bool + """ + if self.isFull(): + return False + self.__buffer[(self.__start+self.__size) % len(self.__buffer)] = value + self.__size += 1 + return True + + def deleteFront(self): + """ + Deletes an item from the front of Deque. Return true if the operation is successful. + :rtype: bool + """ + if self.isEmpty(): + return False + self.__start = (self.__start+1) % len(self.__buffer) + self.__size -= 1 + return True + + def deleteLast(self): + """ + Deletes an item from the rear of Deque. Return true if the operation is successful. + :rtype: bool + """ + if self.isEmpty(): + return False + self.__size -= 1 + return True + + def getFront(self): + """ + Get the front item from the deque. + :rtype: int + """ + return -1 if self.isEmpty() else self.__buffer[self.__start] + + def getRear(self): + """ + Get the last item from the deque. + :rtype: int + """ + return -1 if self.isEmpty() else self.__buffer[(self.__start+self.__size-1) % len(self.__buffer)] + + def isEmpty(self): + """ + Checks whether the circular deque is empty or not. + :rtype: bool + """ + return self.__size == 0 + + def isFull(self): + """ + Checks whether the circular deque is full or not. + :rtype: bool + """ + return self.__size == len(self.__buffer) + + +# Your MyCircularDeque object will be instantiated and called as such: +# obj = MyCircularDeque(k) +# param_1 = obj.insertFront(value) +# param_2 = obj.insertLast(value) +# param_3 = obj.deleteFront() +# param_4 = obj.deleteLast() +# param_5 = obj.getFront() +# param_6 = obj.getRear() +# param_7 = obj.isEmpty() +# param_8 = obj.isFull() From c40bc85122ebaacf69a4f8d3ec67550882212bf8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:29:36 +0800 Subject: [PATCH 4963/4971] Update minimum-number-of-refueling-stops.py --- Python/minimum-number-of-refueling-stops.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/minimum-number-of-refueling-stops.py b/Python/minimum-number-of-refueling-stops.py index 19ce7cf0a..f39d48883 100644 --- a/Python/minimum-number-of-refueling-stops.py +++ b/Python/minimum-number-of-refueling-stops.py @@ -48,6 +48,9 @@ # - 0 <= stations.length <= 500 # - 0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target +import heapq + + class Solution(object): def minRefuelStops(self, target, startFuel, stations): """ From a11ad186d2afd06767a7b2554e0cb91eae9ca122 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:30:37 +0800 Subject: [PATCH 4964/4971] Update reordered-power-of-2.py --- Python/reordered-power-of-2.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Python/reordered-power-of-2.py b/Python/reordered-power-of-2.py index f889dfbe7..dff436f8f 100644 --- a/Python/reordered-power-of-2.py +++ b/Python/reordered-power-of-2.py @@ -32,6 +32,9 @@ # Note: # - 1 <= N <= 10^9 +import collections + + class Solution(object): def reorderedPowerOf2(self, N): """ From 10a6a135b141458de1c18eeb227b59cfc7b119c8 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:37:54 +0800 Subject: [PATCH 4965/4971] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 5518265c4..2f8db6559 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 645 | [Set Mismatch](https://leetcode.com/problems/set-mismatch/) | [C++](./C++/set-mismatch.cpp) [Python](./Python/set-mismatch.py) | _O(n)_ | _O(1)_ | Easy || 693 | [Binary Number with Alternating Bits](https://leetcode.com/problems/binary-number-with-alternating-bits/) | [C++](./C++/binary-number-with-alternating-bits.cpp) [Python](./Python/binary-number-with-alternating-bits.py) | _O(1)_ | _O(1)_ | Easy || 762 | [Prime Number of Set Bits in Binary Representation](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/) | [C++](./C++/prime-number-of-set-bits-in-binary-representation.cpp) [Python](./Python/prime-number-of-set-bits-in-binary-representation.py) | _O(1)_ | _O(1)_ | Easy || +868 | [Binary Gap](https://leetcode.com/problems/binary-gap/) | [C++](./C++/binary-gap.cpp) [Python](./Python/binary-gap.py) | _O(1)_ | _O(1)_ | Easy || ## Array | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -322,6 +323,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 846 | [Hand of Straights](https://leetcode.com/problems/hand-of-straights/) | [C++](./C++/hand-of-straights.cpp) [Python](./Python/hand-of-straights.py) | _O(nlogn)_ | _O(n)_ | Medium ||| 855 | [Exam Room](https://leetcode.com/problems/exam-room/) | [C++](./C++/exam-room.cpp) [Python](./Python/exam-room.py) | seat: _O(logn)_
leave: _O(logn)_ | _O(n)_ | Medium || BST, Hash | 857 | [Minimum Cost to Hire K Workers](https://leetcode.com/problems/minimum-cost-to-hire-k-workers/) | [C++](./C++/minimum-cost-to-hire-k-workers.cpp) [Python](./Python/minimum-cost-to-hire-k-workers.py) | _O(nlogn)_ | _O(n)_ | Hard || Sort | +871 | [Minimum Number of Refueling Stops](https://leetcode.com/problems/minimum-number-of-refueling-stops/) | [C++](./C++/minimum-number-of-refueling-stops.cpp) [Python](./Python/minimum-number-of-refueling-stops.py) | _O(nlogn)_ | _O(n)_ | Hard || Sort | ## Tree | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -424,6 +426,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 811 | [Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-count/) | [C++](./C++/subdomain-visit-count.cpp) [Python](./Python/subdomain-visit-count.py) | _O(n)_ | _O(n)_ | Easy || 822 | [Card Flipping Game](https://leetcode.com/problems/card-flipping-game/) | [C++](./C++/card-flipping-game.cpp) [Python](./Python/card-flipping-game.py) | _O(n)_ | _O(n)_ | Medium || 825 | [Friends Of Appropriate Ages](https://leetcode.com/problems/friends-of-appropriate-ages/) | [C++](./C++/friends-of-appropriate-ages.cpp) [Python](./Python/friends-of-appropriate-ages.py) | _O(a^2 + n)_ | _O(a)_ | Medium || +869 | [Reordered Power of 2](https://leetcode.com/problems/reordered-power-of-2/) | [C++](./C++/reordered-power-of-2.cpp) [Python](./Python/reordered-power-of-2.py) | _O(1)_ | _O(1)_ | Medium || ## Math | # | Title | Solution | Time | Space | Difficulty | Tag | Note| @@ -859,6 +862,7 @@ I'll keep updating for full summary and better solutions. Stay tuned for updates 798 | [Smallest Rotation with Highest Score](https://leetcode.com/problems/smallest-rotation-with-highest-score/) | [C++](./C++/smallest-rotation-with-highest-score.cpp) [Python](./Python/smallest-rotation-with-highest-score.py) | _O(n)_ | _O(1)_ | Hard | | 843 | [Guess the Word](https://leetcode.com/problems/guess-the-word/) | [C++](./C++/guess-the-word.cpp) [Python](./Python/guess-the-word.py) | _O(n^2)_ | _O(n)_ | Hard || MinMax | 861 | [Score After Flipping Matrix](https://leetcode.com/problems/score-after-flipping-matrix/) | [C++](./C++/score-after-flipping-matrix.cpp) [Python](./Python/score-after-flipping-matrix.py) | _O(r * c)_ | _O(1)_ | Medium || +870 | [Advantage Shuffle](https://leetcode.com/problems/advantage-shuffle/) | [C++](./C++/advantage-shuffle.cpp) [Python](./Python/advantage-shuffle.py) | _O(nlogn)_ | _O(n)_ | Medium || ## Graph | # | Title | Solution | Time | Space | Difficulty | Tag | Note| From 875a897fbe7279d12cc9db8c019c30c7a0b8b986 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:38:29 +0800 Subject: [PATCH 4966/4971] Update binary-gap.py --- Python/binary-gap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/binary-gap.py b/Python/binary-gap.py index 74067559c..7cb1526c8 100644 --- a/Python/binary-gap.py +++ b/Python/binary-gap.py @@ -1,4 +1,4 @@ -# Time: O(logn) +# Time: O(logn) = O(1) due to n is 32-bit number # Space: O(1) # Given a positive integer N, find and return the longest distance From 8a678ca8321115ff518591f604934bb70a736027 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:38:46 +0800 Subject: [PATCH 4967/4971] Update binary-gap.py --- Python/binary-gap.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/binary-gap.py b/Python/binary-gap.py index 7cb1526c8..3e07b0043 100644 --- a/Python/binary-gap.py +++ b/Python/binary-gap.py @@ -1,4 +1,4 @@ -# Time: O(logn) = O(1) due to n is 32-bit number +# Time: O(logn) = O(1) due to n is a 32-bit number # Space: O(1) # Given a positive integer N, find and return the longest distance From 1113e49cdf07ffc08bd73502f49852105f5a6c6e Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:39:03 +0800 Subject: [PATCH 4968/4971] Update binary-gap.cpp --- C++/binary-gap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C++/binary-gap.cpp b/C++/binary-gap.cpp index 97a9affaa..084fdf2a1 100644 --- a/C++/binary-gap.cpp +++ b/C++/binary-gap.cpp @@ -1,4 +1,4 @@ -// Time: O(logn) +// Time: O(logn) = O(1) due to n is a 32-bit number // Space: O(1) class Solution { From 8027af94f19e1a3f6327652fb56a72ba44df2cc6 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:39:23 +0800 Subject: [PATCH 4969/4971] Update reordered-power-of-2.py --- Python/reordered-power-of-2.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/reordered-power-of-2.py b/Python/reordered-power-of-2.py index dff436f8f..ed4e0200a 100644 --- a/Python/reordered-power-of-2.py +++ b/Python/reordered-power-of-2.py @@ -1,5 +1,5 @@ -# Time: O((logn)^2) -# Space: O(logn) +# Time: O((logn)^2) = O(1) due to n is a 32-bit number +# Space: O(logn) = O(1) # Starting with a positive integer N, # we reorder the digits in any order (including the original order) From 4bdfaf28c8608032bba66239942e005d56c4d024 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:39:45 +0800 Subject: [PATCH 4970/4971] Update reordered-power-of-2.cpp --- C++/reordered-power-of-2.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/C++/reordered-power-of-2.cpp b/C++/reordered-power-of-2.cpp index 3f4d56cc2..26bef5bb9 100644 --- a/C++/reordered-power-of-2.cpp +++ b/C++/reordered-power-of-2.cpp @@ -1,5 +1,5 @@ -// Time: O((logn)^2) -// Space: O(logn) +// Time: O((logn)^2) = O(1) due to n is a 32-bit number +// Space: O(logn) = O(1) class Solution { public: From 9109012b44daa15d292ba065150526ba2a57cf89 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 15 Jul 2018 17:56:38 +0800 Subject: [PATCH 4971/4971] Update design-circular-deque.py --- Python/design-circular-deque.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/design-circular-deque.py b/Python/design-circular-deque.py index 9802eb08a..fa591ebd7 100644 --- a/Python/design-circular-deque.py +++ b/Python/design-circular-deque.py @@ -13,6 +13,7 @@ # getRear(): Gets the last item from Deque. If the deque is empty, return -1. # isEmpty(): Checks whether Deque is empty or not. # isFull(): Checks whether Deque is full or not. +# # Example: # # MyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be 3