From 6f08c06c4f89456ba2817594b5a1eb47e940ed5c Mon Sep 17 00:00:00 2001 From: kamyu Date: Fri, 16 Jan 2015 13:27:27 +0800 Subject: [PATCH 0001/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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/3210] 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