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