From 99e14f23edc52b5031dd4f7cba9368d03d07c325 Mon Sep 17 00:00:00 2001 From: Qilin ZHANG Date: Sun, 31 May 2020 00:11:57 +0200 Subject: [PATCH 001/281] Add Java solution for day30: K Closest Points to Origin --- .../K-Closest-Points-To-Origin.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.java diff --git a/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.java b/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.java new file mode 100644 index 0000000..d8832a2 --- /dev/null +++ b/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.java @@ -0,0 +1,17 @@ +class Solution { + public int[][] kClosest(int[][] points, int K) { + int[][] res = new int[K][2]; + PriorityQueue minHeap = new PriorityQueue<> + ((a, b) -> (a[0]*a[0] + a[1]*a[1]) - (b[0]*b[0] + b[1]*b[1])); + + for (int[] point : points) { + minHeap.add(point); + } + + for (int i = 0; i < K; i++) { + res[i] = minHeap.poll(); + + } + return res; + } +} \ No newline at end of file From 203211e6570dd0f4545c6b941fbdd720987a95d8 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 31 May 2020 10:18:36 +0200 Subject: [PATCH 002/281] add cpp solution --- .../31-Edit-Distance/Edit-Distance.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.cpp diff --git a/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.cpp b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.cpp new file mode 100644 index 0000000..3a28c8d --- /dev/null +++ b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int minDistance(string word1, string word2) { + int n = word1.size(); + int m = word2.size(); + vector> dp(n+1, vector(m+1, 0)); + for (int i = 1; i <= m; i++) dp[0][i] = i; + for (int i = 1; i <= n; i++) dp[i][0] = i; + + for (int i = 1; i <= n; i++) + for (int j = 1; j <= m; j++){ + dp[i][j] = min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j])) + 1; + if (word1[i-1] == word2[j-1]) + dp[i][j] = min(dp[i][j], dp[i-1][j-1]); + } + return dp[n][m]; + } +}; \ No newline at end of file From 942e48e7506ab84e0e5ef98df280d1c3e90dc58f Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 31 May 2020 10:19:53 +0200 Subject: [PATCH 003/281] update doc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 0c4c3c4..98a9941 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ Recursion 28. [Counting Bits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/May-LeetCoding-Challenge/28-Counting-Bits): Math 29. [Course Schedule](https://github.com/AlgoStudyGroup/Leetcode/tree/master/May-LeetCoding-Challenge/29-Course-Schedule): Topological Sort 30. [K Closest Points to Origin](https://github.com/AlgoStudyGroup/Leetcode/tree/master/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin): Priority_queue, Sort +31. [Edit Distance](https://github.com/AlgoStudyGroup/Leetcode/tree/master/May-LeetCoding-Challenge/31-Edit-Distance): DP ## 30-Day (April) LeetCoding Challenge From 78b47c0823317c25b7b3180831cd6b4f4ccde559 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 31 May 2020 10:22:07 +0200 Subject: [PATCH 004/281] update doc --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 98a9941..4bbe73a 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,14 @@ https://leetcode.com + +## June LeetCoding Challenge +Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. + +Solutions in various programming languages are provided. Enjoy it. + +Coming soon... + ## May LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/may-leetcoding-challenge/) for problem descriptions. From 65444d6225ae6430f2c1d7d5c5bf2987819dfe2e Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Sun, 31 May 2020 13:41:36 +0200 Subject: [PATCH 005/281] add kotlin solution for 72 Edit-Distance.kt --- .../31-Edit-Distance/Edit-Distance.kt | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.kt diff --git a/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.kt b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.kt new file mode 100644 index 0000000..8096db9 --- /dev/null +++ b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.kt @@ -0,0 +1,29 @@ +class EditDistanceKotlin72 { + fun minDistance(word1: String, word2: String): Int { + val dynamicProgramming = Array(word1.length + 1) { IntArray(word2.length + 1) } + for (index in dynamicProgramming.indices) { + dynamicProgramming[index][0] = index + } + for (index in dynamicProgramming[0].indices) { + dynamicProgramming[0][index] = index + } + for (i1 in 1 until dynamicProgramming.size) { + for (j2 in 1 until dynamicProgramming[0].size) { + dynamicProgramming[i1][j2] = when { + word1[i1 - 1] == word2[j2 - 1] -> dynamicProgramming[i1 - 1][j2 - 1] + else -> 1 + minOf( + dynamicProgramming[i1 - 1][j2 - 1], + dynamicProgramming[i1 - 1][j2], + dynamicProgramming[i1][j2 - 1] + ) + } + } + } + return dynamicProgramming[word1.length][word2.length] + } +} + +fun main() { + val solution = EditDistanceKotlin72() + println(solution.minDistance("horse", "ros")) +} \ No newline at end of file From d999de8a19c90bd567cc7217d865d0426f49f830 Mon Sep 17 00:00:00 2001 From: Mincong HUANG Date: Sun, 31 May 2020 14:38:46 +0200 Subject: [PATCH 006/281] Day-30: K-Closest-Points-To-Origin (Java) --- .../K-Closest-Points-To-Origin.java | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.java b/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.java index d8832a2..34ce6a7 100644 --- a/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.java +++ b/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.java @@ -14,4 +14,46 @@ public int[][] kClosest(int[][] points, int K) { } return res; } -} \ No newline at end of file +} + +// quick select +class Solution2 { + public int[][] kClosest(int[][] points, int K) { + int from = 0; + int to = points.length - 1; + + while (from < to) { + int left = from; + int right = to; + int[] pivot = points[(from + to) / 2]; + + while (left < right) { + if (compare(points[left], pivot) >= 0) { + int[] point = points[right]; + points[right] = points[left]; + points[left] = point; + right--; + } else { + left++; + } + } + + // if we stepped up (left++), we need to step one down + if (compare(points[left], pivot) > 0) { + left--; + } + if (K <= left) { + to = left; + } else { + from = left + 1; + } + } + return Arrays.copyOfRange(points, 0, K); + } + + private int compare(int[] a, int[] b) { + // distanceA^2: ax^2 + ay^2 + // distanceB^2: bx^2 + by^2 + return a[0] * a[0] + a[1] * a[1] - b[0] * b[0] - b[1] * b[1]; + } +} From 109a84307f2804ea7145c2d47eafdd32907d306f Mon Sep 17 00:00:00 2001 From: Qilin ZHANG Date: Sun, 31 May 2020 15:00:35 +0200 Subject: [PATCH 007/281] Add Java solution for day31: Edit Distance --- .../31-Edit-Distance/Edit-Distance.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java diff --git a/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java new file mode 100644 index 0000000..bb9084e --- /dev/null +++ b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java @@ -0,0 +1,29 @@ +class Solution { + public int minDistance(String word1, String word2) { + int m = word1.length(), n = word2.length(); + + int dp[][] = new int[m+1][n+1]; + for (int i = 0; i <= m; i++) { + dp[i][0] = i; + } + + for (int j = 0; j <= n; j++) { + dp[0][j] = j; + } + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + char c1 = word1.charAt(i); + char c2 = word2.charAt(j); + + if (c1 == c2) { + dp[i + 1][j + 1] = dp[i][j]; + } else { + dp[i + 1][j + 1] = Math.min(dp[i][j], Math.min(dp[i+1][j], dp[i][j+1])) + 1; + } + } + } + + return dp[m][n]; + } +} \ No newline at end of file From 7f710b40cb38e6453b321f71d580d55454b714bd Mon Sep 17 00:00:00 2001 From: Qilin ZHANG Date: Sun, 31 May 2020 15:23:05 +0200 Subject: [PATCH 008/281] Add comments for Java solution of day31 --- .../31-Edit-Distance/Edit-Distance.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java index bb9084e..87a2efb 100644 --- a/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java +++ b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java @@ -1,8 +1,22 @@ +/** + * Dynamic programming, operation of previous string plus one if the last character is not the same + * XXXb -> YYYc => operation(XXX to YYY) + 1 + * XXXm -> XXXm => operation(XXX to YYY) + */ class Solution { public int minDistance(String word1, String word2) { int m = word1.length(), n = word2.length(); - int dp[][] = new int[m+1][n+1]; + + /** + * Construct a dp table + * __|''|a|b|c| + * ''| 0|1|2|3|... + * ''|0 + * d |1 + * e |2 + * f |3 + */ for (int i = 0; i <= m; i++) { dp[i][0] = i; } @@ -16,9 +30,11 @@ public int minDistance(String word1, String word2) { char c1 = word1.charAt(i); char c2 = word2.charAt(j); + // If the last character is the same, we do nothing compare to previous string if (c1 == c2) { dp[i + 1][j + 1] = dp[i][j]; } else { + // we chose the minimum operation of three operation: insert, delete, replace dp[i + 1][j + 1] = Math.min(dp[i][j], Math.min(dp[i+1][j], dp[i][j+1])) + 1; } } From c39b554a5787e5af391e5301ba5f62753ce5ad45 Mon Sep 17 00:00:00 2001 From: Qilin ZHANG Date: Sun, 31 May 2020 15:25:33 +0200 Subject: [PATCH 009/281] Add comments for Java solution of day31 --- .../31-Edit-Distance/Edit-Distance.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java diff --git a/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java new file mode 100644 index 0000000..87a2efb --- /dev/null +++ b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java @@ -0,0 +1,45 @@ +/** + * Dynamic programming, operation of previous string plus one if the last character is not the same + * XXXb -> YYYc => operation(XXX to YYY) + 1 + * XXXm -> XXXm => operation(XXX to YYY) + */ +class Solution { + public int minDistance(String word1, String word2) { + int m = word1.length(), n = word2.length(); + int dp[][] = new int[m+1][n+1]; + + /** + * Construct a dp table + * __|''|a|b|c| + * ''| 0|1|2|3|... + * ''|0 + * d |1 + * e |2 + * f |3 + */ + for (int i = 0; i <= m; i++) { + dp[i][0] = i; + } + + for (int j = 0; j <= n; j++) { + dp[0][j] = j; + } + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + char c1 = word1.charAt(i); + char c2 = word2.charAt(j); + + // If the last character is the same, we do nothing compare to previous string + if (c1 == c2) { + dp[i + 1][j + 1] = dp[i][j]; + } else { + // we chose the minimum operation of three operation: insert, delete, replace + dp[i + 1][j + 1] = Math.min(dp[i][j], Math.min(dp[i+1][j], dp[i][j+1])) + 1; + } + } + } + + return dp[m][n]; + } +} \ No newline at end of file From 07b223d1103c114bbb1917219ef5decb324fb15f Mon Sep 17 00:00:00 2001 From: Qilin ZHANG Date: Sun, 31 May 2020 15:26:27 +0200 Subject: [PATCH 010/281] Add comments for Java solution of day31 --- .../31-Edit-Distance/Edit-Distance.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java index 87a2efb..7c0be7d 100644 --- a/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java +++ b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.java @@ -12,10 +12,10 @@ public int minDistance(String word1, String word2) { * Construct a dp table * __|''|a|b|c| * ''| 0|1|2|3|... - * ''|0 - * d |1 - * e |2 - * f |3 + * ''| 0 + * d | 1 + * e | 2 + * f | 3 */ for (int i = 0; i <= m; i++) { dp[i][0] = i; From f270611f3216255e73fe50984e83122ccc7552bd Mon Sep 17 00:00:00 2001 From: Longjun XU Date: Mon, 1 Jun 2020 00:37:24 +0200 Subject: [PATCH 011/281] Create Edit-Distance.cs --- .../31-Edit-Distance/Edit-Distance.cs | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.cs diff --git a/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.cs b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.cs new file mode 100644 index 0000000..f23fc0d --- /dev/null +++ b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.cs @@ -0,0 +1,29 @@ +public class Solution { + public int MinDistance(string word1, string word2) { + int m = word1.Length; + int n = word2.Length; + int[,] dp = new int[2, n + 1]; + + for (int i = 0; i <= n; i++) + dp[0, i] = i; + + for (int i = 1; i <= m; i++) + { + for (int j = 0; j <= n; j++) + { + if (j == 0) + dp[i % 2, j] = i; + + else if (word1[i - 1] == word2[j - 1]) + dp[i % 2, j] = dp[(i - 1) % 2, j - 1]; + + else + dp[i % 2, j] = 1 + Math.Min(Math.Min(dp[i % 2, j - 1], // Insert + dp[(i - 1) % 2, j]), // Remove + dp[(i - 1) % 2, j - 1]); // Replace + } + } + + return dp[m % 2, n]; + } +} From 590801b465ab87af5d104cf770d2647ffbd50c83 Mon Sep 17 00:00:00 2001 From: Hang JI Date: Mon, 1 Jun 2020 01:57:28 +0200 Subject: [PATCH 012/281] add scala solutions for Question 28 30 31 --- .../28-Counting-Bits/Counting-Bits.scala | 23 +++++++++++ .../K-Closest-Points-To-Origin.scala | 41 +++++++++++++++++++ .../31-Edit-Distance/Edit-Distance.scala | 14 +++++++ 3 files changed, 78 insertions(+) create mode 100644 May-LeetCoding-Challenge/28-Counting-Bits/Counting-Bits.scala create mode 100644 May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.scala diff --git a/May-LeetCoding-Challenge/28-Counting-Bits/Counting-Bits.scala b/May-LeetCoding-Challenge/28-Counting-Bits/Counting-Bits.scala new file mode 100644 index 0000000..3f2671e --- /dev/null +++ b/May-LeetCoding-Challenge/28-Counting-Bits/Counting-Bits.scala @@ -0,0 +1,23 @@ +object Solution { + def countBits(num: Int): Array[Int] = { + val res = Array.fill(num + 1)(0) + for (i <- 0 to num) { + res(i) = countOne(i) + } + res + } + + def countOne(num: Int): Int = { + var count = 0 + var rest = num + while (rest > 1) { + count += rest % 2 + rest = rest / 2 + } + count + rest + } +} + +object Solution2 { + def countBits(num: Int): Array[Int] = Range(0, num + 1).map(Solution.countOne).toArray +} \ No newline at end of file diff --git a/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.scala b/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.scala index 8e1fad2..71f886b 100644 --- a/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.scala +++ b/May-LeetCoding-Challenge/30-K-Closest-Points-To-Origin/K-Closest-Points-To-Origin.scala @@ -7,3 +7,44 @@ object Solution { (arr1(0) * arr1(0) + arr1(1) * arr1(1)) < (arr2(0) * arr2(0) + arr2(1) * arr2(1)) } + + +//simplest solution O(n * log(n)) +object Solution2 { + def kClosest(points: Array[Array[Int]], K: Int): Array[Array[Int]] = + points.sortBy(p => p(0) * p(0) + p(1) * p(1)).take(K) +} + +//QuickSelect solution with random pivot O(n) to 0(n*n) +object Solution3 { + def kClosest(points: Array[Array[Int]], K: Int): Array[Array[Int]] = + quickSelect(points, 0, points.length - 1, K) + + def quickSelect(points: Array[Array[Int]], start: Int, end: Int, K: Int): Array[Array[Int]] = { + val pivot = scala.util.Random.nextInt(end - start + 1) + start + var i = start + var j = start + swap(points, pivot, end) + + while (j < end) { + if (SqAddition(points(j)) <= SqAddition(points(end))) { + swap(points, i, j) + i += 1 + } + j += 1 + } + + swap(points, i, j) + if (K == i + 1 - start) points.take(i + 1) + else if (K > i + 1 - start) quickSelect(points, i + 1, end, K - i - 1 + start) + else quickSelect(points, start, i - 1, K) + } + + def swap(points: Array[Array[Int]], i: Int, j: Int): Unit = { + val tmp = points(i) + points(i) = points(j) + points(j) = tmp + } + + def SqAddition(point: Array[Int]): Int = point(0) * point(0) + point(1) * point(1) +} \ No newline at end of file diff --git a/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.scala b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.scala new file mode 100644 index 0000000..8c35c32 --- /dev/null +++ b/May-LeetCoding-Challenge/31-Edit-Distance/Edit-Distance.scala @@ -0,0 +1,14 @@ +//Dynamic programming solution +object Solution { + def minDistance(word1: String, word2: String): Int = { + val (l1, l2) = (word1.length, word2.length) + val dp = Array.ofDim[Int](l1 + 1, l2 + 1) + for (i <- 0 to l1) { dp(i)(0) = i } + for (j <- 0 to l2) { dp(0)(j) = j } + for (i <- 0 until l1; j <- 0 until l2) { + if (word1(i) == word2(j)) dp(i + 1)(j + 1) = dp(i)(j) + else dp(i + 1)(j + 1) = (dp(i)(j) min (dp(i)(j + 1) min dp(i + 1)(j))) + 1 + } + dp(l1)(l2) + } +} \ No newline at end of file From 60c3906a69f2f1467d56690b3e95a6dfe69858c4 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 1 Jun 2020 10:02:07 +0200 Subject: [PATCH 013/281] add cpp solution --- .../Invert-Binary-Tree.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp diff --git a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp new file mode 100644 index 0000000..2872396 --- /dev/null +++ b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + void dfs(TreeNode* r1, TreeNode** r2){ + if (r1 == NULL) return; + *r2 = new TreeNode(r1->val); + dfs(r1->left, &((*r2)->right)); + dfs(r1->right, &((*r2)->left)); + } + + TreeNode* invertTree(TreeNode* root) { + TreeNode* root2 = NULL; + dfs(root, &root2); + if (root2 == NULL) { + cout << "NULL" << endl; + } + return root2; + } +}; \ No newline at end of file From 8e153b81ca3f34448f3843ab37054aafdcb8a464 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 1 Jun 2020 10:04:29 +0200 Subject: [PATCH 014/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4bbe73a..4bc30e1 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challen Solutions in various programming languages are provided. Enjoy it. -Coming soon... +1. [Invert Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/01-Invert-Binary-Tree): Tree Traversal ## May LeetCoding Challenge From 522f163eb10f2b62d5c286effb5679ce7ac60d9c Mon Sep 17 00:00:00 2001 From: WANGZijian1994 Date: Mon, 1 Jun 2020 10:18:53 +0200 Subject: [PATCH 015/281] Add Java Solution --- .../Invert-Binary-Tree.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.java diff --git a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.java b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.java new file mode 100644 index 0000000..dec1b9b --- /dev/null +++ b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.java @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode invertTree(TreeNode root) { + if(root!=null){ + TreeNode tmp = root.left; + root.left = root.right; + root.right = tmp; + root.left = invertTree(root.left); + root.right = invertTree(root.right); + } + return root; + } +} From 81775992a6e094f3b577889560747dd4d4815314 Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Mon, 1 Jun 2020 12:46:43 +0200 Subject: [PATCH 016/281] add kotlin solution for 226 Invert-Binary-Tree.kt --- .../Invert-Binary-Tree.kt | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.kt diff --git a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.kt b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.kt new file mode 100644 index 0000000..a529b66 --- /dev/null +++ b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.kt @@ -0,0 +1,22 @@ +class InvertBinaryTreeKotlin226 { + fun invertTree(root: TreeNode?): TreeNode? { + invert(root) + return root + } + + private fun invert(root: TreeNode?) { + if (root == null) { + return + } + val temp = root.left + root.left = root.right + root.right = temp + root.left?.let { invert(it) } + root.right?.let { invert(it) } + } + + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } +} \ No newline at end of file From cf0bb752ac68852b3825546e66de7becfe7ff065 Mon Sep 17 00:00:00 2001 From: Hang JI Date: Mon, 1 Jun 2020 14:07:20 +0200 Subject: [PATCH 017/281] add scala solutions for Invert-Binary-Tree 0601 --- .../Invert-Binary-Tree.scala | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.scala diff --git a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.scala b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.scala new file mode 100644 index 0000000..a96b027 --- /dev/null +++ b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.scala @@ -0,0 +1,40 @@ +class Question01 { + + class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) { + var value: Int = _value + var left: TreeNode = _left + var right: TreeNode = _right + } + + //space complexity O(1) + object Solution { + def invertTree(root: TreeNode): TreeNode = { + def recursiveInvert(root: TreeNode): Unit = { + if (root != null) { + val tmp = root.left + root.left = root.right + root.right = tmp + recursiveInvert(root.left) + recursiveInvert(root.right) + } + } + recursiveInvert(root) + root + } + } + + //space complexity 0(n) + object Solution2 { + def invertTree(root: TreeNode): TreeNode = recursiveInvert(root) + + def recursiveInvert(root: TreeNode): TreeNode = { + if (root == null) null + else { + val tmp = root.left + root.left = recursiveInvert(root.right) + root.right = recursiveInvert(tmp) + root + } + } + } +} From caf52a86ba855d3e9d9b1aeea1a634151481dce3 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 1 Jun 2020 14:13:10 +0200 Subject: [PATCH 018/281] improve cpp' ' --- .../01-Invert-Binary-Tree/Invert-Binary-Tree.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp index 2872396..41e06bd 100644 --- a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp +++ b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp @@ -10,9 +10,6 @@ class Solution { TreeNode* invertTree(TreeNode* root) { TreeNode* root2 = NULL; dfs(root, &root2); - if (root2 == NULL) { - cout << "NULL" << endl; - } return root2; } }; \ No newline at end of file From 07952516bbb0271a46000e3a03ede91856b26375 Mon Sep 17 00:00:00 2001 From: yujie <451181270@qq.com> Date: Mon, 1 Jun 2020 21:18:55 +0200 Subject: [PATCH 019/281] Create Invert-Binary-Tree.cs --- .../01-Invert-Binary-Tree/Invert-Binary-Tree.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cs diff --git a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cs b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cs new file mode 100644 index 0000000..e71e5e8 --- /dev/null +++ b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cs @@ -0,0 +1,13 @@ +public class Solution { + public TreeNode InvertTree(TreeNode root) { + if (root != null) + { + InvertTree(root.left); + InvertTree(root.right); + TreeNode temps = root.left; + root.left=root.right; + root.right= temps; + } + return root; + } +} From 0a8d84ec68ae49923c739d1fb737f8b61a5a7694 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 2 Jun 2020 09:24:59 +0200 Subject: [PATCH 020/281] add cpp solution --- .../Delete-Node-In-A-Linked-List.cpp | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.cpp diff --git a/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.cpp b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.cpp new file mode 100644 index 0000000..bb71ae6 --- /dev/null +++ b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + void deleteNode(ListNode* node) { + node->val = node->next->val; + node->next = node->next->next; + } +}; \ No newline at end of file From 53c026b428672b1758489df818539dadfb77d4cd Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 2 Jun 2020 09:27:09 +0200 Subject: [PATCH 021/281] update doc --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 4bc30e1..b05ef31 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,8 @@ Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challen Solutions in various programming languages are provided. Enjoy it. 1. [Invert Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/01-Invert-Binary-Tree): Tree Traversal +2. [Delete Node in a Linked List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List): Linked List + ## May LeetCoding Challenge From 5538139b8d6238c05e3936a8a6fe9ed9004acb0e Mon Sep 17 00:00:00 2001 From: WANGZijian1994 Date: Tue, 2 Jun 2020 09:31:41 +0200 Subject: [PATCH 022/281] Add Java and javaScript Solution --- .../Delete-Node-in-a-Linked-List.java | 14 ++++++++++++++ .../Delete-Node-in-a-Linked-List.js | 15 +++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.java create mode 100644 June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.js diff --git a/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.java b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.java new file mode 100644 index 0000000..4f92a36 --- /dev/null +++ b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.java @@ -0,0 +1,14 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public void deleteNode(ListNode node) { + node.val = node.next.val; + node.next = node.next.next; + } +} diff --git a/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.js b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.js new file mode 100644 index 0000000..04eaeae --- /dev/null +++ b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.js @@ -0,0 +1,15 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} node + * @return {void} Do not return anything, modify node in-place instead. + */ +var deleteNode = function(node) { + node.val = node.next.val; + node.next = node.next.next; +}; From 6e34acbe207452d54f1a05a53d0d6148386c8dcb Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Tue, 2 Jun 2020 14:28:32 +0200 Subject: [PATCH 023/281] add kotlin solution for 237 Delete-Node-In-A-Linked-List.kt --- .../Delete-Node-In-A-Linked-List.kt | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.kt diff --git a/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.kt b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.kt new file mode 100644 index 0000000..7d777cd --- /dev/null +++ b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.kt @@ -0,0 +1,11 @@ +class DeleteNodeinaLinkedListKotlin237 { + fun deleteNode(node: ListNode?) { + val next = node!!.next!! + node.`val` = next.`val` + node.next = next.next + } + + class ListNode(var `val`: Int) { + var next: ListNode? = null + } +} \ No newline at end of file From fa1742a24026de95a061d0e891b3bc05165fd618 Mon Sep 17 00:00:00 2001 From: Hang JI Date: Wed, 3 Jun 2020 00:26:58 +0200 Subject: [PATCH 024/281] Q0602: add scala solution --- .../Delete-Node-In-A-Linked-List.scala | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.scala diff --git a/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.scala b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.scala new file mode 100644 index 0000000..a4db9fa --- /dev/null +++ b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.scala @@ -0,0 +1,15 @@ +class Question02 { + + class ListNode(var _x: Int = 0) { + var next: ListNode = null + var x: Int = _x + } + + object Solution { + def deleteNode(node: ListNode): Unit = { + node.x = node.next.x + node.next = node.next.next + } + } +} + From c25febd789a8da19c1b50e7172d09bc12a512072 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 3 Jun 2020 13:16:14 +0200 Subject: [PATCH 025/281] add cpp solution --- .../Two-City-Scheduling.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cpp diff --git a/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cpp b/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cpp new file mode 100644 index 0000000..fee80bf --- /dev/null +++ b/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cpp @@ -0,0 +1,21 @@ +// Time Complexity O(n^2), space complexity O(n^2) +class Solution1 { +public: + int twoCitySchedCost(vector>& costs) { + int N = costs.size(); + if (N == 0) return 0; + int n = N / 2; + + vector> dp(N+1, vector(n+1, 0)); + for (int i = 1; i <= N; i++) dp[i][0] = dp[i-1][0] + costs[i-1][1]; + + + for (int i = 1; i <= N; i++) + for (int j = 0; j <= min(n, i); j++){ + dp[i][j] = dp[i-1][j-1] + costs[i-1][0]; + if (i-1 >= j) + dp[i][j] = min(dp[i][j], dp[i-1][j] + costs[i-1][1]); + } + return dp[N][n]; + } +}; From 0e84cb16a891d32bc845634f4af4149a96f3e1ed Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 3 Jun 2020 13:16:36 +0200 Subject: [PATCH 026/281] add cpp solution --- .../03-Two-City-Scheduling/Two-City-Scheduling.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cpp b/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cpp index fee80bf..ce70d47 100644 --- a/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cpp +++ b/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cpp @@ -1,5 +1,5 @@ // Time Complexity O(n^2), space complexity O(n^2) -class Solution1 { +class Solution { public: int twoCitySchedCost(vector>& costs) { int N = costs.size(); From 0a43171081b1b04599480c09eb3e20b1ca2b9ab0 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 3 Jun 2020 13:17:20 +0200 Subject: [PATCH 027/281] 1 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b05ef31..8095667 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Solutions in various programming languages are provided. Enjoy it. 1. [Invert Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/01-Invert-Binary-Tree): Tree Traversal 2. [Delete Node in a Linked List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List): Linked List +3. [Two City Scheduling](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/03-Two-City-Scheduling): DP ## May LeetCoding Challenge From dcc8020707194d8d25be27a2de827209cfa8a5d3 Mon Sep 17 00:00:00 2001 From: DiSaBor Date: Wed, 3 Jun 2020 14:01:19 +0200 Subject: [PATCH 028/281] added c# solution (non optimized) --- .../Two-City-Scheduling.cs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cs diff --git a/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cs b/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cs new file mode 100644 index 0000000..041297f --- /dev/null +++ b/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.cs @@ -0,0 +1,27 @@ +public class Helper { + public int a; + public int b; + public int diff {get {return b-a;}} +} + +public class Solution { + public int TwoCitySchedCost(int[][] costs) { + var helpers = new List(); + for(int i = 0; i < costs.Length; i++) + { + helpers.Add(new Helper(){ + a = costs[i][0], + b = costs[i][1], + }); + } + helpers = helpers.OrderBy(h => h.diff ).ToList(); + + int result = 0; + for(int i = 0; i < helpers.Count; i++) + { + var helper = helpers[i]; + result += i < helpers.Count/2 ? helper.b : helper.a; + } + return result; + } +} From 4ceb767f3a8b668af1f6fb86e88ab550e13165e6 Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Wed, 3 Jun 2020 16:56:59 +0200 Subject: [PATCH 029/281] add kotlin solution for 1029 Two-City-Scheduling.kt --- .../Two-City-Scheduling.kt | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.kt diff --git a/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.kt b/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.kt new file mode 100644 index 0000000..293764e --- /dev/null +++ b/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.kt @@ -0,0 +1,60 @@ +class TwoCitySchedulingKotlin1029 { + + fun twoCitySchedCost(costs: Array): Int { + costs.sortWith(Comparator { ints1, ints2 -> compareValues(ints1[0] - ints1[1], ints2[0] - ints2[1]) }) + val half = costs.size / 2 + var sum = 0 + costs.forEachIndexed { index, ints -> + sum += when { + index < half -> ints[0] + else -> ints[1] + } + } + return sum + } + /* + fun twoCitySchedCost(costs: Array): Int { + val half = costs.size.shr(1) + val dp = Array(half + 1) { IntArray(half + 1) } + for (index in 1 until dp.size) { + dp[0][index] = dp[0][index - 1] + costs[index - 1][0] + } + for (i in 1 until dp.size) { + dp[i][0] = dp[i - 1][0] + costs[i - 1][1] + for (j in 1 until dp.size) { + dp[i][j] = minOf( + dp[i - 1][j] + costs[i + j - 1][1], + dp[i][j - 1] + costs[i + j - 1][0] + ) + } + } + return dp[half][half] + } + */ +} + +fun main() { + val solution = TwoCitySchedulingKotlin1029() + // 110 + println( + solution.twoCitySchedCost( + arrayOf( + intArrayOf(10, 20), + intArrayOf(30, 200), + intArrayOf(400, 50), + intArrayOf(30, 20) + ) + ) + ) + // 130 + println( + solution.twoCitySchedCost( + arrayOf( + intArrayOf(10, 20), + intArrayOf(30, 200), + intArrayOf(400, 50), + intArrayOf(30, 200) + ) + ) + ) +} \ No newline at end of file From 74f669e38b20092a3c97f466cd545f5853cd3c7c Mon Sep 17 00:00:00 2001 From: Hang JI Date: Thu, 4 Jun 2020 03:12:52 +0200 Subject: [PATCH 030/281] Q0603: add scala solution --- .../03-Two-City-Scheduling/Two-City-Scheduling.scala | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.scala diff --git a/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.scala b/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.scala new file mode 100644 index 0000000..2768d77 --- /dev/null +++ b/June-LeetCoding-Challenge/03-Two-City-Scheduling/Two-City-Scheduling.scala @@ -0,0 +1,10 @@ +class Question03 { + // sort by difference O(n2) + object Solution { + def twoCitySchedCost(costs: Array[Array[Int]]): Int = { + costs.sortBy(t => t(0) - t(1)).zipWithIndex.foldLeft(0) { + case (acc, (t, index)) => acc + (if (index < costs.length / 2) t(0) else t(1)) + } + } + } +} From a1cefaf50509306f4d730ad8693b140dc0c04050 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 4 Jun 2020 09:11:23 +0200 Subject: [PATCH 031/281] add cpp solution --- .../04-Reverse-String/Reverse-String.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.cpp diff --git a/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.cpp b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.cpp new file mode 100644 index 0000000..73f35f6 --- /dev/null +++ b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + void reverseString(vector& s) { + int n = s.size(); + for (int i = 0; i < n / 2; i++){ + char t = s[i]; + s[i] = s[n - i - 1]; + s[n - i- 1] = t; + } + } +}; \ No newline at end of file From cc9fe7dee95e946cdeb4e2916e085ed698ea5e89 Mon Sep 17 00:00:00 2001 From: WANGZijian1994 Date: Thu, 4 Jun 2020 09:21:51 +0200 Subject: [PATCH 032/281] Add Solution JavaScript --- .../04-Reverse-String/Reverse-String.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.js diff --git a/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.js b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.js new file mode 100644 index 0000000..59b4cac --- /dev/null +++ b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.js @@ -0,0 +1,16 @@ +/** + * @param {character[]} s + * @return {void} Do not return anything, modify s in-place instead. + */ +var reverseString = function(s) { + var i = 0; + var j = s.length-1; + while(i Date: Thu, 4 Jun 2020 11:20:39 +0200 Subject: [PATCH 033/281] Q0604: add scala solution --- .../04-Reverse-String/Reverse-String.scala | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.scala diff --git a/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.scala b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.scala new file mode 100644 index 0000000..495ba4d --- /dev/null +++ b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.scala @@ -0,0 +1,16 @@ +class Question04 { + + object Solution { + def reverseString(s: Array[Char]): Unit = { + var index = 0 + //not necessary to revert middle char in a odd array + while (index < (s.length.toDouble - 1) / 2) { + val tmp = s(index) + s(index) = s(s.length - 1 - index) + s(s.length - 1 - index) = tmp + index += 1 + } + } + } + +} From be198147feb5eb228afa6939a4d057b52c5570a9 Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Thu, 4 Jun 2020 14:49:15 +0200 Subject: [PATCH 034/281] add kotlin solution for 344 Reverse-String.kt --- .../04-Reverse-String/Reverse-String.kt | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.kt diff --git a/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.kt b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.kt new file mode 100644 index 0000000..5d18cc0 --- /dev/null +++ b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.kt @@ -0,0 +1,13 @@ +class ReverseStringKotlin344 { + fun reverseString(s: CharArray): Unit { + var left = 0 + var right = s.size - 1 + while (left < right) { + val temp = s[left] + s[left] = s[right] + s[right] = temp + ++left + --right + } + } +} From 37ac038a36a8f38e6ed47095a4a270d416c4e9fc Mon Sep 17 00:00:00 2001 From: LI Jiayi Date: Thu, 4 Jun 2020 14:54:38 +0200 Subject: [PATCH 035/281] Add c# solution --- .../04-Reverse-String/Reverse-String.cs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.cs diff --git a/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.cs b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.cs new file mode 100644 index 0000000..eba7276 --- /dev/null +++ b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.cs @@ -0,0 +1,30 @@ +public class Solution { + + public void ReverseString(char[] s) { + int left = 0; + int right = s.Length-1; + while (left < right) + { + char temp = s[left]; + s[left] = s[right]; + s[right] = temp; + left++; + right--; + } + } + + public void ReverseString2(char[] s) { + helper(s, 0, s.Length-1); + } + + public void helper(char[] s, int left, int right) + { + if (left < right) + { + char temp = s[left]; + s[left] = s[right]; + s[right] = temp; + helper(s, left+1, right-1); + } + } +} From b4d4becd76915d897d3f8594a8dbaa7d2a196127 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 4 Jun 2020 15:36:42 +0200 Subject: [PATCH 036/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8095667..98158dd 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Solutions in various programming languages are provided. Enjoy it. 1. [Invert Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/01-Invert-Binary-Tree): Tree Traversal 2. [Delete Node in a Linked List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List): Linked List 3. [Two City Scheduling](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/03-Two-City-Scheduling): DP - +4. [Reverse String](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/04-Reverse-String): String ## May LeetCoding Challenge From 48500f4490f84a1000a61b360363039d27d826b4 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 5 Jun 2020 09:13:41 +0200 Subject: [PATCH 037/281] add cpp solution --- .../Random-Pick-With-Weight.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cpp diff --git a/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cpp b/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cpp new file mode 100644 index 0000000..677f1d5 --- /dev/null +++ b/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector sum; + + Solution(vector& w) { + if (w.size() > 0){ + sum.push_back(w[0]); + for (int i = 1; i < w.size(); i++) sum.push_back(sum[i-1] + w[i]); + } + } + + int pickIndex() { + int p = (rand() % sum[sum.size() - 1]) + 1; + return lower_bound(sum.begin(), sum.end(), p) - sum.begin(); + } +}; \ No newline at end of file From 3637bb51f021ce932e3c7db6dc4aa859f5f2f432 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 5 Jun 2020 09:15:01 +0200 Subject: [PATCH 038/281] update doc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 98158dd..3ae87cf 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Solutions in various programming languages are provided. Enjoy it. 2. [Delete Node in a Linked List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List): Linked List 3. [Two City Scheduling](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/03-Two-City-Scheduling): DP 4. [Reverse String](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/04-Reverse-String): String +5. [Random Pick With Weight](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/05-Random-Pick-With-Weight): Binary Search + Probability ## May LeetCoding Challenge From 747f62ff506135c548548db51435609f3448e5a7 Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Fri, 5 Jun 2020 12:08:13 +0200 Subject: [PATCH 039/281] add kotlin solution for 528 Random-Pick-With-Weight.kt --- .../Random-Pick-With-Weight.kt | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.kt diff --git a/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.kt b/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.kt new file mode 100644 index 0000000..acf90d1 --- /dev/null +++ b/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.kt @@ -0,0 +1,31 @@ +import kotlin.random.Random + +class RandomPickwithWeightKotlin528(w: IntArray) { + private val accumulateSum: MutableList = mutableListOf() + + init { + accumulateSum.add(w[0]) + for (index in 1 until w.size) { + accumulateSum.add(accumulateSum[index - 1] + w[index]) + } + } + + fun pickIndex(): Int { + val target = Random.Default.nextInt(accumulateSum[accumulateSum.size - 1]) + 1 + var left = 0 + var right = accumulateSum.size - 1 + while (left + 1 < right) { + val mid = left + (right - left) / 2 + when { + accumulateSum[mid] == target -> return mid + accumulateSum[mid] < target -> left = mid + accumulateSum[mid] > target -> right = mid + } + } + return when { + accumulateSum[left] >= target -> left + accumulateSum[right] >= target -> right + else -> -1 + } + } +} \ No newline at end of file From a318aac1de6e6f5c65df313fe9b2e8146bb8ce92 Mon Sep 17 00:00:00 2001 From: Hang JI Date: Fri, 5 Jun 2020 17:54:07 +0200 Subject: [PATCH 040/281] Q0605: add scala solution --- .../Random-Pick-With-Weight.scala | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.scala diff --git a/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.scala b/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.scala new file mode 100644 index 0000000..0275aee --- /dev/null +++ b/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.scala @@ -0,0 +1,29 @@ + +class Question05 { + import scala.util.Random + //create a new array of integers represent the bounds of proportion + //ex: (1, 4, 5, 100) => (0 ,1, 5, 10, 100), take last value as seed (100) + //if randomValue == 8 -> 8 <= 10 -> take index - 1 -> indexOf(10) - 1 = 2 + //if randomValue == 30 -> 30 <= 100 -> take index - 1 -> indexOf(100) - 1 = 3 + class Solution(_w: Array[Int]) { + var acc: Int = 0 + val w: Array[Int] = Array.fill(_w.length + 1)(0) + for (i <- 1 until w.length) { + w(i) = _w(i - 1) + acc + acc = w(i) + } + + def pickIndex(): Int = { + val randomValue = Random.nextInt(acc) + 1 + var index = 0 + var done = false + while (!done && index < _w.length) { + if (randomValue <= w(index)) done = true + else index += 1 + } + index - 1 + } + } + +} + From 5aa4e392e1dedad4eb5fe74f8eba1d3467b23572 Mon Sep 17 00:00:00 2001 From: kerms Date: Fri, 5 Jun 2020 22:31:51 +0200 Subject: [PATCH 041/281] [05, June 2020] cpp add map solution time: construction O(n log n), search: O(log n) space: O(n) --- .../Random-Pick-With-Weight.cpp | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cpp b/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cpp index 677f1d5..cac22ca 100644 --- a/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cpp +++ b/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cpp @@ -13,4 +13,24 @@ class Solution { int p = (rand() % sum[sum.size() - 1]) + 1; return lower_bound(sum.begin(), sum.end(), p) - sum.begin(); } -}; \ No newline at end of file +}; + +class Solution2 { + // space: O(n) + map m; + int sum; +public: + // time O(n log n) + Solution(vector& w) { + sum = 0; + for (int i = 0; i < w.size(); ++i) { + sum += w[i]; + m[sum] = i; + } + } + + // time O(log n) + int pickIndex() { + return m.upper_bound(rand()%sum)->second; + } +}; From e5b27d2ccec528cdc70e8257f4f910232d046d7e Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 6 Jun 2020 13:29:02 +0200 Subject: [PATCH 042/281] add cpp solution --- .../Queue-Reconstruction-By-Height.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.cpp diff --git a/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.cpp b/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.cpp new file mode 100644 index 0000000..798fbd3 --- /dev/null +++ b/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.cpp @@ -0,0 +1,14 @@ +bool compare(vector& p, vector& q) { + return (p[0] > q[0]) || (p[0] == q[0] && p[1] < q[1]); +} + +class Solution { +public: + vector> reconstructQueue(vector>& people) { + sort(people.begin(), people.end(), compare); + vector> ans; + for(int i = 0; i < people.size(); i++) + ans.insert(ans.begin() + people[i][1], people[i]); + return ans; + } +}; \ No newline at end of file From ecfb17a90168c53d057967fe2a460e4d6d567c40 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 6 Jun 2020 13:30:34 +0200 Subject: [PATCH 043/281] update doc --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3ae87cf..e0c93a5 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,8 @@ Solutions in various programming languages are provided. Enjoy it. 3. [Two City Scheduling](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/03-Two-City-Scheduling): DP 4. [Reverse String](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/04-Reverse-String): String 5. [Random Pick With Weight](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/05-Random-Pick-With-Weight): Binary Search + Probability +6. [Queue Reconstruction by Height](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height): Greedy + ## May LeetCoding Challenge From e855d9967df4862764cbf52c412181a53435084a Mon Sep 17 00:00:00 2001 From: Jingwen ZHENG Date: Sat, 6 Jun 2020 19:26:53 +0200 Subject: [PATCH 044/281] Add python solution (#164) * Add python solution * Update Reverse-String.py --- .../04-Reverse-String/Reverse-String.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.py diff --git a/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.py b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.py new file mode 100644 index 0000000..9cb578e --- /dev/null +++ b/June-LeetCoding-Challenge/04-Reverse-String/Reverse-String.py @@ -0,0 +1,6 @@ +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + s.reverse() From 4381417282891fce1afe0362b4200fd9a94a88e0 Mon Sep 17 00:00:00 2001 From: WANGZijian1994 Date: Sat, 6 Jun 2020 21:11:12 +0200 Subject: [PATCH 045/281] Add Solution Python --- .../Queue-Reconstruction-By-Height.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.py diff --git a/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.py b/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.py new file mode 100644 index 0000000..4ec2c12 --- /dev/null +++ b/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.py @@ -0,0 +1,23 @@ +class Solution1: + def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: + if len(people)<=1: + return people + people.sort(reverse=True) + queue = [] + tmp = [people[0]] + for i in range(1,len(people)): + if people[i-1][0]==people[i][0]: + tmp.append(people[i]) + else: + queue+=sorted(tmp) + tmp = [people[i]] + queue+=sorted(tmp) + res = [queue[0]] + i = 1 + while queue[i][0]==queue[0][0] and i Date: Sun, 7 Jun 2020 10:05:47 +0200 Subject: [PATCH 046/281] add cpp soluion --- .../07-Coin-Change-2/Coin-Change-2.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.cpp diff --git a/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.cpp b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.cpp new file mode 100644 index 0000000..7d5f515 --- /dev/null +++ b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.cpp @@ -0,0 +1,19 @@ +// Time complexity O(n^2); Space complexity O(n^2) +class Solution { +public: + int change(int amount, vector& coins) { + vector> dp(2, vector(amount+1, 0)); + dp[0][0] = 1; + + int flag = 1; + for (int i = 1; i <= coins.size(); i++){ + for (int j = 0; j <= amount; j++){ + dp[flag][j] = dp[1-flag][j]; + if (j >= coins[i-1]) + dp[flag][j] += dp[flag][j-coins[i-1]]; + } + flag = 1 - flag; + } + return dp[1-flag][amount]; + } +}; \ No newline at end of file From 42af292b187897fcc36bf6842626d70b9907d3a2 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 7 Jun 2020 10:06:41 +0200 Subject: [PATCH 047/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e0c93a5..b0379c0 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Solutions in various programming languages are provided. Enjoy it. 4. [Reverse String](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/04-Reverse-String): String 5. [Random Pick With Weight](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/05-Random-Pick-With-Weight): Binary Search + Probability 6. [Queue Reconstruction by Height](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height): Greedy - +7. [Coin Change 2](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/07-Coin-Change-2): DP ## May LeetCoding Challenge From fe282d3ac80cc919918709ccdc9ad0e195b0a1a2 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+YvanEnihc@users.noreply.github.com> Date: Sun, 7 Jun 2020 10:58:39 +0200 Subject: [PATCH 048/281] Update Coin-Change-2.cpp --- .../07-Coin-Change-2/Coin-Change-2.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.cpp b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.cpp index 7d5f515..480100a 100644 --- a/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.cpp +++ b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.cpp @@ -16,4 +16,16 @@ class Solution { } return dp[1-flag][amount]; } -}; \ No newline at end of file +}; + +class Solution { +public: + int change(int amount, vector& coins) { + int dp[5001] = { 1 }; + for(int c : coins) + for(int j=c; j<=amount; ++j) + dp[j] += dp[j-c]; + return dp[amount]; + } + +}; From 87aabda57d90a78d02331c265b807b03643e8b09 Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Sun, 7 Jun 2020 15:19:54 +0200 Subject: [PATCH 049/281] add kotlin solution for 406 Queue-Reconstruction-By-Height.kt --- .../Queue-Reconstruction-By-Height.kt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.kt diff --git a/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.kt b/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.kt new file mode 100644 index 0000000..0e016de --- /dev/null +++ b/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height/Queue-Reconstruction-By-Height.kt @@ -0,0 +1,15 @@ +class QueueReconstructionbyHeightKotlin406 { + fun reconstructQueue(people: Array): Array { + people.sortWith(Comparator { t, t2 -> + when { + t[0] == t2[0] -> compareValues(t[1], t2[1]) + else -> compareValues(t2[0], t[0]) + } + }) + val result: MutableList = ArrayList() + people.forEach { + result.add(it[1], it) + } + return result.toTypedArray() + } +} From 2167ae3ecf3c9bce09486f8f72f082f141c85c33 Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Sun, 7 Jun 2020 15:32:12 +0200 Subject: [PATCH 050/281] add kotlin solution for 518 Coin-Change-2.kt --- .../07-Coin-Change-2/Coin-Change-2.kt | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.kt diff --git a/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.kt b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.kt new file mode 100644 index 0000000..924fc23 --- /dev/null +++ b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.kt @@ -0,0 +1,26 @@ +// https://www.youtube.com/watch?v=e1omSFakK7o +class CoinChange2Kotlin518 { + fun change(amount: Int, coins: IntArray): Int { + val dp = IntArray(amount + 1) + dp[0] = 1 + for (coin in coins) { + for (index in coin..amount) { + dp[index] += dp[index - coin] + } + } + return dp[amount] + } +} + +fun main() { + val solution = CoinChange2Kotlin518() + println(solution.change(10, intArrayOf(1, 2, 5))) + // 4 + println(solution.change(5, intArrayOf(1, 2, 5))) + // 0 + println(solution.change(3, intArrayOf(2))) + // 1 + println(solution.change(10, intArrayOf(10))) + // 12701 + println(solution.change(500, intArrayOf(5, 2, 1))) +} \ No newline at end of file From f2abbace71c799aba47e3763ba414e357c01959d Mon Sep 17 00:00:00 2001 From: WANGZijian1994 Date: Sun, 7 Jun 2020 22:50:25 +0200 Subject: [PATCH 051/281] Add Solution JavaScript --- .../07-Coin-Change-2/Coin-Change-2.js | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.js diff --git a/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.js b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.js new file mode 100644 index 0000000..9bae8b7 --- /dev/null +++ b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.js @@ -0,0 +1,22 @@ +/** + * @param {number} amount + * @param {number[]} coins + * @return {number} + */ +var change = function(amount, coins) { + coins.sort(function(a,b){return a-b;}) + if(amount>0 && coins.length==0){ + return 0; + } + var dp = new Array(amount+1); + dp.fill(0); + dp[0] = 1; + for(let coin of coins){ + for(let i = 1;i<=amount;i++){ + if(i>=coin){ + dp[i]+=dp[i-coin]; + } + } + } + return dp[amount]; +}; From b7096ec24c45b707802518cf3a2f0dcdd68e3fb3 Mon Sep 17 00:00:00 2001 From: WANGZijian1994 Date: Sun, 7 Jun 2020 22:54:24 +0200 Subject: [PATCH 052/281] Add Solution Python --- .../07-Coin-Change-2/Coin-Change-2.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.py diff --git a/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.py b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.py new file mode 100644 index 0000000..c3d3780 --- /dev/null +++ b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.py @@ -0,0 +1,11 @@ +class Solution: + def change(self, amount: int, coins: List[int]) -> int: + if not coins and amount!=0: + return 0 + dp = [0 for x in range(amount+1)] + dp[0] = 1 + for coin in coins: + for i in range(1,amount+1): + if i >= coin: + dp[i] += dp[i-coin] + return dp[amount] From 661ed3f78430061fae117b4995c496cce7d93b40 Mon Sep 17 00:00:00 2001 From: WANGZijian1994 Date: Sun, 7 Jun 2020 22:57:58 +0200 Subject: [PATCH 053/281] Improve Solution JavaScript --- June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.js | 1 - 1 file changed, 1 deletion(-) diff --git a/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.js b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.js index 9bae8b7..a087287 100644 --- a/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.js +++ b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.js @@ -4,7 +4,6 @@ * @return {number} */ var change = function(amount, coins) { - coins.sort(function(a,b){return a-b;}) if(amount>0 && coins.length==0){ return 0; } From 48884c1b26e3ed251d8565aa4cf59f154258f278 Mon Sep 17 00:00:00 2001 From: Mincong HUANG Date: Sun, 7 Jun 2020 22:58:50 +0200 Subject: [PATCH 054/281] Coin-Change-2 (Java) --- .../07-Coin-Change-2/Coin-Change-2.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.java diff --git a/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.java b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.java new file mode 100644 index 0000000..521dbf8 --- /dev/null +++ b/June-LeetCoding-Challenge/07-Coin-Change-2/Coin-Change-2.java @@ -0,0 +1,15 @@ +class Solution { + public int change(int amount, int[] coins) { + int[] combinations = new int[amount + 1]; + combinations[0] = 1; + for (int coin : coins) { + for (int i = coin; i <= amount; i++) { + int prev = i - coin; + if (prev >= 0) { + combinations[i] += combinations[prev]; + } + } + } + return combinations[amount]; + } +} From a343f3bf93bd77897cf045ddfeae6db273a40afb Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 8 Jun 2020 10:02:59 +0200 Subject: [PATCH 055/281] add cpp solution --- .../08-Power-Of-Two/Power-Of-Two.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.cpp diff --git a/June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.cpp b/June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.cpp new file mode 100644 index 0000000..c657d51 --- /dev/null +++ b/June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.cpp @@ -0,0 +1,8 @@ +class Solution { +public: + bool isPowerOfTwo(int n) { + long long x = n; + if (x == 0) return false; + return (x & (-x)) == x; + } +}; \ No newline at end of file From 605f19d8aec5765e68bd0475c1753441dcc4132f Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 8 Jun 2020 10:04:46 +0200 Subject: [PATCH 056/281] update doc --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index b0379c0..41b6aa5 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,9 @@ Solutions in various programming languages are provided. Enjoy it. 5. [Random Pick With Weight](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/05-Random-Pick-With-Weight): Binary Search + Probability 6. [Queue Reconstruction by Height](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height): Greedy 7. [Coin Change 2](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/07-Coin-Change-2): DP +8. [Power of Two](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/08-Power-Of-Two): Bitwise manipulation + + ## May LeetCoding Challenge From c3a9a5f95905c1f00d355a667464178000985ad1 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Mon, 8 Jun 2020 10:22:44 +0200 Subject: [PATCH 057/281] Update Power-Of-Two.cpp --- .../08-Power-Of-Two/Power-Of-Two.cpp | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.cpp b/June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.cpp index c657d51..4f69b13 100644 --- a/June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.cpp +++ b/June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.cpp @@ -5,4 +5,25 @@ class Solution { if (x == 0) return false; return (x & (-x)) == x; } -}; \ No newline at end of file +}; + +class Solution { +public: + int right_most_setbit(int num) { + int pos = 0; + // counting the position of first set bit + for (int i = 0; i < 32; i++) { + if (!(num & (1 << i))) + pos++; + else + break; + } + return pos; + } + + bool isPowerOfTwo(int n) { + if(n<=0) return false; + else return right_most_setbit(n) == int(log2(n)); + + } +}; From 3f2e7d6b5e5ae8c9361025f2a5390b91bd91871d Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Mon, 8 Jun 2020 11:47:08 +0200 Subject: [PATCH 058/281] Update Invert-Binary-Tree.cpp --- .../01-Invert-Binary-Tree/Invert-Binary-Tree.cpp | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp index 41e06bd..ac28ca9 100644 --- a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp +++ b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cpp @@ -12,4 +12,17 @@ class Solution { dfs(root, &root2); return root2; } -}; \ No newline at end of file +}; + +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if(!root) return nullptr; + auto left = (root->left)?invertTree(root->left):nullptr; + auto right = (root->right)?invertTree(root->right):nullptr; + root->left = right; + root->right = left; + return root; + } + +}; From 8056406d50d65131a31698529835255979876a82 Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Mon, 8 Jun 2020 16:13:15 +0200 Subject: [PATCH 059/281] add kotlin solution for 231 Power-Of-Two.kt --- .../08-Power-Of-Two/Power-Of-Two.kt | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.kt diff --git a/June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.kt b/June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.kt new file mode 100644 index 0000000..06d2fe8 --- /dev/null +++ b/June-LeetCoding-Challenge/08-Power-Of-Two/Power-Of-Two.kt @@ -0,0 +1,61 @@ +class PowerofTwoKotlin231 { + + companion object { + val resultSet = setOf( + 1, + 2, + 4, + 8, + 16, + 32, + 64, + 128, + 256, + 512, + 1024, + 2048, + 4096, + 8192, + 16384, + 32768, + 65536, + 131072, + 262144, + 524288, + 1048576, + 2097152, + 4194304, + 8388608, + 16777216, + 33554432, + 67108864, + 134217728, + 268435456, + 536870912, + 1073741824 + ) + } + + fun isPowerOfTwo(n: Int): Boolean { + return resultSet.contains(n) + } + /* + fun isPowerOfTwo(n: Int): Boolean { + if (n == 1) { + return true + } + var current = 2 + while (current < n && current <= 1073741823) { + current = current.shl(1) + } + return current == n + } + */ +} + +fun main() { + val solution = PowerofTwoKotlin231() + println(solution.isPowerOfTwo(4)) + println(solution.isPowerOfTwo(1073741825)) + println(solution.isPowerOfTwo(2)) +} \ No newline at end of file From 9b48d5ef7624040e630cfcfb7f16d0025214ca5d Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Tue, 9 Jun 2020 09:51:21 +0200 Subject: [PATCH 060/281] Create 08-Is-Subsequence --- June-LeetCoding-Challenge/08-Is-Subsequence | 1 + 1 file changed, 1 insertion(+) create mode 100644 June-LeetCoding-Challenge/08-Is-Subsequence diff --git a/June-LeetCoding-Challenge/08-Is-Subsequence b/June-LeetCoding-Challenge/08-Is-Subsequence new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/June-LeetCoding-Challenge/08-Is-Subsequence @@ -0,0 +1 @@ + From 9543a6f0532bb699f6c7cb72604541ae2883158c Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Tue, 9 Jun 2020 09:52:17 +0200 Subject: [PATCH 061/281] Delete 08-Is-Subsequence --- June-LeetCoding-Challenge/08-Is-Subsequence | 1 - 1 file changed, 1 deletion(-) delete mode 100644 June-LeetCoding-Challenge/08-Is-Subsequence diff --git a/June-LeetCoding-Challenge/08-Is-Subsequence b/June-LeetCoding-Challenge/08-Is-Subsequence deleted file mode 100644 index 8b13789..0000000 --- a/June-LeetCoding-Challenge/08-Is-Subsequence +++ /dev/null @@ -1 +0,0 @@ - From 6043e0fa729ae3f571495d5c35dc03112a867b9f Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Tue, 9 Jun 2020 09:53:05 +0200 Subject: [PATCH 062/281] Create 08-Is-Subsequence.cpp --- .../08-Is-Subsequence/08-Is-Subsequence.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 June-LeetCoding-Challenge/08-Is-Subsequence/08-Is-Subsequence.cpp diff --git a/June-LeetCoding-Challenge/08-Is-Subsequence/08-Is-Subsequence.cpp b/June-LeetCoding-Challenge/08-Is-Subsequence/08-Is-Subsequence.cpp new file mode 100644 index 0000000..c298544 --- /dev/null +++ b/June-LeetCoding-Challenge/08-Is-Subsequence/08-Is-Subsequence.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + bool isSubsequence(string s, string t) { + int i=0, j=0; + while(i Date: Tue, 9 Jun 2020 10:01:14 +0200 Subject: [PATCH 063/281] rename files --- .../08-Is-Subsequence.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename June-LeetCoding-Challenge/{08-Is-Subsequence => 09-Is-Subsequence}/08-Is-Subsequence.cpp (100%) diff --git a/June-LeetCoding-Challenge/08-Is-Subsequence/08-Is-Subsequence.cpp b/June-LeetCoding-Challenge/09-Is-Subsequence/08-Is-Subsequence.cpp similarity index 100% rename from June-LeetCoding-Challenge/08-Is-Subsequence/08-Is-Subsequence.cpp rename to June-LeetCoding-Challenge/09-Is-Subsequence/08-Is-Subsequence.cpp From 14f7e6c486a49eb1177aa624756513b8cb178c3f Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 9 Jun 2020 10:23:16 +0200 Subject: [PATCH 064/281] add cpp solution2 --- .../09-Is-Subsequence/08-Is-Subsequence.cpp | 12 -------- .../09-Is-Subsequence/Is-Subsequence.cpp | 28 +++++++++++++++++++ 2 files changed, 28 insertions(+), 12 deletions(-) delete mode 100644 June-LeetCoding-Challenge/09-Is-Subsequence/08-Is-Subsequence.cpp create mode 100644 June-LeetCoding-Challenge/09-Is-Subsequence/Is-Subsequence.cpp diff --git a/June-LeetCoding-Challenge/09-Is-Subsequence/08-Is-Subsequence.cpp b/June-LeetCoding-Challenge/09-Is-Subsequence/08-Is-Subsequence.cpp deleted file mode 100644 index c298544..0000000 --- a/June-LeetCoding-Challenge/09-Is-Subsequence/08-Is-Subsequence.cpp +++ /dev/null @@ -1,12 +0,0 @@ -class Solution { -public: - bool isSubsequence(string s, string t) { - int i=0, j=0; - while(i> dp(n+1, vector(m+1, false)); + for (int i = 0; i <= m; i++) dp[0][i] = true; + for (int i = 1; i <= n; i++) + for (int j = 1; j <= m; j++){ + if (s[i-1] == t[j-1]) dp[i][j] = dp[i][j] or dp[i-1][j-1]; + dp[i][j] = dp[i][j] or dp[i][j-1]; + } + return dp[n][m]; + } +}; From 8faeefefff2ddc2b38040b7fad1b22ce1aa8709c Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 9 Jun 2020 10:25:04 +0200 Subject: [PATCH 065/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 41b6aa5..f00b49a 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Solutions in various programming languages are provided. Enjoy it. 6. [Queue Reconstruction by Height](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/06-Queue-Reconstruction-By-Height): Greedy 7. [Coin Change 2](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/07-Coin-Change-2): DP 8. [Power of Two](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/08-Power-Of-Two): Bitwise manipulation - +9. [Is Subsequence](https://github.com/AlgoStudyGroup/Leetcode/blob/master/June-LeetCoding-Challenge/09-Is-Subsequence): Two pointers / DP ## May LeetCoding Challenge From 1ad9691b6963eaba356e3fd8d1380d152f4172b4 Mon Sep 17 00:00:00 2001 From: LI Jiayi Date: Tue, 9 Jun 2020 14:10:21 +0200 Subject: [PATCH 066/281] Add c# solution --- .../09-Is-Subsequence/Is-Subsequence.cs | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 June-LeetCoding-Challenge/09-Is-Subsequence/Is-Subsequence.cs diff --git a/June-LeetCoding-Challenge/09-Is-Subsequence/Is-Subsequence.cs b/June-LeetCoding-Challenge/09-Is-Subsequence/Is-Subsequence.cs new file mode 100644 index 0000000..ffb9414 --- /dev/null +++ b/June-LeetCoding-Challenge/09-Is-Subsequence/Is-Subsequence.cs @@ -0,0 +1,41 @@ +public class Solution { + + // A faster method + public bool IsSubsequence(string s, string t) { + if (s == "") + return true; + + if (s.Length > t.Length) + return false; + + int inds = 0; + foreach (char c in t) { + if (s[inds] == c) { + inds++; + if (inds == s.Length) + return true; + } + } + return false; + } + + // A more general method + public bool IsSubsequenceMine(string s, string t) { + + if (s.Length > t.Length) + return false; + + // the following comparison makes the method faster + if (s.Length == t.Length) + return s == t; + + int inds = 0, indt = 0; + while (inds < s.Length && indt < t.Length) { + if (s[inds] == t[indt]) { + inds++; + } + indt++; + } + return inds > s.Length-1; + } +} From e6c2312d4916dc35956b447a04d6fb7aa58a5b4e Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Wed, 10 Jun 2020 09:25:36 +0200 Subject: [PATCH 067/281] Create Search-Insert-Position.cpp --- .../10-Search-Insert-Position/Search-Insert-Position.cpp | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.cpp diff --git a/June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.cpp b/June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.cpp new file mode 100644 index 0000000..1b02c2a --- /dev/null +++ b/June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + int searchInsert(vector& nums, int target) { + return distance(nums.begin(), lower_bound(nums.begin(), nums.end(), target)); + } +}; From 3f60121c59edc32a7e1a32879153edaa20f6416e Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 10 Jun 2020 10:20:51 +0200 Subject: [PATCH 068/281] add cpp solution2 --- .../10-Search-Insert-Position/Search-Insert-Position.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.cpp b/June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.cpp index 1b02c2a..defec81 100644 --- a/June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.cpp +++ b/June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.cpp @@ -4,3 +4,11 @@ class Solution { return distance(nums.begin(), lower_bound(nums.begin(), nums.end(), target)); } }; + + +class Solution2 { +public: + int searchInsert(vector& nums, int target) { + return lower_bound(nums.begin(), nums.end(), target) - nums.begin(); + } +}; \ No newline at end of file From 343054956c1656b200fe7b5a6157880428efc350 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 10 Jun 2020 10:22:13 +0200 Subject: [PATCH 069/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f00b49a..ff92290 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Solutions in various programming languages are provided. Enjoy it. 7. [Coin Change 2](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/07-Coin-Change-2): DP 8. [Power of Two](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/08-Power-Of-Two): Bitwise manipulation 9. [Is Subsequence](https://github.com/AlgoStudyGroup/Leetcode/blob/master/June-LeetCoding-Challenge/09-Is-Subsequence): Two pointers / DP - +10. [Search Insert Position](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/10-Search-Insert-Position): Binary Search ## May LeetCoding Challenge From 0b359e67add1f08207f169cc3e63080bef2c865e Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 11 Jun 2020 10:11:51 +0200 Subject: [PATCH 070/281] add cpp solution --- .../11-Sort-Colors/Sort-Colors.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 June-LeetCoding-Challenge/11-Sort-Colors/Sort-Colors.cpp diff --git a/June-LeetCoding-Challenge/11-Sort-Colors/Sort-Colors.cpp b/June-LeetCoding-Challenge/11-Sort-Colors/Sort-Colors.cpp new file mode 100644 index 0000000..9e037b7 --- /dev/null +++ b/June-LeetCoding-Challenge/11-Sort-Colors/Sort-Colors.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + void swap(int& a, int& b) { + int tmp = a; + a = b; + b = tmp; + } + + void sortColors(vector& nums) { + int a = 0, b = nums.size()-1; + int i = 0; + while (i <= b){ + if (nums[i] == 2){ + swap(nums[b], nums[i]); + b--; + continue; + } + + if (nums[i] == 0) { + swap(nums[a], nums[i]); + a++; + } + i++; + } + } +}; \ No newline at end of file From 5ff3ca4b95a966e227a9b5a95ab5a99a25b2d7fa Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 11 Jun 2020 10:12:57 +0200 Subject: [PATCH 071/281] update doc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ff92290..879dcf6 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ Solutions in various programming languages are provided. Enjoy it. 8. [Power of Two](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/08-Power-Of-Two): Bitwise manipulation 9. [Is Subsequence](https://github.com/AlgoStudyGroup/Leetcode/blob/master/June-LeetCoding-Challenge/09-Is-Subsequence): Two pointers / DP 10. [Search Insert Position](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/10-Search-Insert-Position): Binary Search +11. [Sort Colors](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/11-Sort-Colors): Two Pointers ## May LeetCoding Challenge From 4163d4ecba21275bb70c7a9aa9d6a60522c515a1 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 12 Jun 2020 14:37:58 +0200 Subject: [PATCH 072/281] add cpp solutoin --- .../Insert-Delete-GetRandom.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.cpp diff --git a/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.cpp b/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.cpp new file mode 100644 index 0000000..f0101a2 --- /dev/null +++ b/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.cpp @@ -0,0 +1,26 @@ +class RandomizedSet { +public: + unordered_map m; + /** Initialize your data structure here. */ + RandomizedSet() { + + } + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + bool insert(int val) { + return (++m[val])==1; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + bool remove(int val) { + if(m.find(val)==m.end()) return false; + m.erase(val); + return true; + } + + /** Get a random element from the set. */ + int getRandom() { + return next(begin(m), rand()%m.size())->first; + } +}; + From 01c18c2fb01aad88978d4fad8027a8344f47ee1b Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 12 Jun 2020 14:39:32 +0200 Subject: [PATCH 073/281] update doc. --- README.md | 2 ++ untitled | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 untitled diff --git a/README.md b/README.md index 879dcf6..ff19858 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,8 @@ Solutions in various programming languages are provided. Enjoy it. 9. [Is Subsequence](https://github.com/AlgoStudyGroup/Leetcode/blob/master/June-LeetCoding-Challenge/09-Is-Subsequence): Two pointers / DP 10. [Search Insert Position](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/10-Search-Insert-Position): Binary Search 11. [Sort Colors](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/11-Sort-Colors): Two Pointers +12. [Insert Delete GetRandom](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom): Hash Table + ## May LeetCoding Challenge diff --git a/untitled b/untitled new file mode 100644 index 0000000..b527a28 --- /dev/null +++ b/untitled @@ -0,0 +1,43 @@ +class RandomizedSet { +public: + vector v; + unordered_map m; + + /** Initialize your data structure here. */ + RandomizedSet() { + v.clear(); + m.clear(); + srand((unsigned)time(NULL)); + } + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + bool insert(int val) { + if (m.find(val) != m.end()) return false; + v.push_back(val); + m[val] = v.size() - 1; + return true; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + bool remove(int val) { + if (m.find(val) == m.end()) return false; + + v[m[val]] = v[v.size() - 1]; + v.pop_back(); + m.erase(val); + return truea; + } + + /** Get a random element from the set. */ + int getRandom() { + return v[rand() % v.size()]; + } +}; + +/** + * Your RandomizedSet object will be instantiated and called as such: + * RandomizedSet* obj = new RandomizedSet(); + * bool param_1 = obj->insert(val); + * bool param_2 = obj->remove(val); + * int param_3 = obj->getRandom(); + */ \ No newline at end of file From 65b3079d730617f99ee60da7def0f6097a496370 Mon Sep 17 00:00:00 2001 From: kerms Date: Fri, 12 Jun 2020 14:41:38 +0200 Subject: [PATCH 074/281] [12, June 2020] Add cpp rand solution Unordered_map + vector --- .../Insert-Delete-GetRandom.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.cpp b/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.cpp index f0101a2..f4051b1 100644 --- a/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.cpp +++ b/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.cpp @@ -24,3 +24,35 @@ class RandomizedSet { } }; +class RandomizedSet { + unordered_map hm; + vector datas; +public: + /** Initialize your data structure here. */ + RandomizedSet() { } + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + bool insert(int val) { + if (hm.find(val) != hm.end()) + return false; + hm[val] = datas.size(); + datas.push_back(val); + return true; + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + bool remove(int val) { + if (hm.find(val) == hm.end()) + return false; + hm[datas.back()] = hm[val]; + datas[hm[val]] = datas.back(); + hm.erase(val); + datas.pop_back(); + return true; + } + + /** Get a random element from the set. */ + int getRandom() { + return datas[random()%datas.size()]; + } +}; From c5c471311d0b575aa5f129a87eb3cd32fc5199eb Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 13 Jun 2020 09:57:53 +0200 Subject: [PATCH 075/281] add cpp solution --- .../Largest-Divisible-Subset.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.cpp diff --git a/June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.cpp b/June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.cpp new file mode 100644 index 0000000..b9b7b36 --- /dev/null +++ b/June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector largestDivisibleSubset(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + if (n == 0) return vector(); + vector dp(n+1, 0); + vector prev(n+1, 0); + + int maxv = 0, p = 0; + + for (int i = 1; i <= n; i++){ + dp[i] = 1; + prev[i] = i; + for (int j = 1; j < i; j++){ + if (nums[i-1] % nums[j-1] == 0 and dp[j] + 1 > dp[i]){ + prev[i] = j; + dp[i] = dp[j] + 1; + } + } + if (dp[i] > maxv){ + maxv = dp[i]; + p = i; + } + } + + vector ans; + while (p != prev[p]) { + ans.push_back(nums[p-1]); + p = prev[p]; + } + ans.push_back(nums[p-1]); + + sort(ans.begin(), ans.end()); + return ans; + } +}; \ No newline at end of file From da76e23cdafd00a1c42c873809d021709d173822 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 13 Jun 2020 09:58:54 +0200 Subject: [PATCH 076/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ff19858..f6e3864 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Solutions in various programming languages are provided. Enjoy it. 10. [Search Insert Position](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/10-Search-Insert-Position): Binary Search 11. [Sort Colors](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/11-Sort-Colors): Two Pointers 12. [Insert Delete GetRandom](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom): Hash Table - +13. [Largest Divisible Subset](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/13-Largest-Divisible-Subset): DP ## May LeetCoding Challenge From 428cc87f9ffd3044984c8179cae97dc7f98095d9 Mon Sep 17 00:00:00 2001 From: kerms Date: Sat, 13 Jun 2020 20:44:14 +0200 Subject: [PATCH 077/281] [13 June, 2020] Add cpp solution 2 with map --- .../Largest-Divisible-Subset.cpp | 71 ++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.cpp b/June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.cpp index b9b7b36..78f8c5e 100644 --- a/June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.cpp +++ b/June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.cpp @@ -34,4 +34,73 @@ class Solution { sort(ans.begin(), ans.end()); return ans; } -}; \ No newline at end of file +}; + +class Solution {/* time: O(n*n), space: O(n) */ +public: + /* + * the idea is for each num in nums, + * find all multiple of num. + * each num have a count of previous multiple + */ + vector largestDivisibleSubset(vector& nums) { + int i; + if (!nums.size()) + return {}; + + map m; + map::iterator it; + vector> dp(nums.size()); + unsigned int acc, num; + int largest_last_index = 0; + int largest_subcount = 0; + + sort(nums.begin(), nums.end()); + for (i = 0; i < nums.size(); ++i) + m[nums[i]] = i; + + if (nums[0] == 1) { + fill(dp.begin()+1, dp.end(), make_pair(0,1)); + dp[0].first = -1; + dp[0].second = 0; + largest_last_index = nums.size()-1; + i = 1; + } else { + i = 0; + fill(dp.begin(), dp.end(), make_pair(-1,0)); + } + + for (; i < nums.size(); ++i) { + num = nums[i]; + acc = num << 1; + if ((int)num > (int)acc) // solve overflow problem + continue; + /* find all multiple of num */ + while ((it = m.upper_bound(acc-1)) != m.end()) { + int mod = it->first % num; + auto &ref = dp[i]; + auto &tgt = dp[it->second]; + /* current list of multiple is larger than the old one */ + if (mod == 0 && ref.second >= tgt.second) { + /* move target into biger list */ + tgt.first = i ; + tgt.second = ref.second +1; + if (tgt.second > largest_subcount) { + largest_subcount = tgt.second; + largest_last_index = it->second; + } + } + acc = it->first - mod + num; + if ((int)num > (int)acc) // solve overflow problem + break; + } + } + + vector ret; + while (largest_last_index >= 0) { + ret.push_back(nums[largest_last_index]); + largest_last_index = dp[largest_last_index].first; + } + return ret; + } +}; From d5e6550f94ea83fd7071dc31d06f2d56d9f060e3 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 14 Jun 2020 10:09:41 +0200 Subject: [PATCH 078/281] add cpp solution --- .../Cheapest-Flights-Within-K-Stops.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.cpp diff --git a/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.cpp b/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.cpp new file mode 100644 index 0000000..8b54c0c --- /dev/null +++ b/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int findCheapestPrice(int n, vector>& flights, int src, int dst, int K) { + vector> a(n, vector(n, 0)); + for (int i = 0; i < flights.size(); i++) + a[flights[i][0]][flights[i][1]] = flights[i][2]; + + + vector> dp(K+2, vector(n, 0)); + + for (int i = 0; i < n; i++) dp[0][i] = 1000000000; + dp[0][src] = 0; + + int ans = min(dp[0][dst], 1000000000); + for (int i = 1; i <= K+1; i++){ + for (int j = 0; j < n; j++){ + dp[i][j] = 1000000000; + for (int k = 0; k < n; k++) + if (a[k][j]) + dp[i][j] = min(dp[i][j], dp[i-1][k] + a[k][j]); + } + ans = min(ans, dp[i][dst]); + } + return (ans == 1000000000)?-1:ans; + } +}; \ No newline at end of file From 153a9c2c51dd91155fb72be28b0183d7acc6eca8 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 14 Jun 2020 10:11:06 +0200 Subject: [PATCH 079/281] update doc --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f6e3864..8876e6f 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,8 @@ Solutions in various programming languages are provided. Enjoy it. 11. [Sort Colors](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/11-Sort-Colors): Two Pointers 12. [Insert Delete GetRandom](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom): Hash Table 13. [Largest Divisible Subset](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/13-Largest-Divisible-Subset): DP +14. [Cheapest Flights Within K Stops](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops): DP + ## May LeetCoding Challenge From 39fa1c68044c6af2d6e5d24ee8057b821f6c7388 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Sun, 14 Jun 2020 12:07:57 +0200 Subject: [PATCH 080/281] Update Cheapest-Flights-Within-K-Stops.cpp --- .../Cheapest-Flights-Within-K-Stops.cpp | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.cpp b/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.cpp index 8b54c0c..fb66225 100644 --- a/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.cpp +++ b/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.cpp @@ -23,4 +23,39 @@ class Solution { } return (ans == 1000000000)?-1:ans; } -}; \ No newline at end of file +}; + +class Solution2 { + // algo dijkstra +public: + typedef tuple typeTuple; // (AccumulatedCost, cityId, stopUsed) + int findCheapestPrice(int n, vector>& flights, int src, int dst, int K) { + + priority_queue, greater> neighs; + + unordered_map>> g; + for (auto& v : flights) + g[v[0]].emplace_back(v[1], v[2]); + + neighs.emplace(0, src, 0); + + while (!neighs.empty()) { + auto t = neighs.top(); + int cost = get<0>(t); // accumulated cost + int u = get<1>(t); // city u -> city v + int stopused = get<2>(t); + neighs.pop(); + + if (u == dst) + return cost; + + if (stopused > K) continue; + + for (auto p : g[u]) + neighs.emplace(cost + p.second, p.first, stopused + 1); // increment stopused + + } + return -1; + + } +}; From 00dfdb4660d9969380a1f2e40a8cae79bda339e8 Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Sun, 14 Jun 2020 19:40:52 +0200 Subject: [PATCH 081/281] add kotlin solutions --- .../09-Is-Subsequence/Is-Subsequence.kt | 54 +++++++++++++++++++ .../Search-Insert-Position.kt | 21 ++++++++ .../11-Sort-Colors/Sort-Colors.kt | 44 +++++++++++++++ .../Insert-Delete-GetRandom.kt | 47 ++++++++++++++++ .../Largest-Divisible-Subset.kt | 32 +++++++++++ .../Cheapest-Flights-Within-K-Stops.kt | 37 +++++++++++++ 6 files changed, 235 insertions(+) create mode 100644 June-LeetCoding-Challenge/09-Is-Subsequence/Is-Subsequence.kt create mode 100644 June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.kt create mode 100644 June-LeetCoding-Challenge/11-Sort-Colors/Sort-Colors.kt create mode 100644 June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.kt create mode 100644 June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.kt create mode 100644 June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.kt diff --git a/June-LeetCoding-Challenge/09-Is-Subsequence/Is-Subsequence.kt b/June-LeetCoding-Challenge/09-Is-Subsequence/Is-Subsequence.kt new file mode 100644 index 0000000..4e73659 --- /dev/null +++ b/June-LeetCoding-Challenge/09-Is-Subsequence/Is-Subsequence.kt @@ -0,0 +1,54 @@ +class IsSubsequenceKotlin392 { + + fun isSubsequence(s: String, t: String): Boolean { + if (s.isEmpty()) { + return true + } + var indexS = 0 + t.forEach { + if (it == s[indexS]) { + if (++indexS == s.length) { + return true + } + } + } + return false + } + + /* + fun isSubsequence(s: String, t: String): Boolean { + val tMap = mutableMapOf>() + t.forEachIndexed { index, c -> + tMap.computeIfAbsent(c) { mutableListOf() }.add(index) + } + var indexOft = 0 + s.forEach { + indexOft = binarySearch(tMap[it], indexOft) + if (indexOft++ == -1) { + return false + } + } + return true + } + + private fun binarySearch(nums: List?, target: Int): Int { + if (nums.isNullOrEmpty()) { + return -1 + } + var left = 0 + var right = nums.size - 1 + while (left + 1 < right) { + val mid = left + (right - left) / 2 + when { + nums[mid] <= target -> left = mid + nums[mid] > target -> right = mid + } + } + return when { + nums[left] >= target -> nums[left] + nums[right] >= target -> nums[right] + else -> -1 + } + } + */ +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.kt b/June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.kt new file mode 100644 index 0000000..fa4496c --- /dev/null +++ b/June-LeetCoding-Challenge/10-Search-Insert-Position/Search-Insert-Position.kt @@ -0,0 +1,21 @@ +class SearchInsertPositionKotlin35 { + fun searchInsert(nums: IntArray, target: Int): Int { + if (nums.isEmpty()) { + return -1 + } + var left = 0 + var right = nums.size - 1 + while (left + 1 < right) { + val mid = left + (right - left) / 2 + when { + nums[mid] <= target -> left = mid + nums[mid] > target -> right = mid + } + } + return when { + target <= nums[left] -> left + target <= nums[right] -> right + else -> right + 1 + } + } +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/11-Sort-Colors/Sort-Colors.kt b/June-LeetCoding-Challenge/11-Sort-Colors/Sort-Colors.kt new file mode 100644 index 0000000..862ed72 --- /dev/null +++ b/June-LeetCoding-Challenge/11-Sort-Colors/Sort-Colors.kt @@ -0,0 +1,44 @@ +class SortColorsKotlin75 { + fun sortColors(nums: IntArray) { + var zeroPosition = 0 + var twoPosition = nums.size - 1 + var index = 0 + while (index <= twoPosition) { + when { + nums[index] == 1 -> ++index + nums[index] == 0 -> swap(nums, zeroPosition++, index++) + else -> swap(nums, twoPosition--, index) + } + } + } + + private fun swap(nums: IntArray, i: Int, j: Int) { + if (i == j) { + return + } + nums[i] = nums[i].xor(nums[j]) + nums[j] = nums[i].xor(nums[j]) + nums[i] = nums[i].xor(nums[j]) + } +} + +fun main() { + val solution = SortColorsKotlin75() + val test = intArrayOf(2, 2) + println(solution.sortColors(test)) + test.forEach(::print) + + // 0 3 + val test2 = intArrayOf(3, 3) + test2[0] = test2[0].xor(test2[0]) + test2[0] = test2[0].xor(test2[0]) + test2[0] = test2[0].xor(test2[0]) + test2.forEach(::print) + + // 4 4 + val test3 = intArrayOf(4, 4) + test3[0] = test3[0].xor(test3[1]) + test3[1] = test3[0].xor(test3[1]) + test3[0] = test3[0].xor(test3[1]) + test3.forEach(::print) +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.kt b/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.kt new file mode 100644 index 0000000..cc4c3d2 --- /dev/null +++ b/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom/Insert-Delete-GetRandom.kt @@ -0,0 +1,47 @@ +import kotlin.random.Random + +class InsertDeleteGetRandomO1Kotlin380 { + /** Initialize your data structure here. */ + private val arrayList: MutableList = ArrayList() + private val map: MutableMap = HashMap() + + /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ + fun insert(`val`: Int): Boolean { + if (map.containsKey(`val`)) { + return false + } + map[`val`] = arrayList.size + arrayList.add(`val`) + return true + } + + /** Removes a value from the set. Returns true if the set contained the specified element. */ + fun remove(`val`: Int): Boolean { + if (!map.containsKey(`val`)) { + return false + } + val removeIndex = map.getValue(`val`) + if (removeIndex != arrayList.size - 1) { + arrayList[removeIndex] = arrayList[arrayList.size - 1] + map[arrayList[arrayList.size - 1]] = removeIndex + } + arrayList.removeAt(arrayList.size - 1) + map.remove(`val`) + return true + } + + /** Get a random element from the set. */ + fun getRandom(): Int { + return arrayList[Random.Default.nextInt(arrayList.size)] + } +} + +fun main() { + val solution = InsertDeleteGetRandomO1Kotlin380() + println(solution.insert(1)) + println(solution.remove(2)) + println(solution.insert(2)) + println(solution.getRandom()) + println(solution.remove(1)) + println(solution.insert(2)) +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.kt b/June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.kt new file mode 100644 index 0000000..2976fbf --- /dev/null +++ b/June-LeetCoding-Challenge/13-Largest-Divisible-Subset/Largest-Divisible-Subset.kt @@ -0,0 +1,32 @@ +class LargestDivisibleSubsetKotlin368 { + fun largestDivisibleSubset(nums: IntArray): List { + if (nums.isEmpty()) { + return emptyList() + } + nums.sort() + val dp = IntArray(nums.size) { 1 } + val links = IntArray(nums.size) { -1 } + var max = 0 + var start = 0 + for (i in nums.indices) { + for (j in i + 1 until nums.size) { + if (nums[j] % nums[i] == 0 && + dp[j] < dp[i] + 1 + ) { + dp[j] = dp[i] + 1 + links[j] = i + if (dp[j] > max) { + max = dp[j] + start = j + } + } + } + } + val result: MutableList = ArrayList() + while (start != -1) { + result.add(nums[start]) + start = links[start] + } + return result + } +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.kt b/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.kt new file mode 100644 index 0000000..beab28e --- /dev/null +++ b/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops/Cheapest-Flights-Within-K-Stops.kt @@ -0,0 +1,37 @@ +class CheapestFlightsWithinKStopsKotlin787 { + /* + fun findCheapestPrice(n: Int, flights: Array, src: Int, dst: Int, K: Int): Int { + val dp = Array(K + 2) { IntArray(n) { 10000 * n } } + dp[0][src] = 0 + for (time in 1..K + 1) { + dp[time][src] = 0 + for (flight in flights) { + dp[time][flight[1]] = minOf( + dp[time][flight[1]], + dp[time - 1][flight[0]] + flight[2] + ) + } + } + return when { + dp[K + 1][dst] >= 10000 * n -> -1 + else -> dp[K + 1][dst] + } + } + */ + + fun findCheapestPrice(n: Int, flights: Array, src: Int, dst: Int, K: Int): Int { + var dp = IntArray(n) { 10000 * n } + dp[src] = 0 + for (time in 0..K) { + val new = dp.copyOf(dp.size) + for (flight in flights) { + new[flight[1]] = minOf(new[flight[1]], dp[flight[0]] + flight[2]) + } + dp = new + } + return when { + dp[dst] >= 10000 * n -> -1 + else -> dp[dst] + } + } +} \ No newline at end of file From d77e4ef18bb110187dde08fec1c7f4436e38e3bb Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 15 Jun 2020 09:08:12 +0200 Subject: [PATCH 082/281] add cpp solution --- .../Search-In-A-Binary-Search-Tree.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.cpp diff --git a/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.cpp b/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.cpp new file mode 100644 index 0000000..e3a5218 --- /dev/null +++ b/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + TreeNode* searchBST(TreeNode* root, int val) { + if (root == NULL) return NULL; + if (root->val == val) return root; + if (root->val < val) return searchBST(root->right, val); + if (root->val > val) return searchBST(root->left, val); + return NULL; + } +}; \ No newline at end of file From a4e9b68f2b1b36209d9308ff39670d32c1a2cd0e Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 15 Jun 2020 09:11:03 +0200 Subject: [PATCH 083/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8876e6f..b1d8a88 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Solutions in various programming languages are provided. Enjoy it. 12. [Insert Delete GetRandom](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/12-Insert-Delete-GetRandom): Hash Table 13. [Largest Divisible Subset](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/13-Largest-Divisible-Subset): DP 14. [Cheapest Flights Within K Stops](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops): DP - +15. [Search in a Binary Search Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree): Recursive ## May LeetCoding Challenge From 5e524d843deefa867de701e0af61beb6a5cfc299 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Mon, 15 Jun 2020 09:33:18 +0200 Subject: [PATCH 084/281] Update Search-In-A-Binary-Search-Tree.cpp --- .../Search-In-A-Binary-Search-Tree.cpp | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.cpp b/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.cpp index e3a5218..1cc2324 100644 --- a/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.cpp +++ b/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.cpp @@ -7,4 +7,28 @@ class Solution { if (root->val > val) return searchBST(root->left, val); return NULL; } -}; \ No newline at end of file +}; + +class Solution2 { +public: + TreeNode* searchBST(TreeNode* root, int val) { + stack st; + + while(!st.empty() || root){ + while(root){ + st.push(root); + root = root->left; + } + + TreeNode* t = st.top(); + if(t->val == val) return t; + if(t->val > val) return nullptr; + st.pop(); + + if(t->right) + root = t->right; + + } + return nullptr; + } +}; From 744f1b1a18840f137e43a817e603cc469cb447f8 Mon Sep 17 00:00:00 2001 From: WANGZijian1994 Date: Mon, 15 Jun 2020 09:50:37 +0200 Subject: [PATCH 085/281] https://github.com/AlgoStudyGroup/Leetcode.git --- .../Search-In-A-Binary-Search-Tree.js | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.js diff --git a/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.js b/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.js new file mode 100644 index 0000000..c6e037b --- /dev/null +++ b/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.js @@ -0,0 +1,8 @@ +let searchBST = function(root, val) { + if(root==null){ + return null; + } + if(root.val===val){return new TreeNode(root.val,root.left,root.right);} + if(root.val>val){return searchBST(root.left,val);} + else{return searchBST(root.right,val);} +}; From 0a192df77adb8901207fc9e81399b6bfcb5e64bf Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 16 Jun 2020 09:53:58 +0200 Subject: [PATCH 086/281] add cpp solution --- .../Validate-IP-Address.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.cpp diff --git a/June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.cpp b/June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.cpp new file mode 100644 index 0000000..744a810 --- /dev/null +++ b/June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.cpp @@ -0,0 +1,48 @@ +class Solution { +public: + void split(string str, char delim, vector& ans) { + int current, previous = 0; + current = str.find(delim); + ans.resize(0); + while (current != std::string::npos) { + ans.push_back(str.substr(previous, current - previous)); + previous = current + 1; + current = str.find(delim, previous); + } + ans.push_back(str.substr(previous, current - previous)); + } + + bool is_IP4(vector& s){ + if (s.size() != 4) return false; + for (int i = 0; i < 4; i++){ + if (s[i].size() == 0 or s[i].size() > 3 or (s[i][0] == '0' and s[i].size() > 1)) return false; + for (auto& c: s[i]) if (!isdigit(c)) return false; + int tmp = stoi(s[i]); + if (tmp < 0 or tmp > 255) return false; + } + return true; + } + + bool is_IP6(vector& s){ + if (s.size() != 8) return false; + for (int i = 0; i < 8; i++){ + if (s[i].size() == 0 or s[i].size() > 4) return false; + for (auto& c: s[i]) { + c = toupper(c); + if (isdigit(c)) continue; + if (c >= 'A' and c <= 'F') continue; + return false; + } + } + return true; + } + + string validIPAddress(string IP) { + vector s; + split(IP, '.', s); + if (is_IP4(s)) return "IPv4"; + split(IP, ':', s); + if (is_IP6(s)) return "IPv6"; + return "Neither"; + } +}; \ No newline at end of file From 7f121d28f916b91959468e896962fa31390691de Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 16 Jun 2020 09:55:03 +0200 Subject: [PATCH 087/281] update doc --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index b1d8a88..1751435 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,8 @@ Solutions in various programming languages are provided. Enjoy it. 13. [Largest Divisible Subset](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/13-Largest-Divisible-Subset): DP 14. [Cheapest Flights Within K Stops](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops): DP 15. [Search in a Binary Search Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree): Recursive +16. [Validate IP Address](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/16-Validate-IP-Address): String + ## May LeetCoding Challenge From 3d6b47ae686bf067557680ab22dc3cb9ef4e7548 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Tue, 16 Jun 2020 10:32:33 +0200 Subject: [PATCH 088/281] Update Validate-IP-Address.cpp --- .../Validate-IP-Address.cpp | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.cpp b/June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.cpp index 744a810..06f58b4 100644 --- a/June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.cpp +++ b/June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.cpp @@ -45,4 +45,29 @@ class Solution { if (is_IP6(s)) return "IPv6"; return "Neither"; } -}; \ No newline at end of file +}; + + +class Solution2 { +public: + string validIPAddress(string IP) { + if (IP.find('.') != string::npos) { + regex ipv4_regex("((2[0-4]\\d|25[0-5]|0|[1-9]\\d?|1\\d\\d)\\.){3}(2[0-4]\\d|25[0-5]|0|[1-9]\\d?|1\\d\\d)"); + // 2[0-4]\\d 200~249 + // 25[0-5] 250~255 + // 0 0 + // [1-9]\\d? 1~99 + // 1\\d\\d 100~199 + if (regex_match(IP, ipv4_regex)) + return "IPv4"; + } + else if (IP.find(':') != string::npos) { + regex ipv6_regex("([\\da-fA-F]{1,4}:){7}([\\da-fA-F]{1,4})"); + // [\\da-fA-F]{1,4} 0000~FFFF + if (regex_match(IP, ipv6_regex)) + return "IPv6"; + } + + return "Neither"; + } +}; From da942922fd50d8d0e41711a62a4e0ef6eb187490 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 17 Jun 2020 10:54:47 +0200 Subject: [PATCH 089/281] add cpp solution --- .../Surrounded-Regions.cpp | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.cpp diff --git a/June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.cpp b/June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.cpp new file mode 100644 index 0000000..7c27d18 --- /dev/null +++ b/June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.cpp @@ -0,0 +1,48 @@ +const int dx[4] = {-1, 0, 1, 0}; +const int dy[4] = {0, -1, 0, 1}; + +class Solution { +public: + int n, m; + void bfs(int x0, int y0, vector>& board, vector>& vis){ + queue> q; + vis[x0][y0] = 1; + q.push(make_pair(x0, y0)); + while(!q.empty()){ + int x = q.front().first, y = q.front().second; + q.pop(); + for (int i = 0; i < 4; i++){ + int xx = x + dx[i]; + int yy = y + dy[i]; + if (xx >= 0 and xx < n and yy >= 0 and yy < m and board[xx][yy] == 'O' and vis[xx][yy] == 0){ + vis[xx][yy] = 1; + q.push(make_pair(xx,yy)); + } + } + + } + } + + void solve(vector>& board) { + n = board.size(); + if (n == 0) return; + m = board[0].size(); + vector> vis(n, vector(m, 0)); + for (int i = 0; i < n; i++) { + if (board[i][0] == 'O' and vis[i][0] == 0) + bfs(i, 0, board, vis); + if (board[i][m-1] == 'O' and vis[i][m-1] == 0) + bfs(i, m-1, board, vis); + } + for (int i = 0; i < m; i++) { + if (board[0][i] == 'O' and vis[0][i] == 0) + bfs(0, i, board, vis); + if (board[n-1][i] == 'O' and vis[n-1][i] == 0) + bfs(n-1, i, board, vis); + } + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + if (board[i][j] == 'O' and vis[i][j] == 0) board[i][j] = 'X'; + + } +}; \ No newline at end of file From 621bbfd63e00a9b37f4d51813544c2051194aa9d Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 17 Jun 2020 10:55:53 +0200 Subject: [PATCH 090/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1751435..a8bf026 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Solutions in various programming languages are provided. Enjoy it. 14. [Cheapest Flights Within K Stops](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/14-Cheapest-Flights-Within-K-Stops): DP 15. [Search in a Binary Search Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree): Recursive 16. [Validate IP Address](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/16-Validate-IP-Address): String - +17. [Surrounded Regions](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/17-Surrounded-Regions): BFS ## May LeetCoding Challenge From 5f5cfb68d6eda2d3f2edf9052477e5243f0dc162 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 18 Jun 2020 09:50:48 +0200 Subject: [PATCH 091/281] add cpp solution --- .../18-H-Index-II/H-Index-II.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.cpp diff --git a/June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.cpp b/June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.cpp new file mode 100644 index 0000000..27525d0 --- /dev/null +++ b/June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int hIndex(vector& citations) { + int n = citations.size(); + int left = 0, right = n - 1; + while (left <= right) { + int mid = (right - left) / 2 + left; + if (n - mid <= citations[mid]) { + right = mid - 1; + } + else left = mid + 1; + } + return n - left; + } +}; \ No newline at end of file From 6f363d63a3ae25027ec91a1567ff39c58c6319a1 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 18 Jun 2020 09:53:42 +0200 Subject: [PATCH 092/281] update doc --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a8bf026..45b7e9c 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,8 @@ Solutions in various programming languages are provided. Enjoy it. 15. [Search in a Binary Search Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree): Recursive 16. [Validate IP Address](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/16-Validate-IP-Address): String 17. [Surrounded Regions](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/17-Surrounded-Regions): BFS +18. [H Index II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/18-H-Index-II): Binary Search + ## May LeetCoding Challenge From 7f1a76ea4cb4697d58b5dd3e77e0f20a0b9f3c64 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Thu, 18 Jun 2020 10:43:32 +0200 Subject: [PATCH 093/281] Update H-Index-II.cpp --- .../18-H-Index-II/H-Index-II.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.cpp b/June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.cpp index 27525d0..5e3b351 100644 --- a/June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.cpp +++ b/June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.cpp @@ -12,4 +12,19 @@ class Solution { } return n - left; } -}; \ No newline at end of file +}; + + +// solution when the citations vector is not initially sorted. +class Solution2 { +public: + int hIndex(vector& citations) { + make_heap(citations.begin(), citations.end(), greater{}); + while(!citations.empty() && citations.front() < citations.size()){ + pop_heap(citations.begin(), citations.end(), greater{}); + citations.pop_back(); + } + + return citations.size(); + } +}; From 2f04864173a561714de0c459e5560c95e476dfd6 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Sat, 20 Jun 2020 09:55:50 +0200 Subject: [PATCH 094/281] Create 20-Permutation-Sequence.cpp --- .../20-Permutation-Sequence.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.cpp diff --git a/June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.cpp b/June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.cpp new file mode 100644 index 0000000..d1667cc --- /dev/null +++ b/June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + string getPermutation(int n, int k) { + vector v(n); + iota(v.begin(), v.end(), 1); + while(k-1){ + next_permutation(v.begin(), v.end()); + --k; + } + string r; + transform(v.begin(), v.end(), back_inserter(r), [](const int num) -> char { return num + '0'; }); + + return r; + } +}; From 7039c2cd3c091c246022660377812f7ce44ce17c Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sat, 20 Jun 2020 19:50:59 +0200 Subject: [PATCH 095/281] 05-First-Unique-Character-In-A-String --- .../First-Unique-Character-In-A-String.cs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 May-LeetCoding-Challenge/05-First-Unique-Character-In-A-String/First-Unique-Character-In-A-String.cs diff --git a/May-LeetCoding-Challenge/05-First-Unique-Character-In-A-String/First-Unique-Character-In-A-String.cs b/May-LeetCoding-Challenge/05-First-Unique-Character-In-A-String/First-Unique-Character-In-A-String.cs new file mode 100644 index 0000000..0b0bd70 --- /dev/null +++ b/May-LeetCoding-Challenge/05-First-Unique-Character-In-A-String/First-Unique-Character-In-A-String.cs @@ -0,0 +1,51 @@ +public class Solution { + + //Better solution + //Runtime: 72 ms, faster than 99.58% of C# online submissions for First Unique Character in a String. + //Memory Usage: 31.9 MB, less than 69.64% of C# online submissions for First Unique Character in a String. + public int FirstUniqChar(string s) { + var arr = new int[26]; + + //array's index means character, 0 to 25 means 'a' to 'z' + //array's value means number of occurrence + foreach(var c in s){ + arr[c - 'a']++; + } + + for(int i=0; i>(); + var chars = s.ToCharArray(); + + for(int i=0; i(i, 1)); + }else{ + var st = dict[chars[i]]; + var newSt = new Tuple(st.Item1, st.Item2+1); + dict[chars[i]] = newSt; + } + } + + foreach(var kv in dict){ + if(kv.Value.Item2 == 1){ + return kv.Value.Item1; + } + } + + return -1; + } + +} \ No newline at end of file From bac77b9ac77af671b07868104455f4369da4ca07 Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Sun, 21 Jun 2020 11:06:30 +0200 Subject: [PATCH 096/281] add kotlin solutions --- .../Search-In-A-Binary-Search-Tree.kt | 16 +++ .../Validate-IP-Address.kt | 76 +++++++++++ .../Surrounded-Regions.kt | 124 ++++++++++++++++++ .../18-H-Index-II/H-Index-II.kt | 22 ++++ .../20-Permutation-Sequence.kt | 32 +++++ 5 files changed, 270 insertions(+) create mode 100644 June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.kt create mode 100644 June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.kt create mode 100644 June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.kt create mode 100644 June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.kt create mode 100644 June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.kt diff --git a/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.kt b/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.kt new file mode 100644 index 0000000..430da52 --- /dev/null +++ b/June-LeetCoding-Challenge/15-Search-In-A-Binary-Search-Tree/Search-In-A-Binary-Search-Tree.kt @@ -0,0 +1,16 @@ +class SearchinaBinarySearchTreeKotlin700 { + fun searchBST(root: TreeNode?, `val`: Int): TreeNode? { + return when { + root == null -> null + root.`val` == `val` -> root + root.`val` < `val` -> searchBST(root.right, `val`) + root.`val` > `val` -> searchBST(root.left, `val`) + else -> null + } + } + + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.kt b/June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.kt new file mode 100644 index 0000000..a3d91fa --- /dev/null +++ b/June-LeetCoding-Challenge/16-Validate-IP-Address/Validate-IP-Address.kt @@ -0,0 +1,76 @@ +class ValidateIPAddressKotlin468 { + fun validIPAddress(IP: String): String { + if (IP.isEmpty() || IP.length < 6) { + return "Neither" + } + val str5 = IP.substring(0, 6) + return when { + str5.contains(".") -> { + val strArray4 = IP.split(".") + if (strArray4.size == 4) { + strArray4.forEach { + if (!isIpV4(it)) { + return "Neither" + } + } + "IPv4" + } else { + "Neither" + } + } + str5.contains(":") -> { + val strArray8 = IP.split(":") + if (strArray8.size == 8) { + strArray8.forEach { + if (!isIpV6(it)) { + return "Neither" + } + } + "IPv6" + } else { + "Neither" + } + } + else -> "Neither" + } + } + + private val validIpV4String = "0123456789" + + private fun isIpV4(string: String): Boolean { + if (string.length in 1..3) { + string.forEach { + if (!validIpV4String.contains(it, ignoreCase = true)) { + return false + } + } + if (string.toInt() !in 0..255) { + return false + } + if (string[0] == '0' && string.length > 1) { + return false + } + return true + } + return false + } + + private val validIpV6String = "0123456789abcdef" + + private fun isIpV6(string: String): Boolean { + if (string.length in 1..4) { + string.forEach { + if (!validIpV6String.contains(it, ignoreCase = true)) { + return false + } + } + return true + } + return false + } +} + +fun main() { + val str = "2001:0db8:85a3:0:0:8A2E:0370:7334:" + println(str.split(":").size) +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.kt b/June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.kt new file mode 100644 index 0000000..4cdb3bc --- /dev/null +++ b/June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.kt @@ -0,0 +1,124 @@ +class SurroundedRegionsKotlin130 { + fun solve(board: Array) { + if (board.isEmpty()) { + return + } + val maxX = board.size + val maxY = board[0].size + val dp = Array(maxX) { IntArray(maxY) { 0 } } + for (index in board[0].indices) { + if (board[0][index] == 'O') { + dfs(board, dp, 0, index, maxX, maxY) + } + if (board[maxX - 1][index] == 'O') { + dfs(board, dp, maxX - 1, index, maxX, maxY) + } + } + for (index in board.indices) { + if (board[index][0] == 'O') { + dfs(board, dp, index, 0, maxX, maxY) + } + if (board[index][maxY - 1] == 'O') { + dfs(board, dp, index, maxY - 1, maxX, maxY) + } + } + for (i in 1..board.size - 2) { + for (j in 1..board[0].size - 2) { + if (board[i][j] == 'O' && dp[i][j] == 0) { + board[i][j] = 'X' + } + } + } + } + + private val deltaX = intArrayOf(0, 0, 1, -1) + private val deltaY = intArrayOf(1, -1, 0, 0) + + private fun dfs( + board: Array, + dp: Array, + x: Int, + y: Int, + maxX: Int, + maxY: Int + ) { + if (dp[x][y] == 0 && board[x][y] == 'O') { + dp[x][y] = 1 + for (index in deltaX.indices) { + val nextX = x + deltaX[index] + val nextY = y + deltaY[index] + if (inBoardMinus1(nextX, nextY, maxX, maxY)) { + dfs(board, dp, nextX, nextY, maxX, maxY) + } + } + } + } + + private fun inBoardMinus1(x: Int, y: Int, maxX: Int, maxY: Int) = x > 0 && y > 0 && x < maxX - 1 && y < maxY - 1 + /* + fun solve(board: Array) { + if (board.isEmpty()) { + return + } + val maxX = board.size + val maxY = board[0].size + val dp = Array(maxX) { IntArray(maxY) { 0 } } + val queue: Queue> = LinkedList() + for (index in board[0].indices) { + if (board[0][index] == 'O') { + queue.offer(Pair(0, index)) + } + if (board[maxX - 1][index] == 'O') { + queue.offer(Pair(maxX - 1, index)) + } + } + for (index in board.indices) { + if (board[index][0] == 'O') { + queue.offer(Pair(index, 0)) + } + if (board[index][maxY - 1] == 'O') { + queue.offer(Pair(index, maxY - 1)) + } + } + val deltaX = intArrayOf(0, 0, 1, -1) + val deltaY = intArrayOf(1, -1, 0, 0) + while (queue.isNotEmpty()) { + val current = queue.poll() + val x = current.first + val y = current.second + if (dp[x][y] == 0 && board[x][y] == 'O') { + dp[x][y] = 1 + for (index in deltaX.indices) { + val nextX = x + deltaX[index] + val nextY = y + deltaY[index] + if (inBoardMinus1(nextX, nextY, maxX, maxY)) { + queue.offer(Pair(nextX, nextY)) + } + } + } + } + for (i in 1..board.size - 2) { + for (j in 1..board[0].size - 2) { + if (board[i][j] == 'O' && dp[i][j] == 0) { + board[i][j] = 'X' + } + } + } + } + + private fun inBoardMinus1(x: Int, y: Int, maxX: Int, maxY: Int) = x > 0 && y > 0 && x < maxX - 1 && y < maxY - 1 + + */ +} + +fun main() { + val solution = SurroundedRegionsKotlin130() + val testArray = arrayOf( + charArrayOf('X', 'X', 'X', 'X'), + charArrayOf('X', 'O', 'O', 'X'), + charArrayOf('X', 'X', 'O', 'X'), + charArrayOf('X', 'O', 'X', 'X') + ) + solution.solve(testArray) + println() +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.kt b/June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.kt new file mode 100644 index 0000000..5a0e58d --- /dev/null +++ b/June-LeetCoding-Challenge/18-H-Index-II/H-Index-II.kt @@ -0,0 +1,22 @@ +class HIndexIIKotlin275 { + fun hIndex(citations: IntArray): Int { + if (citations.isEmpty()) { + return 0 + } + var left = 0 + var right = citations.size + while (left + 1 < right) { + val mid = left + (right - left) / 2 + when { + citations[citations.size - mid] >= mid -> left = mid + else -> right = mid + } + } + return when { + citations[citations.size - right] >= right -> right + left == 0 -> 0 + citations[citations.size - left] >= left -> left + else -> -1 + } + } +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.kt b/June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.kt new file mode 100644 index 0000000..44577e0 --- /dev/null +++ b/June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.kt @@ -0,0 +1,32 @@ +class PermutationSequenceKotlin60 { + + private val permutation: IntArray = IntArray(10) + + init { + permutation[0] = 1 + for (index in 1 until permutation.size) { + permutation[index] = permutation[index - 1] * index + } + } + + fun getPermutation(n: Int, k: Int): String { + val stringBuild = StringBuilder() + var current = k - 1 + val numberList: MutableList = ArrayList() + for (i in 1..n) { + numberList.add(i) + } + for (index in n downTo 1) { + val p = permutation[index - 1] + stringBuild.append(numberList[current / p]) + numberList.removeAt(current / p) + current %= p + } + return stringBuild.toString() + } +} + +fun main() { + val solution = PermutationSequenceKotlin60() + println(solution.getPermutation(4, 9)) +} \ No newline at end of file From b402672050b3bd0760d202f09b45953ddc393711 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 21 Jun 2020 19:19:31 +0200 Subject: [PATCH 097/281] c# solution for Delete-Node-In-A-Linked-List and Random Pick with Weight --- .../Delete-Node-in-a-Linked-List.cs | 6 ++ .../Random-Pick-With-Weight.cs | 80 +++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.cs create mode 100644 June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cs diff --git a/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.cs b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.cs new file mode 100644 index 0000000..9978cab --- /dev/null +++ b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.cs @@ -0,0 +1,6 @@ +public class Solution { + public void DeleteNode(ListNode node) { + node.val = node.next.val; + node.next = node.next.next; + } +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cs b/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cs new file mode 100644 index 0000000..ed15138 --- /dev/null +++ b/June-LeetCoding-Challenge/05-Random-Pick-With-Weight/Random-Pick-With-Weight.cs @@ -0,0 +1,80 @@ +// Solution: Binary search +// Runtime: 208 ms, faster than 95.23% of C# online submissions for Random Pick with Weight. +// Memory Usage: 47.2 MB, less than 5.10% of C# online submissions for Random Pick with Weight. +public class Solution +{ + private int sum = 0; //sum of all integers of array w + private int[] arr; //new Array, its index means index, its value means weight + private Random random = new Random(); + public Solution(int[] w) + { + arr = new int[w.Length]; + for (var i = 0; i < w.Length; i++) + { + sum += w[i]; + arr[i] = sum; + } + } + + //Binary search + public int PickIndex() + { + //Generate a random value between 0 and sum + var randomValue = random.Next(0, sum) + 1; + int left = 0, right = arr.Length - 1; + while (left <= right) + { + int mid = left + (right - left) / 2; + if (arr[mid] == randomValue) + return mid; + else if (arr[mid] > randomValue) + right = mid - 1; + else + left = mid + 1; + } + + return left; + } +} + + +// Solution: Linear search +// Runtime: 400 ms, faster than 37.10% of C# online submissions for Random Pick with Weight. +// Memory Usage: 47 MB, less than 5.10% of C# online submissions for Random Pick with Weight. +public class Solution +{ + private int sum = 0; //sum of all integers of array w + private int[] arr; //new Array, its index means index, its value means weight + private Random random = new Random(); + public Solution(int[] w) + { + arr = new int[w.Length]; + for (var i = 0; i < w.Length; i++) + { + sum += w[i]; + arr[i] = sum; + } + } + + //Linear search + public int PickIndex() + { + //Generate a random value between 0 and sum + var randomeValue = random.Next(0, sum); + + for (int i = 0; i < arr.Length; i++) + { + if (randomeValue < arr[i]) + { + return i; + } + } + return 0; + } +} + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(w); + * int param_1 = obj.PickIndex(); + */ \ No newline at end of file From dda78fd6b591bc763c5e72310575dc7a9302ce4e Mon Sep 17 00:00:00 2001 From: student114 Date: Sun, 21 Jun 2020 23:22:17 +0200 Subject: [PATCH 098/281] Dungeon Game --- .../21-Dungeon-Game/Dungeon-Game.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.py diff --git a/June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.py b/June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.py new file mode 100644 index 0000000..869584f --- /dev/null +++ b/June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.py @@ -0,0 +1,18 @@ +class Solution: + + def calculateMinimumHP(self, dungeon: List[List[int]]) -> int: + a = len(dungeon) + b = len(dungeon[0]) + dp = [[0 for x in range(b)] for y in range(a)] + if dungeon[-1][-1]<=0: + dp[-1][-1] = 1 - dungeon[-1][-1] + else: + dp[-1][-1] = 1 + for i in range(b-2,-1,-1): + dp[-1][i] = max(1,dp[-1][i+1]-dungeon[-1][i]) + for j in range(a-2,-1,-1): + dp[j][-1] = max(1,dp[j+1][-1]-dungeon[j][-1]) + for i in range(a-2,-1,-1): + for j in range(b-2,-1,-1): + dp[i][j] = max(1,min(dp[i+1][j],dp[i][j+1])-dungeon[i][j]) + return dp[0][0] From 146d180042aea52b1066443b373ce7cc7b3bf1c6 Mon Sep 17 00:00:00 2001 From: student114 Date: Sun, 21 Jun 2020 23:27:26 +0200 Subject: [PATCH 099/281] Add Solution python --- .../Surrounded-Regions.py | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.py diff --git a/June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.py b/June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.py new file mode 100644 index 0000000..57f9490 --- /dev/null +++ b/June-LeetCoding-Challenge/17-Surrounded-Regions/Surrounded-Regions.py @@ -0,0 +1,46 @@ +class Solution: + def solve(self, board: List[List[str]]) -> None: + """ + Do not return anything, modify board in-place instead. + """ + if board: + for i in range(len(board)): + if board[i][0]=='O': + self.bfs(board,i,0) + if board[i][len(board[0])-1]=='O': + self.bfs(board,i,len(board[0])-1) + for j in range(len(board[0])): + if board[0][j]=='O': + self.bfs(board,0,j) + if board[len(board)-1][j]=='O': + self.bfs(board,len(board)-1,j) + for i in range(len(board)): + for j in range(len(board[0])): + if board[i][j]=='O': + board[i][j]='X' + if board[i][j]=='2': + board[i][j]='O' + + def bfs(self,board,i,j): + q = [[i,j]] + while q!=[]: + pos = q.pop(0) + a = pos[0] + b = pos[1] + board[a][b] = '2' + if 0<=a+1 Date: Mon, 22 Jun 2020 21:24:51 +0200 Subject: [PATCH 100/281] Flood Fill C# solution --- .../11-Flood-Fill/Flood-Fill.cs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 May-LeetCoding-Challenge/11-Flood-Fill/Flood-Fill.cs diff --git a/May-LeetCoding-Challenge/11-Flood-Fill/Flood-Fill.cs b/May-LeetCoding-Challenge/11-Flood-Fill/Flood-Fill.cs new file mode 100644 index 0000000..460346c --- /dev/null +++ b/May-LeetCoding-Challenge/11-Flood-Fill/Flood-Fill.cs @@ -0,0 +1,32 @@ +// Runtime: 248 ms, faster than 93.23% of C# online submissions for Flood Fill. +// Memory Usage: 32.7 MB, less than 73.36% of C# online submissions for Flood Fill. +public class Solution +{ + public int[][] FloodFill(int[][] image, int sr, int sc, int newColor) + { + //sr is starting row position, sc is column position + if (image[sr][sc] == newColor) + { + return image; + } + + DfsFill(image, sr, sc, image[sr][sc], newColor); + + return image; + } + + public void DfsFill(int[][] image, int row, int column, int oldColor, int newColor) + { + if (row < 0 || row >= image.Length || column < 0 || column >= image[row].Length || image[row][column] != oldColor) + { + return; + } + + image[row][column] = newColor; + + DfsFill(image, row - 1, column, oldColor, newColor); + DfsFill(image, row + 1, column, oldColor, newColor); + DfsFill(image, row, column - 1, oldColor, newColor); + DfsFill(image, row, column + 1, oldColor, newColor); + } +} \ No newline at end of file From afe0e4ea9c93764606a75bad578e321c5396c0da Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 23 Jun 2020 12:31:18 +0200 Subject: [PATCH 101/281] add cpp solutions & rename files --- .../20-Permutation-Sequence.cpp | 15 --------- .../Permutation-Sequence.cpp | 33 +++++++++++++++++++ ...on-Sequence.kt => Permutation-Sequence.kt} | 0 .../21-Dungeon-Game/Dungeon-Game.cpp | 15 +++++++++ .../22-Single-Number-II/Single-Number-II.cpp | 14 ++++++++ .../Count-Complete-Tree-Nodes.cpp | 7 ++++ 6 files changed, 69 insertions(+), 15 deletions(-) delete mode 100644 June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.cpp create mode 100644 June-LeetCoding-Challenge/20-Permutation-Sequence/Permutation-Sequence.cpp rename June-LeetCoding-Challenge/20-Permutation-Sequence/{20-Permutation-Sequence.kt => Permutation-Sequence.kt} (100%) create mode 100644 June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.cpp create mode 100644 June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.cpp create mode 100644 June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.cpp diff --git a/June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.cpp b/June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.cpp deleted file mode 100644 index d1667cc..0000000 --- a/June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution { -public: - string getPermutation(int n, int k) { - vector v(n); - iota(v.begin(), v.end(), 1); - while(k-1){ - next_permutation(v.begin(), v.end()); - --k; - } - string r; - transform(v.begin(), v.end(), back_inserter(r), [](const int num) -> char { return num + '0'; }); - - return r; - } -}; diff --git a/June-LeetCoding-Challenge/20-Permutation-Sequence/Permutation-Sequence.cpp b/June-LeetCoding-Challenge/20-Permutation-Sequence/Permutation-Sequence.cpp new file mode 100644 index 0000000..2685d27 --- /dev/null +++ b/June-LeetCoding-Challenge/20-Permutation-Sequence/Permutation-Sequence.cpp @@ -0,0 +1,33 @@ +class Solution1 { +public: + string getPermutation(int n, int k) { + vector v(n); + iota(v.begin(), v.end(), 1); + while(k-1){ + next_permutation(v.begin(), v.end()); + --k; + } + string r; + transform(v.begin(), v.end(), back_inserter(r), [](const int num) -> char { return num + '0'; }); + + return r; + } +}; + + +class Solution2 { +public: + string getPermutation(int n, int k) { + vector a(n, 0); + for (int i = 0; i < n; i++) a[i] = i + 1; + int j = 1; + while (j < k) { + next_permutation(a.begin(), a.begin()+n); + j++; + } + + string ans; + for (int i = 0; i < n; i++) ans += to_string(a[i]); + return ans; + } +}; \ No newline at end of file diff --git a/June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.kt b/June-LeetCoding-Challenge/20-Permutation-Sequence/Permutation-Sequence.kt similarity index 100% rename from June-LeetCoding-Challenge/20-Permutation-Sequence/20-Permutation-Sequence.kt rename to June-LeetCoding-Challenge/20-Permutation-Sequence/Permutation-Sequence.kt diff --git a/June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.cpp b/June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.cpp new file mode 100644 index 0000000..5e16bdd --- /dev/null +++ b/June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int calculateMinimumHP(vector>& dungeon) { + int n = dungeon.size(); + int m = dungeon[0].size(); + vector> dp(n+1, vector(m+1, 1000000000)); + dp[n-1][m] = dp[n][m-1] = 1; + + for (int i = n-1; i>=0; i--) + for (int j = m-1; j>=0; j--) + dp[i][j] = max(min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], 1); + + return dp[0][0]; + } +}; \ No newline at end of file diff --git a/June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.cpp b/June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.cpp new file mode 100644 index 0000000..1b8bfed --- /dev/null +++ b/June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int singleNumber(vector& nums) { + int ans = 0; + for (int i = 0; i < 32; i++){ + int p = 1 << i; + int sum = 0; + for (int j = 0; j < nums.size(); j++) + if (nums[j] & p) sum++; + if (sum % 3 != 0) ans += p; + } + return ans; + } +}; \ No newline at end of file diff --git a/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.cpp b/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.cpp new file mode 100644 index 0000000..3a6742f --- /dev/null +++ b/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int countNodes(TreeNode* root) { + if (root == NULL) return 0; + return 1 + countNodes(root->left) + countNodes(root->right); + } +}; \ No newline at end of file From 6998b93262e9a3593db91a45baabd0178e6afec9 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 23 Jun 2020 18:45:46 +0200 Subject: [PATCH 102/281] Add Single Number II, Count Complete Tree Nodes --- .../22-Single-Number-II/Single-Number-II.cs | 22 +++++++ .../Count-Complete-Tree-Nodes.cs | 59 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.cs create mode 100644 June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.cs diff --git a/June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.cs b/June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.cs new file mode 100644 index 0000000..557a45f --- /dev/null +++ b/June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.cs @@ -0,0 +1,22 @@ +// Runtime: 96 ms, faster than 82.24% of C# online submissions for Single Number II. +// Memory Usage: 25.3 MB, less than 40.54% of C# online submissions for Single Number II. +public class Solution { + public int SingleNumber(int[] nums) { + var dict = new Dictionary(); + for(var i=0; i kv in dict){ + if(kv.Value == 1){ + return kv.Key; + } + } + + return -1; + } +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.cs b/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.cs new file mode 100644 index 0000000..f1c892b --- /dev/null +++ b/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.cs @@ -0,0 +1,59 @@ +public class Solution +{ + //Solution 1 + // Runtime: 100 ms, faster than 96.07% of C# online submissions for Count Complete Tree Nodes. + // Memory Usage: 32.3 MB, less than 97.70% of C# online submissions for Count Complete Tree Nodes. + public int CountNodes(TreeNode root) + { + var count = 0; + if (root == null) + { + return count; + } + DfsPreorderTraversal(root, ref count); + return count; + } + public void DfsPreorderTraversal(TreeNode node, ref int count) + { + if (node != null) + { + count++; + } + if (node.left != null) + { + DfsPreorderTraversal(node.left, ref count); + } + if (node.right != null) + { + DfsPreorderTraversal(node.right, ref count); + } + return; + } + + //Solution 2 + // Runtime: 112 ms, faster than 50.00% of C# online submissions for Count Complete Tree Nodes. + // Memory Usage: 32.5 MB, less than 87.10% of C# online submissions for Count Complete Tree Nodes. + public int CountNodes(TreeNode root) + { + if (root == null) + { + return 0; + } + return 1 + CountNodes(root.left) + CountNodes(root.right); + } +} + + +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ \ No newline at end of file From 8546a351c4bb3cc1646e9c3016725fd559813b66 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 24 Jun 2020 10:16:17 +0200 Subject: [PATCH 103/281] add cpp solution --- .../Unique-Binary-Search-Trees.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.cpp diff --git a/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.cpp b/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.cpp new file mode 100644 index 0000000..1312a1b --- /dev/null +++ b/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int numTrees(int n) { + vector dp(n+1, 0); + dp[0] = 1; + for (int i = 1; i <= n; i++) + for (int j = 0; j < i; j++) + dp[i] += dp[j] * dp[i-1-j]; + return dp[n]; + } +}; \ No newline at end of file From 026add71c80b505b5e29e1a12060286de9f27dd8 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 24 Jun 2020 10:24:19 +0200 Subject: [PATCH 104/281] update doc --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 45b7e9c..a025c21 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,12 @@ Solutions in various programming languages are provided. Enjoy it. 16. [Validate IP Address](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/16-Validate-IP-Address): String 17. [Surrounded Regions](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/17-Surrounded-Regions): BFS 18. [H Index II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/18-H-Index-II): Binary Search +19. [Longest Duplicate Substring](): +20. [Permutation Sequence](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/20-Permutation-Sequence): Maths +21. [Dungeon Game](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/21-Dungeon-Game): DP +22. [Single Number II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/22-Single-Number-II): Bitwise Manipulation +23. [Count Complete Tree Nodes](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes): Tree Traversal +24. [Unique Binary Search Trees](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees): DP ## May LeetCoding Challenge From 7d603ffca65a7755fd0cdf349ba0e0a2da3f1ac4 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 24 Jun 2020 22:29:49 +0200 Subject: [PATCH 105/281] Add Unique Binary Search Trees --- .../Unique-Binary-Search-Trees.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.cs diff --git a/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.cs b/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.cs new file mode 100644 index 0000000..2f7bbcf --- /dev/null +++ b/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.cs @@ -0,0 +1,14 @@ +// Runtime: 40 ms, faster than 78.73% of C# online submissions for Unique Binary Search Trees. +// Memory Usage: 14.4 MB, less than 98.08% of C# online submissions for Unique Binary Search Trees. +public class Solution { + public int NumTrees(int n) { + var dp = new int[n+1]; + dp[0] =1; + for(int i=1; i<=n; i++){ + for(int j=0; j Date: Thu, 25 Jun 2020 20:32:56 +0200 Subject: [PATCH 106/281] Add Find the Duplicate Number --- .../Find-the-Duplicate-Number.cs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.cs diff --git a/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.cs b/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.cs new file mode 100644 index 0000000..f1a405f --- /dev/null +++ b/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.cs @@ -0,0 +1,30 @@ +// Runtime: 100 ms, faster than 61.31% of C# online submissions for Find the Duplicate Number. +// Memory Usage: 25.2 MB, less than 88.84% of C# online submissions for Find the Duplicate Number. +public class Solution { + public int FindDuplicate(int[] nums) { + + int slow = 0; + int fast = 0; + int finder = 0; + + while (true) + { + slow = nums[slow]; + fast = nums[nums[fast]]; + + if (slow == fast) + break; + } + + while (true) + { + slow = nums[slow]; + finder = nums[finder]; + if (slow == finder) + break; + } + + return finder; + + } +} \ No newline at end of file From 7d6e480f3eee668243a4519a2e50c1d95a244f0c Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 25 Jun 2020 22:21:44 +0200 Subject: [PATCH 107/281] add cpp solution --- .../Find-the-Duplicate-Number.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.cpp diff --git a/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.cpp b/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.cpp new file mode 100644 index 0000000..746185c --- /dev/null +++ b/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int findDuplicate(vector& nums) { + int a = 0, b = 0; + do{ + a = nums[a]; + b = nums[nums[b]]; + } while (a != b); + + b = 0; + while (a != b){ + a = nums[a]; + b = nums[b]; + } + return a; + } +}; \ No newline at end of file From e1fbff114436b91047a65d954ed2995ca7bad5c7 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 25 Jun 2020 22:23:06 +0200 Subject: [PATCH 108/281] update doc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a025c21..73b4032 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ Solutions in various programming languages are provided. Enjoy it. 22. [Single Number II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/22-Single-Number-II): Bitwise Manipulation 23. [Count Complete Tree Nodes](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes): Tree Traversal 24. [Unique Binary Search Trees](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees): DP +25. [Find the Duplicate Number](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number): Cycle Detect ## May LeetCoding Challenge From 355cb2302bd182f48e6952d026befbb4f5368d9b Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Fri, 26 Jun 2020 10:06:19 +0200 Subject: [PATCH 109/281] Create Sum-Root-to-Leaf-Numbers.cpp --- .../Sum-Root-to-Leaf-Numbers.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cpp diff --git a/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cpp b/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cpp new file mode 100644 index 0000000..d119b36 --- /dev/null +++ b/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int sumNumbers(TreeNode* root) { + stack s; + int sum=0, acc = 0; + TreeNode* prev; + while(root || !s.empty()){ + while(root){ + s.push(root); + acc = 10*acc + root->val; + root = root->left; + + } + auto t = s.top(); + if(!t->left && !t->right) + sum+=acc; + + if(t->right && t->right != prev) + root = t->right; + else{ + prev = t; + acc = acc/10; + s.pop(); + } + } + return sum; + } +}; From 4804ec81be6669f9d59b2716703fe2c63839bcf9 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 26 Jun 2020 10:08:18 +0200 Subject: [PATCH 110/281] add cpp solution2 --- .../Sum-Root-to-Leaf-Numbers.cpp | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cpp b/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cpp index d119b36..571d20e 100644 --- a/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cpp +++ b/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution1 { public: int sumNumbers(TreeNode* root) { stack s; @@ -26,3 +26,24 @@ class Solution { return sum; } }; + + +class Solution2 { +public: + long long ans; + void dfs(TreeNode* root, long long x){ + if (root == NULL) return; + if (root->left == NULL and root->right == NULL){ + ans += x * 10 + root->val; + return ; + } + if (root->left) dfs(root->left, x * 10 + root->val); + if (root->right) dfs(root->right, x * 10 + root->val); + } + + int sumNumbers(TreeNode* root) { + ans = 0; + dfs(root, 0); + return ans; + } +}; \ No newline at end of file From 64d6bd00612aa78e236448bfdf69713b7d7c3ed6 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 26 Jun 2020 10:17:39 +0200 Subject: [PATCH 111/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 73b4032..644d011 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Solutions in various programming languages are provided. Enjoy it. 23. [Count Complete Tree Nodes](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes): Tree Traversal 24. [Unique Binary Search Trees](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees): DP 25. [Find the Duplicate Number](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number): Cycle Detect - +26. [Sum Root To Leaf Numbers](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers): DFS ## May LeetCoding Challenge From 4e39f4c7598456f1003aaca7b27c0fc8878057e6 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 26 Jun 2020 19:06:54 +0200 Subject: [PATCH 112/281] Add Sum Root to Leaf Numbers --- .../Sum-Root-to-Leaf-Numbers.cs | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cs diff --git a/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cs b/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cs new file mode 100644 index 0000000..972ef07 --- /dev/null +++ b/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.cs @@ -0,0 +1,45 @@ +// Runtime: 92 ms, faster than 76.74% of C# online submissions for Sum Root to Leaf Numbers. +// Memory Usage: 24.6 MB, less than 5.88% of C# online submissions for Sum Root to Leaf Numbers. +public class Solution { + public int SumNumbers(TreeNode root) { + if(root == null) return 0; + if(root.left == null && root.right == null) return root.val; + + var result = 0; + Calculate(0, root, ref result); + return result; + } + + public void Calculate(int v, TreeNode node, ref int num) + { + if(node != null) + { + v = v * 10 + node.val; + if(node.left == null && node.right == null) + { + num +=v; + } + if(node.left != null) + { + Calculate(v, node.left, ref num); + } + if(node.right != null) + { + Calculate(v, node.right, ref num); + } + } + } +} +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ \ No newline at end of file From 360dec8d5c1f7f914d22b4a72a519dfbb38bbab7 Mon Sep 17 00:00:00 2001 From: Mincong HUANG Date: Fri, 26 Jun 2020 20:59:38 +0200 Subject: [PATCH 113/281] Day-26 Sum-Root-to-Leaf-Numbers --- .../Sum-Root-to-Leaf-Numbers.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.java diff --git a/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.java b/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.java new file mode 100644 index 0000000..c39e360 --- /dev/null +++ b/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.java @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int sumNumbers(TreeNode root) { + return dfs(root, 0); + } + + private int dfs(TreeNode root, int acc) { + if (root == null) { + return 0; + } + int sum = acc * 10 + root.val; + if (root.left == null && root.right == null) { + return sum; + } + return dfs(root.left, sum) + dfs(root.right, sum); + } +} From 5178493da42927aef9ebd97661378995a9fb153d Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 27 Jun 2020 13:35:17 +0200 Subject: [PATCH 114/281] add cpp solution --- .../27-Perfect-Squares/Perfect-Squares.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.cpp diff --git a/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.cpp b/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.cpp new file mode 100644 index 0000000..5c522ba --- /dev/null +++ b/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector dp; + int calc(int n){ + if (n == 0) return 0; + if (dp[n]) return dp[n]; + int m = (int)(sqrt(n)); + int sum = n; + for (int i = 1; i <= m; i++) + sum = min(sum, calc(n - i * i) + 1); + dp[n] = sum; + return sum; + } + + int numSquares(int n) { + dp.resize(n+1); + for (int i = 1; i <= n; i++){ + calc(i); + } + return dp[n]; + } +}; \ No newline at end of file From a5908c176c48960acb4cb74bf0b17f767773d971 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 27 Jun 2020 13:41:32 +0200 Subject: [PATCH 115/281] update doc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 644d011..c57fb14 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ Solutions in various programming languages are provided. Enjoy it. 24. [Unique Binary Search Trees](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees): DP 25. [Find the Duplicate Number](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number): Cycle Detect 26. [Sum Root To Leaf Numbers](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers): DFS +27. [Perfect Squares](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/27-Perfect-Squares): DP ## May LeetCoding Challenge From e358f0bcea93d15244e5bba612c5f90e78833ba7 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sat, 27 Jun 2020 16:29:24 +0200 Subject: [PATCH 116/281] Add Perfect Squares --- .../27-Perfect-Squares/Perfect-Squares.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.cs diff --git a/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.cs b/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.cs new file mode 100644 index 0000000..13b0a8c --- /dev/null +++ b/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.cs @@ -0,0 +1,18 @@ +// Runtime: 88 ms, faster than 90.00% of C# online submissions for Perfect Squares. +// Memory Usage: 16.1 MB, less than 88.06% of C# online submissions for Perfect Squares. +public class Solution { + public int NumSquares(int n) { + var dp = new int[n+1]; + dp[0] = 0; + for(int i=1; i<=n; i++){ + var j = 1; + var min = n; + while(i >= j*j){ + min = Math.Min(min, dp[i - j*j] +1); + ++j; + } + dp[i] = min; + } + return dp[n]; + } +} \ No newline at end of file From ffe6aa1f5ffbe5de152dff63d6915af9bbad9312 Mon Sep 17 00:00:00 2001 From: Mincong HUANG Date: Sat, 27 Jun 2020 22:14:18 +0200 Subject: [PATCH 117/281] Day-27 Perfect-Squares --- .../27-Perfect-Squares/Perfect-Squares.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.java diff --git a/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.java b/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.java new file mode 100644 index 0000000..b5db64a --- /dev/null +++ b/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.java @@ -0,0 +1,15 @@ +class Solution { + public int numSquares(int n) { + int[] dp = new int[n + 1]; + for (int i = 1; i <= n; i++) { + int j = 1; + int min = Integer.MAX_VALUE; + while (i >= j * j) { + min = Math.min(min, dp[i - j * j] + 1); + j++; + } + dp[i] = min; + } + return dp[n]; + } +} From 6a02554474804e7e16f902a3a39c67121123f44d Mon Sep 17 00:00:00 2001 From: Shendan Jin Date: Sun, 28 Jun 2020 09:34:25 +0200 Subject: [PATCH 118/281] Delete untitled --- untitled | 43 ------------------------------------------- 1 file changed, 43 deletions(-) delete mode 100644 untitled diff --git a/untitled b/untitled deleted file mode 100644 index b527a28..0000000 --- a/untitled +++ /dev/null @@ -1,43 +0,0 @@ -class RandomizedSet { -public: - vector v; - unordered_map m; - - /** Initialize your data structure here. */ - RandomizedSet() { - v.clear(); - m.clear(); - srand((unsigned)time(NULL)); - } - - /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ - bool insert(int val) { - if (m.find(val) != m.end()) return false; - v.push_back(val); - m[val] = v.size() - 1; - return true; - } - - /** Removes a value from the set. Returns true if the set contained the specified element. */ - bool remove(int val) { - if (m.find(val) == m.end()) return false; - - v[m[val]] = v[v.size() - 1]; - v.pop_back(); - m.erase(val); - return truea; - } - - /** Get a random element from the set. */ - int getRandom() { - return v[rand() % v.size()]; - } -}; - -/** - * Your RandomizedSet object will be instantiated and called as such: - * RandomizedSet* obj = new RandomizedSet(); - * bool param_1 = obj->insert(val); - * bool param_2 = obj->remove(val); - * int param_3 = obj->getRandom(); - */ \ No newline at end of file From 1cdd779051a8834dcf2bab5df324206517f783d6 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 28 Jun 2020 11:23:58 +0200 Subject: [PATCH 119/281] Add Invert Binary Tree - Stack solution --- .../Invert-Binary-Tree.cs | 113 ++++++++++++++++-- 1 file changed, 103 insertions(+), 10 deletions(-) diff --git a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cs b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cs index e71e5e8..6cbf404 100644 --- a/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cs +++ b/June-LeetCoding-Challenge/01-Invert-Binary-Tree/Invert-Binary-Tree.cs @@ -1,13 +1,106 @@ -public class Solution { - public TreeNode InvertTree(TreeNode root) { +public class Solution +{ + public TreeNode InvertTree(TreeNode root) + { if (root != null) - { - InvertTree(root.left); - InvertTree(root.right); - TreeNode temps = root.left; - root.left=root.right; - root.right= temps; - } - return root; + { + InvertTree(root.left); + InvertTree(root.right); + TreeNode temps = root.left; + root.left = root.right; + root.right = temps; + } + return root; } } + +// Stack solution +// Runtime: 92 ms, faster than 78.61% of C# online submissions for Invert Binary Tree. +// Memory Usage: 24.1 MB, less than 62.37% of C# online submissions for Invert Binary Tree. +public class Solution +{ + public TreeNode InvertTree(TreeNode root) + { + if (root == null) + { + return null; + } + var stack = new Stack(); + stack.Push(root); + + while (stack.Count > 0) + { + var node = stack.Pop(); + var temp = node.right; + node.right = node.left; + node.left = temp; + if (node.left != null) + { + stack.Push(node.left); + } + if (node.right != null) + { + stack.Push(node.right); + } + } + + return root; + } +} + +//Code to play with for stack solution demo +public static class Program +{ + public static void Main() + { + var subleft = new TreeNode(4, null, null); + var subright = new TreeNode(5, null, null); + var left = new TreeNode(2, subleft, subright); + var right = new TreeNode(3, null, null); + var root = new TreeNode(1, left, right); + InvertTree(root); + } + + public static TreeNode InvertTree(TreeNode root) + { + if (root == null) + { + return null; + } + var stack = new Stack(); + stack.Push(root); + + while (stack.Count > 0) + { + var node = stack.Pop(); + Console.WriteLine("poping:" + node.val); + var temp = node.right; + node.right = node.left; + node.left = temp; + if (node.left != null) + { + Console.WriteLine("pushing left node:" + node.left?.val); + stack.Push(node.left); + } + if (node.right != null) + { + Console.WriteLine("pushing right node:" + node.right?.val); + stack.Push(node.right); + } + } + + return root; + } +} +public class TreeNode +{ + public int val; + public TreeNode left; + public TreeNode right; + public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) + { + this.val = val; + this.left = left; + this.right = right; + } +} \ No newline at end of file From 618d17d51f6f34fb9a4110ba7fdb786584981b8a Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 28 Jun 2020 12:48:05 +0200 Subject: [PATCH 120/281] add cpp solution --- .../Reconstruct-Itinerary.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.cpp diff --git a/June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.cpp b/June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.cpp new file mode 100644 index 0000000..3584bdb --- /dev/null +++ b/June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + int n; + vector ans; + map> a; + + + bool dfs(string s){ + ans.push_back(s); + if (ans.size() == n + 1) return true; + for (auto& t: a[s]){ + if (t != "") { + string tmp = t; + t = ""; + if (dfs(tmp)) return true; + t = tmp; + } + } + ans.pop_back(); + return 0; + } + + vector findItinerary(vector>& tickets) { + n = tickets.size(); + + for (int i = 0; i < n; i++) + a[tickets[i][0]].push_back(tickets[i][1]); + + for (int i = 0; i < n; i++) + sort(a[tickets[i][0]].begin(), a[tickets[i][0]].end()); + dfs("JFK"); + return ans; + } +}; \ No newline at end of file From 16ace99816a1708431ef87239e2b78e2f7f96d48 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 28 Jun 2020 12:49:27 +0200 Subject: [PATCH 121/281] update doc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c57fb14..c367df8 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ Solutions in various programming languages are provided. Enjoy it. 25. [Find the Duplicate Number](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number): Cycle Detect 26. [Sum Root To Leaf Numbers](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers): DFS 27. [Perfect Squares](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/27-Perfect-Squares): DP +28. [Reconstruct Itinerary](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/28-Reconstruct-Itinerary): DFS ## May LeetCoding Challenge From 1991d4cb4a90ab7d4ef062d7746bc889e363b988 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 28 Jun 2020 19:20:13 +0200 Subject: [PATCH 122/281] Add Reconstruct Itinerary --- .../Reconstruct-Itinerary.cs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.cs diff --git a/June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.cs b/June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.cs new file mode 100644 index 0000000..db36602 --- /dev/null +++ b/June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.cs @@ -0,0 +1,36 @@ +public class Solution +{ + public IList FindItinerary(IList> tickets) + { + var result = new List(); + var dict = new Dictionary>(); + for (int i = 0; i < tickets.Count(); i++) + { + var from = tickets[i][0]; + var to = tickets[i][1]; + if (!dict.ContainsKey(from)) + { + dict[from] = new List(); + } + dict[from].Add(to); + } + //Sort items in value list for each dictionary key + foreach (var kv in dict) + { + kv.Value.Sort(); + } + var stack = new Stack(); + stack.Push("JFK"); + while (stack.Count > 0) + { + while (dict.ContainsKey(stack.Peek()) && dict[stack.Peek()].Count > 0) + { + var firstDest = dict[stack.Peek()].First(); + dict[stack.Peek()].Remove(firstDest); + stack.Push(firstDest); + } + result.Insert(0, stack.Pop()); + } + return result; + } +} From 9a6957dd9d725ea29f5cc6959202eed56c8c76d7 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 29 Jun 2020 19:51:35 +0200 Subject: [PATCH 123/281] Add Unique Paths --- .../29-Unique-Paths/Unique-Paths.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cs diff --git a/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cs b/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cs new file mode 100644 index 0000000..e49e68e --- /dev/null +++ b/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cs @@ -0,0 +1,15 @@ +public class Solution { + public int UniquePaths(int m, int n) { + int[,] dp = new int[m, n]; + for(int i=0; i Date: Mon, 29 Jun 2020 20:07:23 +0200 Subject: [PATCH 124/281] add cpp solution --- June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cpp diff --git a/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cpp b/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cpp new file mode 100644 index 0000000..e69de29 From d4bce68342f74f33a2d83a3beeb695c8b5adbb9b Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 29 Jun 2020 20:09:20 +0200 Subject: [PATCH 125/281] add cpp solution --- .../29-Unique-Paths/Unique-Paths.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cpp b/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cpp index e69de29..3975d76 100644 --- a/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cpp +++ b/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int uniquePaths(int m, int n) { + vector> dp(n, vector(m, 0)); + for (int i = 0; i < m; i++) dp[0][i] = 1; + for (int i = 0; i < n; i++) dp[i][0] = 1; + + for (int i = 1; i < n; i++) + for (int j = 1; j < m; j++) + dp[i][j] = dp[i-1][j] + dp[i][j-1]; + return dp[n-1][m-1]; + } +}; \ No newline at end of file From 5e3fadb05c4071b36dd38af9ccc39ec25682d307 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 29 Jun 2020 20:10:45 +0200 Subject: [PATCH 126/281] update doc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c367df8..0473a50 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ Solutions in various programming languages are provided. Enjoy it. 26. [Sum Root To Leaf Numbers](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers): DFS 27. [Perfect Squares](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/27-Perfect-Squares): DP 28. [Reconstruct Itinerary](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/28-Reconstruct-Itinerary): DFS +29. [Unique Paths](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/29-Unique-Paths): DP ## May LeetCoding Challenge From 97c612e6e85a841a149b8bba66a17207e8ab5be8 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 30 Jun 2020 11:28:47 +0200 Subject: [PATCH 127/281] add cpp solution --- .../30-Word-Search-II/Word-Search.cpp | 94 +++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cpp diff --git a/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cpp b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cpp new file mode 100644 index 0000000..a87d707 --- /dev/null +++ b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cpp @@ -0,0 +1,94 @@ +class Trie { +public: + vector> ch; + vector val; + int size; + + /** Initialize your data structure here. */ + Trie() { + size = 1; + ch.resize(1); + ch[0].resize(26); + val.resize(1); + } + + /** Inserts a word into the trie. */ + void insert(string word) { + int cur = 0, n = word.length(); + for (int i = 0; i < n; i++){ + int j = word[i] - 'a'; + if (!ch[cur][j]){ + ch.push_back(vector(26, 0)); + val.push_back(0); + ch[cur][j] = size++; + } + cur = ch[cur][j]; + } + val[cur] = 1; + } +}; + +const int dx[4] = {-1, 0, 1, 0}; +const int dy[4] = {0, -1, 0, 1}; + +struct T { + int x, y, r; + string str; + T(){} + T(int x, int y, int r, string str):x(x),y(y),r(r), str(str){} +}; + +class Solution { +public: + int n, m; + Trie* t; + set s; + + void dfs(int x, int y, int r, string u, vector>& board, vector>& vis){ + + if (!r) return; + + if (t->val[r]) s.insert(u); + + for (int i = 0; i < 4; i++){ + int xx = x + dx[i]; + int yy = y + dy[i]; + if (xx >= 0 and xx < n and yy >= 0 and yy < m and t->ch[r][board[xx][yy]-'a'] and !vis[xx][yy]){ + int rr = t->ch[r][board[xx][yy]-'a']; + vis[xx][yy] = 1; + + string uu = u; + uu += board[xx][yy]; + if (t->val[rr]) s.insert(uu); + + dfs(xx, yy, rr, uu, board, vis); + vis[xx][yy] = 0; + } + + } + } + + vector findWords(vector>& board, vector& words) { + t = new Trie(); + for (auto& s: words) t->insert(s); + + n = board.size(); + if (n == 0) return vector(); + m = board[0].size(); + + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++){ + vector> vis(n, vector(m, 0)); + vis[i][j] = 1; + string u; + u += board[i][j]; + dfs(i, j, t->ch[0][board[i][j]-'a'], u, board, vis); + } + + vector ans; + for (auto tmp: s) + ans.push_back(tmp); + return ans; + + } +}; \ No newline at end of file From a17060e088239c909ee9100bfe17f7ea9c1d82e3 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 30 Jun 2020 11:30:45 +0200 Subject: [PATCH 128/281] update doc --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index 0473a50..32795bf 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,15 @@ https://leetcode.com + +## July LeetCoding Challenge +Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. + +Solutions in various programming languages are provided. Enjoy it. + + + + ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. @@ -37,6 +46,8 @@ Solutions in various programming languages are provided. Enjoy it. 27. [Perfect Squares](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/27-Perfect-Squares): DP 28. [Reconstruct Itinerary](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/28-Reconstruct-Itinerary): DFS 29. [Unique Paths](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/29-Unique-Paths): DP +30. [Word Search](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/30-Word-Search-II): Trie + DFS + ## May LeetCoding Challenge From c7036021773bdbaf3ce2f09f8ede622728c049c3 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Tue, 30 Jun 2020 11:47:13 +0200 Subject: [PATCH 129/281] Update Word-Search.cpp --- .../30-Word-Search-II/Word-Search.cpp | 94 ++++++++++++++++++- 1 file changed, 93 insertions(+), 1 deletion(-) diff --git a/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cpp b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cpp index a87d707..46b77f7 100644 --- a/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cpp +++ b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cpp @@ -91,4 +91,96 @@ class Solution { return ans; } -}; \ No newline at end of file +}; + + + + +const int dx[4] = { -1, 0, 1, 0 }; +const int dy[4] = { 0, -1, 0, 1 }; +#define ALPHABET_SIZE 26 + +class Solution2 { +private: + class Trie { + public: + bool isEnd; + bool isUsed; + unique_ptr links[ALPHABET_SIZE]; + /** Initialize your data structure here. */ + Trie() { + this->isEnd = false; + this->isUsed = false; + } + + bool containsChar(char ch) { + return links[ch - 'a'] != nullptr; + } + void put(char ch, Trie* newt) { + links[ch - 'a'].reset(newt); + } + + Trie* get(char ch) { + return links[ch - 'a'].get(); + } + + /** Inserts a word into the trie. */ + void insert(string word) { + // start from root node + Trie* root = this; + for (int i = 0; i < word.length(); i++) { + // create a new node if path doesn't exists + if (!root->containsChar(word[i])) { + root->put(word[i], new Trie()); + } + root = root->get(word[i]); + } + // make current node as a keyword + root->isEnd = true; + } + + ~Trie() {} + }; +public: + vector r; + + vector findWords(vector>& board, vector& words) { + Trie* root = new Trie(); + for (const string& s : words) + root->insert(s); + + string acc; + for (int i = 0, lenx = board.size(); i < lenx; ++i) + for (int j = 0, leny = board[0].size(); j < leny; ++j) + explore(board, i, j, root, acc); + + delete root; + return r; + + } + + void explore(vector>& board, int i, int j, Trie* root, string& acc) { + char curr = board[i][j]; + if (curr== '#' || !root->containsChar(curr)) return; + + acc.push_back(curr); + root = root->get(curr); + if (root->isEnd) { + if(!root->isUsed){ // in case of board = [["a","a"]], words = ["a"] + r.push_back(acc); + root->isUsed = true; + } + } + + board[i][j] = '*'; + for (int k = 0; k < 4; ++k) { + int tox = i + dx[k], toy = j + dy[k]; + if (tox < board.size() && tox >= 0 && toy >= 0 && toy < board[0].size() && board[tox][toy] != '*') + explore(board, tox, toy, root, acc); + + } + + acc.pop_back(); + board[i][j] = curr; + } +}; From 1dd16fcea2f5cd8c111246330799c0eb4172bfbd Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Tue, 30 Jun 2020 19:44:46 +0200 Subject: [PATCH 130/281] add kotlin solutions --- .../21-Dungeon-Game/Dungeon-Game.kt | 59 ++++++ .../22-Single-Number-II/Single-Number-II.kt | 13 ++ .../Count-Complete-Tree-Nodes.kt | 120 ++++++++++++ .../Unique-Binary-Search-Trees.kt | 13 ++ .../Find-the-Duplicate-Number.kt | 50 +++++ .../Sum-Root-to-Leaf-Numbers.kt | 69 +++++++ .../27-Perfect-Squares/Perfect-Squares.kt | 64 +++++++ .../Reconstruct-Itinerary.kt | 33 ++++ .../29-Unique-Paths/Unique-Paths.kt | 22 +++ .../30-Word-Search-II/Word-Search.kt | 177 ++++++++++++++++++ 10 files changed, 620 insertions(+) create mode 100644 June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.kt create mode 100644 June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.kt create mode 100644 June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.kt create mode 100644 June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.kt create mode 100644 June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.kt create mode 100644 June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.kt create mode 100644 June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.kt create mode 100644 June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.kt create mode 100644 June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.kt create mode 100644 June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.kt diff --git a/June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.kt b/June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.kt new file mode 100644 index 0000000..ff45bf7 --- /dev/null +++ b/June-LeetCoding-Challenge/21-Dungeon-Game/Dungeon-Game.kt @@ -0,0 +1,59 @@ +package dynamic_programming + +class DungeonGameKotlin174 { + fun calculateMinimumHP(dungeon: Array): Int { + val dynamicProgramming = IntArray(dungeon[0].size + 1) { Int.MAX_VALUE } + dynamicProgramming[dynamicProgramming.size - 1] = 1 + for (i in dungeon.size - 1 downTo 0) { + if (dynamicProgramming[dynamicProgramming.size - 1] == 1 && i != dungeon.size - 1) { + dynamicProgramming[dynamicProgramming.size - 1] = Int.MAX_VALUE + } + for (j in dungeon[0].size - 1 downTo 0) { + dynamicProgramming[j] = + maxOf(1, minOf(dynamicProgramming[j], dynamicProgramming[j + 1]) - dungeon[i][j]) + } + } + return dynamicProgramming[0] + } + /* + fun calculateMinimumHP(dungeon: Array): Int { + val dynamicProgramming = Array(dungeon.size + 1) { IntArray(dungeon[0].size + 1) { Int.MAX_VALUE } } + dynamicProgramming[dynamicProgramming.size - 1][dynamicProgramming[0].size - 2] = 1 + dynamicProgramming[dynamicProgramming.size - 2][dynamicProgramming[0].size - 1] = 1 + for (i in dungeon.size - 1 downTo 0) { + for (j in dungeon[0].size - 1 downTo 0) { + dynamicProgramming[i][j] = + maxOf(1, minOf(dynamicProgramming[i + 1][j], dynamicProgramming[i][j + 1]) - dungeon[i][j]) + } + } + return dynamicProgramming[0][0] + } + */ +} + +fun main() { + val solution = DungeonGameKotlin174() + println( + solution.calculateMinimumHP( + arrayOf( + intArrayOf(-2, -3, 3), + intArrayOf(-5, -10, 1), + intArrayOf(10, 30, -5) + ) + ) + ) + println( + solution.calculateMinimumHP( + arrayOf( + intArrayOf(0, -3) + ) + ) + ) + println( + solution.calculateMinimumHP( + arrayOf( + intArrayOf(100) + ) + ) + ) +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.kt b/June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.kt new file mode 100644 index 0000000..ff71f91 --- /dev/null +++ b/June-LeetCoding-Challenge/22-Single-Number-II/Single-Number-II.kt @@ -0,0 +1,13 @@ +package string_integer + +class SingleNumberIIKotlin137 { + fun singleNumber(nums: IntArray): Int { + var one = 0 + var two = 0 + nums.forEach { + one = one.xor(it).and(two.inv()) + two = two.xor(it).and(one.inv()) + } + return one + } +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.kt b/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.kt new file mode 100644 index 0000000..0225e07 --- /dev/null +++ b/June-LeetCoding-Challenge/23-Count-Complete-Tree-Nodes/Count-Complete-Tree-Nodes.kt @@ -0,0 +1,120 @@ +package binary_search + +class CountCompleteTreeNodesKotlin222 { + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } + + fun countNodes(root: TreeNode?): Int { + if (root == null) { + return 0 + } + return 1 + countNodes(root?.left) + countNodes(root?.right) + } +/* +fun countNodes(root: TreeNode?): Int { + if (root == null) { + return 0 + } + var level = 0 + var current = root + while (current!!.left != null) { + level++ + current = current.left + } + return search(root, level) +} + +private fun search(root: TreeNode, level: Int): Int { + var left = 1.shl(level) + var right = 1.shl(level + 1) - 1 + while (left + 1 < right) { + val mid = left + (right - left) / 2 + when { + isNotNull(root, mid, level) -> left = mid + else -> right = mid + } + } + return when { + isNotNull(root, right, level) -> right + isNotNull(root, left, level) -> left + else -> -1 + } +} + +private fun isNotNull(root: TreeNode, target: Int, level: Int): Boolean { + var result: TreeNode? = root + var start = 1.shl(level) + var end = 1.shl(level + 1) - 1 + var currentLevel = level + while (currentLevel > 0) { + val mid = start + (end - start).shr(1) + if (target > mid) { + result = result?.right + start = mid + } else { + result = result?.left + end = mid + } + currentLevel-- + } + return result != null +} + +/* +private fun isNotNull(root: TreeNode, target: Int): Boolean { + var current = target + val stack = Stack() + while (current != 1) { + stack.push(current % 2) + current = current.shr(1) + } + var result: TreeNode? = root + while (stack.size != 0) { + when (stack.pop()) { + 1 -> result = result?.right + 0 -> result = result?.left + } + } + return result != null +} + */ +} + + +fun main() { +val solution = CountCompleteTreeNodesKotlin222() + +val test = TreeNode(1) +val test2 = TreeNode(2) +test.left = test2 +println(solution.countNodes(test)) + +val root = TreeNode(1) +val node2 = TreeNode(2) +val node3 = TreeNode(3) +val node4 = TreeNode(4) +val node5 = TreeNode(5) +val node6 = TreeNode(6) +val node7 = TreeNode(7) +val node8 = TreeNode(8) +val node9 = TreeNode(9) +val node10 = TreeNode(10) +val node11 = TreeNode(11) +val node12 = TreeNode(12) +root.left = node2 +root.right = node3 +node2.left = node4 +node2.right = node5 +node3.left = node6 +node3.right = node7 +node4.left = node8 +node4.right = node9 +node5.left = node10 +node5.right = node11 +node6.left = node12 + +println(solution.countNodes(root)) +} +*/ \ No newline at end of file diff --git a/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.kt b/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.kt new file mode 100644 index 0000000..f7e40b6 --- /dev/null +++ b/June-LeetCoding-Challenge/24-Unique-Binary-Search-Trees/Unique-Binary-Search-Trees.kt @@ -0,0 +1,13 @@ +package depth_first_search + +class UniqueBinarySearchTreesKotlin96 { + // https://zh.wikipedia.org/wiki/%E5%8D%A1%E5%A1%94%E5%85%B0%E6%95%B0 + // https://en.wikipedia.org/wiki/Catalan_number + fun numTrees(n: Int): Int { + var result = 1L + for (index in n + 1..n * 2) { + result = result * index / (index - n) + } + return (result / (n + 1)).toInt() + } +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.kt b/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.kt new file mode 100644 index 0000000..fa9f7c2 --- /dev/null +++ b/June-LeetCoding-Challenge/25-Find-the-Duplicate-Number/Find-the-Duplicate-Number.kt @@ -0,0 +1,50 @@ +package binary_search + +class FindtheDuplicateNumberKotlin287 { + fun findDuplicate(nums: IntArray): Int { + var fast = 0 + var slow = 0 + while (true) { + fast = nums[nums[fast]] + slow = nums[slow] + if (fast == slow) { + break + } + } + fast = 0 + while (true) { + fast = nums[fast] + slow = nums[slow] + if (fast == slow) { + break + } + } + return fast + } + /* + fun findDuplicate(nums: IntArray): Int { + var left = 0 + var right = nums.size - 1 + while (left + 1 < right) { + val mid = left + (right - left) / 2 + when { + nums.count { it <= mid } <= mid -> left = mid + else -> right = mid + } + } + return right + } + */ + /* + fun findDuplicate(nums: IntArray): Int { + nums.forEachIndexed { index, i -> + nums.forEachIndexed { index2, i2 -> + if (i == i2 && index != index2) { + return i + } + } + } + return -1 + } + */ +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.kt b/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.kt new file mode 100644 index 0000000..13529cd --- /dev/null +++ b/June-LeetCoding-Challenge/26-Sum-Root-to-Leaf-Numbers/Sum-Root-to-Leaf-Numbers.kt @@ -0,0 +1,69 @@ +package breadth_first_search + +class SumRoottoLeafNumbersKotlin129 { + fun sumNumbers(root: TreeNode?): Int { + root ?: return 0 + return dfs(root, "") + } + + private fun dfs(node: TreeNode, string: String): Int { + val currentString = string + node.`val`.toString() + val leftNode = node.left + val rightNode = node.right + + if (leftNode == null && rightNode == null) { + return currentString.toInt() + } + val leftVal = if (leftNode == null) 0 else dfs(leftNode, currentString) + val rightVal = if (rightNode == null) 0 else dfs(rightNode, currentString) + return leftVal + rightVal + } + /* + fun sumNumbers(root: TreeNode?): Int { + if (root == null) { + return 0 + } + val queue: Queue> = LinkedList() + queue.offer(Pair(root, "")) + var sum = 0 + while (queue.isNotEmpty()) { + val currentPair = queue.poll() + val currentNode = currentPair.first + val currentString = currentPair.second + currentNode.`val`.toString() + val leftNode = currentNode.left + val rightNode = currentNode.right + + if (leftNode == null && rightNode == null) { + sum += currentString.toInt() + } + if (leftNode != null) { + queue.offer(Pair(leftNode, currentString)) + } + if (rightNode != null) { + queue.offer(Pair(rightNode, currentString)) + } + + } + return sum + } + */ + + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } +} + +fun main() { + val solution = SumRoottoLeafNumbersKotlin129() + val t0 = SumRoottoLeafNumbersKotlin129.TreeNode(0) + val t4 = SumRoottoLeafNumbersKotlin129.TreeNode(4) + val t9 = SumRoottoLeafNumbersKotlin129.TreeNode(9) + val t5 = SumRoottoLeafNumbersKotlin129.TreeNode(5) + val t1 = SumRoottoLeafNumbersKotlin129.TreeNode(1) + t4.left = t9 + t4.right = t0 + t9.left = t5 + t9.right = t1 + println(solution.sumNumbers(t4)) +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.kt b/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.kt new file mode 100644 index 0000000..0345193 --- /dev/null +++ b/June-LeetCoding-Challenge/27-Perfect-Squares/Perfect-Squares.kt @@ -0,0 +1,64 @@ +package dynamic_programming + +import kotlin.math.sqrt + +class PerfectSquaresKotlin279 { + + // https://zh.wikipedia.org/wiki/%E5%9B%9B%E5%B9%B3%E6%96%B9%E5%92%8C%E5%AE%9A%E7%90%86 + // 四平方和定理 + fun numSquares(n: Int): Int { + var current = n + while (current % 4 == 0) { + current /= 4 + } + if (current % 8 == 7) { + return 4 + } + var a1 = 0 + while (a1 * a1 <= current) { + val b2 = sqrt((current - a1 * a1).toDouble()).toInt() + if (a1 * a1 + b2 * b2 == current) { + return if (a1 != 0 && b2 != 0) { + 2 + } else { + 1 + } + } + ++a1 + } + return 3 + } + /* + fun numSquares(n: Int): Int { + val coins: MutableList = ArrayList() + var current = 1 + while (current * current <= n) { + coins.add(current * current) + ++current + } + val dp = IntArray(n + 1) { n + 1 } + dp[0] = 0 + for (index in 1..n) { + for (coin in coins) { + if (coin <= index) { + dp[index] = minOf(dp[index], dp[index - coin] + 1) + } + } + } + return when { + dp[n] > n -> -1 + else -> dp[n] + } + } + */ +} + +fun main() { + val solution = PerfectSquaresKotlin279() + // 2 + println(solution.numSquares(8)) + // 3 + println(solution.numSquares(12)) + // 2 + println(solution.numSquares(13)) +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.kt b/June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.kt new file mode 100644 index 0000000..a8c41e5 --- /dev/null +++ b/June-LeetCoding-Challenge/28-Reconstruct-Itinerary/Reconstruct-Itinerary.kt @@ -0,0 +1,33 @@ +package depth_first_search + +import java.util.* +import kotlin.collections.HashMap + +class ReconstructItineraryKotlin332 { + fun findItinerary(tickets: List>): List { + val result: MutableList = LinkedList() + if (tickets.isEmpty()) { + return result + } + val map: MutableMap> = HashMap() + tickets.forEach { + map.computeIfAbsent(it[0]) { PriorityQueue() }.offer(it[1]) + } + dfs(map, "JFK", result) + return result + } + + private fun dfs( + map: MutableMap>, + s: String, + result: MutableList + ) { + if (map.containsKey(s)) { + val current = map.getValue(s) + while (current.isNotEmpty()) { + dfs(map, current.poll(), result) + } + } + result.add(0, s) + } +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.kt b/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.kt new file mode 100644 index 0000000..f7a7df4 --- /dev/null +++ b/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.kt @@ -0,0 +1,22 @@ +package dynamic_programming + +class UniquePathsKotlin62 { + fun uniquePaths(m: Int, n: Int): Int { + val dp = Array(m + 1) { IntArray(n + 1) } + dp[0][1] = 1 + for (i in 1..m) { + for (j in 1..n) { + dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + } + } + return dp[m][n] + } +} + +fun main() { + val solution = UniquePathsKotlin62() + // 3 + println(solution.uniquePaths(3, 2)) + // 28 + println(solution.uniquePaths(7, 3)) +} \ No newline at end of file diff --git a/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.kt b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.kt new file mode 100644 index 0000000..f6dd815 --- /dev/null +++ b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.kt @@ -0,0 +1,177 @@ +package depth_first_search + +class WordSearchIIKotlin212 { + private var result: MutableSet = HashSet() + private val prefixTree = TriePrefixTreeKotlin() + + fun findWords(board: Array, words: Array): List { + words.forEach { + prefixTree.insert(it) + } + result.clear() + for (x in board.indices) { + for (y in board[0].indices) { + if (prefixTree.root.getByChar(board[x][y]) != null) { + dfs(board, x, y, prefixTree.root.getByChar(board[x][y])!!, board[x][y].toString()) + } + } + } + return result.toList() + } + + private val deltaX = intArrayOf(0, 0, -1, 1) + private val deltaY = intArrayOf(-1, 1, 0, 0) + + private fun dfs( + board: Array, + x: Int, + y: Int, + current: TriePrefixTreeKotlin.PrefixTree, + str: String + ) { + if (current.isEnd()) { + result.add(str) + // prefixTree.remove(str) + } + val value = board[x][y] + board[x][y] = '*' + for (index in deltaX.indices) { + val nextX = x + deltaX[index] + val nextY = y + deltaY[index] + + if (inBound(board, nextX, nextY)) { + val nextChar = board[nextX][nextY] + if (nextChar != '*' && current.getByChar(nextChar) != null) { + dfs(board, nextX, nextY, current.getByChar(nextChar)!!, str + nextChar) + } + } + } + board[x][y] = value + } + + private fun inBound( + grid: Array, + x: Int, + y: Int + ) = x >= 0 && y >= 0 && x < grid.size && y < grid[0].size + + class TriePrefixTreeKotlin { + /** Initialize your data structure here. */ + val root = PrefixTree() + + /** Inserts a word into the trie. */ + fun insert(word: String) { + var current = root + word.forEach { + if (current.getByChar(it) == null) { + current.addChar(it, PrefixTree()) + } + current = current.getByChar(it)!! + } + current.setEnd(true) + } + + /** Returns if the word is in the trie. */ + fun search(word: String): Boolean { + var current = root + word.forEach { + when { + current.getByChar(it) != null -> current = current.getByChar(it)!! + else -> return false + } + } + return current.isEnd() + } + + /** Returns if there is any word in the trie that starts with the given prefix. */ + fun startsWith(prefix: String): Boolean { + var current = root + prefix.forEach { + when { + current.getByChar(it) != null -> current = current.getByChar(it)!! + else -> return false + } + } + return true + } + + /** remove a work */ + fun remove(word: String) { + if (search(word)) { + recursionRemove(word, 0, root) + } + } + + private fun recursionRemove(word: String, index: Int, prefixTree: PrefixTree) { + if (word.length - 2 >= 0 && index != word.length - 2) { + recursionRemove(word, index + 1, prefixTree.getByChar(word[index])!!) + } + val current = prefixTree.getByChar(word[index])!! + if (index + 1 < word.length) { + val next = current.getByChar(word[index + 1])!! + if (next.canDelete()) { + current.remove(word[index + 1]) + } + } + if (index == 0 && current.canDelete()) { + prefixTree.remove(word[0]) + } + } + + class PrefixTree { + private val links: Array = Array(26) { null } + private var isEnd = false + + fun addChar(c: Char, prefixTree: PrefixTree) { + this.links[c - 'a'] = prefixTree + } + + fun isEnd() = this.isEnd + + fun getByChar(c: Char): PrefixTree? = this.links[c - 'a'] + + fun setEnd(boolean: Boolean) { + this.isEnd = boolean + } + + fun canDelete(): Boolean = links.filterNotNull().isEmpty() + + fun remove(c: Char) { + this.links[c - 'a'] = null + } + } + } +} + +fun main() { + val solution = WordSearchIIKotlin212() + val test3 = arrayOf( + charArrayOf('a', 'b'), + charArrayOf('a', 'a') + ) + // ["aaa","aaab","aaba","aba","baa"] + println(solution.findWords(test3, arrayOf("aba", "baa", "bab", "aaab", "aaa", "aaaa", "aaba"))) + + val test2 = arrayOf(charArrayOf('a')) + println(solution.findWords(test2, arrayOf("a"))) + + val test = arrayOf( + charArrayOf('o', 'a', 'a', 'n'), + charArrayOf('e', 't', 'a', 'e'), + charArrayOf('i', 'h', 'k', 'r'), + charArrayOf('i', 'f', 'l', 'v') + ) + val words = arrayOf("oath", "pea", "eat", "rain") + // ["eat","oath"] + println(solution.findWords(test, words)) + + /* + input + [["a","b"],["a","a"]] + ["aba","baa","bab","aaab","aaa","aaaa","aaba"] + Output + ["aaa","aba","aaba","baa"] + Expected + ["aaa","aaab","aaba","aba","baa"] + */ +} From caa2074411d05c5660ca2af21b0bd85cc369651c Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 30 Jun 2020 22:38:33 +0200 Subject: [PATCH 131/281] Add Word Search --- .../30-Word-Search-II/Word-Search.cs | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cs diff --git a/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cs b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cs new file mode 100644 index 0000000..d5acde3 --- /dev/null +++ b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cs @@ -0,0 +1,65 @@ +public class Solution +{ + + public IList FindWords(char[][] board, string[] words) + { + var res = new List(); + var root = BuildTrie(words); + for (var i = 0; i < board.Length; i++) + { + for (var j = 0; j < board[0].Length; j++) + { + Dfs(board, i, j, root, res); + } + } + return res; + } + + public void Dfs(char[][] board, int x, int y, Trie node, List res) + { + var c = board[x][y]; + if (c == '#' || node.Next[c - 'a'] == null) + { + return; + } + node = node.Next[c - 'a']; + if (node.Word != null) + { + res.Add(node.Word); + node.Word = null; + } + + board[x][y] = '#'; + if (x > 0) Dfs(board, x - 1, y, node, res); + if (y > 0) Dfs(board, x, y - 1, node, res); + if (x < board.Length - 1) Dfs(board, x + 1, y, node, res); + if (y < board[0].Length - 1) Dfs(board, x, y + 1, node, res); + board[x][y] = c; + } + + public Trie BuildTrie(string[] words) + { + var trie = new Trie(); + foreach (string word in words) + { + var node = trie; + foreach (char c in word) + { + int i = c - 'a'; + if (node.Next[i] == null) + { + node.Next[i] = new Trie(); + } + node = node.Next[i]; + } + node.Word = word; + } + return trie; + } +} + +public class Trie +{ + public string Word { get; set; } + public Trie[] Next = new Trie[26]; +} \ No newline at end of file From 6200a47784d7e2e1a19f6d18dc3700c02382a031 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 1 Jul 2020 09:19:29 +0200 Subject: [PATCH 132/281] add cpp solution --- .../01-Arranging-Coins/Arranging-Coins.cpp | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.cpp diff --git a/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.cpp b/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.cpp new file mode 100644 index 0000000..0a12df3 --- /dev/null +++ b/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.cpp @@ -0,0 +1,7 @@ +class Solution { +public: + int arrangeCoins(int n) { + double m = (sqrt(1 + 8.0 * n) - 1) / 2; + return m; + } +}; \ No newline at end of file From 263d37e221c2672fd8f6323b1b7a558fa53b6456 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Wed, 1 Jul 2020 09:22:16 +0200 Subject: [PATCH 133/281] update doc --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 32795bf..f739b1a 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,9 @@ Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challeng Solutions in various programming languages are provided. Enjoy it. +1. [Arranging Coins](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/01-Arranging-Coins): Maths + + From ead226ff5ae5d26039b711802f725a0af67e3984 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 1 Jul 2020 20:41:13 +0200 Subject: [PATCH 134/281] Add Arranging Coins --- .../01-Arranging-Coins/Arranging-Coins.cs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.cs diff --git a/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.cs b/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.cs new file mode 100644 index 0000000..aa1b1d3 --- /dev/null +++ b/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.cs @@ -0,0 +1,27 @@ +public class Solution +{ + public int ArrangeCoins(int n) + { + return (int)((Math.Sqrt(8 * (long)n + 1) - 1) / 2); + } +} + +/* +n stars on row x: +x = 1, n = 1 +x = 2, n = 1 + 2 = 3 +x = 3, n = 1 + 2 + 3 = 6 +x = 4, n = 1 + 2 + 3 + 4 = 10 + +formula: n = (x * (x + 1)) / 2 + +calculation steps: +2n = x * (x + 1) = x2 + x = x2 + x + 1/4 - 1/4 = (x + 1/2)2 - 1/4 +2n + 1/4 = (x + 1/2)2 +(8n + 1)/4 = (x + 1/2)2 +x + 1/2 = sqrt((8n + 1)/4) +x = sqrt((8n + 1)/4) - 1/2 +x = sqrt(8n +1)/2 - 1/2 +x = (sqrt(8n +1)-1)/2 + +*/ \ No newline at end of file From 56b11d74826cf5099ea515e62db8a42259227b59 Mon Sep 17 00:00:00 2001 From: Qilin ZHANG Date: Thu, 2 Jul 2020 01:04:56 +0200 Subject: [PATCH 135/281] Add Java solution for July day01 --- .../01-Arranging-Coins/Arranging-Coins.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.java diff --git a/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.java b/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.java new file mode 100644 index 0000000..a500bb2 --- /dev/null +++ b/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.java @@ -0,0 +1,17 @@ +/** + * We can treat it like a problem of Arithmetic progression with a1 = 1, d = 1 + * The sum of this arithmetic sequence is i(i+1)/2, when the sum is first big than we can get that + * the maxmum staircase shap is i - 1 + */ +class Solution { + public int arrangeCoins(int n) { + if(n == 0 || n == 1) return n; + + int m = 0; + for(int i = 2; i <= n; i++) { + if((Math.pow(i, 2) + i) / 2 > n) return (i-1); + } + + return m; + } +} \ No newline at end of file From 36a082ed0282ec82fc700eb3cd13bd8a21c00bde Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 2 Jul 2020 09:46:04 +0200 Subject: [PATCH 136/281] add cpp solution --- .../Binary-Tree-Level-Order-Traversal-II.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.cpp diff --git a/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.cpp b/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.cpp new file mode 100644 index 0000000..0e1b2de --- /dev/null +++ b/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + vector> ans; + void dfs(int dep, TreeNode* root){ + if (root == NULL) return; + while (dep >= ans.size()) ans.push_back(vector()); + ans[dep].push_back(root->val); + dfs(dep + 1, root->left); + dfs(dep + 1, root->right); + } + vector> levelOrderBottom(TreeNode* root) { + dfs(0, root); + reverse(ans.begin(), ans.end()); + return ans; + } +}; \ No newline at end of file From d10209bc877e79f9fe993b79cdc04ed6691746fe Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 2 Jul 2020 09:47:12 +0200 Subject: [PATCH 137/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f739b1a..dab35ca 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challeng Solutions in various programming languages are provided. Enjoy it. 1. [Arranging Coins](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/01-Arranging-Coins): Maths - +2. [Binary Tree Level Order Traversal II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II): DFS From bc96824cda28b6e226f2b0972d7c667aafc4ad9e Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Thu, 2 Jul 2020 22:13:30 +0200 Subject: [PATCH 138/281] Add Binary Tree Level Order Traversal II --- .../Binary-Tree-Level-Order-Traversal-II.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.cs diff --git a/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.cs b/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.cs new file mode 100644 index 0000000..6c7336e --- /dev/null +++ b/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.cs @@ -0,0 +1,38 @@ +public class Solution { + public IList> LevelOrderBottom(TreeNode root) { + var result = new List>(); + var level = 0; + Recursion(root, result, level); + result.Reverse(); + return result; + } + + private void Recursion(TreeNode node, List> list, int level){ + if(node == null) return; + if(list.Count() == level) + { + list.Add(new List()); + } + list[level].Add(node.val); + + if(node.left != null){ + Recursion(node.left, list, level+1); + } + if(node.right != null){ + Recursion(node.right, list, level+1); + } + } +} +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ \ No newline at end of file From dace54c7fd094418f6bada8cfeb7426065acb646 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Fri, 3 Jul 2020 09:51:31 +0200 Subject: [PATCH 139/281] Create Prison-Cells-After-N-Days.cpp --- .../Prison-Cells-After-N-Days.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cpp diff --git a/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cpp b/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cpp new file mode 100644 index 0000000..6a7835a --- /dev/null +++ b/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + vector prisonAfterNDays(vector& cells, int N) { + // vector> memo; + //memo.push_back(cells); + N=(N%14==0)?14:N%14; + for(int i=1; i<=N; ++i){ + vector cpy = cells; + for(int j=0; j<8; ++j){ + if(j-1>=0&&j+1<8&&cells[j-1]==cells[j+1]) cpy[j]=1; + else cpy[j]=0; + } + /* + for(int j=0; j Date: Fri, 3 Jul 2020 10:23:21 +0200 Subject: [PATCH 140/281] add cpp solution --- .../Prison-Cells-After-N-Days.cpp | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cpp b/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cpp index 6a7835a..3f9fe5e 100644 --- a/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cpp +++ b/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cpp @@ -1,4 +1,4 @@ -class Solution { +class Solution1 { public: vector prisonAfterNDays(vector& cells, int N) { // vector> memo; @@ -21,3 +21,19 @@ class Solution { return cells; } }; + + +class Solution2 { +public: + vector prisonAfterNDays(vector& cells, int N) { + N = N % 14; + if (N == 0) N = 14; + vector v(8, 0); + for (int j = 0; j < N; j++){ + for(int i = 1; i < 7; i++) + v[i] = (cells[i-1] == cells[i+1]) ? 1 : 0; + cells = v; + } + return cells; + } +}; \ No newline at end of file From 2d024c7bd731e075e97f465d97192b7732b08969 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Fri, 3 Jul 2020 10:24:43 +0200 Subject: [PATCH 141/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dab35ca..a04d730 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Solutions in various programming languages are provided. Enjoy it. 1. [Arranging Coins](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/01-Arranging-Coins): Maths 2. [Binary Tree Level Order Traversal II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II): DFS - +3. [Prison Cells After N Days](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days): Maths From b769cb4e16b68a564b805d19e06b2154e75c53a7 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 3 Jul 2020 19:39:29 +0200 Subject: [PATCH 142/281] Add Prison Cells After N Days --- .../Prison-Cells-After-N-Days.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cs diff --git a/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cs b/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cs new file mode 100644 index 0000000..dda4cb8 --- /dev/null +++ b/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.cs @@ -0,0 +1,19 @@ +public class Solution { + public int[] PrisonAfterNDays(int[] cells, int N) { + var length = cells.Length; + var startCells = new int[length]; + var runningCells = new int[length]; + for(int i=0; N-->0; cells=runningCells.ToArray(), ++i){ + for(int x=1; x Date: Sat, 4 Jul 2020 07:18:58 +0200 Subject: [PATCH 143/281] Day-29 Unique Paths --- .../29-Unique-Paths/Unique-Paths.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.java diff --git a/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.java b/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.java new file mode 100644 index 0000000..b7f4f20 --- /dev/null +++ b/June-LeetCoding-Challenge/29-Unique-Paths/Unique-Paths.java @@ -0,0 +1,16 @@ +class Solution { + public int uniquePaths(int width, int height) { + int[][] grid = new int[height][width]; + + for (int row = 0; row < height; row++) { + for (int col = 0; col < width; col++) { + if (row == 0 || col == 0) { + grid[row][col] = 1; + } else { + grid[row][col] = grid[row - 1][col] + grid[row][col - 1]; + } + } + } + return grid[height - 1][width - 1]; + } +} From 09f9462b542d7efd4eebbce7527eda0e56165160 Mon Sep 17 00:00:00 2001 From: Mincong HUANG Date: Sat, 4 Jul 2020 07:35:39 +0200 Subject: [PATCH 144/281] Day-02 Binary Tree Level Order Traversal II --- .../Binary-Tree-Level-Order-Traversal-II.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.java diff --git a/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.java b/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.java new file mode 100644 index 0000000..e9d974d --- /dev/null +++ b/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.java @@ -0,0 +1,62 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +// BFS +class Solution { + + public List> levelOrderBottom(TreeNode root) { + if (root == null) { + return List.of(); + } + + var levels = new LinkedList>(); + var todo = new LinkedList(); + todo.add(root); + + while (!todo.isEmpty()) { + int remaining = todo.size(); + var values = new ArrayList(remaining); + for (int i = 0; i < remaining; i++) { + var node = todo.poll(); + values.add(node.val); + if (node.left != null) { + todo.add(node.left); + } + if (node.right != null) { + todo.add(node.right); + } + } + levels.addFirst(values); + } + return levels; + } +} + +// DFS +class Solution2 { + + public List> levelOrderBottom(TreeNode root) { + var results = new ArrayList>(); + dfs(root, 0, results); + Collections.reverse(results); + return results; + } + + public void dfs(TreeNode root, int level, List> results) { + if (root == null) { + return; + } + while (level >= results.size()) { + results.add(new ArrayList<>()); + } + results.get(level).add(root.val); + dfs(root.left, level + 1, results); + dfs(root.right, level + 1, results); + } +} From abb0cc4f53d9e5b925349839cdabc774bd209085 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sat, 4 Jul 2020 17:04:04 +0200 Subject: [PATCH 145/281] Add Ugly Number II --- .../04-Ugly-Number-II/Ugly-Number-II.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.cs diff --git a/July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.cs b/July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.cs new file mode 100644 index 0000000..30dffac --- /dev/null +++ b/July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.cs @@ -0,0 +1,17 @@ +public class Solution { + public int NthUglyNumber(int n) { + if(n<1) return 0; + if(n==1) return 1; + int m2 = 0, m3 = 0, m5 = 0; + var v = new int[n]; + v[0] =1; + for(int i=1; i Date: Sun, 5 Jul 2020 08:31:59 +0200 Subject: [PATCH 146/281] add cpp solution --- .../04-Ugly-Number-II/Ugly-Number-II.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.cpp diff --git a/July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.cpp b/July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.cpp new file mode 100644 index 0000000..80b136c --- /dev/null +++ b/July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int nthUglyNumber(int n) { + if (n == 1) return 1; + vector a(n, 0); + a[0] = 1; + int i = 0, j = 0, k = 0; + for(int p = 1 ; p < n; p++) { + a[p] = min(2 * a[i], min(3 * a[j], 5 * a[k])); + if(a[p] == 2 * a[i]) i++; + if(a[p] == 3 * a[j]) j++; + if(a[p] == 5 * a[k]) k++; + } + return a[n - 1]; + } +}; \ No newline at end of file From c68e8523dd16e5398b796f6ee6154783322668e9 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 5 Jul 2020 08:35:07 +0200 Subject: [PATCH 147/281] update doc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a04d730..45644be 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Solutions in various programming languages are provided. Enjoy it. 1. [Arranging Coins](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/01-Arranging-Coins): Maths 2. [Binary Tree Level Order Traversal II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II): DFS 3. [Prison Cells After N Days](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days): Maths +4. [Ugly Number II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/04-Ugly-Number-II): DP From d322a18f14dfda84604843f9455139ce43f1f515 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 5 Jul 2020 09:04:25 +0200 Subject: [PATCH 148/281] add cpp solution --- .../05-Hamming-Distance/Hamming-Distance.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.cpp diff --git a/July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.cpp b/July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.cpp new file mode 100644 index 0000000..b859372 --- /dev/null +++ b/July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int hammingDistance(int x, int y) { + int z = x xor y; + int ans = 0; + while (z){ + z -= z & (-z); + ans ++; + } + return ans; + } +}; \ No newline at end of file From 9a87834e21138e961db1da275cd5221cf186ce3f Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 5 Jul 2020 09:05:32 +0200 Subject: [PATCH 149/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 45644be..603694a 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Solutions in various programming languages are provided. Enjoy it. 2. [Binary Tree Level Order Traversal II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II): DFS 3. [Prison Cells After N Days](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days): Maths 4. [Ugly Number II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/04-Ugly-Number-II): DP - +5. [Hamming Distance](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/05-Hamming-Distance): Bitwise Manipulation ## June LeetCoding Challenge From 3fc36e5f12e52f0dc9e4b0de7025c859a43a5d4e Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 5 Jul 2020 11:46:50 +0200 Subject: [PATCH 150/281] Add Hamming Distance --- .../05-Hamming-Distance/Hamming-Distance.cs | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.cs diff --git a/July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.cs b/July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.cs new file mode 100644 index 0000000..245a479 --- /dev/null +++ b/July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.cs @@ -0,0 +1,75 @@ +public class Solution +{ + //Queue solution + public int HammingDistance(int x, int y) + { + if (x == y) return 0; + var queueX = ToQueue(x); + var queueY = ToQueue(y); + return CompareTwoQueues(queueX, queueY); + } + + private int CompareTwoQueues(Queue x, Queue y) + { + var r = 0; + while (x.Count > 0 && y.Count > 0) + { + var vx = x.Dequeue(); + var vy = y.Dequeue(); + if (vx != vy) + { + r++; + } + } + + if (x.Count > 0) + { + r += Count(x); + } + else if (y.Count > 0) + { + r += Count(y); + } + return r; + } + + private Queue ToQueue(int x) + { + var queue = new Queue(); + while (x >= 1) + { + if (x % 2 == 0) queue.Enqueue(0); + else queue.Enqueue(1); + x = x / 2; + } + return queue; + } + + private int Count(Queue q) + { + var r = 0; + while (q.Count > 0) + { + var v = q.Dequeue(); + if (v == 1) + { + r++; + } + } + return r; + } + + + //XOR solution + public int HammingDistance(int x, int y) + { + var xor = x ^ y; + var res = 0; + for (int i = 0; i < 32; i++) + { + var r = xor >> i; + if ((r & 1) == 1) res++; + } + return res; + } +} \ No newline at end of file From 5b9088838cb7e72ffd3edc667007adf472e7a68d Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 6 Jul 2020 09:52:43 +0200 Subject: [PATCH 151/281] add cpp solution --- .../06-Plus-One/Plus-One.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 July-LeetCoding-Challenge/06-Plus-One/Plus-One.cpp diff --git a/July-LeetCoding-Challenge/06-Plus-One/Plus-One.cpp b/July-LeetCoding-Challenge/06-Plus-One/Plus-One.cpp new file mode 100644 index 0000000..baf50b0 --- /dev/null +++ b/July-LeetCoding-Challenge/06-Plus-One/Plus-One.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector plusOne(vector& digits) { + int n = digits.size(); + int i = n-1; + while (i >= 0 and digits[i] == 9) digits[i--] = 0; + if (i < 0) { + vector ans (n+1, 0); + ans[0] = 1; + return ans; + } + digits[i]++; + return digits; + } +}; \ No newline at end of file From 891e28fc3afe1279f7fd9a189014c767f4511e0a Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 6 Jul 2020 09:54:41 +0200 Subject: [PATCH 152/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 603694a..9a7edb2 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Solutions in various programming languages are provided. Enjoy it. 3. [Prison Cells After N Days](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days): Maths 4. [Ugly Number II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/04-Ugly-Number-II): DP 5. [Hamming Distance](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/05-Hamming-Distance): Bitwise Manipulation - +6. [Plus One](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/06-Plus-One): Maths ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From 8a40f5a567b423e72a5283bf94f527a5d3e1177f Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 6 Jul 2020 19:22:57 +0200 Subject: [PATCH 153/281] Add Plus One C# --- .../06-Plus-One/Plus-One.cs | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 July-LeetCoding-Challenge/06-Plus-One/Plus-One.cs diff --git a/July-LeetCoding-Challenge/06-Plus-One/Plus-One.cs b/July-LeetCoding-Challenge/06-Plus-One/Plus-One.cs new file mode 100644 index 0000000..58be644 --- /dev/null +++ b/July-LeetCoding-Challenge/06-Plus-One/Plus-One.cs @@ -0,0 +1,59 @@ +public class Solution +{ + //Shorter solution + public int[] PlusOne(int[] digits) + { + for (int i = digits.Length - 1; i >= 0; i--) + { + if (digits[i] < 9) + { + digits[i]++; + return digits; + } + digits[i] = 0; + } + var n = new int[digits.Length + 1]; + n[0] = 1; + return n; + } + + //Stack solution + public int[] PlusOne(int[] digits) + { + var stack = new Stack(); + var carry = 0; + if (digits[digits.Length - 1] == 9) + { + carry = 1; + } + else + { + digits[digits.Length - 1]++; + } + + for (int i = digits.Length - 1; i >= 0; i--) + { + var v = digits[i]; + if (carry == 1) + { + v += 1; + } + if (v == 10) + { + digits[i] = 0; + carry = 1; + } + else + { + digits[i] = v; + carry = 0; + } + stack.Push(digits[i]); + } + if (carry == 1) + { + stack.Push(1); + } + return stack.ToArray(); + } +} \ No newline at end of file From 8d36d631c13f05b9a5accf3b36ab3c3a91d42901 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 7 Jul 2020 12:22:47 +0200 Subject: [PATCH 154/281] add cpp solution --- .../07-Island-Perimeter/Island-Perimeter.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.cpp diff --git a/July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.cpp b/July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.cpp new file mode 100644 index 0000000..238bb79 --- /dev/null +++ b/July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.cpp @@ -0,0 +1,58 @@ +const int dx[4] = {-1, 0, 1, 0}; +const int dy[4] = {0, -1, 0, 1}; + +class Solution { +public: + int n, m; + + void bfs(int x0, int y0, vector>& grid, vector>& vis){ + queue> q; + q.push(make_pair(x0, y0)); + vis[x0][y0] = 1; + while(!q.empty()){ + auto cur = q.front(); + q.pop(); + for (int i = 0; i < 4; i++){ + int x = cur.first + dx[i]; + int y = cur.second + dy[i]; + if (x >=0 and x < n and y >=0 and y < m and !vis[x][y] and grid[x][y] == 1){ + vis[x][y] = 1; + q.push(make_pair(x, y)); + } + } + } + + } + + void count (int& sum, int x, int y, vector>& grid, vector>& vis){ + int num = 0; + for (int i = 0; i < 4; i++){ + int xx = x + dx[i]; + int yy = y + dy[i]; + + if (xx >=0 and xx < n and yy >=0 and yy < m and vis[xx][yy] and grid[x][y] == 1) + num ++; + } + sum += 4 - num; + + } + + int islandPerimeter(vector>& grid) { + n = grid.size(); + if (n == 0) return 0; + m = grid[0].size(); + vector> vis(n, vector(m, 0)); + + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + if (!vis[i][j] and grid[i][j] == 1) + bfs(i, j, grid, vis); + + int sum = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + if (vis[i][j]) + count(sum, i, j, grid, vis); + return sum; + } +}; \ No newline at end of file From d4b7ce74b0f9743e65e3059ae924bb27aec3db78 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 7 Jul 2020 12:27:49 +0200 Subject: [PATCH 155/281] update doc --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 9a7edb2..78b60a1 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,8 @@ Solutions in various programming languages are provided. Enjoy it. 4. [Ugly Number II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/04-Ugly-Number-II): DP 5. [Hamming Distance](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/05-Hamming-Distance): Bitwise Manipulation 6. [Plus One](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/06-Plus-One): Maths +7. [Island Perimeter](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/07-Island-Perimeter): BFS + ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From 51203d53e26b51bbc8d98edf9ccc0a50bb253717 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 7 Jul 2020 16:07:27 +0200 Subject: [PATCH 156/281] Add Island Perimeter C# --- .../07-Island-Perimeter/Island-Perimeter.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.cs diff --git a/July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.cs b/July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.cs new file mode 100644 index 0000000..3ba69f3 --- /dev/null +++ b/July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.cs @@ -0,0 +1,20 @@ +public class Solution +{ + public int IslandPerimeter(int[][] grid) + { + int islands = 0, neighbours = 0; + for (int i = 0; i < grid.Length; i++) + { + for (int j = 0; j < grid[0].Length; j++) + { + if (grid[i][j] == 1) + { + islands++; + if (j < grid[0].Length - 1 && grid[i][j + 1] == 1) neighbours++; + if (i < grid.Length - 1 && grid[i + 1][j] == 1) neighbours++; + } + } + } + return islands * 4 - neighbours * 2; + } +} \ No newline at end of file From f3e9a06624d6a0f64fa9c56166dfd952b9b24e58 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 8 Jul 2020 17:19:34 +0200 Subject: [PATCH 157/281] Add 3Sum C# --- July-LeetCoding-Challenge/08-3Sum/3Sum.cs | 27 +++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 July-LeetCoding-Challenge/08-3Sum/3Sum.cs diff --git a/July-LeetCoding-Challenge/08-3Sum/3Sum.cs b/July-LeetCoding-Challenge/08-3Sum/3Sum.cs new file mode 100644 index 0000000..b493210 --- /dev/null +++ b/July-LeetCoding-Challenge/08-3Sum/3Sum.cs @@ -0,0 +1,27 @@ +public class Solution { + public IList> ThreeSum(int[] nums) { + Array.Sort(nums); + var result = new List>(); + for(int i=0; i0 && nums[i] == nums[i-1]) + continue; + + int j=i+1, k=nums.Length-1; + int target = -nums[i]; + while(j < k){ + if(nums[j] + nums[k] == target){ + result.Add(new int[3]{nums[i], nums[j], nums[k]}.ToList()); + j++; + k--; + while(j target){ + k--; + }else if(nums[j] + nums[k] < target){ + j++; + } + } + } + return result; + } +} \ No newline at end of file From f170d423f6584e7028703a14cdf56b3a1536b1c5 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 9 Jul 2020 08:25:35 +0200 Subject: [PATCH 158/281] add cpp solution --- July-LeetCoding-Challenge/08-3Sum/3Sum.cpp | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 July-LeetCoding-Challenge/08-3Sum/3Sum.cpp diff --git a/July-LeetCoding-Challenge/08-3Sum/3Sum.cpp b/July-LeetCoding-Challenge/08-3Sum/3Sum.cpp new file mode 100644 index 0000000..2f0d251 --- /dev/null +++ b/July-LeetCoding-Challenge/08-3Sum/3Sum.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector> threeSum(vector& nums) { + sort(nums.begin(), nums.end()); + vector> ans; + + set>s; + int n = nums.size(); + for (int i = 0; i < n - 2; i++) { + int left = i + 1, right = n - 1; + while (left < right) { + int sum = nums[i] + nums[left] + nums[right]; + if (sum == 0) + s.insert({nums[i],nums[left++], nums[right--]}); + else if (sum < 0) + left++; + else + right--; + } + } + + for(auto v: s){ + ans.push_back(v); + } + return ans; + } +}; \ No newline at end of file From e8d54156cbbd4f863bfb4446e8c686e6bd66e612 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Thu, 9 Jul 2020 08:27:46 +0200 Subject: [PATCH 159/281] update doc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 78b60a1..1cdb067 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Solutions in various programming languages are provided. Enjoy it. 5. [Hamming Distance](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/05-Hamming-Distance): Bitwise Manipulation 6. [Plus One](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/06-Plus-One): Maths 7. [Island Perimeter](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/07-Island-Perimeter): BFS - +8. [3Sum](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/08-3Sum): Two pointers ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From ddf1cad8e0ae9eafe8ed3785765408e47daedacf Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Thu, 9 Jul 2020 19:45:56 +0200 Subject: [PATCH 160/281] Create Maximum-Width-of-Binary-Tree.cpp --- .../Maximum-Width-of-Binary-Tree.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.cpp diff --git a/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.cpp b/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.cpp new file mode 100644 index 0000000..7296271 --- /dev/null +++ b/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.cpp @@ -0,0 +1,22 @@ +typedef pair tp; // use unsigned long to pass a tricky testcase.. +class Solution1 { +public: + int widthOfBinaryTree(TreeNode* root) { + queue q; + if (root) q.emplace(root, 1); + int maxW = 0; + while (!q.empty()) { + const int n = q.size(); + unsigned long lm = INT_MAX, rm = 0; + for (int i = 0; i < n; ++i) { + auto f = q.front(); q.pop(); + lm = min(lm, f.second); + rm = max(rm, f.second); + if (f.first->left) q.emplace(f.first->left, 2*f.second); + if (f.first->right) q.emplace(f.first->right, 2*f.second + 1); + } + maxW = max(maxW, (int)(rm - lm + 1)); + } + return maxW; + } +}; From f872e8e5a93e1de243ad35c135df7c7a543468af Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Thu, 9 Jul 2020 21:17:41 +0200 Subject: [PATCH 161/281] Add Maximum Width of Binary Tree C# --- .../Maximum-Width-of-Binary-Tree.cs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.cs diff --git a/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.cs b/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.cs new file mode 100644 index 0000000..e39f4c6 --- /dev/null +++ b/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.cs @@ -0,0 +1,31 @@ +public class Solution { + private int maxWidth = 0; + public int WidthOfBinaryTree(TreeNode root) { + var list = new List(); + Dfs(root, 1, 0, list); + return maxWidth; + } + + private void Dfs(TreeNode node, int index, int depth, List countByLevel) { + if (depth >= countByLevel.Count) countByLevel.Add(index); + maxWidth = Math.Max(maxWidth, index - countByLevel[depth] + 1); + + if (node.left != null) + Dfs(node.left, index * 2, depth + 1, countByLevel); + if (node.right != null) + Dfs(node.right, index * 2 + 1, depth + 1, countByLevel); + } +} +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ \ No newline at end of file From 0faa97af04304dca9fb748e5e3e5f3ec0b0fcfb1 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Fri, 10 Jul 2020 11:36:34 +0200 Subject: [PATCH 162/281] Create Flatten-a-Multilevel-Doubly-Linked-List.cpp --- ...latten-a-Multilevel-Doubly-Linked-List.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.cpp diff --git a/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.cpp b/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.cpp new file mode 100644 index 0000000..b64c708 --- /dev/null +++ b/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.cpp @@ -0,0 +1,21 @@ +class Solution1 { +public: + Node* flatten(Node* head, Node* tail = nullptr) { + if(!head) return nullptr; + Node* read = head, *pre; + while(read){ + if(read->child){ + Node* tmp = read->next; + Node* connect = flatten(read->child, tmp); + read->child = nullptr; + read->next = connect; + read->next->prev = read; + } + pre = read; + read = read->next; + } + if(tail) + pre->next = tail, tail->prev = pre; + return head; + } +}; From 1a5abce8c1dd54aadfa3317cc48b33764c32da67 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 10 Jul 2020 20:08:32 +0200 Subject: [PATCH 163/281] Add Flatten a Multilevel Doubly Linked List C# --- ...Flatten-a-Multilevel-Doubly-Linked-List.cs | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.cs diff --git a/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.cs b/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.cs new file mode 100644 index 0000000..881ddcd --- /dev/null +++ b/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.cs @@ -0,0 +1,35 @@ +public class Solution { + public Node Flatten(Node head) { + if(head == null) return null; + var stack = new Stack(); + var c = head; + + while(c != null){ + if(c.child != null){ + if(c.next != null){ + stack.Push(c.next); + } + c.next = c.child; + c.next.prev = c; + c.child = null; + }else if(c.next == null && stack.Count > 0){ + c.next = stack.Pop(); + c.next.prev = c; + } + + c = c.next; + } + + return head; + } +} + +/* +// Definition for a Node. +public class Node { + public int val; + public Node prev; + public Node next; + public Node child; +} +*/ \ No newline at end of file From f103c8d4bbf05d70a83429026fb3de6b4878d504 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 10 Jul 2020 20:20:20 +0200 Subject: [PATCH 164/281] update ReadMe --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 1cdb067..f74e0c9 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,8 @@ Solutions in various programming languages are provided. Enjoy it. 6. [Plus One](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/06-Plus-One): Maths 7. [Island Perimeter](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/07-Island-Perimeter): BFS 8. [3Sum](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/08-3Sum): Two pointers +9. [Maximum Width of Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree): DFS +10. [Flatten a Multilevel Doubly Linked List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List): Queue ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From 9b64224d7c16ee9a6788aef5222277eee43f86f5 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Sat, 11 Jul 2020 10:08:11 +0200 Subject: [PATCH 165/281] Create Subsets.cpp --- .../11-Subsets/Subsets.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 July-LeetCoding-Challenge/11-Subsets/Subsets.cpp diff --git a/July-LeetCoding-Challenge/11-Subsets/Subsets.cpp b/July-LeetCoding-Challenge/11-Subsets/Subsets.cpp new file mode 100644 index 0000000..a0907b1 --- /dev/null +++ b/July-LeetCoding-Challenge/11-Subsets/Subsets.cpp @@ -0,0 +1,18 @@ +class Solution1 { +public: + vector> subsets(vector& nums) { + vector> r; + vector sub; + recur(r, nums, 0, sub); + return r; + } + + void recur(vector>& r, vector& nums, int pos, vector sub){ + r.push_back(sub); + for(int i=pos, n=nums.size(); i Date: Sat, 11 Jul 2020 11:05:04 +0200 Subject: [PATCH 166/281] Add Subsets C# --- .../11-Subsets/Subsets.cs | 21 +++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 July-LeetCoding-Challenge/11-Subsets/Subsets.cs diff --git a/July-LeetCoding-Challenge/11-Subsets/Subsets.cs b/July-LeetCoding-Challenge/11-Subsets/Subsets.cs new file mode 100644 index 0000000..94ba4ea --- /dev/null +++ b/July-LeetCoding-Challenge/11-Subsets/Subsets.cs @@ -0,0 +1,21 @@ +public class Solution +{ + public IList> Subsets(int[] nums) + { + Array.Sort(nums); + var res = new List>(); + backtrack(res, new List(), nums, 0); + return res; + } + + private void backtrack(List> list, List temp, int[] nums, int start) + { + list.Add(temp.ToList()); + for (int i = start; i < nums.Length; i++) + { + temp.Add(nums[i]); + backtrack(list, temp, nums, i + 1); + temp.RemoveAt(temp.Count - 1); + } + } +} diff --git a/README.md b/README.md index f74e0c9..2d3c081 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ Solutions in various programming languages are provided. Enjoy it. 8. [3Sum](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/08-3Sum): Two pointers 9. [Maximum Width of Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree): DFS 10. [Flatten a Multilevel Doubly Linked List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List): Queue +11. [Subsets](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/11-Subsets): Backtrack ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From c821c3ab69152d113e302db63d9e1435284bdab7 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 11 Jul 2020 11:20:25 +0200 Subject: [PATCH 167/281] add cpp solution2 --- .../11-Subsets/Subsets.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/July-LeetCoding-Challenge/11-Subsets/Subsets.cpp b/July-LeetCoding-Challenge/11-Subsets/Subsets.cpp index a0907b1..abd6c3b 100644 --- a/July-LeetCoding-Challenge/11-Subsets/Subsets.cpp +++ b/July-LeetCoding-Challenge/11-Subsets/Subsets.cpp @@ -16,3 +16,20 @@ class Solution1 { } } }; + +class Solution2 { +public: + vector> subsets(vector& nums) { + vector> ans; + ans.push_back(vector()); + for (int i = 0; i < nums.size(); i++){ + int m = ans.size(); + for (int j = 0; j < m; j++){ + vector v = ans[j]; + v.push_back(nums[i]); + ans.push_back(v); + } + } + return ans; + } +}; \ No newline at end of file From 8bc71d3e39b736d44de66c2a082514a3970954cd Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sat, 11 Jul 2020 11:22:14 +0200 Subject: [PATCH 168/281] update doc --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f74e0c9..ed54f03 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ Solutions in various programming languages are provided. Enjoy it. 8. [3Sum](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/08-3Sum): Two pointers 9. [Maximum Width of Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree): DFS 10. [Flatten a Multilevel Doubly Linked List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List): Queue +11. [Subsets](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/11-Subsets): DP ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From ba16d8afd2dcb2267770217bb28b87ee3b4f3037 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Sun, 12 Jul 2020 09:14:37 +0200 Subject: [PATCH 169/281] Create Reverse-Bits.cpp --- .../12-Reverse-Bits/Reverse-Bits.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.cpp diff --git a/July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.cpp b/July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.cpp new file mode 100644 index 0000000..2708576 --- /dev/null +++ b/July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.cpp @@ -0,0 +1,13 @@ +class Solution1 { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t r = 0; + + for(int i=0; i<32; ++i){ + if(n&(1< Date: Sun, 12 Jul 2020 13:05:01 +0200 Subject: [PATCH 170/281] Add Reverse Bits, Single Number, Happy Number C# --- .../01-Single-Number/Single-Number.cs | 23 ++++++++ .../02-Happy-Number/Happy-Number.cs | 29 ++++++++++ .../12-Reverse-Bits/Reverse-Bits.cs | 53 +++++++++++++++++++ 3 files changed, 105 insertions(+) create mode 100644 30-Day-Leetcoding-Challenge/01-Single-Number/Single-Number.cs create mode 100644 30-Day-Leetcoding-Challenge/02-Happy-Number/Happy-Number.cs create mode 100644 July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.cs diff --git a/30-Day-Leetcoding-Challenge/01-Single-Number/Single-Number.cs b/30-Day-Leetcoding-Challenge/01-Single-Number/Single-Number.cs new file mode 100644 index 0000000..ccc1fae --- /dev/null +++ b/30-Day-Leetcoding-Challenge/01-Single-Number/Single-Number.cs @@ -0,0 +1,23 @@ +public class Solution { + //XOR solution + public int SingleNumber(int[] nums) { + var result = 0; + for(int i=0; i(); + for(int i=0; i x.Value == 1).Key; + } +} \ No newline at end of file diff --git a/30-Day-Leetcoding-Challenge/02-Happy-Number/Happy-Number.cs b/30-Day-Leetcoding-Challenge/02-Happy-Number/Happy-Number.cs new file mode 100644 index 0000000..ec32518 --- /dev/null +++ b/30-Day-Leetcoding-Challenge/02-Happy-Number/Happy-Number.cs @@ -0,0 +1,29 @@ +public class Solution +{ + public bool IsHappy(int n) + { + var hs = new HashSet(); + var left = 0; + //HashSet is the key + while (hs.Add(n)) + { + var sum = 0; + while (n > 0) + { + left = n % 10; + sum += left * left; + n /= 10; + } + + if (sum == 1) + { + return true; + } + else + { + n = sum; + } + } + return false; + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.cs b/July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.cs new file mode 100644 index 0000000..956f7af --- /dev/null +++ b/July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.cs @@ -0,0 +1,53 @@ +public class Solution +{ + + //Bitwise solution + public uint reverseBits(uint n) { + if(n == 0) return 0; + uint result = 0; + for(int i=0; i<32; i++){ + result <<= 1; + if((n & 1) == 1) result++; + n >>= 1; + } + return result; + } + + + //Stack solution + public uint reverseBits(uint n) + { + //Push to stack + var stack = new Stack(); + while (n > 0) + { + stack.Push(n % 2); + n = n / 2; + } + + //Fill empty slots + var length = stack.Count; + if (length < 32) + { + var tl = 32 - length; + for (int i = 0; i < tl; i++) + { + stack.Push(0); + } + } + + //Construct number + uint b = 1; + uint result = 0; + if (stack.Pop() == 0) result = 0; + else result = 1; + while (stack.Count > 0) + { + b *= 2; + var r = stack.Pop(); + result = result + b * r; + } + + return result; + } +} \ No newline at end of file From a04339de3cbe29afdbce5c36fbcea06cec3bb370 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 13 Jul 2020 09:17:45 +0200 Subject: [PATCH 171/281] add cpp solution --- July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.cpp diff --git a/July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.cpp b/July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.cpp new file mode 100644 index 0000000..bf1bf67 --- /dev/null +++ b/July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + if (p == NULL and q == NULL) return true; + if (p == NULL and q) return false; + if (p and q == NULL) return false; + if (p->val != q->val) return false; + return isSameTree(p->left, q->left) and isSameTree(p->right, q->right); + } +}; \ No newline at end of file From 9c280603a9ec6aefcecdafb4bf88cb3308b3c809 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 13 Jul 2020 11:09:22 +0200 Subject: [PATCH 172/281] Add Same Tree C# --- .../13-Same-Tree/Same-Tree.cs | 26 +++++++++++++++++++ README.md | 8 +++--- 2 files changed, 30 insertions(+), 4 deletions(-) create mode 100644 July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.cs diff --git a/July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.cs b/July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.cs new file mode 100644 index 0000000..b356abf --- /dev/null +++ b/July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.cs @@ -0,0 +1,26 @@ +public class Solution +{ + public bool IsSameTree(TreeNode p, TreeNode q) + { + if (p == null && q == null) return true; + if (p == null || q == null) return false; + if (p.val == q.val) + { + return IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right); + } + return false; + } +} +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ \ No newline at end of file diff --git a/README.md b/README.md index ed54f03..21c0f9c 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,10 @@ https://leetcode.com - - ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. -Solutions in various programming languages are provided. Enjoy it. +Solutions in various programming languages are provided. Enjoy it. 1. [Arranging Coins](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/01-Arranging-Coins): Maths 2. [Binary Tree Level Order Traversal II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II): DFS @@ -20,11 +18,13 @@ Solutions in various programming languages are provided. Enjoy it. 9. [Maximum Width of Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree): DFS 10. [Flatten a Multilevel Doubly Linked List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List): Queue 11. [Subsets](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/11-Subsets): DP +12. [Reverse Bits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/12-Reverse-Bits): Bitwise +13. [Same Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/13-Same-Tree): DFS ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. -Solutions in various programming languages are provided. Enjoy it. +Solutions in various programming languages are provided. Enjoy it. 1. [Invert Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/01-Invert-Binary-Tree): Tree Traversal 2. [Delete Node in a Linked List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List): Linked List From 6664f0daac2e30175ecd356ccc7f20cb6e7ee57e Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Mon, 13 Jul 2020 11:26:22 +0200 Subject: [PATCH 173/281] add kotlin solutions --- .../01-Arranging-Coins/Arranging-Coins.kt | 29 ++++ .../Binary-Tree-Level-Order-Traversal-II.kt | 34 +++++ .../Prison-Cells-After-N-Days.kt | 28 ++++ .../04-Ugly-Number-II/Ugly-Number-II.kt | 39 +++++ .../05-Hamming-Distance/Hamming-Distance.kt | 15 ++ .../06-Plus-One/Plus-One.kt | 38 +++++ .../07-Island-Perimeter/Island-Perimeter.kt | 41 ++++++ July-LeetCoding-Challenge/08-3Sum/3Sum.kt | 42 ++++++ .../Maximum-Width-of-Binary-Tree.kt | 39 +++++ ...Flatten-a-Multilevel-Doubly-Linked-List.kt | 133 ++++++++++++++++++ .../11-Subsets/Subsets.kt | 30 ++++ .../12-Reverse-Bits/Reverse-Bits.kt | 18 +++ .../13-Same-Tree/Same-Tree.kt | 15 ++ 13 files changed, 501 insertions(+) create mode 100644 July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.kt create mode 100644 July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.kt create mode 100644 July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.kt create mode 100644 July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.kt create mode 100644 July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.kt create mode 100644 July-LeetCoding-Challenge/06-Plus-One/Plus-One.kt create mode 100644 July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.kt create mode 100644 July-LeetCoding-Challenge/08-3Sum/3Sum.kt create mode 100644 July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.kt create mode 100644 July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.kt create mode 100644 July-LeetCoding-Challenge/11-Subsets/Subsets.kt create mode 100644 July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.kt create mode 100644 July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.kt diff --git a/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.kt b/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.kt new file mode 100644 index 0000000..74d4d58 --- /dev/null +++ b/July-LeetCoding-Challenge/01-Arranging-Coins/Arranging-Coins.kt @@ -0,0 +1,29 @@ +package binary_search + +class ArrangingCoinsKotlin441 { + fun arrangeCoins(n: Int): Int { + var left = 1L + var right = n.toLong().shr(1) // n / 2 + right = if (right <= left) left + 1 else right + while (left + 1 < right) { + val mid: Long = left + (right - left) / 2L + val current: Long = (mid * (mid + 1)).shr(1) + when { + current == n.toLong() -> return mid.toInt() + current < n -> left = mid + current > n -> right = mid + } + } + return when { + (right * (right + 1)).shr(1) <= n -> right.toInt() + (left * (left + 1)).shr(1) <= n -> left.toInt() + else -> 0 + } + } +} + +fun main() { + val solution = ArrangingCoinsKotlin441() + println(solution.arrangeCoins(1)) + println(solution.arrangeCoins(1804289383)) // 60070 +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.kt b/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.kt new file mode 100644 index 0000000..dc07c97 --- /dev/null +++ b/July-LeetCoding-Challenge/02-Binary-Tree-Level-Order-Traversal-II/Binary-Tree-Level-Order-Traversal-II.kt @@ -0,0 +1,34 @@ +package breadth_first_search + +import java.util.* + +class BinaryTreeLevelOrderTraversalIIKotlin107 { + fun levelOrderBottom(root: TreeNode?): List> { + val result = mutableListOf>() + if (root == null) { + return result + } + val treeNodeQueue: Queue = LinkedList() + treeNodeQueue.offer(root) + while (treeNodeQueue.isNotEmpty()) { + val currentLevel = mutableListOf() + /* + val currentSize = treeNodeQueue.size + for (i in 0 until currentSize) { + */ + for (i in 0 until treeNodeQueue.size) { + val current = treeNodeQueue.poll() + currentLevel.add(current.`val`) + current.left?.let { treeNodeQueue.offer(it) } + current.right?.let { treeNodeQueue.offer(it) } + } + result.add(0, currentLevel) + } + return result + } + + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.kt b/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.kt new file mode 100644 index 0000000..c74d64f --- /dev/null +++ b/July-LeetCoding-Challenge/03-Prison-Cells-After-N-Days/Prison-Cells-After-N-Days.kt @@ -0,0 +1,28 @@ +package string_integer + +class PrisonCellsAfterNDaysKotlin957 { + fun prisonAfterNDays(cells: IntArray, N: Int): IntArray { + var result = cells + for (times in 0..((N - 1) % 14)) { + val new = IntArray(cells.size) + for (index in 1..cells.size - 2) { + if (result[index - 1] == result[index + 1]) { + new[index] = 1 + } else { + new[index] = 0 + } + } + result = new + } + return result + } +} + +fun main() { + val solution = PrisonCellsAfterNDaysKotlin957() + // [0,0,1,1,0,0,0,0] + solution.prisonAfterNDays(intArrayOf(0, 1, 0, 1, 1, 0, 0, 1), 7).forEach(::print) + println() + // [0,0,1,1,1,1,1,0] + solution.prisonAfterNDays(intArrayOf(1, 0, 0, 1, 0, 0, 1, 0), 1000000000).forEach(::print) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.kt b/July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.kt new file mode 100644 index 0000000..cf66516 --- /dev/null +++ b/July-LeetCoding-Challenge/04-Ugly-Number-II/Ugly-Number-II.kt @@ -0,0 +1,39 @@ +package binary_search + +class UglyNumberIIKotlin264 { + /* + (1) (1x2), 2x2, (2x2), (3x2), 3x2, (4x2), 5x2... + (2) 1x3, (1x3), 2x3, (2x3), 2x3, 3x3, (3x3)... + (3) 1x5, 1x5, 1x5, (1x5), 2x5, 2x5, 2x5... + */ + fun nthUglyNumber(n: Int): Int { + val list: MutableList = ArrayList() + var int1 = 0 + var int2 = 0 + var int3 = 0 + list.add(1) + while (list.size < n) { + val new1 = list[int1] * 2 + val new2 = list[int2] * 3 + val new3 = list[int3] * 5 + val min = minOf(new1, new2, new3) + if (min == new1) { + ++int1 + } + if (min == new2) { + ++int2 + } + if (min == new3) { + ++int3 + } + list.add(min) + } + return list[n - 1] + } +} + +fun main() { + val solution = UglyNumberIIKotlin264() + // 12 + println(solution.nthUglyNumber(10)) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.kt b/July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.kt new file mode 100644 index 0000000..963a69e --- /dev/null +++ b/July-LeetCoding-Challenge/05-Hamming-Distance/Hamming-Distance.kt @@ -0,0 +1,15 @@ +package string_integer + +class HammingDistanceKotlin461 { + fun hammingDistance(x: Int, y: Int): Int { + var xor = x.xor(y) + var count = 0 + for (times in 1..32) { + if (xor.and(1) == 1) { + ++count + } + xor = xor.shr(1) + } + return count + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/06-Plus-One/Plus-One.kt b/July-LeetCoding-Challenge/06-Plus-One/Plus-One.kt new file mode 100644 index 0000000..525496f --- /dev/null +++ b/July-LeetCoding-Challenge/06-Plus-One/Plus-One.kt @@ -0,0 +1,38 @@ +package string_integer + +class PlusOneKotlin66 { + fun plusOne(digits: IntArray): IntArray { + if (digits[digits.size - 1] != 9) { + ++digits[digits.size - 1] + return digits + } + var next = 1 + digits[digits.size - 1] = 0 + for (index in digits.size - 2 downTo 0) { + if (next == 1) { + if (digits[index] == 9) { + digits[index] = 0 + next = 1 + } else { + ++digits[index] + next = 0 + } + } + } + if (next == 1 && digits[0] == 0) { + return intArrayOf(1).plus(digits) + } + return digits + } +} + +fun main() { + val solution = PlusOneKotlin66() + solution.plusOne(intArrayOf(1, 0, 0)).forEach(::print) + println() + solution.plusOne(intArrayOf(1, 9, 9)).forEach(::print) + println() + solution.plusOne(intArrayOf(9, 9, 9)).forEach(::print) + println() + solution.plusOne(intArrayOf(1, 0, 9)).forEach(::print) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.kt b/July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.kt new file mode 100644 index 0000000..b41beb3 --- /dev/null +++ b/July-LeetCoding-Challenge/07-Island-Perimeter/Island-Perimeter.kt @@ -0,0 +1,41 @@ +package string_integer + +class IslandPerimeterKotlin463 { + fun islandPerimeter(grid: Array): Int { + var count = 0 + for (i in grid.indices) { + for (j in grid[0].indices) { + if (grid[i][j] == 1) { + count += 4 + if (i > 0 && grid[i - 1][j] == 1) { + --count + } + if (j > 0 && grid[i][j - 1] == 1) { + --count + } + if (i < grid.size - 1 && grid[i + 1][j] == 1) { + --count + } + if (j < grid[0].size - 1 && grid[i][j + 1] == 1) { + --count + } + } + } + } + return count + } +} + +fun main() { + val solution = IslandPerimeterKotlin463() + println( + solution.islandPerimeter( + arrayOf( + intArrayOf(0, 1, 0, 0), + intArrayOf(1, 1, 1, 0), + intArrayOf(0, 1, 0, 0), + intArrayOf(1, 1, 0, 0) + ) + ) + ) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/08-3Sum/3Sum.kt b/July-LeetCoding-Challenge/08-3Sum/3Sum.kt new file mode 100644 index 0000000..19b0866 --- /dev/null +++ b/July-LeetCoding-Challenge/08-3Sum/3Sum.kt @@ -0,0 +1,42 @@ +package string_integer + +import java.util.* + +class ThreeSumKotlin15 { + fun threeSum(nums: IntArray): List> { + val result: MutableList> = LinkedList() + if (nums.isEmpty()) { + return result + } + nums.sort() + for (i in 0..nums.size - 3) { + if (nums[i] > 0) { + break + } + if (i > 0 && nums[i] == nums[i - 1]) { + continue + } + var j = i + 1 + var k = nums.size - 1 + while (j < k) { + val sum = nums[i] + nums[j] + nums[k] + when { + sum == 0 -> { + result.add(listOf(nums[i], nums[j], nums[k])) + ++j + --k + } + sum < 0 -> ++j + sum > 0 -> --k + } + while (j > i + 1 && j < k && nums[j] == nums[j - 1]) { + ++j + } + while (k < nums.size - 1 && j < k && nums[k] == nums[k + 1]) { + --k + } + } + } + return result + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.kt b/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.kt new file mode 100644 index 0000000..3a06b3c --- /dev/null +++ b/July-LeetCoding-Challenge/09-Maximum-Width-of-Binary-Tree/Maximum-Width-of-Binary-Tree.kt @@ -0,0 +1,39 @@ +package breadth_first_search + +import java.util.* + +class MaximumWidthofBinaryTreeKotlin662 { + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } + + fun widthOfBinaryTree(root: TreeNode?): Int { + if (root == null) { + return 0 + } + var result = 1 + val queue: Queue> = LinkedList() + queue.offer(Pair(root, 1)) + while (queue.isNotEmpty()) { + if (queue.size == 1) { + val current = queue.poll() + current.first.left?.let { queue.offer(Pair(it, 2)) } + current.first.right?.let { queue.offer(Pair(it, 3)) } + } else { + var min = Int.MAX_VALUE + var max = Int.MIN_VALUE + for (index in 0 until queue.size) { + val current = queue.poll() + val value = current.second + min = minOf(value, min) + max = maxOf(value, max) + current.first.left?.let { queue.offer(Pair(it, value.shl(1))) } + current.first.right?.let { queue.offer(Pair(it, value.shl(1) + 1)) } + } + result = maxOf(result, max - min + 1) + } + } + return result + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.kt b/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.kt new file mode 100644 index 0000000..149e4e8 --- /dev/null +++ b/July-LeetCoding-Challenge/10-Flatten-a-Multilevel-Doubly-Linked-List/Flatten-a-Multilevel-Doubly-Linked-List.kt @@ -0,0 +1,133 @@ +package list_array + +class FlattenaMultilevelDoublyLinkedListKotlin430 { + fun flatten(root: Node?): Node? { + var current = root + while (current != null) { + current.child?.let { + val flatten = current!! + val next = flatten.next + var lastChild = it + while (lastChild.next != null) { + lastChild = lastChild.next!! + } + flatten.next = it + it.prev = flatten + flatten.child = null + lastChild.next = next + next?.let { n -> n.prev = lastChild } + } + current = current.next + } + return root + } + /* + fun flatten(root: Node?): Node? { + if (root == null) { + return root + } + dfs(root) + return root + } + + private fun dfs(root: Node): Node { + var current = root + /* + 1 -> 2 -> 3 + ->4 -> 5 + + current = 2 + nextNode = 3 + 2.next = 4 + 4.prev = 2 + + result = 5 + 3.pre = 5 + 5.next = 3 + + 2.child = null + current = 5 + */ + current.child?.let { + val nextNode = current.next + current.next = it + it.prev = current + val result = dfs(it) + nextNode?.prev = result + result.next = nextNode + current.child = null + current = result + } + while (current.next != null) { + current = current.next!! + current.child?.let { + val nextNode = current.next + current.next = it + it.prev = current + val result = dfs(it) + nextNode?.prev = result + result.next = nextNode + current.child = null + current = result + } + } + return current + } + + */ + + class Node(var `val`: Int) { + var prev: Node? = null + var next: Node? = null + var child: Node? = null + } +} + +fun main() { + val node1 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(1) + val node2 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(2) + val node3 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(3) + val node4 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(4) + val node5 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(5) + val node6 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(6) + val node7 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(7) + val node8 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(8) + val node9 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(9) + val node10 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(10) + val node11 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(11) + val node12 = FlattenaMultilevelDoublyLinkedListKotlin430.Node(12) + node1.next = node2 + node2.prev = node1 + + node2.next = node3 + node3.prev = node2 + + node3.next = node4 + node4.prev = node3 + + node4.next = node5 + node5.prev = node4 + + node5.next = node6 + node6.prev = node5 + + node3.child = node7 + + node7.next = node8 + node8.prev = node7 + + node8.next = node9 + node9.prev = node8 + + node9.next = node10 + node10.prev = node9 + + node8.child = node11 + + node11.next = node12 + node12.prev = node11 + + val solution = FlattenaMultilevelDoublyLinkedListKotlin430() + val result = solution.flatten(node1) + println(result) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/11-Subsets/Subsets.kt b/July-LeetCoding-Challenge/11-Subsets/Subsets.kt new file mode 100644 index 0000000..7588050 --- /dev/null +++ b/July-LeetCoding-Challenge/11-Subsets/Subsets.kt @@ -0,0 +1,30 @@ +package depth_first_search + +import java.util.* +import kotlin.collections.ArrayList + +class SubsetsKotlin78 { + fun subsets(nums: IntArray): List> { + val results: MutableList> = LinkedList() + if (nums.isEmpty()) { + return results + } + val subSet: MutableList = LinkedList() + dfs(nums, 0, subSet, results) + return results + } + + private fun dfs( + nums: IntArray, + startIndex: Int, + subSet: MutableList, + results: MutableList> + ) { + results.add(ArrayList(subSet)) + for (i in startIndex until nums.size) { + subSet.add(nums[i]) + dfs(nums, i + 1, subSet, results) + subSet.removeAt(subSet.size - 1) + } + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.kt b/July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.kt new file mode 100644 index 0000000..9a70130 --- /dev/null +++ b/July-LeetCoding-Challenge/12-Reverse-Bits/Reverse-Bits.kt @@ -0,0 +1,18 @@ +package string_integer + +class ReverseBitsKotlin190 { + // you need treat n as an unsigned value + fun reverseBits(n: Int): Int { + var current = n + var result = 0 + for (time in 0 until 32) { + result = if (current.and(1) == 1) { + result.shl(1) + 1 + } else { + result.shl(1) + } + current = current.shr(1) + } + return result + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.kt b/July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.kt new file mode 100644 index 0000000..3082905 --- /dev/null +++ b/July-LeetCoding-Challenge/13-Same-Tree/Same-Tree.kt @@ -0,0 +1,15 @@ +package not_categorized_easy + +class SameTreeKotlin100 { + fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean = when { + p == null && q == null -> true + p == null || q == null || p.`val` != q.`val` -> false + else -> isSameTree(p.left, q.left) && + isSameTree(p.right, q.right) + } + + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } +} \ No newline at end of file From 93ed7949ae53131ebcab78955d197ee243bc2914 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 14 Jul 2020 12:02:43 +0200 Subject: [PATCH 174/281] Add Angle Between Hands of a Clock C# --- .../Angle-Between-Hands-of-a-Clock.cs | 7 +++++++ README.md | 1 + 2 files changed, 8 insertions(+) create mode 100644 July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cs diff --git a/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cs b/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cs new file mode 100644 index 0000000..6f6f7fc --- /dev/null +++ b/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cs @@ -0,0 +1,7 @@ +public class Solution { + public double AngleClock(int hour, int minutes) { + var angle = Math.Abs((double)(hour + (double)minutes/60) / 12 * 360 - (double)minutes / 60 * 360); + if(angle >= 180) angle = (double)360 - angle; + return Math.Round(angle, 1); + } +} \ No newline at end of file diff --git a/README.md b/README.md index 21c0f9c..ad49464 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Solutions in various programming languages are provided. Enjoy it. 11. [Subsets](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/11-Subsets): DP 12. [Reverse Bits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/12-Reverse-Bits): Bitwise 13. [Same Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/13-Same-Tree): DFS +14. [Angle Between Hands of a Clock](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock): Math ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From b6125fde19fa97c35255424d588a596ff0182fd9 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 14 Jul 2020 17:32:54 +0200 Subject: [PATCH 175/281] add cpp solution --- .../Angle-Between-Hands-of-a-Clock.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cpp diff --git a/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cpp b/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cpp new file mode 100644 index 0000000..2556679 --- /dev/null +++ b/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cpp @@ -0,0 +1,9 @@ +class Solution { +public: + double angleClock(int hour, int minutes) { + double f1 = (hour % 12) * 30.0 + 0.5 * minutes; + double f2 = 6.0 * minutes; + double t = abs(f1 - f2); + return min(t, 360 - t); + } +}; \ No newline at end of file From 52b69d5b5bb549195fce778f9477443a68ecd139 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 14 Jul 2020 22:16:49 +0200 Subject: [PATCH 176/281] add solutions --- .../Angle-Between-Hands-of-a-Clock.cpp | 2 +- ...Remove-Duplicates-From-Sorted-Array-II.cpp | 15 ++++++++++++ .../Remove-Duplicates-From-Sorted-Array-II.py | 13 ++++++++++ .../101-Symmetric-Tree/Symmetric-Tree.cpp | 24 +++++++++++++++++++ .../Tree/101-Symmetric-Tree/Symmetric-Tree.py | 14 +++++++++++ 5 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 Problems/Array/80-Remove-Duplicates-From-Sorted-Array-II/80-Remove-Duplicates-From-Sorted-Array-II.cpp create mode 100644 Problems/Array/80-Remove-Duplicates-From-Sorted-Array-II/Remove-Duplicates-From-Sorted-Array-II.py create mode 100644 Problems/Tree/101-Symmetric-Tree/Symmetric-Tree.cpp create mode 100644 Problems/Tree/101-Symmetric-Tree/Symmetric-Tree.py diff --git a/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cpp b/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cpp index 2556679..9bea966 100644 --- a/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cpp +++ b/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.cpp @@ -6,4 +6,4 @@ class Solution { double t = abs(f1 - f2); return min(t, 360 - t); } -}; \ No newline at end of file +}; \ No newline at end of file diff --git a/Problems/Array/80-Remove-Duplicates-From-Sorted-Array-II/80-Remove-Duplicates-From-Sorted-Array-II.cpp b/Problems/Array/80-Remove-Duplicates-From-Sorted-Array-II/80-Remove-Duplicates-From-Sorted-Array-II.cpp new file mode 100644 index 0000000..088273d --- /dev/null +++ b/Problems/Array/80-Remove-Duplicates-From-Sorted-Array-II/80-Remove-Duplicates-From-Sorted-Array-II.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int removeDuplicates(vector& nums) { + int n = nums.size(); + if (n < 3) return n; + int i = 2, j = 2; + while (j < n){ + while (j < n and nums[j] == nums[i-1] and nums[i-1] == nums[i-2]) + j++; + if (j < n) + nums[i++] = nums[j++]; + } + return i; + } +}; \ No newline at end of file diff --git a/Problems/Array/80-Remove-Duplicates-From-Sorted-Array-II/Remove-Duplicates-From-Sorted-Array-II.py b/Problems/Array/80-Remove-Duplicates-From-Sorted-Array-II/Remove-Duplicates-From-Sorted-Array-II.py new file mode 100644 index 0000000..aba13f4 --- /dev/null +++ b/Problems/Array/80-Remove-Duplicates-From-Sorted-Array-II/Remove-Duplicates-From-Sorted-Array-II.py @@ -0,0 +1,13 @@ +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + n = len(nums) + if (n < 3): return n + i = j = 2 + while(j < n): + while (j < n and nums[i-2] == nums[i-1] and nums[i-1] == nums[j]): + j += 1 + if (j < n): + nums[i] = nums[j] + i += 1 + j += 1 + return i \ No newline at end of file diff --git a/Problems/Tree/101-Symmetric-Tree/Symmetric-Tree.cpp b/Problems/Tree/101-Symmetric-Tree/Symmetric-Tree.cpp new file mode 100644 index 0000000..9e3fdf8 --- /dev/null +++ b/Problems/Tree/101-Symmetric-Tree/Symmetric-Tree.cpp @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + bool check(TreeNode* r1, TreeNode* r2){ + if (r1 == NULL and r2 == NULL) return true; + if (r1 and r2 == NULL) return false; + if (r1 == NULL and r2) return false; + if (r1->val != r2->val) return false; + return check(r1->left, r2->right) and check(r1->right, r2->left); + } + bool isSymmetric(TreeNode* root) { + return check(root, root); + } +}; \ No newline at end of file diff --git a/Problems/Tree/101-Symmetric-Tree/Symmetric-Tree.py b/Problems/Tree/101-Symmetric-Tree/Symmetric-Tree.py new file mode 100644 index 0000000..2e762ef --- /dev/null +++ b/Problems/Tree/101-Symmetric-Tree/Symmetric-Tree.py @@ -0,0 +1,14 @@ +# Runtime: 48 ms, faster than 21.52% of Python3 online submissions for Symmetric Tree. + +# Memory Usage: 14 MB, less than 56.03% of Python3 online submissions for Symmetric Tree. +class Solution: + def check(self, r1, r2): + if (r1 and r2 == None): return False + if (r1 == None and r2): return False + if (r1 == None and r2 == None): return True + if (r1.val != r2.val): return False + return self.check(r1.left, r2.right) and self.check(r1.right, r2.left) + + def isSymmetric(self, root: TreeNode) -> bool: + return self.check(root, root) + From 5520711692bc661232b00b7b4e701510c5796ac7 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Tue, 14 Jul 2020 22:32:17 +0200 Subject: [PATCH 177/281] add solutions --- .../Average-Of-Levels-In-Binary-Tree.cpp | 31 +++++++++++++++++++ .../Average-Of-Levels-In-Binary-Tree.py | 11 +++++++ 2 files changed, 42 insertions(+) create mode 100644 Problems/Tree/637-Average-Of-Levels-In-Binary-Tree/Average-Of-Levels-In-Binary-Tree.cpp create mode 100644 Problems/Tree/637-Average-Of-Levels-In-Binary-Tree/Average-Of-Levels-In-Binary-Tree.py diff --git a/Problems/Tree/637-Average-Of-Levels-In-Binary-Tree/Average-Of-Levels-In-Binary-Tree.cpp b/Problems/Tree/637-Average-Of-Levels-In-Binary-Tree/Average-Of-Levels-In-Binary-Tree.cpp new file mode 100644 index 0000000..5650372 --- /dev/null +++ b/Problems/Tree/637-Average-Of-Levels-In-Binary-Tree/Average-Of-Levels-In-Binary-Tree.cpp @@ -0,0 +1,31 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector> v; + void dfs(TreeNode* root, int dep){ + if (root == NULL) return; + while (dep >= v.size()) v.push_back(make_pair(0, 0)); + v[dep].first += root->val; + v[dep].second ++; + dfs(root->left, dep + 1); + dfs(root->right, dep + 1); + } + + vector averageOfLevels(TreeNode* root) { + dfs(root, 0); + vector ans(v.size(), 0); + for (int i = 0; i < ans.size(); i++) + ans[i] = v[i].first / v[i].second; + return ans; + } +}; \ No newline at end of file diff --git a/Problems/Tree/637-Average-Of-Levels-In-Binary-Tree/Average-Of-Levels-In-Binary-Tree.py b/Problems/Tree/637-Average-Of-Levels-In-Binary-Tree/Average-Of-Levels-In-Binary-Tree.py new file mode 100644 index 0000000..21b8795 --- /dev/null +++ b/Problems/Tree/637-Average-Of-Levels-In-Binary-Tree/Average-Of-Levels-In-Binary-Tree.py @@ -0,0 +1,11 @@ +class Solution: + def averageOfLevels(self, root: TreeNode) -> List[float]: + from collections import defaultdict + d = defaultdict(list) + def dfs(root, dep): + if root: + d[dep].append(root.val) + dfs(root.left, dep + 1) + dfs(root.right, dep + 1) + dfs(root , 0) + return [sum(x)/len(x) for x in d.values()] \ No newline at end of file From 24006a5d0a401f5794667503eae71d0efd17d0bf Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 15 Jul 2020 18:54:23 +0200 Subject: [PATCH 178/281] Add Reverse Words in a String C# --- .../Reverse-Words-in-a-String.cs | 69 +++++++++++++++++++ README.md | 1 + 2 files changed, 70 insertions(+) create mode 100644 July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.cs diff --git a/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.cs b/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.cs new file mode 100644 index 0000000..eb1272e --- /dev/null +++ b/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.cs @@ -0,0 +1,69 @@ +public class Solution +{ + //Pointer solution + public string ReverseWords(string s) + { + var arr = s.ToCharArray(); + var start = 0; + var end = arr.Length; + reverse(arr, start, end - 1); + + reverseWords(arr, start, end); + + return cleanSpaces(arr, end); + } + + private void reverse(char[] arr, int start, int end) + { + while (start < end) + { + var temp = arr[end]; + arr[end] = arr[start]; + arr[start] = temp; + end--; + start++; + } + } + + private void reverseWords(char[] arr, int start, int end) + { + int b = 0, e = 0; + while (b < end) + { + while (b < e || (b < end && arr[b] == ' ')) b++; //skip spaces + while (e < b || (e < end && arr[e] != ' ')) e++; //skip non spaces + reverse(arr, b, e - 1); //reverse the word + } + } + + private string cleanSpaces(char[] arr, int n) + { + int b = 0, e = 0; + while (e < n) + { + while (e < n && arr[e] == ' ') e++; + while (e < n && arr[e] != ' ') arr[b++] = arr[e++]; + while (e < n && arr[e] == ' ') e++; + if (e < n) arr[b++] = ' '; + } + return new string(arr).Substring(0, b); + } + + //Stack solution + public string ReverseWords(string s) + { + var v = System.Text.RegularExpressions.Regex.Replace(s, " {2,}", " "); + var arr = v.Trim().Split(" ").ToArray(); + var sb = new StringBuilder(); + var stack = new Stack(); + for (int i = 0; i < arr.Length; i++) + { + stack.Push(arr[i]); + } + while (stack.Count > 0) + { + sb.Append(stack.Pop() + " "); + } + return sb.ToString().Trim(); + } +} \ No newline at end of file diff --git a/README.md b/README.md index ad49464..ff4046d 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ Solutions in various programming languages are provided. Enjoy it. 12. [Reverse Bits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/12-Reverse-Bits): Bitwise 13. [Same Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/13-Same-Tree): DFS 14. [Angle Between Hands of a Clock](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock): Math +15. [Reverse Words in a String](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String): Pointer ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From 1742d20851bf2a05c1a7ae4b53a27186df6cd2da Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Thu, 16 Jul 2020 15:50:55 +0200 Subject: [PATCH 179/281] Add Pow(x,n) C# --- July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).cs | 13 +++++++++++++ README.md | 2 ++ 2 files changed, 15 insertions(+) create mode 100644 July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).cs diff --git a/July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).cs b/July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).cs new file mode 100644 index 0000000..cc575b9 --- /dev/null +++ b/July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).cs @@ -0,0 +1,13 @@ +public class Solution { + public double MyPow(double x, int n) { + if(n < 0) return Pow(1/x, -n); + return Pow(x, n); + } + + public double Pow(double x, int n){ + if(n == 0) return 1; + if(n == 1) return x; + if(n % 2 == 0) return Pow(x * x, n/2); + return x * Pow(x * x, n / 2); + } +} \ No newline at end of file diff --git a/README.md b/README.md index ff4046d..8659e83 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ Solutions in various programming languages are provided. Enjoy it. 13. [Same Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/13-Same-Tree): DFS 14. [Angle Between Hands of a Clock](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock): Math 15. [Reverse Words in a String](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String): Pointer +16. [16-Pow(x,n)](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/16-Pow(x,n)): Pointer + ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From f15065ac83161841644df16b5c3390455e4c1f33 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Thu, 16 Jul 2020 15:51:12 +0200 Subject: [PATCH 180/281] update --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8659e83..f4bc9d5 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Solutions in various programming languages are provided. Enjoy it. 13. [Same Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/13-Same-Tree): DFS 14. [Angle Between Hands of a Clock](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock): Math 15. [Reverse Words in a String](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String): Pointer -16. [16-Pow(x,n)](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/16-Pow(x,n)): Pointer +16. [16-Pow(x,n)](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/16-Pow(x,n)): Recursion ## June LeetCoding Challenge From a3d551881860f1c71308f45c22859bc35991a8e4 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 17 Jul 2020 20:18:06 +0200 Subject: [PATCH 181/281] Add Top K Frequent Elements C# --- .../Top-K-Frequent-Elements.cs | 34 +++++++++++++++++++ README.md | 4 +-- 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.cs diff --git a/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.cs b/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.cs new file mode 100644 index 0000000..fa0701a --- /dev/null +++ b/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.cs @@ -0,0 +1,34 @@ +public class Solution { + public int[] TopKFrequent(int[] nums, int k) { + //Count occurrence for each value + var dict = new Dictionary(); + for(int i=0; i[nums.Length+1]; + foreach(var kv in dict){ + var occurrence = kv.Value; + if(numbersByCount[occurrence] == null){ + numbersByCount[occurrence] = new List(); + } + numbersByCount[occurrence].Add(kv.Key); + } + + //Decrease numbersByCount.Length as the number of occurence, and check the a sublist's existence + var res = new List(); + for(int i=numbersByCount.Length-1; i>0 && k>0; i--){ + if(numbersByCount[i] != null){ + res.AddRange(numbersByCount[i]); + k = k - numbersByCount[i].Count; + } + } + + return res.ToArray(); + } +} \ No newline at end of file diff --git a/README.md b/README.md index f4bc9d5..f35eec8 100644 --- a/README.md +++ b/README.md @@ -22,8 +22,8 @@ Solutions in various programming languages are provided. Enjoy it. 13. [Same Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/13-Same-Tree): DFS 14. [Angle Between Hands of a Clock](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock): Math 15. [Reverse Words in a String](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String): Pointer -16. [16-Pow(x,n)](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/16-Pow(x,n)): Recursion - +16. [Pow(x,n)](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/16-Pow(x,n)): Recursion +17. [Top K Frequent Elements](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements): Bucket ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From 4255ab198a747e83d0fcb95a3f412c4e26328f1b Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sat, 18 Jul 2020 20:33:23 +0200 Subject: [PATCH 182/281] Add Course Schedule II C# --- .../Course-Schedule-II.cs | 35 +++++++++++++++++++ README.md | 2 ++ 2 files changed, 37 insertions(+) create mode 100644 July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.cs diff --git a/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.cs b/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.cs new file mode 100644 index 0000000..35dd5c5 --- /dev/null +++ b/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.cs @@ -0,0 +1,35 @@ +public class Solution { + public int[] FindOrder(int numCourses, int[][] prerequisites) { + if(numCourses == 0) return new int[0]; + + var indegree = new int[numCourses]; + for(int i=0; i queue = new Queue(); + for(int i=0; i 0){ + var prerequi = queue.Dequeue(); + for(int i=0; i Date: Sat, 18 Jul 2020 22:44:10 +0200 Subject: [PATCH 183/281] add cpp solution --- .../Course-Schedule-II.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.cpp diff --git a/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.cpp b/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.cpp new file mode 100644 index 0000000..0143700 --- /dev/null +++ b/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + + vector findOrder(int numCourses, vector>& prerequisites) { + vector deg(numCourses, 0); + vector> G(numCourses, vector()); + for (auto v: prerequisites){ + deg[v[0]] ++; + G[v[1]].push_back(v[0]); + } + + + queue q; + for (int i = 0; i < numCourses; i++) if (!deg[i]) q.push(i); + + vector ans; + while(!q.empty()){ + int i = q.front(); q.pop(); + ans.push_back(i); + for (auto j: G[i]){ + deg[j]--; + if (!deg[j]) q.push(j); + } + } + + if (ans.size() == numCourses) return ans; + return vector(); + } +}; \ No newline at end of file From 513a3dc4948086861f2d3703ada0784e6df01838 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 19 Jul 2020 14:18:54 +0200 Subject: [PATCH 184/281] Add Add Binary C# --- .../19-Add-Binary/Add-Binary.cs | 18 ++++++++++++++++++ README.md | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.cs diff --git a/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.cs b/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.cs new file mode 100644 index 0000000..aad67af --- /dev/null +++ b/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.cs @@ -0,0 +1,18 @@ +public class Solution { + public string AddBinary(string a, string b) + { + var sb = new StringBuilder(); + int i = a.Length-1, j = b.Length-1, carry = 0; + while(i >=0 || j >= 0){ + int sum = carry; + if(i >= 0) sum += a[i--] - '0'; + if(j >= 0) sum += b[j--] - '0'; + sb.Append(sum % 2); + carry = sum /2; + } + if(carry != 0) sb.Append(carry); + var arr = sb.ToString().ToCharArray(); + Array.Reverse(arr); + return new String(arr); + } +} \ No newline at end of file diff --git a/README.md b/README.md index b7cdcc1..72fda06 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Solutions in various programming languages are provided. Enjoy it. 16. [Pow(x,n)](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/16-Pow(x,n)): Recursion 17. [Top K Frequent Elements](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements): Bucket 18. [Course Schedule II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/18-Course-Schedule-II): BFS - +19. [Add Binary](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/19-Add-Binary) ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From c73ca5a646977ed7073bdb4d5c310bb4053d32b0 Mon Sep 17 00:00:00 2001 From: jinshendan Date: Sun, 19 Jul 2020 14:40:30 +0200 Subject: [PATCH 185/281] add cpp solution --- .../19-Add-Binary/Add-Binary.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.cpp diff --git a/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.cpp b/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.cpp new file mode 100644 index 0000000..90d5147 --- /dev/null +++ b/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + string addBinary(string a, string b) { + string ans = (a.length() > b.length())?a:b; + int sum = 0; + for (int i = 0; i < ans.length(); i++){ + if (i < a.length()) sum += (a[a.length() - i - 1] == '1')?1:0; + if (i < b.length()) sum += (b[b.length() - i - 1] == '1')?1:0; + ans[ans.length() - i - 1] = (sum & 1) + '0'; + sum >>= 1; + } + if (sum == 1) ans = "1" + ans; + return ans; + } +}; \ No newline at end of file From 8f07edd79179523dd97d5e2040f208892828447a Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Mon, 20 Jul 2020 09:28:31 +0200 Subject: [PATCH 186/281] Create Remove-Linked-List-Elements.cpp --- .../Remove-Linked-List-Elements.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.cpp diff --git a/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.cpp b/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.cpp new file mode 100644 index 0000000..10cb9d0 --- /dev/null +++ b/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.cpp @@ -0,0 +1,18 @@ +class Solution1 { +public: + ListNode* removeElements(ListNode* head, int val) { + + head = new ListNode(-1,head); + ListNode* prev = head, *curr = head->next; + + while(curr){ + if(curr->val == val) + prev->next = prev->next->next; + else + prev = curr; + curr = curr->next; + } + + return head->next; + } +}; From 664c72ee4986a8c4bfad3ac6f48f426ea87ca3da Mon Sep 17 00:00:00 2001 From: jinshendan Date: Mon, 20 Jul 2020 10:49:11 +0200 Subject: [PATCH 187/281] add py solution --- .../Remove-Linked-List-Elements.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.py diff --git a/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.py b/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.py new file mode 100644 index 0000000..b5da6ce --- /dev/null +++ b/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.py @@ -0,0 +1,18 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeElements(self, head: ListNode, val: int) -> ListNode: + prev = ListNode(-1, head) + h = prev + cur = head + while(cur): + while (cur and cur.val == val): + cur = cur.next + prev.next = cur + prev = cur + if (cur): + cur = cur.next + return h.next \ No newline at end of file From ea696f611d55b2b9b0d24530f4a2788cf540bdd7 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 20 Jul 2020 18:34:08 +0200 Subject: [PATCH 188/281] Add Remove Linked List Elements C# --- .../Remove-Linked-List-Elements.cs | 28 +++++++++++++++++++ README.md | 1 + 2 files changed, 29 insertions(+) create mode 100644 July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.cs diff --git a/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.cs b/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.cs new file mode 100644 index 0000000..9f0e1f2 --- /dev/null +++ b/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.cs @@ -0,0 +1,28 @@ +public class Solution { + public ListNode RemoveElements(ListNode head, int val) { + if(head == null) return null; + var curr = new ListNode(-1); + curr.next = head; + head = curr; + while(curr.next != null){ + if(curr.next.val == val){ + curr.next = curr.next.next; + }else{ + curr = curr.next; + } + } + return head.next; + } +} + +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ \ No newline at end of file diff --git a/README.md b/README.md index 72fda06..e7ef1ef 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Solutions in various programming languages are provided. Enjoy it. 17. [Top K Frequent Elements](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements): Bucket 18. [Course Schedule II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/18-Course-Schedule-II): BFS 19. [Add Binary](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/19-Add-Binary) +20. [Remove Linked List Elements](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements) ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From 1cac7a569110de661fc5579b05d169e3954bd2da Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 21 Jul 2020 20:12:49 +0200 Subject: [PATCH 189/281] Add Word Search C# --- .../21-Word-Search/Word-Search.cs | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 July-LeetCoding-Challenge/21-Word-Search/Word-Search.cs diff --git a/July-LeetCoding-Challenge/21-Word-Search/Word-Search.cs b/July-LeetCoding-Challenge/21-Word-Search/Word-Search.cs new file mode 100644 index 0000000..c674490 --- /dev/null +++ b/July-LeetCoding-Challenge/21-Word-Search/Word-Search.cs @@ -0,0 +1,29 @@ +public class Solution { + public bool Exist(char[][] board, string word) { + var arr = word.ToCharArray(); + for(int i=0; i Date: Wed, 22 Jul 2020 10:24:51 +0200 Subject: [PATCH 190/281] Create Binary-Tree-Zigzag-Level-Order-Traversal.cpp --- ...nary-Tree-Zigzag-Level-Order-Traversal.cpp | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.cpp diff --git a/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.cpp b/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.cpp new file mode 100644 index 0000000..44ccf2e --- /dev/null +++ b/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector> zigzagLevelOrder(TreeNode* root) { + vector> r; + queue q; + if(root) q.push(root); + int h = 1, n; + while(!q.empty()){ + n = q.size(); + vector ins; + for(int i=0; ileft) q.push(node->left); + if(node->right) q.push(node->right); + ins.push_back(node->val); + } + if(!(h&1)) + reverse(ins.begin(),ins.end()); + r.push_back(ins); + ++h; + } + return r; + } +}; From 44f97d27f349cbe78ff9a744a002fe30d6ed069b Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 22 Jul 2020 20:58:20 +0200 Subject: [PATCH 191/281] Add Binary Tree Zigzag Level Order Traversal C# --- ...inary-Tree-Zigzag-Level-Order-Traversal.cs | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.cs diff --git a/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.cs b/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.cs new file mode 100644 index 0000000..53168b4 --- /dev/null +++ b/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.cs @@ -0,0 +1,33 @@ +public class Solution { + public IList> ZigzagLevelOrder(TreeNode root) { + var res = new List>(); + if(root == null) return res; + var level = 0; + Dfs(root, level, res); + return res; + } + + private void Dfs(TreeNode node, int level, List> res){ + if(node == null) return; + if(res.Count <= level) res.Add(new List()); + + if(level % 2 == 1) res[level].Insert(0, node.val); + else res[level].Add(node.val); + + Dfs(node.left, level+1, res); + Dfs(node.right, level+1, res); + } +} +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ \ No newline at end of file From 2f124b0b66670eed62dfd53fba18ef268c0d2757 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Thu, 23 Jul 2020 21:21:34 +0200 Subject: [PATCH 192/281] Add Single Number III C# --- .../23-Single-Number-III/Single-Number-III.cs | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.cs diff --git a/July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.cs b/July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.cs new file mode 100644 index 0000000..8986501 --- /dev/null +++ b/July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.cs @@ -0,0 +1,37 @@ +public class Solution +{ + public int[] SingleNumber(int[] nums) + { + int xor = 0; + foreach (int num in nums) + { + xor = xor ^ num; + } + + int lowBitSet = xor & (-xor); // get the lowest bit set + int a = 0; + int b = 0; + foreach (int num in nums) + { + if ((lowBitSet & num) == 0) + { + // num has ith bit unset that's why & operation is returning zero + a = a ^ num; + } + else + { + // num has ith bit set that's why & operation is returning non zero + b = b ^ num; + } + } + return new int[] { a, b }; + } + + public void Test() + { + var nums = new int[] { 1, 2, 3, 4, 1, 3 }; + var r = SingleNumber(nums); + Console.WriteLine(string.Join(",", r)); + } + +} \ No newline at end of file From 9f6e166f44ffb8dce5d837294ff7f9efe2797ff2 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Fri, 24 Jul 2020 09:14:20 +0200 Subject: [PATCH 193/281] Create All-Paths-From-Source-to-Target.cpp --- .../All-Paths-From-Source-to-Target.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.cpp diff --git a/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.cpp b/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.cpp new file mode 100644 index 0000000..1209c27 --- /dev/null +++ b/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.cpp @@ -0,0 +1,23 @@ +class Solution1 { +public: + vector> r; + vector> allPathsSourceTarget(vector>& graph) { + const int N = graph.size(); + vector ins; + dfs(0, N, graph, ins); + return r; + } + + void dfs(int curr, const int N, vector>& adj, vector& ins){ + if(curr == N-1){ + ins.push_back(curr); + r.push_back(ins); + return; + } + ins.push_back(curr); + for(int i: adj[curr]){ + dfs(i, N, adj, ins); + ins.pop_back(); + } + } +}; From 8b9e6de198ec6bd19f7318800902dd262eb193c4 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 24 Jul 2020 22:03:00 +0200 Subject: [PATCH 194/281] Add All Paths From Source to Target C# --- .../All-Paths-From-Source-to-Target.cs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.cs diff --git a/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.cs b/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.cs new file mode 100644 index 0000000..c7868b3 --- /dev/null +++ b/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.cs @@ -0,0 +1,21 @@ +public class Solution { + public IList> AllPathsSourceTarget(int[][] graph) { + var res = new List>(); + var path = new List(); + path.Add(0); + Dfs(graph, 0, res, path); + return res; + } + + public void Dfs(int[][] graph, int node, List> res, List path){ + if(node == graph.Length-1) { + res.Add(new List(path)); + return; + } + foreach(var n in graph[node]){ + path.Add(n); + Dfs(graph, n, res, path); + path.RemoveAt(path.Count()-1); + } + } +} \ No newline at end of file From 47325777f46e564f4ec2b0c4c565c1024de5ba1b Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sat, 25 Jul 2020 18:55:50 +0200 Subject: [PATCH 195/281] Add Find Minimum in Rotated Sorted Array II C# --- .../Find-Minimum-in-Rotated-Sorted-Array-II.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.cs diff --git a/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.cs b/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.cs new file mode 100644 index 0000000..f700fa1 --- /dev/null +++ b/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.cs @@ -0,0 +1,18 @@ +public class Solution { + public int FindMin(int[] nums) { + var h = nums.Length-1; + var l = 0; + while(l < h){ + int mid = (l + h-1)/2; + if(nums[mid] > nums[h]){ + l = mid +1; + }else if(nums[mid] < nums[l]){ + h = mid; + l++; + }else { + h--; + } + } + return nums[l]; + } +} \ No newline at end of file From 8c679dc805131b68789b51d8c613151dc1f3f899 Mon Sep 17 00:00:00 2001 From: Mincong HUANG Date: Sat, 25 Jul 2020 21:47:22 +0200 Subject: [PATCH 196/281] Check all directories ending with *-Challenge --- .github/scripts/check.sh | 37 ++++++++++++++++++++----------------- .github/workflows/main.yml | 6 ++---- 2 files changed, 22 insertions(+), 21 deletions(-) diff --git a/.github/scripts/check.sh b/.github/scripts/check.sh index fabdb00..cbde59a 100755 --- a/.github/scripts/check.sh +++ b/.github/scripts/check.sh @@ -7,28 +7,31 @@ # cd "$(dirname ${BASH_SOURCE})"/../.. -challenge_dir="${PWD}/${1}" errors=0 -echo "Checking ${challenge_dir}" -echo - -for question_path in $challenge_dir/* +for challenge_dir in $PWD/*-Challenge do - dirname="${question_path##*/}" # remove parent directoris - question="${dirname#*-}" # remove leading day prefix - echo "Question ${dirname}:" + echo "Checking ${challenge_dir}" + echo - for filepath in $question_path/* + for question_path in $challenge_dir/* do - filename="${filepath##*/}" - if [[ "${filename%.*}" == "$question" || "$filename" == "README.md" ]] - then - echo " PASSED: ${filename}" - else - echo " FAILED: ${filename}" - errors=$((errors + 1)) - fi + dirname="${question_path##*/}" # remove parent directoris + question="${dirname#*-}" # remove leading day prefix + echo "Question ${dirname}:" + + for filepath in $question_path/* + do + filename="${filepath##*/}" + if [[ "${filename%.*}" == "$question" || "$filename" == "README.md" ]] + then + echo " PASSED: ${filename}" + else + echo " FAILED: ${filename}" + errors=$((errors + 1)) + fi + done + echo done echo done diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5f7d895..6e8cad6 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -10,7 +10,5 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: Check LeetCoding Challenge Apr 2020 - run: .github/scripts/check.sh 30-Day-Leetcoding-Challenge - - name: Check LeetCoding Challenge May 2020 - run: .github/scripts/check.sh May-LeetCoding-Challenge + - name: Check File Naming + run: .github/scripts/check.sh From 35e42f9e99b0bb9c15ebefd6d9bf9b192d9a6d2e Mon Sep 17 00:00:00 2001 From: Mincong HUANG Date: Sat, 25 Jul 2020 21:55:39 +0200 Subject: [PATCH 197/281] Fix file naming --- ...e-Node-in-a-Linked-List.cs => Delete-Node-In-A-Linked-List.cs} | 0 ...de-in-a-Linked-List.java => Delete-Node-In-A-Linked-List.java} | 0 ...e-Node-in-a-Linked-List.js => Delete-Node-In-A-Linked-List.js} | 0 .../30-Word-Search-II/{Word-Search.cpp => Word-Search-II.cpp} | 0 .../30-Word-Search-II/{Word-Search.cs => Word-Search-II.cs} | 0 .../30-Word-Search-II/{Word-Search.kt => Word-Search-II.kt} | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/{Delete-Node-in-a-Linked-List.cs => Delete-Node-In-A-Linked-List.cs} (100%) rename June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/{Delete-Node-in-a-Linked-List.java => Delete-Node-In-A-Linked-List.java} (100%) rename June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/{Delete-Node-in-a-Linked-List.js => Delete-Node-In-A-Linked-List.js} (100%) rename June-LeetCoding-Challenge/30-Word-Search-II/{Word-Search.cpp => Word-Search-II.cpp} (100%) rename June-LeetCoding-Challenge/30-Word-Search-II/{Word-Search.cs => Word-Search-II.cs} (100%) rename June-LeetCoding-Challenge/30-Word-Search-II/{Word-Search.kt => Word-Search-II.kt} (100%) diff --git a/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.cs b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.cs similarity index 100% rename from June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.cs rename to June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.cs diff --git a/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.java b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.java similarity index 100% rename from June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.java rename to June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.java diff --git a/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.js b/June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.js similarity index 100% rename from June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-in-a-Linked-List.js rename to June-LeetCoding-Challenge/02-Delete-Node-In-A-Linked-List/Delete-Node-In-A-Linked-List.js diff --git a/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cpp b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search-II.cpp similarity index 100% rename from June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cpp rename to June-LeetCoding-Challenge/30-Word-Search-II/Word-Search-II.cpp diff --git a/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cs b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search-II.cs similarity index 100% rename from June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.cs rename to June-LeetCoding-Challenge/30-Word-Search-II/Word-Search-II.cs diff --git a/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.kt b/June-LeetCoding-Challenge/30-Word-Search-II/Word-Search-II.kt similarity index 100% rename from June-LeetCoding-Challenge/30-Word-Search-II/Word-Search.kt rename to June-LeetCoding-Challenge/30-Word-Search-II/Word-Search-II.kt From 308d32065ac9f2d0fba1ee07856ac11401182fbe Mon Sep 17 00:00:00 2001 From: Mincong HUANG Date: Sat, 25 Jul 2020 22:01:30 +0200 Subject: [PATCH 198/281] Update comment --- .github/scripts/check.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/scripts/check.sh b/.github/scripts/check.sh index cbde59a..e4c8482 100755 --- a/.github/scripts/check.sh +++ b/.github/scripts/check.sh @@ -1,9 +1,9 @@ #!/bin/bash # -# Check file naming convention of challenges. +# Check file naming convention of all the challenges. # # Usage: -# check.sh May-LeetCoding-Challenge +# check.sh # cd "$(dirname ${BASH_SOURCE})"/../.. From 6fc33395b4dcefc3052af1b8abd3966d5ef31cde Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 26 Jul 2020 11:45:04 +0200 Subject: [PATCH 199/281] Add Add Digits C# --- July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.cs | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.cs diff --git a/July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.cs b/July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.cs new file mode 100644 index 0000000..cfc43bd --- /dev/null +++ b/July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.cs @@ -0,0 +1,7 @@ +public class Solution { + public int AddDigits(int num) { + if(num == 0) return 0; + if(num % 9 == 0) return 9; + else return num % 9; + } +} \ No newline at end of file From 64b4d79303f997fbd4d06dba5d2f2fec7492e07f Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Sun, 26 Jul 2020 23:06:42 +0200 Subject: [PATCH 200/281] add kotlin solutions --- .../Angle-Between-Hands-of-a-Clock.kt | 35 ++++++ .../Reverse-Words-in-a-String.kt | 45 ++++++++ .../16-Pow(x,n)/Pow(x,n).kt | 31 ++++++ .../Top-K-Frequent-Elements.kt | 16 +++ .../Course-Schedule-II.kt | 75 +++++++++++++ .../19-Add-Binary/Add-Binary.kt | 61 +++++++++++ .../Remove-Linked-List-Elements.kt | 55 ++++++++++ .../21-Word-Search/Word-Search.kt | 102 ++++++++++++++++++ ...inary-Tree-Zigzag-Level-Order-Traversal.kt | 36 +++++++ .../23-Single-Number-III/Single-Number-III.kt | 18 ++++ .../All-Paths-From-Source-to-Target.kt | 44 ++++++++ ...Find-Minimum-in-Rotated-Sorted-Array-II.kt | 24 +++++ .../26-Add-Digits/Add-Digits.kt | 31 ++++++ 13 files changed, 573 insertions(+) create mode 100644 July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.kt create mode 100644 July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.kt create mode 100644 July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).kt create mode 100644 July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.kt create mode 100644 July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.kt create mode 100644 July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.kt create mode 100644 July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.kt create mode 100644 July-LeetCoding-Challenge/21-Word-Search/Word-Search.kt create mode 100644 July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.kt create mode 100644 July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.kt create mode 100644 July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.kt create mode 100644 July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.kt create mode 100644 July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.kt diff --git a/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.kt b/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.kt new file mode 100644 index 0000000..614ae40 --- /dev/null +++ b/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.kt @@ -0,0 +1,35 @@ +package string_integer + +import kotlin.math.abs + +class AngleBetweenHandsofaClockKotlin1344 { + fun angleClock(hour: Int, minutes: Int): Double { + val baseHour = when (hour) { + 12 -> 0 + else -> 30 * hour + } + val hourVal = minutes.toDouble() / 2 + baseHour + + val minutesVal = minutes.toDouble() * 6 + + val result = abs(hourVal - minutesVal) + + return if (result > 180) 360 - result else result + } +} + +fun main() { + val solution = AngleBetweenHandsofaClockKotlin1344() + // 165 + println(solution.angleClock(12, 30)) + // 75 + println(solution.angleClock(3, 30)) + // 7.5 + println(solution.angleClock(3, 15)) + // 155 + println(solution.angleClock(4, 50)) + // 0 + println(solution.angleClock(12, 0)) + // 76.5 + println(solution.angleClock(1, 57)) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.kt b/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.kt new file mode 100644 index 0000000..57bea8e --- /dev/null +++ b/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.kt @@ -0,0 +1,45 @@ +package string_integer + +class ReverseWordsinaStringKotlin151 { + fun reverseWords(s: String): String = + s.trim() + .split("\\s+".toRegex()) + .reversed() + .joinToString(separator = " ") + /* + fun reverseWords(s: String): String { + val list: MutableList = LinkedList() + var index = 0 + while (index < s.length) { + if (s[index] == ' ') { + ++index + } else { + val stringBuilder = StringBuilder() + while (index < s.length && s[index] != ' ') { + stringBuilder.append(s[index]) + ++index + } + list.add(stringBuilder.toString()) + } + } + val result = StringBuilder() + for (i in list.size - 1 downTo 0) { + result.append(list[i]) + if (i != 0){ + result.append(" ") + } + } + return result.toString() + } + */ +} + +fun main() { + val solution = ReverseWordsinaString151() + // blue is sky the + println(solution.reverseWords("the sky is blue")) + // world! hello + println(solution.reverseWords(" hello world! ")) + // example good a + println(solution.reverseWords("a good example")) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).kt b/July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).kt new file mode 100644 index 0000000..e18364d --- /dev/null +++ b/July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).kt @@ -0,0 +1,31 @@ +package binary_search + +class PowxnKotlin50 { + fun myPow(x: Double, n: Int): Double { + return when { + x == 0.0 -> 0.0 + n == 1 -> x + n == -1 -> 1 / x + n == 0 -> 1.0 + // Int.MIN_VALUE = Int.MAX_VALUE + 1 + n == Int.MIN_VALUE -> 1 / powLog(x, Int.MAX_VALUE) * x + n > 0 -> powLog(x, n) + n < 0 -> 1 / powLog(x, -n) + else -> -1.0 + } + } + + private fun powLog(x: Double, n: Int): Double = + when { + n == 1 -> x + n % 2 == 0 -> { + val result = powLog(x, n.shr(1)) + result * result + } + n % 2 == 1 -> { + val result = powLog(x, n.shr(1)) + result * result * x + } + else -> -1.0 + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.kt b/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.kt new file mode 100644 index 0000000..9093960 --- /dev/null +++ b/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.kt @@ -0,0 +1,16 @@ +package list_array + +class TopKFrequentElementsKotlin347 { + fun topKFrequent(nums: IntArray, k: Int): IntArray { + val map: MutableMap = HashMap() + nums.forEach { + map[it] = map.getOrDefault(it, 0) + 1 + } + return map + .toList() + .sortedByDescending(Pair::second) + .subList(0, k) + .map { it.first } + .toIntArray() + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.kt b/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.kt new file mode 100644 index 0000000..76fde3e --- /dev/null +++ b/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.kt @@ -0,0 +1,75 @@ +package graph + +class CourseScheduleKotlin207 { + fun canFinish(numCourses: Int, prerequisites: Array): Boolean { + // 1 true, -1 false, 0 not judge + val coursesArray = IntArray(numCourses) + val graph: MutableMap> = HashMap() + for (pre in prerequisites) { + graph.computeIfAbsent(pre[1]) { mutableListOf() }.add(pre[0]) + } + for (index in coursesArray.indices) { + if (!dfs(index, coursesArray, graph)) { + return false + } + } + return true + } + + // true -> can finish + private fun dfs( + current: Int, + coursesArray: IntArray, + graph: Map> + ): Boolean { + return when { + coursesArray[current] == -1 -> false + coursesArray[current] == 1 -> true + else -> { + coursesArray[current] = -1 + graph[current]?.forEach { + if (!dfs(it, coursesArray, graph)) { + return false + } + } + coursesArray[current] = 1 + true + } + } + } + /* + fun canFinish(numCourses: Int, prerequisites: Array): Boolean { + val coursesArray = IntArray(numCourses) + val graph: MutableMap> = HashMap() + for (pre in prerequisites) { + graph.computeIfAbsent(pre[1]) { mutableListOf() }.add(pre[0]) + ++coursesArray[pre[0]] + } + val queue: Queue = LinkedList() + coursesArray.forEachIndexed { index, i -> + if (i == 0) { + queue.offer(index) + } + } + while (queue.isNotEmpty()) { + val current = queue.poll() + graph[current]?.forEach { + if (--coursesArray[it] == 0) { + queue.offer(it) + } + } + } + return coursesArray.count { it == 0 } == numCourses + } + */ +} + +fun main() { + val solution = CourseScheduleKotlin207() + // true + println(solution.canFinish(2, arrayOf(intArrayOf(0, 1)))) + // false + println(solution.canFinish(2, arrayOf(intArrayOf(0, 1), intArrayOf(1, 0)))) + // true + println(solution.canFinish(3, arrayOf(intArrayOf(2, 1), intArrayOf(1, 0)))) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.kt b/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.kt new file mode 100644 index 0000000..a1d29c3 --- /dev/null +++ b/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.kt @@ -0,0 +1,61 @@ +package string_integer + +class AddBinaryKotlin67 { + fun addBinary(a: String, b: String): String { + if (a.length > b.length) { + return addBinary(b, a) + } + val diff = b.length - a.length + var next = 0 + val result = StringBuilder() + for (index in a.length - 1 downTo 0) { + val currentA = a[index].toString().toInt() + val currentB = b[index + diff].toString().toInt() + when (next + currentA + currentB) { + 0 -> result.append(0) + 1 -> { + result.append(1) + next = 0 + } + 2 -> { + result.append(0) + next = 1 + } + 3 -> { + result.append(1) + next = 1 + } + } + } + for (index in diff - 1 downTo 0) { + val currentB = b[index].toString().toInt() + when (currentB + next) { + 0 -> result.append(0) + 1 -> { + result.append(1) + next = 0 + } + 2 -> { + result.append(0) + next = 1 + } + } + } + if (next == 1) { + result.append(next) + } + return result.reverse().toString() + } +} + +fun main() { + val solution = AddBinaryKotlin67() + // 100 + println(solution.addBinary("11", "1")) + // 10101 + println(solution.addBinary("1010", "1011")) + // 1100 + println(solution.addBinary("1011", "1")) + // 1110 + println(solution.addBinary("1011", "11")) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.kt b/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.kt new file mode 100644 index 0000000..cb58b1b --- /dev/null +++ b/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.kt @@ -0,0 +1,55 @@ +package list_array + +class RemoveLinkedListElementsKotlin203 { + class ListNode(var `val`: Int) { + var next: ListNode? = null + } + + fun removeElements(head: ListNode?, `val`: Int): ListNode? { + if (head == null) { + return null + } + if (head.`val` == `val`) { + return removeElements(head.next, `val`) + } + head.next = removeElements(head.next, `val`) + return head + } + /* + fun removeElements(head: ListNode?, `val`: Int): ListNode? { + var current: ListNode? = head ?: return head + while (current != null && current.`val` == `val`) { + current = current.next + } + val result = current + var previous = current + current = current?.next + while (current != null) { + if (current.`val` == `val`) { + while (current != null && current.`val` == `val`) { + current = current.next + } + previous!!.next = current + } + previous = current + current = current?.next + } + return result + } + */ +} + +fun main() { + val solution = RemoveLinkedListElementsKotlin203() + val l1 = RemoveLinkedListElementsKotlin203.ListNode(1) + val l2 = RemoveLinkedListElementsKotlin203.ListNode(2) + val l22 = RemoveLinkedListElementsKotlin203.ListNode(2) + val l12 = RemoveLinkedListElementsKotlin203.ListNode(1) + + l1.next = l2 + l2.next = l22 + l22.next = l12 + + val result = solution.removeElements(l1, 2) + println(result) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/21-Word-Search/Word-Search.kt b/July-LeetCoding-Challenge/21-Word-Search/Word-Search.kt new file mode 100644 index 0000000..d103ca4 --- /dev/null +++ b/July-LeetCoding-Challenge/21-Word-Search/Word-Search.kt @@ -0,0 +1,102 @@ +package depth_first_search + +class WordSearchKotlin79 { + var result = false + + fun exist(board: Array, word: String): Boolean { + result = false + for (x in board.indices) { + for (y in board[0].indices) { + if (result) { + return true + } + if (board[x][y] == word[0]) { + dfs(board, x, y, word, 0) + } + } + } + return result + } + + private val deltaX = intArrayOf(0, 0, -1, 1) + private val deltaY = intArrayOf(-1, 1, 0, 0) + + private fun dfs(board: Array, x: Int, y: Int, word: String, current: Int) { + if (current == word.length - 1) { + result = true + return + } + val value = board[x][y] + board[x][y] = '*' + for (index in deltaX.indices) { + val nextX = x + deltaX[index] + val nextY = y + deltaY[index] + if (inBound(board, nextX, nextY) && board[nextX][nextY] == word[current + 1] && !result) { + dfs(board, nextX, nextY, word, current + 1) + } + } + board[x][y] = value + } + + private fun inBound( + grid: Array, + x: Int, + y: Int + ) = x >= 0 && y >= 0 && x < grid.size && y < grid[0].size + /* + fun exist(board: Array, word: String): Boolean { + for (x in board.indices) { + for (y in board[0].indices) { + if (board[x][y] == word[0]) { + if (dfs(board, x, y, word, 0)) { + return true + } + } + } + } + return false + } + + private val deltaX = intArrayOf(0, 0, -1, 1) + private val deltaY = intArrayOf(-1, 1, 0, 0) + + private fun dfs(board: Array, x: Int, y: Int, word: String, current: Int): Boolean { + if (current == word.length - 1) { + return true + } + val value = board[x][y] + board[x][y] = '*' + var result = false + for (index in deltaX.indices) { + val nextX = x + deltaX[index] + val nextY = y + deltaY[index] + if (inBound(board, nextX, nextY) && board[nextX][nextY] == word[current + 1] && !result) { + if (dfs(board, nextX, nextY, word, current + 1)) { + result = true + } + } + } + board[x][y] = value + return result + } + + private fun inBound( + grid: Array, + x: Int, + y: Int + ) = x >= 0 && y >= 0 && x < grid.size && y < grid[0].size + */ +} + +fun main() { + val test = arrayOf( + charArrayOf('A', 'B', 'C', 'E'), + charArrayOf('S', 'F', 'C', 'S'), + charArrayOf('A', 'D', 'E', 'E') + ) + val solution = WordSearchKotlin79() + // true true false + println(solution.exist(test, "ABCCED")) + println(solution.exist(test, "SEE")) + println(solution.exist(test, "ABCB")) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.kt b/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.kt new file mode 100644 index 0000000..d5efca2 --- /dev/null +++ b/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.kt @@ -0,0 +1,36 @@ +package breadth_first_search + +import java.util.* + +class BinaryTreeZigzagLevelOrderTraversalKotlin103 { + fun zigzagLevelOrder(root: TreeNode?): List> { + val result = mutableListOf>() + if (root == null) { + return result + } + val treeNodeQueue: Queue = LinkedList() + treeNodeQueue.offer(root) + var flag = false + while (treeNodeQueue.isNotEmpty()) { + val currentLevel = mutableListOf() + for (i in 0 until treeNodeQueue.size) { + val current = treeNodeQueue.poll() + if (flag) { + currentLevel.add(0, current.`val`) + } else { + currentLevel.add(current.`val`) + } + current.left?.let { treeNodeQueue.offer(it) } + current.right?.let { treeNodeQueue.offer(it) } + } + result.add(currentLevel) + flag = !flag + } + return result + } + + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.kt b/July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.kt new file mode 100644 index 0000000..68a29b0 --- /dev/null +++ b/July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.kt @@ -0,0 +1,18 @@ +package string_integer + +class SingleNumberIIIKotlin260 { + fun singleNumber(nums: IntArray): IntArray { + var flag = nums.reduce { acc, i -> acc.xor(i) } + flag = flag.and(-flag) + var r1 = 0 + var r2 = 0 + nums.forEach { + if (it.and(flag) == 0) { + r1 = r1.xor(it) + } else { + r2 = r2.xor(it) + } + } + return intArrayOf(r1, r2) + } +} diff --git a/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.kt b/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.kt new file mode 100644 index 0000000..db96359 --- /dev/null +++ b/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.kt @@ -0,0 +1,44 @@ +package depth_first_search + +import java.util.* +import kotlin.collections.ArrayList + +class AllPathsFromSourcetoTargetKotlin797 { + fun allPathsSourceTarget(graph: Array): List> { + val result: MutableList> = LinkedList() + val subsets: MutableList = LinkedList() + + dfs(result, subsets, graph, 0) + return result + } + + private fun dfs( + result: MutableList>, + subsets: MutableList, + graph: Array, + index: Int + ) { + subsets.add(index) + if (graph[index].isEmpty()) { + result.add(ArrayList(subsets)) + } else { + graph[index].forEach { + dfs(result, subsets, graph, it) + subsets.removeAt(subsets.size - 1) + } + } + } +} + +fun main() { + val solution = AllPathsFromSourcetoTargetKotlin797() + val result = solution.allPathsSourceTarget( + arrayOf( + intArrayOf(1, 2), + intArrayOf(3), + intArrayOf(3), + intArrayOf() + ) + ) + println(result) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.kt b/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.kt new file mode 100644 index 0000000..a174855 --- /dev/null +++ b/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.kt @@ -0,0 +1,24 @@ +package binary_search + +class FindMinimuminRotatedSortedArrayKotlin153 { + fun findMin(nums: IntArray): Int { + var left = 0 + var right = nums.size - 1 + while (left + 1 < right) { + val mid = left + (right - left) / 2 + when { + nums[mid] >= nums[0] -> { + if (nums[mid] < nums[nums.size - 1]) { + return nums[0] + } else { + left = mid + } + } + nums[mid] <= nums[nums.size - 1] -> { + right = mid + } + } + } + return minOf(nums[left], nums[right]) + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.kt b/July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.kt new file mode 100644 index 0000000..50a5adb --- /dev/null +++ b/July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.kt @@ -0,0 +1,31 @@ +package string_integer + +class AddDigitsKotlin258 { + fun addDigits(num: Int): Int = + if (num == 0) 0 else 1 + (num - 1) % 9 + + /* + fun addDigits(num: Int): Int { + return when { + num == 0 -> 0 + num % 9 == 0 -> 9 + else -> num % 9 + } + } + */ + /* + fun addDigits(num: Int): Int { + var result = 0 + var current = num + while (current != 0) { + result += current % 10 + current /= 10 + if (current == 0 && result > 9) { + current = result + result = 0 + } + } + return result + } + */ +} \ No newline at end of file From 50b0633fa88ff9ace028266086618aad12b2fc16 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 27 Jul 2020 21:48:58 +0200 Subject: [PATCH 201/281] Add Construct Binary Tree from Inorder and Postorder Traversal C# --- ...ee-from-Inorder-and-Postorder-Traversal.cs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.cs diff --git a/July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.cs b/July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.cs new file mode 100644 index 0000000..6ce0aea --- /dev/null +++ b/July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.cs @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public TreeNode BuildTree(int[] inorder, int[] postorder) { + if(inorder == null || postorder == null || inorder.Length != postorder.Length) return null; + var dict = new Dictionary(); + for(int i=0; i dict) + { + if(pb>pe || ib>ie) return null; + var root = new TreeNode(postorder[pe]); + var rootIdx = dict[postorder[pe]]; + var left = BuildTree(inorder, ib, rootIdx-1, postorder, pb, pb+rootIdx-ib-1, dict); + var right = BuildTree(inorder, rootIdx+1, ie, postorder, pb+rootIdx-ib, pe-1, dict); + root.left = left; + root.right = right; + return root; + } +} \ No newline at end of file From 75df90f3ff53b732d24b804b7f40c9bec3773f1a Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 27 Jul 2020 21:53:28 +0200 Subject: [PATCH 202/281] update readme --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index b9cec4f..a364b72 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,12 @@ Solutions in various programming languages are provided. Enjoy it. 19. [Add Binary](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/19-Add-Binary) 20. [Remove Linked List Elements](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements) 21. [Word Search](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/21-Word-Search) +22. [Binary Tree Zigzag Level Order Traversal](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal) +23. [Single Number III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/23-Single-Number-III) +24. [All Paths From Source to Target](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target) +25. [Find Minimum in Rotated Sorted Array II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II) +26. [Add Digits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/26-Add-Digits) +27. [Construct Binary Tree from Inorder and Postorder Traversal](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal) ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From 965ec1e02282ebab01b917202f74020bdc28e38e Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 28 Jul 2020 19:25:30 +0200 Subject: [PATCH 203/281] Add Task Scheduler C# --- .../28-Task-Scheduler/Task-Scheduler.cs | 29 +++++++++++++++++++ README.md | 1 + 2 files changed, 30 insertions(+) create mode 100644 July-LeetCoding-Challenge/28-Task-Scheduler/Task-Scheduler.cs diff --git a/July-LeetCoding-Challenge/28-Task-Scheduler/Task-Scheduler.cs b/July-LeetCoding-Challenge/28-Task-Scheduler/Task-Scheduler.cs new file mode 100644 index 0000000..ab726ea --- /dev/null +++ b/July-LeetCoding-Challenge/28-Task-Scheduler/Task-Scheduler.cs @@ -0,0 +1,29 @@ +public class Solution { + public int LeastInterval(char[] tasks, int n) { + var counter = new int[26]; + //The maximum frequency of all chars + var maxFrequency = 0; + //The number of char which have the maximum frequency + var numberOfCharsWithMaxFrequency = 0; + foreach(char c in tasks){ + counter[c - 'A']++; + if(maxFrequency == counter[c - 'A']){ + numberOfCharsWithMaxFrequency++; + }else if(maxFrequency < counter[c - 'A']){ + maxFrequency = counter[c - 'A']; + numberOfCharsWithMaxFrequency = 1; + } + } + + //Number of parts splitted by maximum frequencied char + var numberOfParts = maxFrequency - 1; + //Length of splitted part, it could be maximum = n, minumum = 0 + var partLength = n - (numberOfCharsWithMaxFrequency - 1); + //Total empty slots between maximum frenquent chars + var emptySlots = numberOfParts * partLength; + var availableChars = tasks.Length - maxFrequency * numberOfCharsWithMaxFrequency; + var idles = Math.Max(0, emptySlots - availableChars); + + return tasks.Length + idles; + } +} diff --git a/README.md b/README.md index a364b72..35e8064 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ Solutions in various programming languages are provided. Enjoy it. 25. [Find Minimum in Rotated Sorted Array II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II) 26. [Add Digits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/26-Add-Digits) 27. [Construct Binary Tree from Inorder and Postorder Traversal](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal) +28. [Task Scheduler](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/28-Task-Scheduler) ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From 574257e053db1403f7ce76c0c047b77022d3f50c Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 29 Jul 2020 19:09:13 +0200 Subject: [PATCH 204/281] Add Best Time to Buy and Sell Stock with Cooldown C# --- ...Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.cs | 13 +++++++++++++ README.md | 2 ++ 2 files changed, 15 insertions(+) create mode 100644 July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.cs diff --git a/July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.cs b/July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.cs new file mode 100644 index 0000000..8911a58 --- /dev/null +++ b/July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.cs @@ -0,0 +1,13 @@ +public class Solution { + public int MaxProfit(int[] prices) { + int sold = 0, hold = Int32.MinValue, rest = 0; + for (int i=0; i Date: Wed, 29 Jul 2020 19:09:31 +0200 Subject: [PATCH 205/281] update --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc0ac73..caa945e 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ Solutions in various programming languages are provided. Enjoy it. 26. [Add Digits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/26-Add-Digits) 27. [Construct Binary Tree from Inorder and Postorder Traversal](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal) 28. [Task Scheduler](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/28-Task-Scheduler) -29. [Best Time to Buy and Sell Stock with Cooldown](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown) +29. [Best Time to Buy and Sell Stock with Cooldown](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown): State machine ## June LeetCoding Challenge From a00b2964d9a9dfba10ebbcc6555806f95a614062 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Thu, 30 Jul 2020 20:00:54 +0200 Subject: [PATCH 206/281] Add Word Break II C# --- .../30-Word-Break-II/Word-Break-II.cs | 26 +++++++++++++++++++ README.md | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 July-LeetCoding-Challenge/30-Word-Break-II/Word-Break-II.cs diff --git a/July-LeetCoding-Challenge/30-Word-Break-II/Word-Break-II.cs b/July-LeetCoding-Challenge/30-Word-Break-II/Word-Break-II.cs new file mode 100644 index 0000000..a998c45 --- /dev/null +++ b/July-LeetCoding-Challenge/30-Word-Break-II/Word-Break-II.cs @@ -0,0 +1,26 @@ +public class Solution { + private Dictionary> dict = new Dictionary>(); + public IList WordBreak(string s, IList wordDict) { + if(dict.ContainsKey(s)){ + return dict[s]; + } + + var res = new List(); + if(s.Length == 0){ + res.Add(""); + return res; + } + + foreach(var word in wordDict){ + if(s.StartsWith(word)){ + var subList = WordBreak(s.Substring(word.Length), wordDict); + foreach(var sub in subList){ + res.Add(word + (String.IsNullOrEmpty(sub) ? "" : " ") + sub); + } + } + } + + dict.Add(s, res); + return res; + } +} \ No newline at end of file diff --git a/README.md b/README.md index caa945e..ade253e 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Solutions in various programming languages are provided. Enjoy it. 27. [Construct Binary Tree from Inorder and Postorder Traversal](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal) 28. [Task Scheduler](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/28-Task-Scheduler) 29. [Best Time to Buy and Sell Stock with Cooldown](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown): State machine - +30. [Word Break II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/30-Word-Break-II) ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From 574dcdca088407c0ec21478e1a2d4f0cae346a00 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 31 Jul 2020 19:02:37 +0200 Subject: [PATCH 207/281] Add Climbing Stairs C# --- .../31-Climbing-Stairs/Climbing-Stairs.cs | 16 ++++++++++++++++ README.md | 2 ++ 2 files changed, 18 insertions(+) create mode 100644 July-LeetCoding-Challenge/31-Climbing-Stairs/Climbing-Stairs.cs diff --git a/July-LeetCoding-Challenge/31-Climbing-Stairs/Climbing-Stairs.cs b/July-LeetCoding-Challenge/31-Climbing-Stairs/Climbing-Stairs.cs new file mode 100644 index 0000000..22c0abf --- /dev/null +++ b/July-LeetCoding-Challenge/31-Climbing-Stairs/Climbing-Stairs.cs @@ -0,0 +1,16 @@ +public class Solution { + public int ClimbStairs(int n) { + if(n == 0) return 0; + if(n == 1) return 1; + if(n == 2) return 2; + + var dp = new int[n+1]; + dp[0] = 0; + dp[1] = 1; + dp[2] = 2; + for(int i=3; i<=n; i++){ + dp[i] = dp[i-1] + dp[i-2]; + } + return dp[n]; + } +} diff --git a/README.md b/README.md index ade253e..0a40d22 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,8 @@ Solutions in various programming languages are provided. Enjoy it. 28. [Task Scheduler](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/28-Task-Scheduler) 29. [Best Time to Buy and Sell Stock with Cooldown](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown): State machine 30. [Word Break II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/30-Word-Break-II) +31. [Climbing Stairs](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/31-Climbing-Stairs): DP + ## June LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions. From 3663329ed5e91e954698f09b31971b5d5af896b0 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sat, 1 Aug 2020 14:01:17 +0200 Subject: [PATCH 208/281] Add Detect Capital C# --- .../01-Detect-Capital/Detect-Capital.cs | 22 +++++++++++++++++++ README.md | 8 +++++++ 2 files changed, 30 insertions(+) create mode 100644 August-LeetCoding-Challenge/01-Detect-Capital/Detect-Capital.cs diff --git a/August-LeetCoding-Challenge/01-Detect-Capital/Detect-Capital.cs b/August-LeetCoding-Challenge/01-Detect-Capital/Detect-Capital.cs new file mode 100644 index 0000000..a22cd38 --- /dev/null +++ b/August-LeetCoding-Challenge/01-Detect-Capital/Detect-Capital.cs @@ -0,0 +1,22 @@ +public class Solution { + + //Solution 1: + public bool DetectCapitalUse(string word) { + int count = 0; + foreach(char c in word){ + if('Z' - c >= 0) count++; + } + //Count == 0 means all characters are lower case. + //Count == word.Length mean all characters are upper case + //Count == 1 && 'Z' - word[0] >=0 means only first character is upper case + return (count == 0) || (count == word.Length) + || (count == 1 && 'Z' - word[0] >=0); + } + + //Solution 2 + public bool DetectCapitalUse(string word) { + return Char.IsUpper(word[0]) + ? word.Substring(1).Equals(word.Substring(1).ToUpper()) || word.Substring(1).Equals(word.Substring(1).ToLower()) + : word.Substring(1).Equals(word.Substring(1).ToLower()); + } +} \ No newline at end of file diff --git a/README.md b/README.md index 0a40d22..6defbaf 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,14 @@ https://leetcode.com + +## August LeetCoding Challenge +Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. + +Solutions in various programming languages are provided. Enjoy it. + +1. [Detect Capital](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/01-Detect-Capital) + ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 7bc7d8911aaf8da8334611dc71bb57d3d7b17dbb Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 2 Aug 2020 15:26:29 +0200 Subject: [PATCH 209/281] Add Design HashSet C# --- .../02-Design-HashSet/Design-HashSet.cs | 71 +++++++++++++++++++ README.md | 1 + 2 files changed, 72 insertions(+) create mode 100644 August-LeetCoding-Challenge/02-Design-HashSet/Design-HashSet.cs diff --git a/August-LeetCoding-Challenge/02-Design-HashSet/Design-HashSet.cs b/August-LeetCoding-Challenge/02-Design-HashSet/Design-HashSet.cs new file mode 100644 index 0000000..230e2ca --- /dev/null +++ b/August-LeetCoding-Challenge/02-Design-HashSet/Design-HashSet.cs @@ -0,0 +1,71 @@ +public class MyHashSet { + + private List[] bucket; + private int capacity; + private int count = 0; + private double loadFactor = 0.75; + + /** Initialize your data structure here. */ + public MyHashSet() { + capacity = 1000; + bucket = new List[capacity]; + } + + public void Add(int key) { + if(Contains(key)){ + return; + } + + if(loadFactor * 2 == count){ + count = 0; + capacity *= 2; + var oldBucket = bucket; + bucket = new List[capacity]; + for(int i=0; i0){ + foreach(var item in list) + Add(item); + } + } + } + + var hash = key % capacity; + if(bucket[hash] == null) bucket[hash] = new List(); + bucket[hash].Add(key); + count++; + } + + public void Remove(int key) { + var hash = key % capacity; + var list = bucket[hash]; + if(list != null && list.Count > 0){ + for(int i=0; i 0){ + foreach(var item in list){ + if(item == key) return true; + } + } + return false; + } +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * MyHashSet obj = new MyHashSet(); + * obj.Add(key); + * obj.Remove(key); + * bool param_3 = obj.Contains(key); + */ \ No newline at end of file diff --git a/README.md b/README.md index 6defbaf..49d7088 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-chall Solutions in various programming languages are provided. Enjoy it. 1. [Detect Capital](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/01-Detect-Capital) +2. [Design HashSet](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/02-Design-HashSet) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From f2a34da40d8611b632f91b743b7659c6a4f12ab5 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 3 Aug 2020 17:24:47 +0200 Subject: [PATCH 210/281] Qdd Valid Palindrome C# --- .../03-Valid-Palindrome/Valid-Palindrome.cs | 20 +++++++++++++++++++ README.md | 2 +- 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 August-LeetCoding-Challenge/03-Valid-Palindrome/Valid-Palindrome.cs diff --git a/August-LeetCoding-Challenge/03-Valid-Palindrome/Valid-Palindrome.cs b/August-LeetCoding-Challenge/03-Valid-Palindrome/Valid-Palindrome.cs new file mode 100644 index 0000000..01a12ba --- /dev/null +++ b/August-LeetCoding-Challenge/03-Valid-Palindrome/Valid-Palindrome.cs @@ -0,0 +1,20 @@ +public class Solution { + public bool IsPalindrome(string s) { + int begin = 0; + int end = s.Length-1; + while(begin <= end){ + while(begin<=end && !Char.IsLetterOrDigit(s[begin])){ + begin++; + } + while(begin<=end && !Char.IsLetterOrDigit(s[end])){ + end--; + } + if(begin<=end && Char.ToLower(s[begin]) != Char.ToLower(s[end])){ + return false; + } + begin++; + end--; + } + return true; + } +} diff --git a/README.md b/README.md index 49d7088..0c945c4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,6 @@ https://leetcode.com - ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. @@ -10,6 +9,7 @@ Solutions in various programming languages are provided. Enjoy it. 1. [Detect Capital](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/01-Detect-Capital) 2. [Design HashSet](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/02-Design-HashSet) +3. [Valid Palindrome](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/03-Valid-Palindrome) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 1bd47da697ccd5d2cd5d145299fa0a9cd5f16c1d Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 4 Aug 2020 17:44:52 +0200 Subject: [PATCH 211/281] Add Power of Four C# --- .../04-Power-of-Four/Power-of-Four.cs | 20 +++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 August-LeetCoding-Challenge/04-Power-of-Four/Power-of-Four.cs diff --git a/August-LeetCoding-Challenge/04-Power-of-Four/Power-of-Four.cs b/August-LeetCoding-Challenge/04-Power-of-Four/Power-of-Four.cs new file mode 100644 index 0000000..32715cb --- /dev/null +++ b/August-LeetCoding-Challenge/04-Power-of-Four/Power-of-Four.cs @@ -0,0 +1,20 @@ +public class Solution { + //Solution 1 + public bool IsPowerOfFour(int num) { + if(num > 1) + { + while(num % 4 == 0){ + num /= 4; + } + } + return num == 1; + } + + //Solution 2 + public bool IsPowerOfFour(int num) { + //0x55555555 (hex) means 0101 0101 0101 0101 0101 0101 0101 0101 (binary) + return (num > 0) + && (num & (num-1)) == 0 + && ((num & 0x55555555) != 0); + } +} \ No newline at end of file diff --git a/README.md b/README.md index 0c945c4..efeebd8 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Solutions in various programming languages are provided. Enjoy it. 1. [Detect Capital](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/01-Detect-Capital) 2. [Design HashSet](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/02-Design-HashSet) 3. [Valid Palindrome](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/03-Valid-Palindrome) +4. [Power of Four](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/04-Power-of-Four) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From f52c43f8ceb78df6fa40108a224f86acbf0cbc22 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Wed, 5 Aug 2020 09:14:09 +0200 Subject: [PATCH 212/281] Create Add-and-Search-Word-Data-structure-design.cpp --- ...-and-Search-Word-Data-structure-design.cpp | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.cpp diff --git a/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.cpp b/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.cpp new file mode 100644 index 0000000..e9fe5df --- /dev/null +++ b/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.cpp @@ -0,0 +1,112 @@ +#define ALPHABET_SIZE 26 +class Trie { +public: + bool isEnd; + unique_ptr links[ALPHABET_SIZE]; + /** Initialize your data structure here. */ + Trie() { + this->isEnd = false; + } + + bool containsChar(char ch) { + return links[ch - 'a'] != nullptr; + } + void put(char ch, Trie* newt) { + links[ch - 'a'].reset(newt); + } + + Trie* get(char ch) { + return links[ch - 'a'].get(); + } + + /** Inserts a word into the trie. */ + void insert(string word) { + // start from root node + Trie* root = this; + for (int i = 0; i < word.length(); i++) { + // create a new node if path doesn't exists + if (!root->containsChar(word[i])) { + root->put(word[i], new Trie()); + } + root = root->get(word[i]); + } + // make current node as a keyword + root->isEnd = true; + } + + /** Returns if the word is in the trie. */ + bool search(string word) { + if (this == nullptr) + return false; + Trie* root = this; + for (int i = 0; i < word.length(); i++) { + root = root->get(word[i]); + if (root == nullptr) + return false; + } + return root->isEnd; + } + + /** Returns if there is any word in the trie that starts with the given prefix. */ + bool startsWith(string prefix) { + if (this == nullptr) + return false; + Trie* root = this; + int i = 0; + for (; i < prefix.length(); i++) { + root = root->get(prefix[i]); + if (root == nullptr) + return false; + } + return i == prefix.length(); + } + + ~Trie(){} +}; + +class WordDictionary { +public: + unique_ptr t; + /** Initialize your data structure here. */ + WordDictionary() { + t.reset(new Trie()); + } + + /** Adds a word into the data structure. */ + void addWord(string word) { + t->insert(word); + } + + /** 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 searchUtil(t.get(), word, 0); + } + + bool searchUtil(Trie* t, const string& word, int index) { + if (!t) + return false; + if (index == word.length()) + return t->isEnd; + char c = word[index]; + if (c == '.') { + for (int i = 0; i < ALPHABET_SIZE; i++) { + if (searchUtil(t->get('a' + i), word, index + 1)) + return true; + } + } + else { + return searchUtil(t->get(c), word, index + 1); + } + return false; + } + + ~WordDictionary(){} +}; + + +/** + * Your WordDictionary object will be instantiated and called as such: + * WordDictionary* obj = new WordDictionary(); + * obj->addWord(word); + * bool param_2 = obj->search(word); + */ From c4095ed55c4b348e8d12d89340f3aa66235dc819 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 5 Aug 2020 20:09:28 +0200 Subject: [PATCH 213/281] Add Add and Search Word Data structure design C# --- ...d-and-Search-Word-Data-structure-design.cs | 53 +++++++++++++++++++ README.md | 1 + 2 files changed, 54 insertions(+) create mode 100644 August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.cs diff --git a/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.cs b/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.cs new file mode 100644 index 0000000..0f5fef9 --- /dev/null +++ b/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.cs @@ -0,0 +1,53 @@ +public class WordDictionary { + + private TrieNode _root; + + /** Initialize your data structure here. */ + public WordDictionary() { + _root = new TrieNode(); + } + + /** Adds a word into the data structure. */ + public void AddWord(string word) { + var node = _root; + foreach(char c in word){ + if(node.Children[c - 'a'] == null){ + node.Children[c - 'a'] = new TrieNode(); + } + node = node.Children[c - 'a']; + } + node.IsWord = true; + } + + /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ + public bool Search(string word) { + return Match(word.ToCharArray(), 0, _root); + } + + private bool Match(char[] arr, int i, TrieNode node){ + if(i == arr.Length) return node.IsWord; + + if(arr[i] == '.'){ + for(int j=0; j Date: Thu, 6 Aug 2020 19:42:50 +0200 Subject: [PATCH 214/281] Add Find All Duplicates in an Array C# --- .../Find-All-Duplicates-in-an-Array.cs | 13 +++++++++++++ README.md | 1 + 2 files changed, 14 insertions(+) create mode 100644 August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array/Find-All-Duplicates-in-an-Array.cs diff --git a/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array/Find-All-Duplicates-in-an-Array.cs b/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array/Find-All-Duplicates-in-an-Array.cs new file mode 100644 index 0000000..00d1af1 --- /dev/null +++ b/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array/Find-All-Duplicates-in-an-Array.cs @@ -0,0 +1,13 @@ +public class Solution { + public IList FindDuplicates(int[] nums) { + var res = new List(); + for(int i = 0; i Date: Fri, 7 Aug 2020 20:16:39 +0200 Subject: [PATCH 215/281] Add Vertical Order Traversal of a Binary Tree C# --- ...rtical-Order-Traversal-of-a-Binary-Tree.cs | 60 +++++++++++++++++++ README.md | 1 + 2 files changed, 61 insertions(+) create mode 100644 August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree/Vertical-Order-Traversal-of-a-Binary-Tree.cs diff --git a/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree/Vertical-Order-Traversal-of-a-Binary-Tree.cs b/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree/Vertical-Order-Traversal-of-a-Binary-Tree.cs new file mode 100644 index 0000000..e11a88a --- /dev/null +++ b/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree/Vertical-Order-Traversal-of-a-Binary-Tree.cs @@ -0,0 +1,60 @@ +public class Solution { + private int _minX = int.MaxValue; + private int _maxX = int.MinValue; + private int _minY = int.MaxValue; + private int _maxY = int.MinValue; + + public IList> VerticalTraversal(TreeNode root) { + var dict = new Dictionary>(); + Dfs(root, dict, 0, 0); + IList> res = new List>(); + for(int i=_minX; i<=_maxX; i++){ + var listY = new List(); + for(int j=_maxY; j>=_minY; j--){ + var pos = i.ToString() + j.ToString(); + if(dict.ContainsKey(pos)){ + var list = dict[pos]; + listY.AddRange(list); + } + } + if(listY.Count > 0){ + res.Add(listY); + } + } + return res; + } + + private void Dfs(TreeNode root, Dictionary> dict, int x, int y){ + if(root == null) return; + var pos = x.ToString() + y.ToString(); + if(dict.ContainsKey(pos)){ + var list = dict[pos]; + list.Add(root.val); + list.Sort(); + dict[pos]=list; + }else { + dict[pos] = new List{ root.val}; + } + + _minX = Math.Min(_minX, x); + _maxX = Math.Max(_maxX, x); + _minY = Math.Min(_minY, y); + _maxY = Math.Max(_maxY, y); + Dfs(root.left, dict, x-1, y-1); + Dfs(root.right, dict, x+1, y-1); + } +} + +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ \ No newline at end of file diff --git a/README.md b/README.md index 3f49843..58227e7 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Solutions in various programming languages are provided. Enjoy it. 4. [Power of Four](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/04-Power-of-Four) 5. [Add and Search Word Data structure design](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design) 6. [Find All Duplicates in an Array](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array) +7. [Vertical Order Traversal of a Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 725a5a5c66501db015c9759f9482edd0f52032df Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Sat, 8 Aug 2020 12:07:18 +0200 Subject: [PATCH 216/281] Create Path-Sum-III.cpp --- .../08-Path-Sum-III/Path-Sum-III.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.cpp diff --git a/August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.cpp b/August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.cpp new file mode 100644 index 0000000..2fa6267 --- /dev/null +++ b/August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int cpt = 0; + int pathSum(TreeNode* root, int sum) { + recur(root, sum); + return cpt; + } + void recur(TreeNode* root, int sum, bool isConsecutive = false){ + if(!root) return; + if(sum == root->val) ++cpt; + recur(root->left, sum - root->val, true); + recur(root->right, sum - root->val, true); + if(!isConsecutive){ + recur(root->left, sum, false); + recur(root->right, sum, false); + } + } +}; From e488fbdb8e11985dd867a487a92b6fd0933ea531 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sat, 8 Aug 2020 19:35:01 +0200 Subject: [PATCH 217/281] Add Path Sum III C# --- .../08-Path-Sum-III/Path-Sum-III.cs | 42 +++++++++++++++++++ README.md | 1 + 2 files changed, 43 insertions(+) create mode 100644 August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.cs diff --git a/August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.cs b/August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.cs new file mode 100644 index 0000000..d103482 --- /dev/null +++ b/August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.cs @@ -0,0 +1,42 @@ +public class Solution { + public int PathSum(TreeNode root, int sum) { + if (root == null) { + return 0; + } + var map = new Dictionary(); + map[0] = 1; + return Dfs(root, 0, sum, map); + } + + private int Dfs(TreeNode curr, int sum, int target, Dictionary map) { + if (curr == null) { + return 0; + } + // update the prefix sum by adding the current val + sum += curr.val; + // get the number of valid path, ended by the current node + int numPathToCurr = map.ContainsKey(sum-target) ? map[sum-target] : 0; + // update the map with the current sum, so the map is good to be passed to the next recursion + map[sum] = (map.ContainsKey(sum) ? map[sum] : 0) + 1; + // add the 3 parts discussed in 8. together + int res = numPathToCurr + Dfs(curr.left, sum, target, map) + + Dfs(curr.right, sum, target, map); + // restore the map, as the recursion goes from the bottom to the top + map[sum] -= 1; + return res; + } +} + +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ \ No newline at end of file diff --git a/README.md b/README.md index 58227e7..8f45365 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Solutions in various programming languages are provided. Enjoy it. 5. [Add and Search Word Data structure design](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design) 6. [Find All Duplicates in an Array](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array) 7. [Vertical Order Traversal of a Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree) +8. [Path Sum III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/08-Path-Sum-III) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 15fa85d33d977bd15e9df2ed2522ca59c06f7854 Mon Sep 17 00:00:00 2001 From: FZ YUAN <42092999+FZYUAN-1@users.noreply.github.com> Date: Sun, 9 Aug 2020 11:09:49 +0200 Subject: [PATCH 218/281] Create Rotting-Oranges.cpp --- .../09-Rotting-Oranges/Rotting-Oranges.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.cpp diff --git a/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.cpp b/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.cpp new file mode 100644 index 0000000..9a53803 --- /dev/null +++ b/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.cpp @@ -0,0 +1,36 @@ + +const int dx[4] = { -1, 0, 1, 0 }; +const int dy[4] = { 0, -1, 0, 1 }; +typedef pair ip; +class Solution { +public: + int orangesRotting(vector>& grid) { + const int m=grid.size(), n=grid[0].size(); + unordered_set freshes; + queue rottens; + int r=0; + for(int i=0; i=0 && toy>=0 && tox Date: Sun, 9 Aug 2020 12:34:08 +0200 Subject: [PATCH 219/281] Add Rotting Oranges C# --- .../09-Rotting-Oranges/Rotting-Oranges.cs | 41 +++++++++++++++++++ README.md | 1 + 2 files changed, 42 insertions(+) create mode 100644 August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.cs diff --git a/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.cs b/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.cs new file mode 100644 index 0000000..42c0af3 --- /dev/null +++ b/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.cs @@ -0,0 +1,41 @@ +public class Solution { + public int OrangesRotting(int[][] grid) { + if(grid == null || grid.Length == 0) return 0; + var rows = grid.Length; + var cols = grid[0].Length; + var count_fresh = 0; + Queue queue = new Queue(); + //Push rotten oranges in the queue, count fresh oranges + for(int i=0; i 0){ + count++; + var size = queue.Count; + for(int i=0; i=rows || y>=cols || grid[x][y] == 0 || grid[x][y] == 2) continue; + + grid[x][y] =2; + queue.Enqueue(new int[2]{x, y}); + count_fresh--; + } + } + } + return count_fresh == 0 ? count-1 : -1; + } +} diff --git a/README.md b/README.md index 8f45365..1287ad8 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ Solutions in various programming languages are provided. Enjoy it. 6. [Find All Duplicates in an Array](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array) 7. [Vertical Order Traversal of a Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree) 8. [Path Sum III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/08-Path-Sum-III) +9. [Rotting Oranges](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/09-Rotting-Oranges) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 9d926b265ced9354babe2d7cd10b6093b048924e Mon Sep 17 00:00:00 2001 From: zijian Date: Mon, 10 Aug 2020 09:20:01 +0200 Subject: [PATCH 220/281] Add Solution Python for Rotting orange --- .../09-Rotting-Oranges/Rotting-Oranges.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.py diff --git a/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.py b/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.py new file mode 100644 index 0000000..7145089 --- /dev/null +++ b/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.py @@ -0,0 +1,44 @@ +class Solution: + + def __init__(self): + self.res = 0 + + def orangesRotting(self, grid: List[List[int]]) -> int: + q = [] + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j]==2: + q.append([i,j]) + self.bfs(grid,q) + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j]==1: + return -1 + return self.res + + def bfs(self,grid,q): + while q!=[]: + l = [] + while q!=[]: + l.append(q.pop(0)) + for tmp in l: + a,b = tmp[0],tmp[1] + length = len(q) + if a+1=0: + if grid[a-1][b]==1: + grid[a-1][b]=2 + q.append([a-1,b]) + if b+1=0: + if grid[a][b-1]==1: + grid[a][b-1]=2 + q.append([a,b-1]) + if len(q) > 0: + self.res+=1 From 1e75031cb47ce118d72544ba2d7151b6087a9382 Mon Sep 17 00:00:00 2001 From: zijian Date: Mon, 10 Aug 2020 09:58:49 +0200 Subject: [PATCH 221/281] Create Exercice 10 and Add Solution JavaScript --- .../Excel_Sheet_Column_Number.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/Excel_Sheet_Column_Number.js diff --git a/August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/Excel_Sheet_Column_Number.js b/August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/Excel_Sheet_Column_Number.js new file mode 100644 index 0000000..78ce8f2 --- /dev/null +++ b/August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/Excel_Sheet_Column_Number.js @@ -0,0 +1,13 @@ +/** + * @param {string} s + * @return {number} + */ +var titleToNumber = function(s) { + var somme = 0; + var digit = 1; + for(let i = s.length - 1;i >= 0;i--){ + somme += (s.charCodeAt(i) - 64) * Math.pow(26,digit-1); + digit++; + } + return somme; +}; From d96992f07dedfcfa49e824207999697bdd1a419a Mon Sep 17 00:00:00 2001 From: zijian Date: Mon, 10 Aug 2020 12:51:01 +0200 Subject: [PATCH 222/281] Add Solution JavaScript --- ...{Excel_Sheet_Column_Number.js => Excel-Sheet-Column-Number.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/{Excel_Sheet_Column_Number.js => Excel-Sheet-Column-Number.js} (100%) diff --git a/August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/Excel_Sheet_Column_Number.js b/August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/Excel-Sheet-Column-Number.js similarity index 100% rename from August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/Excel_Sheet_Column_Number.js rename to August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/Excel-Sheet-Column-Number.js From 0d1e40a1500259c3233e00839900c932ee9fd93b Mon Sep 17 00:00:00 2001 From: zijian Date: Mon, 10 Aug 2020 12:54:18 +0200 Subject: [PATCH 223/281] Add Solution JavaScript --- .../Excel-Sheet-Column-Number.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename August-LeetCoding-Challenge/{10-Excel-Sheet-Solumn-Number => 10-Excel-Sheet-Column-Number}/Excel-Sheet-Column-Number.js (100%) diff --git a/August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/Excel-Sheet-Column-Number.js b/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number/Excel-Sheet-Column-Number.js similarity index 100% rename from August-LeetCoding-Challenge/10-Excel-Sheet-Solumn-Number/Excel-Sheet-Column-Number.js rename to August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number/Excel-Sheet-Column-Number.js From 64afd774af5ed92ddaec503c2d201a742622cf15 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 10 Aug 2020 21:12:08 +0200 Subject: [PATCH 224/281] Add Excel Sheet Column Number C# --- .../Excel-Sheet-Column-Number.cs | 10 ++++++++++ README.md | 1 + 2 files changed, 11 insertions(+) create mode 100644 August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number/Excel-Sheet-Column-Number.cs diff --git a/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number/Excel-Sheet-Column-Number.cs b/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number/Excel-Sheet-Column-Number.cs new file mode 100644 index 0000000..666b1b7 --- /dev/null +++ b/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number/Excel-Sheet-Column-Number.cs @@ -0,0 +1,10 @@ +public class Solution { + public int TitleToNumber(string s) { + int res = 0; + var chars = s.ToCharArray(); + foreach(var c in chars){ + res = res*26 + (c-'A') + 1; + } + return res; + } +} \ No newline at end of file diff --git a/README.md b/README.md index 1287ad8..8de9d0c 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Solutions in various programming languages are provided. Enjoy it. 7. [Vertical Order Traversal of a Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree) 8. [Path Sum III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/08-Path-Sum-III) 9. [Rotting Oranges](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/09-Rotting-Oranges) +10. [Excel Sheet Column Number](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 93bc56f72c7e1939c3ef7bfdc5ea914e18ee8040 Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Tue, 11 Aug 2020 14:39:24 +0200 Subject: [PATCH 225/281] add kotlin solutions --- .../01-Detect-Capital/Detect-Capital.kt | 13 +++ .../02-Design-HashSet/Design-HashSet.kt | 19 ++++ .../03-Valid-Palindrome/Valid-Palindrome.kt | 28 ++++++ .../04-Power-of-Four/Power-of-Four.kt | 61 +++++++++++++ ...d-and-Search-Word-Data-structure-design.kt | 68 +++++++++++++++ .../Find-All-Duplicates-in-an-Array.kt | 31 +++++++ ...rtical-Order-Traversal-of-a-Binary-Tree.kt | 63 ++++++++++++++ .../08-Path-Sum-III/Path-Sum-III.kt | 62 +++++++++++++ .../09-Rotting-Oranges/Rotting-Oranges.kt | 80 +++++++++++++++++ .../Excel-Sheet-Column-Number.kt | 23 +++++ ...ee-from-Inorder-and-Postorder-Traversal.kt | 48 +++++++++++ .../28-Task-Scheduler/Task-Scheduler.kt | 17 ++++ ...ime-to-Buy-and-Sell-Stock-with-Cooldown.kt | 25 ++++++ .../30-Word-Break-II/Word-Break-II.kt | 86 +++++++++++++++++++ .../31-Climbing-Stairs/Climbing-Stairs.kt | 31 +++++++ 15 files changed, 655 insertions(+) create mode 100644 August-LeetCoding-Challenge/01-Detect-Capital/Detect-Capital.kt create mode 100644 August-LeetCoding-Challenge/02-Design-HashSet/Design-HashSet.kt create mode 100644 August-LeetCoding-Challenge/03-Valid-Palindrome/Valid-Palindrome.kt create mode 100644 August-LeetCoding-Challenge/04-Power-of-Four/Power-of-Four.kt create mode 100644 August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.kt create mode 100644 August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array/Find-All-Duplicates-in-an-Array.kt create mode 100644 August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree/Vertical-Order-Traversal-of-a-Binary-Tree.kt create mode 100644 August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.kt create mode 100644 August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.kt create mode 100644 August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number/Excel-Sheet-Column-Number.kt create mode 100644 July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.kt create mode 100644 July-LeetCoding-Challenge/28-Task-Scheduler/Task-Scheduler.kt create mode 100644 July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.kt create mode 100644 July-LeetCoding-Challenge/30-Word-Break-II/Word-Break-II.kt create mode 100644 July-LeetCoding-Challenge/31-Climbing-Stairs/Climbing-Stairs.kt diff --git a/August-LeetCoding-Challenge/01-Detect-Capital/Detect-Capital.kt b/August-LeetCoding-Challenge/01-Detect-Capital/Detect-Capital.kt new file mode 100644 index 0000000..9744801 --- /dev/null +++ b/August-LeetCoding-Challenge/01-Detect-Capital/Detect-Capital.kt @@ -0,0 +1,13 @@ +package string_integer + +class DetectCapitalKotlin520 { + fun detectCapitalUse(word: String): Boolean { + val count = word.count { it.isUpperCase() } + return when { + count == word.length -> true + count == 1 && word[0].isUpperCase() -> true + count == 0 -> true + else -> false + } + } +} \ No newline at end of file diff --git a/August-LeetCoding-Challenge/02-Design-HashSet/Design-HashSet.kt b/August-LeetCoding-Challenge/02-Design-HashSet/Design-HashSet.kt new file mode 100644 index 0000000..2380638 --- /dev/null +++ b/August-LeetCoding-Challenge/02-Design-HashSet/Design-HashSet.kt @@ -0,0 +1,19 @@ +package hash_map_set + +class DesignHashSetKotlin705 { + /** Initialize your data structure here. */ + private val table = BooleanArray(1000001) + + fun add(key: Int) { + table[key] = true + } + + fun remove(key: Int) { + table[key] = false + } + + /** Returns true if this set contains the specified element */ + fun contains(key: Int): Boolean { + return table[key] + } +} \ No newline at end of file diff --git a/August-LeetCoding-Challenge/03-Valid-Palindrome/Valid-Palindrome.kt b/August-LeetCoding-Challenge/03-Valid-Palindrome/Valid-Palindrome.kt new file mode 100644 index 0000000..fa08247 --- /dev/null +++ b/August-LeetCoding-Challenge/03-Valid-Palindrome/Valid-Palindrome.kt @@ -0,0 +1,28 @@ +package string_integer + +class ValidPalindromeKotlin125 { + fun isPalindrome(s: String): Boolean { + var left = 0 + var right = s.length - 1 + while (left < right) { + while (left < right && !s[left].isLetterOrDigit()) { + ++left + } + while (left < right && !s[right].isLetterOrDigit()) { + --right + } + if (s[left++].toUpperCase() != s[right--].toUpperCase()) { + return false + } + } + return true + } +} + +fun main() { + val solution = ValidPalindromeKotlin125() + // true + println(solution.isPalindrome("A man, a plan, a canal: Panama")) + // false + println(solution.isPalindrome("0P")) +} \ No newline at end of file diff --git a/August-LeetCoding-Challenge/04-Power-of-Four/Power-of-Four.kt b/August-LeetCoding-Challenge/04-Power-of-Four/Power-of-Four.kt new file mode 100644 index 0000000..52a2c3a --- /dev/null +++ b/August-LeetCoding-Challenge/04-Power-of-Four/Power-of-Four.kt @@ -0,0 +1,61 @@ +package string_integer + +class PowerofFourKotlin342 { + fun isPowerOfFour(num: Int): Boolean { + var current = num + if (current < 1) { + return false + } + while (current % 4 == 0) { + current /= 4 + } + return current == 1 + } + /* + fun isPowerOfFour(num: Int): Boolean { + return num > 0 && (num.and(num - 1)) == 0 && (num.and(0x55555555)) != 0 + } + */ + + /* + private val set = setOf( + 1, + 4, + 16, + 64, + 256, + 1024, + 4096, + 16384, + 65536, + 262144, + 1048576, + 4194304, + 16777216, + 67108864, + 268435456, + 1073741824 + ) + + fun isPowerOfFour(num: Int): Boolean { + return set.contains(num) + } + */ + /* + fun isPowerOfFour(num: Int): Boolean { + if (num == 1) { + return true + } + var current = 4 + while (current < num && current <= 1073741823) { + current *= 4 + } + return current == num + } + */ +} + +fun main() { + val solution = PowerofFourKotlin342() + println(solution.isPowerOfFour(1162261466)) +} \ No newline at end of file diff --git a/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.kt b/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.kt new file mode 100644 index 0000000..7d28505 --- /dev/null +++ b/August-LeetCoding-Challenge/05-Add-and-Search-Word-Data-structure-design/Add-and-Search-Word-Data-structure-design.kt @@ -0,0 +1,68 @@ +package binary_tree + +class AddandSearchWordKotlin211 { + /** Initialize your data structure here. */ + val root = PrefixTree() + + /** Adds a word into the data structure. */ + fun addWord(word: String) { + var current = root + word.forEach { + if (current.getByChar(it) == null) { + current.addChar(it, PrefixTree()) + } + current = current.getByChar(it)!! + } + current.setEnd(true) + } + + /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ + fun search(word: String): Boolean = search(word, root) + + private fun search(word: String, prefixTree: PrefixTree): Boolean { + var current = prefixTree + word.forEachIndexed { index, c -> + when { + c == '.' -> { + val new = word.substring(index + 1, word.length) + for (char in 'a'..'z') { + if (current.getByChar(char) != null && search(new, current.getByChar(char)!!)) { + return true + } + } + return false + } + current.getByChar(c) != null -> current = current.getByChar(c)!! + else -> return false + } + } + return current.isEnd() + } + + class PrefixTree { + private val links: Array = Array(26) { null } + private var isEnd = false + + fun addChar(c: Char, prefixTree: PrefixTree) { + this.links[c - 'a'] = prefixTree + } + + fun isEnd() = this.isEnd + + fun getByChar(c: Char): PrefixTree? = this.links[c - 'a'] + + fun setEnd(boolean: Boolean) { + this.isEnd = boolean + } + } +} + +fun main() { + val solution = AddandSearchWordKotlin211() + solution.addWord("a") + println(solution.search("a.")) + solution.addWord("bad") + println(solution.search("bad")) + println(solution.search(".ad")) + println(solution.search("..d")) +} \ No newline at end of file diff --git a/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array/Find-All-Duplicates-in-an-Array.kt b/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array/Find-All-Duplicates-in-an-Array.kt new file mode 100644 index 0000000..452afd3 --- /dev/null +++ b/August-LeetCoding-Challenge/06-Find-All-Duplicates-in-an-Array/Find-All-Duplicates-in-an-Array.kt @@ -0,0 +1,31 @@ +package string_integer + +import java.util.* +import kotlin.math.abs + +class FindAllDuplicatesinanArrayKotlin442 { + fun findDuplicates(nums: IntArray): List { + val results: MutableList = LinkedList() + nums.forEach { + val index = abs(it) - 1 + if (nums[index] < 0) { + results.add(index + 1) + } + nums[index] = -nums[index] + } + return results + } + /* + fun findDuplicates(nums: IntArray): List { + val results: MutableList = LinkedList() + val set: MutableSet = HashSet() + nums.forEach { + if (set.contains(it)) { + results.add(it) + } + set.add(it) + } + return results + } + */ +} \ No newline at end of file diff --git a/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree/Vertical-Order-Traversal-of-a-Binary-Tree.kt b/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree/Vertical-Order-Traversal-of-a-Binary-Tree.kt new file mode 100644 index 0000000..6a66a32 --- /dev/null +++ b/August-LeetCoding-Challenge/07-Vertical-Order-Traversal-of-a-Binary-Tree/Vertical-Order-Traversal-of-a-Binary-Tree.kt @@ -0,0 +1,63 @@ +package breadth_first_search + +import java.util.* +import kotlin.collections.ArrayList +import kotlin.collections.HashMap + +class VerticalOrderTraversalofaBinaryTreeKotlin987 { + fun verticalTraversal(root: TreeNode?): List> { + val result: MutableList> = LinkedList() + if (root == null) { + return result + } + val map: MutableMap> = HashMap() + val queue: Queue> = LinkedList() + queue.offer(Pair(root, 0)) + while (queue.isNotEmpty()) { + val currentMap: MutableMap> = HashMap() + for (size in queue.indices) { + val current = queue.poll() + val node = current.first + val xIndex = current.second + currentMap.computeIfAbsent(xIndex) { ArrayList() }.add(node.`val`) + + node.left?.let { + queue.offer(Pair(it, xIndex - 1)) + } + node.right?.let { + queue.offer(Pair(it, xIndex + 1)) + } + } + for (entry in currentMap) { + map.computeIfAbsent(entry.key) { ArrayList() }.addAll(entry.value.sorted()) + } + } + return map.toList().sortedBy(Pair>::first).map { it.second } + } + + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } +} + +fun main() { + val solution = VerticalOrderTraversalofaBinaryTreeKotlin987() + val node3 = VerticalOrderTraversalofaBinaryTreeKotlin987.TreeNode(3) + val node9 = VerticalOrderTraversalofaBinaryTreeKotlin987.TreeNode(9) + val node20 = VerticalOrderTraversalofaBinaryTreeKotlin987.TreeNode(20) + val node15 = VerticalOrderTraversalofaBinaryTreeKotlin987.TreeNode(15) + val node7 = VerticalOrderTraversalofaBinaryTreeKotlin987.TreeNode(7) + + node3.left = node9 + node3.right = node20 + node20.left = node15 + node20.right = node7 + + val result = solution.verticalTraversal(node3) + + result.forEach { + it.forEach(::print) + println() + } +} \ No newline at end of file diff --git a/August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.kt b/August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.kt new file mode 100644 index 0000000..0144527 --- /dev/null +++ b/August-LeetCoding-Challenge/08-Path-Sum-III/Path-Sum-III.kt @@ -0,0 +1,62 @@ +package binary_tree + +class PathSumIIIKotlin437 { + fun pathSum(root: TreeNode?, sum: Int): Int { + if (root == null) { + return 0 + } + return dfs(root, sum, 0) + pathSum(root.left, sum) + pathSum(root.right, sum) + } + + private fun dfs( + root: TreeNode?, + sum: Int, + pre: Int + ): Int { + if (root == null) { + return 0 + } + val current = pre + root.`val` + return if (current == sum) { + 1 + } else { + 0 + } + dfs(root.left, sum, current) + dfs(root.right, sum, current) + } + + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } +} + +fun main() { + val solution = PathSumIIIKotlin437() + val node11 = PathSumIIIKotlin437.TreeNode(0) + val node22 = PathSumIIIKotlin437.TreeNode(1) + val node33 = PathSumIIIKotlin437.TreeNode(1) + node11.left = node22 + node11.right = node33 + println(solution.pathSum(node11, 1)) + + val node1 = PathSumIIIKotlin437.TreeNode(10) + val node2 = PathSumIIIKotlin437.TreeNode(5) + val node3 = PathSumIIIKotlin437.TreeNode(-3) + val node4 = PathSumIIIKotlin437.TreeNode(3) + val node5 = PathSumIIIKotlin437.TreeNode(2) + val node6 = PathSumIIIKotlin437.TreeNode(11) + val node7 = PathSumIIIKotlin437.TreeNode(3) + val node8 = PathSumIIIKotlin437.TreeNode(-2) + val node9 = PathSumIIIKotlin437.TreeNode(1) + + node1.left = node2 + node1.right = node3 + node3.right = node6 + node2.left = node4 + node2.right = node5 + node4.left = node7 + node4.right = node8 + node5.right = node9 + + println(solution.pathSum(node1, 8)) +} \ No newline at end of file diff --git a/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.kt b/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.kt new file mode 100644 index 0000000..e8ef1f3 --- /dev/null +++ b/August-LeetCoding-Challenge/09-Rotting-Oranges/Rotting-Oranges.kt @@ -0,0 +1,80 @@ +package breadth_first_search + +import java.util.* + +class RottingOrangesKotlin994 { + fun orangesRotting(grid: Array): Int { + val visited = Array(grid.size) { BooleanArray(grid[0].size) } + val queue: Queue = LinkedList() + // add all rotten orange into the queue,visited + var freshOranges = 0 + for (i in grid.indices) { + for (j in grid[0].indices) { + if (grid[i][j] == 2) { + queue.offer(intArrayOf(i, j)) + visited[i][j] = true + } + if (grid[i][j] == 1) { + ++freshOranges + } + } + } + if (freshOranges == 0) { + return 0 + } + // bfs + var level = -1 + var count = 0 + while (queue.isNotEmpty()) { + for (size in queue.indices) { + val current = queue.poll() + for (index in 0..3) { + val nextX = current[0] + deltaX[index] + val nextY = current[1] + deltaY[index] + if (inBound(grid, nextX, nextY) && + !visited[nextX][nextY] && + grid[nextX][nextY] == 1 + ) { + queue.offer(intArrayOf(nextX, nextY)) + visited[nextX][nextY] = true + ++count + } + } + } + ++level + } + return if (count == freshOranges) level else -1 + } + + private val deltaX = intArrayOf(0, 0, -1, 1) + private val deltaY = intArrayOf(-1, 1, 0, 0) + private fun inBound( + grid: Array, + x: Int, + y: Int + ) = x >= 0 && y >= 0 && x < grid.size && y < grid[0].size +} + +fun main() { + val solution = RottingOrangesKotlin994() + // 4 + println( + solution.orangesRotting( + arrayOf( + intArrayOf(2, 1, 1), + intArrayOf(1, 1, 0), + intArrayOf(0, 1, 1) + ) + ) + ) + // -1 + println( + solution.orangesRotting( + arrayOf( + intArrayOf(2, 1, 1), + intArrayOf(0, 1, 1), + intArrayOf(1, 0, 1) + ) + ) + ) +} \ No newline at end of file diff --git a/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number/Excel-Sheet-Column-Number.kt b/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number/Excel-Sheet-Column-Number.kt new file mode 100644 index 0000000..9795f0d --- /dev/null +++ b/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number/Excel-Sheet-Column-Number.kt @@ -0,0 +1,23 @@ +package string_integer + +class ExcelSheetColumnNumberKotlin171 { + + fun titleToNumber(s: String): Int { + var base = 26 + if (s.length == 1) { + return s[0] - '@' + } + var result = s[s.length - 1] - '@' + for (index in s.length - 2 downTo 0) { + result += (s[index] - '@') * base + base *= 26 + } + return result + } +} + +fun main() { + val solution = ExcelSheetColumnNumberKotlin171() + // 701 + println(solution.titleToNumber("ZY")) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.kt b/July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.kt new file mode 100644 index 0000000..5bed7b1 --- /dev/null +++ b/July-LeetCoding-Challenge/27-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal.kt @@ -0,0 +1,48 @@ +package binary_tree + +class ConstructBinaryTreefromInorderandPostorderTraversalKotlin106 { + fun buildTree(inorder: IntArray, postorder: IntArray): TreeNode? = + construct( + inorder, + 0, + inorder.size - 1, + postorder, + 0, + postorder.size - 1 + ) + + private fun construct( + inorder: IntArray, + iStart: Int, + iEnd: Int, + postorder: IntArray, + pStart: Int, + pEnd: Int + ): TreeNode? { + if (iStart > iEnd || pStart > pEnd) { + return null + } + val treeNode = TreeNode(postorder[pEnd]) + var index = iStart + while (iStart < inorder.size && inorder[index] != treeNode.`val`) { + ++index + } + treeNode.left = construct(inorder, iStart, index - 1, postorder, pStart, pStart + index - 1 - iStart) + treeNode.right = construct(inorder, index + 1, iEnd, postorder, pStart + index - iStart, pEnd - 1) + return treeNode + } + + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } +} + +fun main() { + val solution = ConstructBinaryTreefromInorderandPostorderTraversalKotlin106() + val result = solution.buildTree( + intArrayOf(9, 3, 15, 20, 7), + intArrayOf(9, 15, 7, 20, 3) + ) + println(result) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/28-Task-Scheduler/Task-Scheduler.kt b/July-LeetCoding-Challenge/28-Task-Scheduler/Task-Scheduler.kt new file mode 100644 index 0000000..dac7c09 --- /dev/null +++ b/July-LeetCoding-Challenge/28-Task-Scheduler/Task-Scheduler.kt @@ -0,0 +1,17 @@ +package string_integer + +class TaskSchedulerKotlin621 { + fun leastInterval(tasks: CharArray, n: Int): Int { + val chars = IntArray(26) + tasks.forEach { + ++chars[it - 'A'] + } + chars.sort() + var index = 25 + while (index >= 0 && chars[index] == chars[25]) { + --index + } + val result = (chars[25] - 1) * (n + 1) + 25 - index + return maxOf(tasks.size, result) + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.kt b/July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.kt new file mode 100644 index 0000000..334faf1 --- /dev/null +++ b/July-LeetCoding-Challenge/29-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown/Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.kt @@ -0,0 +1,25 @@ +package dynamic_programming + +class BestTimetoBuyandSellStockwithCooldownKotlin309 { + fun maxProfit(prices: IntArray): Int { + if (prices.isEmpty()) { + return 0 + } + val cooldown = IntArray(prices.size) + val buy = IntArray(prices.size) + val sell = IntArray(prices.size) + buy[0] = -prices[0] + for (i in 1 until prices.size) { + cooldown[i] = maxOf(cooldown[i - 1], sell[i - 1]) + buy[i] = maxOf(buy[i - 1], cooldown[i - 1] - prices[i]) + sell[i] = buy[i - 1] + prices[i] + } + return maxOf(cooldown[prices.size - 1], sell[prices.size - 1]) + } +} + +fun main() { + val solution = BestTimetoBuyandSellStockwithCooldownKotlin309() + // 3 + println(solution.maxProfit(intArrayOf(1, 2, 3, 0, 2))) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/30-Word-Break-II/Word-Break-II.kt b/July-LeetCoding-Challenge/30-Word-Break-II/Word-Break-II.kt new file mode 100644 index 0000000..9543e10 --- /dev/null +++ b/July-LeetCoding-Challenge/30-Word-Break-II/Word-Break-II.kt @@ -0,0 +1,86 @@ +package depth_first_search + +class WordBreakIIKotlin140 { + fun wordBreak(s: String, wordDict: List): List { + val map: MutableMap> = HashMap() + return dfs(s, wordDict, map) + } + + private fun dfs( + s: String, + wordDict: List, + map: MutableMap> + ): List { + if (map.containsKey(s)) { + return map.getValue(s) + } + val results: MutableList = ArrayList() + if (s.isEmpty()) { + results.add("") + return results + } + + for (word in wordDict) { + if (s.startsWith(word)) { + val subResult = dfs(s.substring(word.length), wordDict, map) + subResult.forEach { + if (it.isEmpty()) { + results.add(word) + } else { + results.add("$word $it") + } + } + } + } + map[s] = results + return results + } + + /* + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"] + Time Limit Exceed + */ + /* + fun wordBreak(s: String, wordDict: List): List { + val wordSet = wordDict.toSet() + val visited = BooleanArray(s.length + 1) + val subsets: MutableList = LinkedList() + val results: MutableList> = LinkedList() + dfs(s, wordSet, visited, 0, subsets, results) + return results.map { it.joinToString(separator = " ") } + } + + private fun dfs( + s: String, + wordSet: Set, + visited: BooleanArray, + current: Int, + subsets: MutableList, + results: MutableList> + ) { + if (current == s.length) { + results.add(ArrayList(subsets)) + return + } + for (index in current + 1..s.length) { + val currentString = s.substring(current, index) + if (!visited[index] && wordSet.contains(currentString)) { + visited[index] = true + subsets.add(currentString) + dfs(s, wordSet, visited, index, subsets, results) + visited[index] = false + subsets.removeAt(subsets.size - 1) + } + } + } + */ +} + +fun main() { + val solution = WordBreakIIKotlin140() + solution.wordBreak( + "catsanddog", + listOf("cat", "cats", "and", "sand", "dog") + ).forEach(::print) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/31-Climbing-Stairs/Climbing-Stairs.kt b/July-LeetCoding-Challenge/31-Climbing-Stairs/Climbing-Stairs.kt new file mode 100644 index 0000000..4a5ad9e --- /dev/null +++ b/July-LeetCoding-Challenge/31-Climbing-Stairs/Climbing-Stairs.kt @@ -0,0 +1,31 @@ +package dynamic_programming + +class ClimbingStairsKotlin70 { + fun climbStairs(n: Int): Int { + if (n == 1) { + return 1 + } + var i1 = 1 + var i2 = 2 + for (index in 3..n) { + val sum = i1 + i2 + i1 = i2 + i2 = sum + } + return i2 + } + /* + fun climbStairs(n: Int): Int { + if (n == 1) { + return 1 + } + val dp = IntArray(n + 1) + dp[1] = 1 + dp[2] = 2 + for (index in 3..n) { + dp[index] = dp[index - 1] + dp[index - 2] + } + return dp[n] + } + */ +} \ No newline at end of file From f5097623ead4d5b84d64ff018a981427f89536a4 Mon Sep 17 00:00:00 2001 From: zijian Date: Tue, 11 Aug 2020 14:49:55 +0200 Subject: [PATCH 226/281] Add Solution JavaScript for H-Index --- August-LeetCoding-Challenge/11-H-Index/H-Index.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 August-LeetCoding-Challenge/11-H-Index/H-Index.js diff --git a/August-LeetCoding-Challenge/11-H-Index/H-Index.js b/August-LeetCoding-Challenge/11-H-Index/H-Index.js new file mode 100644 index 0000000..e69de29 From d95d7124b09796a440522dc5c5c3bab740f6b68d Mon Sep 17 00:00:00 2001 From: zijian Date: Tue, 11 Aug 2020 14:52:07 +0200 Subject: [PATCH 227/281] Add Solution JavaScript for H-Index --- .../11-H-Index/H-Index.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/August-LeetCoding-Challenge/11-H-Index/H-Index.js b/August-LeetCoding-Challenge/11-H-Index/H-Index.js index e69de29..cc47fc7 100644 --- a/August-LeetCoding-Challenge/11-H-Index/H-Index.js +++ b/August-LeetCoding-Challenge/11-H-Index/H-Index.js @@ -0,0 +1,19 @@ +var hIndex = function(citations) { + if(citations.length==0){return 0;} + citations.sort(function(a,b){ + return b-a; + }); + var res = 0; + if(citations[0] < 1){return 0;} + for(let i=0;i citations[i]){ + let reste = citations.length-a+1; + res = citations[i]; + while(citations.length-res > reste){res++;} + return res; + } + } + return citations.length; +}; From 7948b397ef1da0efd3b27661f5a7feb46a5af3bd Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 11 Aug 2020 20:06:53 +0200 Subject: [PATCH 228/281] Add H-Index C# --- .../11-H-Index/H-Index.cs | 20 +++++++++++++++++++ README.md | 1 + 2 files changed, 21 insertions(+) create mode 100644 August-LeetCoding-Challenge/11-H-Index/H-Index.cs diff --git a/August-LeetCoding-Challenge/11-H-Index/H-Index.cs b/August-LeetCoding-Challenge/11-H-Index/H-Index.cs new file mode 100644 index 0000000..213666d --- /dev/null +++ b/August-LeetCoding-Challenge/11-H-Index/H-Index.cs @@ -0,0 +1,20 @@ +public class Solution { + public int HIndex(int[] citations) { + //Counting sort + int[] counts = new int[citations.Length + 2]; + for (int i = citations.Length - 1; i >= 0; i--) + { + var idx = Math.Min(citations[i], citations.Length); + counts[idx]++; + } + + var r = 0; + for (int i = citations.Length +1; i >= 0; i--) + { + r += counts[i]; + if (r >= i) + return i; + } + return 0; + } +} \ No newline at end of file diff --git a/README.md b/README.md index 8de9d0c..35b9711 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ Solutions in various programming languages are provided. Enjoy it. 8. [Path Sum III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/08-Path-Sum-III) 9. [Rotting Oranges](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/09-Rotting-Oranges) 10. [Excel Sheet Column Number](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number) +11. [H-Index](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/11-H-Index) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 5a762cbf4ff225f534f1b78a1df6bee059942802 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 12 Aug 2020 20:43:44 +0200 Subject: [PATCH 229/281] Add Pascal's Triangle II C# --- .../12-Pascal's-Triangle-II/Pascal's-Triangle-II.Cs | 13 +++++++++++++ README.md | 1 + 2 files changed, 14 insertions(+) create mode 100644 August-LeetCoding-Challenge/12-Pascal's-Triangle-II/Pascal's-Triangle-II.Cs diff --git a/August-LeetCoding-Challenge/12-Pascal's-Triangle-II/Pascal's-Triangle-II.Cs b/August-LeetCoding-Challenge/12-Pascal's-Triangle-II/Pascal's-Triangle-II.Cs new file mode 100644 index 0000000..d1712d0 --- /dev/null +++ b/August-LeetCoding-Challenge/12-Pascal's-Triangle-II/Pascal's-Triangle-II.Cs @@ -0,0 +1,13 @@ +public class Solution { + //Formula solution + public IList GetRow(int rowIndex) { + int[] arr = new int[rowIndex+1]; + arr[0] = 1; + for (int i = 1; i < rowIndex + 1; i++) + { + arr[i] = (int)(((long)arr[i - 1] * (rowIndex - i + 1)) / i); + } + + return arr; + } +} diff --git a/README.md b/README.md index 35b9711..5f054d0 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ Solutions in various programming languages are provided. Enjoy it. 9. [Rotting Oranges](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/09-Rotting-Oranges) 10. [Excel Sheet Column Number](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number) 11. [H-Index](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/11-H-Index) +12. [Pascal's Triangle II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/12-Pascal's-Triangle-II) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From b021efb2f515816ab1b4b8efd8b1e31ee9922789 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 12 Aug 2020 20:46:37 +0200 Subject: [PATCH 230/281] update --- .../Pascals-Triangle-II.Cs} | 0 README.md | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename August-LeetCoding-Challenge/{12-Pascal's-Triangle-II/Pascal's-Triangle-II.Cs => 12-Pascals-Triangle-II/Pascals-Triangle-II.Cs} (100%) diff --git a/August-LeetCoding-Challenge/12-Pascal's-Triangle-II/Pascal's-Triangle-II.Cs b/August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.Cs similarity index 100% rename from August-LeetCoding-Challenge/12-Pascal's-Triangle-II/Pascal's-Triangle-II.Cs rename to August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.Cs diff --git a/README.md b/README.md index 5f054d0..ad12f80 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Solutions in various programming languages are provided. Enjoy it. 9. [Rotting Oranges](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/09-Rotting-Oranges) 10. [Excel Sheet Column Number](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/10-Excel-Sheet-Column-Number) 11. [H-Index](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/11-H-Index) -12. [Pascal's Triangle II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/12-Pascal's-Triangle-II) +12. [Pascal's Triangle II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/12-Pascals-Triangle-II) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From fe403886eb7306cca78d616d657177142ce63229 Mon Sep 17 00:00:00 2001 From: zijian Date: Thu, 13 Aug 2020 11:09:47 +0200 Subject: [PATCH 231/281] Iterator for Combination, Add Solution in Python3 --- .../Pascals-Triangle-II.js | 21 ++++++++++++++ .../Iterator-for-Combination.py | 29 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js create mode 100644 August-LeetCoding-Challenge/13-Iterator-for-Combination/Iterator-for-Combination.py diff --git a/August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js b/August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js new file mode 100644 index 0000000..58cf6dd --- /dev/null +++ b/August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js @@ -0,0 +1,21 @@ +var getRow = function(rowIndex) { + var res = new Array(); + res.push(1); + if(rowIndex==0){return res;} + res.push(1); + if(rowIndex==1){return res;} + var k = 2; + return recursion(k,rowIndex,res); +}; + +var recursion = function(k,rowIndex,res){ + if(k-1==rowIndex){return res;} + var result = new Array(); + result.push(1); + for(let i = 1;i < res.length;i++){ + result.push(res[i]+res[i-1]); + } + result.push(1); + //console.log(k+" "+result); + return recursion(k+1,rowIndex,result); +} diff --git a/August-LeetCoding-Challenge/13-Iterator-for-Combination/Iterator-for-Combination.py b/August-LeetCoding-Challenge/13-Iterator-for-Combination/Iterator-for-Combination.py new file mode 100644 index 0000000..215390b --- /dev/null +++ b/August-LeetCoding-Challenge/13-Iterator-for-Combination/Iterator-for-Combination.py @@ -0,0 +1,29 @@ +class CombinationIterator: + + def __init__(self, characters: str, combinationLength: int): + self.res = [] + if combinationLength==1: + self.res = [x for x in characters] + else: + self.bk([],characters,combinationLength) + + + def bk(self,cur,choice,fin): + if len(cur) == fin: + self.res.append("".join(cur)) + return + for i in range(len(choice)): + cur.append(choice[i]) + self.bk(cur,choice[i+1:],fin) + cur.pop(-1) + return + + + def next(self) -> str: + tmp = self.res[0] + self.res.pop(0) + return tmp + + def hasNext(self) -> bool: + return self.res!=[] + From c061789688fe8e84ca124de18d64dd38eaeb2fbe Mon Sep 17 00:00:00 2001 From: zijian Date: Thu, 13 Aug 2020 11:10:58 +0200 Subject: [PATCH 232/281] Iterator for Combination, Add Solution in Python3 --- .../Pascals-Triangle-II.js | 21 ------------------- 1 file changed, 21 deletions(-) delete mode 100644 August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js diff --git a/August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js b/August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js deleted file mode 100644 index 58cf6dd..0000000 --- a/August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js +++ /dev/null @@ -1,21 +0,0 @@ -var getRow = function(rowIndex) { - var res = new Array(); - res.push(1); - if(rowIndex==0){return res;} - res.push(1); - if(rowIndex==1){return res;} - var k = 2; - return recursion(k,rowIndex,res); -}; - -var recursion = function(k,rowIndex,res){ - if(k-1==rowIndex){return res;} - var result = new Array(); - result.push(1); - for(let i = 1;i < res.length;i++){ - result.push(res[i]+res[i-1]); - } - result.push(1); - //console.log(k+" "+result); - return recursion(k+1,rowIndex,result); -} From 573e66f3a4b6fb7abb9f1ef96a6dc5f47244a2b7 Mon Sep 17 00:00:00 2001 From: zijian Date: Thu, 13 Aug 2020 11:12:10 +0200 Subject: [PATCH 233/281] Add Solution in JavaScript --- .../Pascals-Triangle-II.js | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js diff --git a/August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js b/August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js new file mode 100644 index 0000000..58cf6dd --- /dev/null +++ b/August-LeetCoding-Challenge/12-Pascals-Triangle-II/Pascals-Triangle-II.js @@ -0,0 +1,21 @@ +var getRow = function(rowIndex) { + var res = new Array(); + res.push(1); + if(rowIndex==0){return res;} + res.push(1); + if(rowIndex==1){return res;} + var k = 2; + return recursion(k,rowIndex,res); +}; + +var recursion = function(k,rowIndex,res){ + if(k-1==rowIndex){return res;} + var result = new Array(); + result.push(1); + for(let i = 1;i < res.length;i++){ + result.push(res[i]+res[i-1]); + } + result.push(1); + //console.log(k+" "+result); + return recursion(k+1,rowIndex,result); +} From 50644ec6fe7ba920e1af6bbd604ae5572ef4240c Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Thu, 13 Aug 2020 21:25:18 +0200 Subject: [PATCH 234/281] Add Iterator for Combination C# --- .../Iterator-for-Combination.cs | 32 +++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 August-LeetCoding-Challenge/13-Iterator-for-Combination/Iterator-for-Combination.cs diff --git a/August-LeetCoding-Challenge/13-Iterator-for-Combination/Iterator-for-Combination.cs b/August-LeetCoding-Challenge/13-Iterator-for-Combination/Iterator-for-Combination.cs new file mode 100644 index 0000000..4f568e3 --- /dev/null +++ b/August-LeetCoding-Challenge/13-Iterator-for-Combination/Iterator-for-Combination.cs @@ -0,0 +1,32 @@ +public class CombinationIterator { + + private Queue queue = new Queue(); + + public CombinationIterator(string characters, int combinationLength) { + Dfs(characters, 0, "", combinationLength); + } + + public string Next() { + return queue.Dequeue(); + } + + public bool HasNext() { + return queue.Count > 0; + } + + private void Dfs(string chars, int start, string curr, int length){ + if(length == 0){ + queue.Enqueue(curr); + } + for(int i=start; i Date: Fri, 14 Aug 2020 18:34:19 +0200 Subject: [PATCH 235/281] Add Longest Palindrome C# --- .../Longest-Palindrome.cs | 30 +++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 August-LeetCoding-Challenge/14-Longest-Palindrome/Longest-Palindrome.cs diff --git a/August-LeetCoding-Challenge/14-Longest-Palindrome/Longest-Palindrome.cs b/August-LeetCoding-Challenge/14-Longest-Palindrome/Longest-Palindrome.cs new file mode 100644 index 0000000..a9f323d --- /dev/null +++ b/August-LeetCoding-Challenge/14-Longest-Palindrome/Longest-Palindrome.cs @@ -0,0 +1,30 @@ +public class Solution { + public int LongestPalindrome(string s) { + var dict = new Dictionary(); + foreach(char c in s){ + if(!dict.ContainsKey(c)){ + dict.Add(c, 1); + }else{ + dict[c]++; + } + } + + var sum = 0; + var hasOdd = false; + var evenChars = new List>(); + foreach(var kv in dict){ + if(kv.Value % 2 == 0){ + sum += kv.Value; + }else if(kv.Value / 2 >= 1){ + sum += kv.Value -1; + hasOdd = true; + }else { + hasOdd = true; + } + } + + sum = hasOdd ? sum +1 : sum; + + return sum; + } +} \ No newline at end of file diff --git a/README.md b/README.md index 671bccf..9cc2743 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Solutions in various programming languages are provided. Enjoy it. 11. [H-Index](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/11-H-Index) 12. [Pascal's Triangle II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/12-Pascals-Triangle-II) 13. [Iterator for Combination](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/13-Iterator-for-Combination) +14. [Longest Palindrome](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/14-Longest-Palindrome) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From baeb0f8adfa67697d2b33f1abe95b9cbc519bfe6 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sat, 15 Aug 2020 20:55:14 +0200 Subject: [PATCH 236/281] Add Non-overlapping Intervals C# --- .../Non-overlapping-Intervals.cs | 21 +++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 August-LeetCoding-Challenge/15-Non-overlapping-Intervals/Non-overlapping-Intervals.cs diff --git a/August-LeetCoding-Challenge/15-Non-overlapping-Intervals/Non-overlapping-Intervals.cs b/August-LeetCoding-Challenge/15-Non-overlapping-Intervals/Non-overlapping-Intervals.cs new file mode 100644 index 0000000..65aed94 --- /dev/null +++ b/August-LeetCoding-Challenge/15-Non-overlapping-Intervals/Non-overlapping-Intervals.cs @@ -0,0 +1,21 @@ +public class Solution { + public int EraseOverlapIntervals(int[][] intervals) { + if(intervals.Length == 0) return 0; + Array.Sort(intervals, new IntArrayComparer()); + var end = intervals[0][1]; + int count =1; + for(int i=1; i= end){ + end = intervals[i][1]; + count++; + } + } + return intervals.Length - count; + } +} + +public class IntArrayComparer : IComparer{ + int IComparer.Compare(int[] a, int[] b){ + return a[1] - b[1]; + } +} \ No newline at end of file diff --git a/README.md b/README.md index 9cc2743..6ecd225 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ Solutions in various programming languages are provided. Enjoy it. 12. [Pascal's Triangle II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/12-Pascals-Triangle-II) 13. [Iterator for Combination](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/13-Iterator-for-Combination) 14. [Longest Palindrome](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/14-Longest-Palindrome) +15. [Non-overlapping Intervals](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/15-Non-overlapping-Intervals) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From d46301693dee297d8167c95d2ee2cdc9ae00c1ff Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 16 Aug 2020 10:49:13 +0200 Subject: [PATCH 237/281] Add Best Time to Buy and Sell Stock III C# --- .../Best-Time-to-Buy-and-Sell-Stock-III.cs | 18 ++++++++++++++++++ README.md | 1 + 2 files changed, 19 insertions(+) create mode 100644 August-LeetCoding-Challenge/16-Best-Time-to-Buy-and-Sell-Stock-III/Best-Time-to-Buy-and-Sell-Stock-III.cs diff --git a/August-LeetCoding-Challenge/16-Best-Time-to-Buy-and-Sell-Stock-III/Best-Time-to-Buy-and-Sell-Stock-III.cs b/August-LeetCoding-Challenge/16-Best-Time-to-Buy-and-Sell-Stock-III/Best-Time-to-Buy-and-Sell-Stock-III.cs new file mode 100644 index 0000000..52f7166 --- /dev/null +++ b/August-LeetCoding-Challenge/16-Best-Time-to-Buy-and-Sell-Stock-III/Best-Time-to-Buy-and-Sell-Stock-III.cs @@ -0,0 +1,18 @@ +public class Solution { + public int MaxProfit(int[] prices) { + var oneBuyOneSell = 0; + var twoBuyTwoSell = 0; + var oneBuy = int.MaxValue; + var twoBuy = int.MaxValue; + + for(int i=0; i Date: Mon, 17 Aug 2020 18:51:31 +0200 Subject: [PATCH 238/281] Add Distribute Candies to People C# --- .../Distribute-Candies-to-People.cs | 30 +++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 August-LeetCoding-Challenge/17-Distribute-Candies-to-People/Distribute-Candies-to-People.cs diff --git a/August-LeetCoding-Challenge/17-Distribute-Candies-to-People/Distribute-Candies-to-People.cs b/August-LeetCoding-Challenge/17-Distribute-Candies-to-People/Distribute-Candies-to-People.cs new file mode 100644 index 0000000..9d4251a --- /dev/null +++ b/August-LeetCoding-Challenge/17-Distribute-Candies-to-People/Distribute-Candies-to-People.cs @@ -0,0 +1,30 @@ +public class Solution { + public int[] DistributeCandies(int candies, int num_people) { + if(candies == 0 || num_people == 0) return new int[num_people]; + var res = new int[num_people]; + var numberOfTours = 0; + var tourIncrement = num_people * num_people; + var tourFixValues = (num_people * (num_people +1))/2; + var usedCandies = tourFixValues; + while(candies - usedCandies >= 0){ + candies -= usedCandies; + numberOfTours++; + usedCandies = tourFixValues + tourIncrement*numberOfTours; + } + + if(numberOfTours > 0){ + for (int i = 0; i < num_people; i++) { + res[i] = num_people * (numberOfTours * (numberOfTours - 1)) / 2 + (i + 1) * numberOfTours; + } + } + + var offset = numberOfTours * num_people +1; + for(int i=0; i0; i++){ + res[i] += Math.Min(candies, offset); + candies -= offset; + offset++; + } + + return res; + } +} diff --git a/README.md b/README.md index 4d90bc6..b103300 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Solutions in various programming languages are provided. Enjoy it. 14. [Longest Palindrome](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/14-Longest-Palindrome) 15. [Non-overlapping Intervals](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/15-Non-overlapping-Intervals) 16. [Best Time to Buy and Sell Stock III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/16-Best-Time-to-Buy-and-Sell-Stock-III) +17. [Distribute Candies to People](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/17-Distribute-Candies-to-People) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 76c8555989827c91bf38abbe2912f781f4d22b00 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 18 Aug 2020 21:43:00 +0200 Subject: [PATCH 239/281] Add Numbers With Same Consecutive Differences C# --- ...Numbers-With-Same-Consecutive-Differences.cs | 17 +++++++++++++++++ README.md | 1 + 2 files changed, 18 insertions(+) create mode 100644 August-LeetCoding-Challenge/18-Numbers-With-Same-Consecutive-Differences/Numbers-With-Same-Consecutive-Differences.cs diff --git a/August-LeetCoding-Challenge/18-Numbers-With-Same-Consecutive-Differences/Numbers-With-Same-Consecutive-Differences.cs b/August-LeetCoding-Challenge/18-Numbers-With-Same-Consecutive-Differences/Numbers-With-Same-Consecutive-Differences.cs new file mode 100644 index 0000000..c0e7be0 --- /dev/null +++ b/August-LeetCoding-Challenge/18-Numbers-With-Same-Consecutive-Differences/Numbers-With-Same-Consecutive-Differences.cs @@ -0,0 +1,17 @@ +public class Solution { + public int[] NumsSameConsecDiff(int N, int K) { + var cur = new List{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + for (int i = 2; i <= N; ++i) { + var cur2 = new List(); + foreach (int x in cur) { + int y = x % 10; + if (x > 0 && y + K < 10) + cur2.Add(x * 10 + y + K); + if (x > 0 && K > 0 && y - K >= 0) + cur2.Add(x * 10 + y - K); + } + cur = cur2; + } + return cur.ToArray(); + } +} diff --git a/README.md b/README.md index b103300..14ad73d 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Solutions in various programming languages are provided. Enjoy it. 15. [Non-overlapping Intervals](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/15-Non-overlapping-Intervals) 16. [Best Time to Buy and Sell Stock III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/16-Best-Time-to-Buy-and-Sell-Stock-III) 17. [Distribute Candies to People](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/17-Distribute-Candies-to-People) +18. [Numbers With Same Consecutive Differences](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/18-Numbers-With-Same-Consecutive-Differences) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 53aba35f73a574b3521e18a0e5a1e94f31e7a2d8 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 19 Aug 2020 19:43:30 +0200 Subject: [PATCH 240/281] Add Goat Latin C# --- .../19-Goat-Latin/Goat-Latin.cs | 30 +++++++++++++++++++ README.md | 1 + 2 files changed, 31 insertions(+) create mode 100644 August-LeetCoding-Challenge/19-Goat-Latin/Goat-Latin.cs diff --git a/August-LeetCoding-Challenge/19-Goat-Latin/Goat-Latin.cs b/August-LeetCoding-Challenge/19-Goat-Latin/Goat-Latin.cs new file mode 100644 index 0000000..1dee1f7 --- /dev/null +++ b/August-LeetCoding-Challenge/19-Goat-Latin/Goat-Latin.cs @@ -0,0 +1,30 @@ +public class Solution { + public string ToGoatLatin(string S) { + var arr = S.Split(" "); + var vowels = new Dictionary(){ + {'a', 0}, {'e', 0}, {'i', 0}, {'o', 0}, {'u', 0}, + {'A', 0}, {'E', 0}, {'I', 0}, {'O', 0}, {'U', 0}}; + + var sb = new StringBuilder(); + var count = 1; + foreach(var item in arr){ + var t = new StringBuilder(); + if(vowels.ContainsKey(item[0])){ + t.Append(item); + t.Append("ma"); + }else{ + if(item.Length>1){ + for(int i=1; i Date: Thu, 20 Aug 2020 19:49:48 +0200 Subject: [PATCH 241/281] Add Reorder List C# --- .../20-Reorder-List/Reorder-List.cs | 47 +++++++++++++++++++ README.md | 1 + 2 files changed, 48 insertions(+) create mode 100644 August-LeetCoding-Challenge/20-Reorder-List/Reorder-List.cs diff --git a/August-LeetCoding-Challenge/20-Reorder-List/Reorder-List.cs b/August-LeetCoding-Challenge/20-Reorder-List/Reorder-List.cs new file mode 100644 index 0000000..ae46485 --- /dev/null +++ b/August-LeetCoding-Challenge/20-Reorder-List/Reorder-List.cs @@ -0,0 +1,47 @@ +public class Solution { + public void ReorderList(ListNode head) { + if(head == null || head.next == null) return; + + //Find the middle of the list: p1 + var p1 = head; + var p2 = head; + while(p2.next != null && p2.next.next != null){ + p1 = p1.next; + p2 = p2.next.next; + } + + //Reverse the second half after middle 1->2->3->4->5->6 to 1->2->3->6->5->4 + var preMiddle = p1; + var preCurrent = p1.next; + while(preCurrent.next != null){ + var current = preCurrent.next; + preCurrent.next = current.next; + current.next = preMiddle.next; + preMiddle.next = current; + } + + //Start reorder one by one 1->2->3->6->5->4 to 1->6->2->5->3->4 + p1 = head; + p2 = preMiddle.next; + while(p1 != preMiddle){ + preMiddle.next = p2.next; + p2.next = p1.next; + p1.next = p2; + p1 = p2.next; + p2 = preMiddle.next; + } + } +} + +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ + \ No newline at end of file diff --git a/README.md b/README.md index 0081cc4..22dfdae 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Solutions in various programming languages are provided. Enjoy it. 17. [Distribute Candies to People](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/17-Distribute-Candies-to-People) 18. [Numbers With Same Consecutive Differences](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/18-Numbers-With-Same-Consecutive-Differences) 19. [Goat Latin](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/19-Goat-Latin) +20. [Reorder List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/20-Reorder-List) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 385390de1f38f924416d4cee89be00e2db887c70 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 21 Aug 2020 20:53:27 +0200 Subject: [PATCH 242/281] Add Sort Array By Parity C# --- .../Sort-Array-By-Parity.cs | 14 ++++++++++++++ README.md | 1 + 2 files changed, 15 insertions(+) create mode 100644 August-LeetCoding-Challenge/21-Sort-Array-By-Parity/Sort-Array-By-Parity.cs diff --git a/August-LeetCoding-Challenge/21-Sort-Array-By-Parity/Sort-Array-By-Parity.cs b/August-LeetCoding-Challenge/21-Sort-Array-By-Parity/Sort-Array-By-Parity.cs new file mode 100644 index 0000000..8e5247f --- /dev/null +++ b/August-LeetCoding-Challenge/21-Sort-Array-By-Parity/Sort-Array-By-Parity.cs @@ -0,0 +1,14 @@ +public class Solution { + public int[] SortArrayByParity(int[] A) { + int temp = 0; + for(int i=0, j=0; j Date: Sat, 22 Aug 2020 18:22:59 +0200 Subject: [PATCH 243/281] Add 22-Random-Point-in-Non-overlapping-Rectangles C# --- ...dom-Point-in-Non-overlapping-Rectangles.cs | 33 +++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 August-LeetCoding-Challenge/22-Random-Point-in-Non-overlapping-Rectangles/Random-Point-in-Non-overlapping-Rectangles.cs diff --git a/August-LeetCoding-Challenge/22-Random-Point-in-Non-overlapping-Rectangles/Random-Point-in-Non-overlapping-Rectangles.cs b/August-LeetCoding-Challenge/22-Random-Point-in-Non-overlapping-Rectangles/Random-Point-in-Non-overlapping-Rectangles.cs new file mode 100644 index 0000000..7b3d466 --- /dev/null +++ b/August-LeetCoding-Challenge/22-Random-Point-in-Non-overlapping-Rectangles/Random-Point-in-Non-overlapping-Rectangles.cs @@ -0,0 +1,33 @@ +public class Solution { + private int[][] _solutionPoints; + private SortedDictionary _area = new SortedDictionary(); + private int _numberOfSolutions = 0; + private Random _random = new Random(); + + public Solution(int[][] rects) { + _solutionPoints = rects; + for(int i=0; i x.Key >= random).Value; + return Pick(_solutionPoints[index]); + } + + private int[] Pick(int[] rectangle){ + var x = _random.Next(rectangle[0], rectangle[2] + 1); + var y = _random.Next(rectangle[1], rectangle[3] + 1); + return new int[]{x , y}; + } +} + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(rects); + * int[] param_1 = obj.Pick(); + */ \ No newline at end of file diff --git a/README.md b/README.md index 070262f..6209ea1 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Solutions in various programming languages are provided. Enjoy it. 19. [Goat Latin](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/19-Goat-Latin) 20. [Reorder List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/20-Reorder-List) 21. [Sort Array By Parity](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/21-Sort-Array-By-Parity) +22. Random Point in Non-overlapping Rectangles](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/22-Random-Point-in-Non-overlapping-Rectangles) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 61f5e647738720c0e06f2e451cfafc083d4b56ff Mon Sep 17 00:00:00 2001 From: student114 Date: Sun, 23 Aug 2020 16:57:08 +0200 Subject: [PATCH 244/281] Stream of Characters using Trie --- .../Stream-of-Characters.java | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 August-LeetCoding-Challenge/23-Stream-of-Characters/Stream-of-Characters.java diff --git a/August-LeetCoding-Challenge/23-Stream-of-Characters/Stream-of-Characters.java b/August-LeetCoding-Challenge/23-Stream-of-Characters/Stream-of-Characters.java new file mode 100644 index 0000000..9b529bd --- /dev/null +++ b/August-LeetCoding-Challenge/23-Stream-of-Characters/Stream-of-Characters.java @@ -0,0 +1,92 @@ +class StreamChecker { + + private Setletters = new HashSet(); + private Setdictionary = new HashSet(); + private Listl = new ArrayList(); + private int seuil = 0; + private int min = Integer.MAX_VALUE; + private StringBuilder sb = new StringBuilder(); + + private class Trie{ + private boolean isWord; + private TreeMapnext; + + public Trie(){ + this.isWord = false; + next = new TreeMap(); + } + } + + private Trie node = new Trie(); + + public void add(String mot){ + Trie cur = node; + for(int i = mot.length()-1;i >= 0;i--){ + char ch = mot.charAt(i); + if(!cur.next.containsKey(ch)){ + cur.next.put(ch,new Trie()); + } + cur = cur.next.get(ch); + } + cur.isWord = true; + } + + public boolean search(String mot){ + /* + c queue : c false + d queue : cd true + e queue : cde true + f queue : def false + k queue : k false + l queue : kl true + */ + Trie cur = node; + for(int i = 0;i < mot.length();i++){ + char ch = mot.charAt(i); + if(!cur.next.containsKey(ch)){ + return cur.isWord; + } + cur = cur.next.get(ch); + if(cur.isWord){ + //System.out.println(mot); + return true; + } + } + //System.out.println(mot+" "+cur.isWord); + return cur.isWord; + } + + public StreamChecker(String[] words) { + for(int i = 0;i < words.length;i++){ + String mot = words[i]; + seuil = Math.max(mot.length(),seuil); + min = Math.min(mot.length(),min); + dictionary.add(mot); + add(mot); + for(int j = mot.length()-1;j>=0;j--){ + char ch = mot.charAt(j); + letters.add(ch); + } + } + } + + public boolean query(char letter) { + if(!letters.contains(letter)){ + sb.delete(0,sb.length()); + return false; + } + sb.append(letter); + if(sb.length()seuil){ + sb.delete(0,1); + } + boolean flag = search(new StringBuilder(sb).reverse().toString()); + return flag; + } +} + +/** + * Your StreamChecker object will be instantiated and called as such: + * StreamChecker obj = new StreamChecker(words); + * boolean param_1 = obj.query(letter); + */ From 1d7df0d3138d5452f0363d86dac08f2cb44f6d23 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 23 Aug 2020 20:58:44 +0200 Subject: [PATCH 245/281] Add Stream-of-Characters C# --- .../Stream-of-Characters.cs | 46 +++++++++++++++++++ README.md | 3 +- 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 August-LeetCoding-Challenge/23-Stream-of-Characters/Stream-of-Characters.cs diff --git a/August-LeetCoding-Challenge/23-Stream-of-Characters/Stream-of-Characters.cs b/August-LeetCoding-Challenge/23-Stream-of-Characters/Stream-of-Characters.cs new file mode 100644 index 0000000..fc54f5e --- /dev/null +++ b/August-LeetCoding-Challenge/23-Stream-of-Characters/Stream-of-Characters.cs @@ -0,0 +1,46 @@ +public class StreamChecker { + private TrieNode root = new TrieNode(); + private StringBuilder sb = new StringBuilder(); + public StreamChecker(string[] words) { + CreateTrie(words); + } + + public bool Query(char letter) { + sb.Append(letter); + TrieNode node = root; + for(int i = sb.Length-1; i>=0 && node!=null; i--){ + char c = sb[i]; + node = node.next[c -'a']; + if(node != null && node.IsWord){ + return true; + } + } + return false; + } + + private void CreateTrie(string[] words){ + foreach(string s in words){ + var node = root; + int length = s.Length; + for(int i= length -1; i>=0; i--){ + char c = s[i]; + if(node.next[c - 'a'] == null){ + node.next[c - 'a'] = new TrieNode(); + } + node = node.next[c - 'a']; + } + node.IsWord = true; + } + } +} + +public class TrieNode{ + public Boolean IsWord {get;set;} + public TrieNode[] next = new TrieNode[26]; +} + +/** + * Your StreamChecker object will be instantiated and called as such: + * StreamChecker obj = new StreamChecker(words); + * bool param_1 = obj.Query(letter); + */ \ No newline at end of file diff --git a/README.md b/README.md index 6209ea1..86d3f9c 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,8 @@ Solutions in various programming languages are provided. Enjoy it. 19. [Goat Latin](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/19-Goat-Latin) 20. [Reorder List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/20-Reorder-List) 21. [Sort Array By Parity](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/21-Sort-Array-By-Parity) -22. Random Point in Non-overlapping Rectangles](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/22-Random-Point-in-Non-overlapping-Rectangles) +22. [Random Point in Non-overlapping Rectangles](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/22-Random-Point-in-Non-overlapping-Rectangles) +23. [Stream of Characters](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/23-Stream-of-Characters) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 0cc23c12c3939ed00cc352cfc5af2802567216fa Mon Sep 17 00:00:00 2001 From: zijian Date: Mon, 24 Aug 2020 12:09:03 +0200 Subject: [PATCH 246/281] Add Solution Python for Sum of Left Leaves --- .../Sum-of-Left-Leaves.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 August-LeetCoding-Challenge/24-Sum-of-Left-Leaves/Sum-of-Left-Leaves.py diff --git a/August-LeetCoding-Challenge/24-Sum-of-Left-Leaves/Sum-of-Left-Leaves.py b/August-LeetCoding-Challenge/24-Sum-of-Left-Leaves/Sum-of-Left-Leaves.py new file mode 100644 index 0000000..528d668 --- /dev/null +++ b/August-LeetCoding-Challenge/24-Sum-of-Left-Leaves/Sum-of-Left-Leaves.py @@ -0,0 +1,22 @@ +class Solution: + def sumOfLeftLeaves(self, root: TreeNode) -> int: + if not root: + return 0 + if not root.left and not root.right: + return 0 + q = [[root,"mid"]] + res = 0 + while q != []: + l = [] + while q: + l.append(q.pop(0)) + for each in l: + x = each[0] + if not x.left and not x.right: + if each[1]=="left": + res += x.val + if x.left: + q.append([x.left,"left"]) + if x.right: + q.append([x.right,"right"]) + return res From caf93920669863a910b8446663880eead7aac13a Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 24 Aug 2020 18:44:00 +0200 Subject: [PATCH 247/281] Add Sum-of-Left-Leaves C# --- .../Sum-of-Left-Leaves.cs | 33 +++++++++++++++++++ README.md | 1 + 2 files changed, 34 insertions(+) create mode 100644 August-LeetCoding-Challenge/24-Sum-of-Left-Leaves/Sum-of-Left-Leaves.cs diff --git a/August-LeetCoding-Challenge/24-Sum-of-Left-Leaves/Sum-of-Left-Leaves.cs b/August-LeetCoding-Challenge/24-Sum-of-Left-Leaves/Sum-of-Left-Leaves.cs new file mode 100644 index 0000000..9b50cc6 --- /dev/null +++ b/August-LeetCoding-Challenge/24-Sum-of-Left-Leaves/Sum-of-Left-Leaves.cs @@ -0,0 +1,33 @@ +public class Solution { + public int SumOfLeftLeaves(TreeNode root) { + if(root == null) return 0; + + Dfs(root.left, 0); + Dfs(root.right, 1); + return sum; + } + private int sum =0; + private void Dfs(TreeNode node, int direction){ + if(node == null) return; + + if(node.left == null && node.right == null && direction == 0){ + sum += node.val; + } + + Dfs(node.left, 0); + Dfs(node.right, 1); + } +} +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ \ No newline at end of file diff --git a/README.md b/README.md index 86d3f9c..34e858f 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ Solutions in various programming languages are provided. Enjoy it. 21. [Sort Array By Parity](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/21-Sort-Array-By-Parity) 22. [Random Point in Non-overlapping Rectangles](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/22-Random-Point-in-Non-overlapping-Rectangles) 23. [Stream of Characters](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/23-Stream-of-Characters) +24. [Sum of Left Leaves](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/24-Sum-of-Left-Leaves) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 85c27475c7d18bd7022369ec47c5d4aa99c555ef Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 25 Aug 2020 21:19:01 +0200 Subject: [PATCH 248/281] Add 25-Minimum-Cost-For-Tickets C# --- .../Minimum-Cost-For-Tickets.cs | 21 +++++++++++++++++++ README.md | 1 + 2 files changed, 22 insertions(+) create mode 100644 August-LeetCoding-Challenge/25-Minimum-Cost-For-Tickets/Minimum-Cost-For-Tickets.cs diff --git a/August-LeetCoding-Challenge/25-Minimum-Cost-For-Tickets/Minimum-Cost-For-Tickets.cs b/August-LeetCoding-Challenge/25-Minimum-Cost-For-Tickets/Minimum-Cost-For-Tickets.cs new file mode 100644 index 0000000..6e37b1c --- /dev/null +++ b/August-LeetCoding-Challenge/25-Minimum-Cost-For-Tickets/Minimum-Cost-For-Tickets.cs @@ -0,0 +1,21 @@ +public class Solution { + public int MincostTickets(int[] days, int[] costs) { + int lastDay = days[days.Length - 1]; + bool[] isTravelDay = new bool[lastDay+1]; + foreach(var day in days){ + isTravelDay[day] = true; + } + int[] dp = new int[lastDay+1]; + for(int i=1; i<=lastDay; i++){ + if(!isTravelDay[i]){ + dp[i] = dp[i-1]; + continue; + } + + dp[i] = dp[i-1] + costs[0]; + dp[i] = Math.Min(dp[i], dp[Math.Max(0, i-7)] + costs[1]); + dp[i] = Math.Min(dp[i], dp[Math.Max(0, i-30)] + costs[2]); + } + return dp[lastDay]; + } +} diff --git a/README.md b/README.md index 34e858f..d9273de 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ Solutions in various programming languages are provided. Enjoy it. 22. [Random Point in Non-overlapping Rectangles](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/22-Random-Point-in-Non-overlapping-Rectangles) 23. [Stream of Characters](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/23-Stream-of-Characters) 24. [Sum of Left Leaves](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/24-Sum-of-Left-Leaves) +25. [Minimum Cost For Tickets](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/25-Minimum-Cost-For-Tickets) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 79c05af2483d9b205c65c3a7d6e17f5c08e2c1cc Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 26 Aug 2020 18:24:52 +0200 Subject: [PATCH 249/281] Add 26-Fizz-Buzz C# --- .../26-Fizz-Buzz/Fizz-Buzz.cs | 44 +++++++++++++++++++ README.md | 1 + 2 files changed, 45 insertions(+) create mode 100644 August-LeetCoding-Challenge/26-Fizz-Buzz/Fizz-Buzz.cs diff --git a/August-LeetCoding-Challenge/26-Fizz-Buzz/Fizz-Buzz.cs b/August-LeetCoding-Challenge/26-Fizz-Buzz/Fizz-Buzz.cs new file mode 100644 index 0000000..521acbd --- /dev/null +++ b/August-LeetCoding-Challenge/26-Fizz-Buzz/Fizz-Buzz.cs @@ -0,0 +1,44 @@ +public class Solution { + //Solution 1 + public IList FizzBuzz(int n) { + int i=1; + var res = new List(); + while(i<=n){ + if(i%15 == 0){ + res.Add("FizzBuzz"); + }else if(i%3==0){ + res.Add("Fizz"); + }else if(i%5 == 0){ + res.Add("Buzz"); + }else{ + res.Add(i.ToString()); + } + i++; + } + return res; + } + + //Solution 2 + public IList FizzBuzz(int n) { + var res = new List(); + int fizz = 0, buzz = 0; + for(int i=1; i<=n; i++){ + fizz++; + buzz++; + if(fizz==3 && buzz == 5){ + res.Add("FizzBuzz"); + fizz=0; + buzz=0; + }else if(fizz == 3){ + res.Add("Fizz"); + fizz=0; + }else if(buzz == 5){ + res.Add("Buzz"); + buzz=0; + }else{ + res.Add(i.ToString()); + } + } + return res; + } +} \ No newline at end of file diff --git a/README.md b/README.md index d9273de..9472387 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ Solutions in various programming languages are provided. Enjoy it. 23. [Stream of Characters](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/23-Stream-of-Characters) 24. [Sum of Left Leaves](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/24-Sum-of-Left-Leaves) 25. [Minimum Cost For Tickets](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/25-Minimum-Cost-For-Tickets) +26. [Fizz Buzz](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/26-Fizz-Buzz) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From f2239bf75875192fa34e2c69784f780b02b81d89 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Thu, 27 Aug 2020 21:55:42 +0200 Subject: [PATCH 250/281] Add Find-Right-Interval C# --- .../Find-Right-Interval.cs | 25 +++++++++++++++++++ README.md | 1 + 2 files changed, 26 insertions(+) create mode 100644 August-LeetCoding-Challenge/27-Find-Right-Interval/Find-Right-Interval.cs diff --git a/August-LeetCoding-Challenge/27-Find-Right-Interval/Find-Right-Interval.cs b/August-LeetCoding-Challenge/27-Find-Right-Interval/Find-Right-Interval.cs new file mode 100644 index 0000000..ebd4d1c --- /dev/null +++ b/August-LeetCoding-Challenge/27-Find-Right-Interval/Find-Right-Interval.cs @@ -0,0 +1,25 @@ +public class Solution { + public int[] FindRightInterval(int[][] intervals) { + int[] ans = new int[intervals.Length]; + var map = new Dictionary, int>(); + int N = intervals.Length; + for(int i = 0; i < N; i++) + map.Add(new KeyValuePair(intervals[i][0], intervals[i][1]), i); + Array.Sort(intervals, (a, b) => { + if(a[0] == b[0]) return a[1] - b[1]; + return a[0] - b[0]; + }); + for(int i = 0; i < N; i++){ + int index = -1; + int b = intervals[i][1]; + for(int j = i + 1; j < N; j++){ + if(b <= intervals[j][0]){ + index = map[new KeyValuePair(intervals[j][0], intervals[j][1])]; + break; + } + } + ans[map[new KeyValuePair(intervals[i][0], b)]] = index; + } + return ans; + } +} diff --git a/README.md b/README.md index 9472387..59a0209 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Solutions in various programming languages are provided. Enjoy it. 24. [Sum of Left Leaves](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/24-Sum-of-Left-Leaves) 25. [Minimum Cost For Tickets](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/25-Minimum-Cost-For-Tickets) 26. [Fizz Buzz](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/26-Fizz-Buzz) +27. [Find Right Interval](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/27-Find-Right-Interval) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 2958396d5198fee4fe63170fd7324e09b8ac7a62 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 28 Aug 2020 19:03:31 +0200 Subject: [PATCH 251/281] Add Implement Rand10() Using Rand7() C# --- .../Implement-Rand10()-Using-Rand7().cs | 13 +++++++++++++ README.md | 1 + 2 files changed, 14 insertions(+) create mode 100644 August-LeetCoding-Challenge/28-Implement-Rand10()-Using-Rand7()/Implement-Rand10()-Using-Rand7().cs diff --git a/August-LeetCoding-Challenge/28-Implement-Rand10()-Using-Rand7()/Implement-Rand10()-Using-Rand7().cs b/August-LeetCoding-Challenge/28-Implement-Rand10()-Using-Rand7()/Implement-Rand10()-Using-Rand7().cs new file mode 100644 index 0000000..6b29f85 --- /dev/null +++ b/August-LeetCoding-Challenge/28-Implement-Rand10()-Using-Rand7()/Implement-Rand10()-Using-Rand7().cs @@ -0,0 +1,13 @@ +/** + * The Rand7() API is already defined in the parent class SolBase. + * public int Rand7(); + * @return a random integer in the range 1 to 7 + */ +public class Solution : SolBase { + public int Rand10() { + while(true){ + int rand = 7*(Rand7() - 1) + (Rand7() - 1); // 0 to 48 + if(rand < 40) return rand % 10 + 1; + } + } +} \ No newline at end of file diff --git a/README.md b/README.md index 59a0209..e530523 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ Solutions in various programming languages are provided. Enjoy it. 25. [Minimum Cost For Tickets](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/25-Minimum-Cost-For-Tickets) 26. [Fizz Buzz](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/26-Fizz-Buzz) 27. [Find Right Interval](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/27-Find-Right-Interval) +28. [Implement Rand10() Using Rand7()](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/28-Implement-Rand10()-Using-Rand7()) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From bb3558038564f8b961550cfbe8c71394d400718e Mon Sep 17 00:00:00 2001 From: jiangl <> Date: Sat, 29 Aug 2020 14:06:33 +0200 Subject: [PATCH 252/281] add pancake sorting ruby version --- .../29-Pancake-Sorting/pancake_sorting.rb | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 August-LeetCoding-Challenge/29-Pancake-Sorting/pancake_sorting.rb diff --git a/August-LeetCoding-Challenge/29-Pancake-Sorting/pancake_sorting.rb b/August-LeetCoding-Challenge/29-Pancake-Sorting/pancake_sorting.rb new file mode 100644 index 0000000..1050af6 --- /dev/null +++ b/August-LeetCoding-Challenge/29-Pancake-Sorting/pancake_sorting.rb @@ -0,0 +1,29 @@ +def pancake_sort(a) + sorted_a = a.sort + max = nil + k = nil + out = [] + while a != sorted_a + max = a.max + if max != a.last + max_index = a.index(max) + if max_index != 0 + left = a[0..max_index] + right = a[max_index+1..-1] + left = left.reverse + a = (left + right).reverse + out << max_index+1 + else + a = a.reverse + end + out << a.length + + a.pop + sorted_a.pop + else + a.pop + sorted_a.pop + end + end + out +end \ No newline at end of file From 9da6fde10aaee8f83a91bd84f1b4394ee822b61f Mon Sep 17 00:00:00 2001 From: jiangl <> Date: Sat, 29 Aug 2020 14:30:38 +0200 Subject: [PATCH 253/281] change name --- .../29-Pancake-Sorting/{pancake_sorting.rb => Pancake-Sorting.rb} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename August-LeetCoding-Challenge/29-Pancake-Sorting/{pancake_sorting.rb => Pancake-Sorting.rb} (100%) diff --git a/August-LeetCoding-Challenge/29-Pancake-Sorting/pancake_sorting.rb b/August-LeetCoding-Challenge/29-Pancake-Sorting/Pancake-Sorting.rb similarity index 100% rename from August-LeetCoding-Challenge/29-Pancake-Sorting/pancake_sorting.rb rename to August-LeetCoding-Challenge/29-Pancake-Sorting/Pancake-Sorting.rb From fc2c2082d4baee2eeed84f216e759f8675d19e93 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 30 Aug 2020 08:42:05 +0200 Subject: [PATCH 254/281] Add 29-Pancake-Sorting C# --- .../29-Pancake-Sorting/Pancake-Sorting.cs | 35 +++++++++++++++++++ README.md | 1 + 2 files changed, 36 insertions(+) create mode 100644 August-LeetCoding-Challenge/29-Pancake-Sorting/Pancake-Sorting.cs diff --git a/August-LeetCoding-Challenge/29-Pancake-Sorting/Pancake-Sorting.cs b/August-LeetCoding-Challenge/29-Pancake-Sorting/Pancake-Sorting.cs new file mode 100644 index 0000000..96a6527 --- /dev/null +++ b/August-LeetCoding-Challenge/29-Pancake-Sorting/Pancake-Sorting.cs @@ -0,0 +1,35 @@ +public class Solution { + public IList PancakeSort(int[] A) { + var res = new List(); + int n = A.Length, largest = n; + for (int i = 0; i < n; i++) { + int index = Find(A, largest); + Flip(A, index); + Flip(A, largest - 1); + res.Add(index + 1); + res.Add(largest--); + } + return res; + } + + private int Find(int[] A, int target){ + for(int i=0; i Date: Sun, 30 Aug 2020 20:32:16 +0200 Subject: [PATCH 255/281] Add Largest Component Size by Common Factor C# --- ...Largest-Component-Size-by-Common-Factor.cs | 51 +++++++++++++++++++ README.md | 1 + 2 files changed, 52 insertions(+) create mode 100644 August-LeetCoding-Challenge/30-Largest-Component-Size-by-Common-Factor/Largest-Component-Size-by-Common-Factor.cs diff --git a/August-LeetCoding-Challenge/30-Largest-Component-Size-by-Common-Factor/Largest-Component-Size-by-Common-Factor.cs b/August-LeetCoding-Challenge/30-Largest-Component-Size-by-Common-Factor/Largest-Component-Size-by-Common-Factor.cs new file mode 100644 index 0000000..9538611 --- /dev/null +++ b/August-LeetCoding-Challenge/30-Largest-Component-Size-by-Common-Factor/Largest-Component-Size-by-Common-Factor.cs @@ -0,0 +1,51 @@ +public class Solution { + int[] par; + int[] cnt; + public int LargestComponentSize(int[] A) { + var n = A.Length; + par = new int[n]; + cnt = new int[n]; + var dict = new Dictionary>(); + for(int i=0; i()); + dict[d].Add(i); + } + d++; + } + if(x>1){ + if(!dict.ContainsKey(x)) + dict.Add(x, new HashSet()); + dict[x].Add(i); + } + } + + for(int i=0; i h in dict.Values){ + int fir = h.First(); + foreach(var idx in h){ + Union(idx, fir); + max = Math.Max(cnt[Find(idx)], max); + } + } + return max; + } + private void Union(int i, int j){ + int pi = Find(i); + int pj = Find(j); + if(pi == pj) return ; + par[pi] = pj; + cnt[pj] += cnt[pi]; + } + + private int Find(int i){ + if(i==par[i]) return i; + return par[i] = Find(par[i]); + } +} \ No newline at end of file diff --git a/README.md b/README.md index f7fa720..a349120 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ Solutions in various programming languages are provided. Enjoy it. 27. [Find Right Interval](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/27-Find-Right-Interval) 28. [Implement Rand10() Using Rand7()](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/28-Implement-Rand10()-Using-Rand7()) 29. [Pancake Sorting](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/29-Pancake-Sorting) +30. [Largest Component Size by Common Factor](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/30-Largest-Component-Size-by-Common-Factor) ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 87197810350111ce5c5fb9ecdc50856d2b91d80a Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 31 Aug 2020 21:51:55 +0200 Subject: [PATCH 256/281] Add Delete-Node-in-a-BST C# --- .../Delete-Node-in-a-BST.cs | 43 +++++++++++++++++++ README.md | 2 + 2 files changed, 45 insertions(+) create mode 100644 August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.cs diff --git a/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.cs b/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.cs new file mode 100644 index 0000000..e6cdf73 --- /dev/null +++ b/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.cs @@ -0,0 +1,43 @@ +public class Solution { + public TreeNode DeleteNode(TreeNode root, int key) { + if(root == null) return null; + if(key < root.val){ + root.left = DeleteNode(root.left, key); + }else if(key > root.val){ + root.right = DeleteNode(root.right, key); + }else{ + if(root.left == null) + { + return root.right; + } + else if(root.right == null){ + return root.left; + } + + var minNode = FindMin(root.right); + root.val = minNode.val; + root.right = DeleteNode(root.right, root.val); + } + return root; + } + + public TreeNode FindMin(TreeNode node){ + while(node.left != null){ + node = node.left; + } + return node; + } +} +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ \ No newline at end of file diff --git a/README.md b/README.md index a349120..53a6b2b 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,8 @@ Solutions in various programming languages are provided. Enjoy it. 28. [Implement Rand10() Using Rand7()](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/28-Implement-Rand10()-Using-Rand7()) 29. [Pancake Sorting](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/29-Pancake-Sorting) 30. [Largest Component Size by Common Factor](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/30-Largest-Component-Size-by-Common-Factor) +31. [Delete Node in a BST](https://github.com/AlgoStudyGroup/Leetcode/tree/master/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST) + ## July LeetCoding Challenge Click [here](https://leetcode.com/explore/featured/card/july-leetcoding-challenge/) for problem descriptions. From 3c10b1cb36bbcee89dbde9912d91af55ee025e8c Mon Sep 17 00:00:00 2001 From: jiangl <> Date: Mon, 31 Aug 2020 22:58:20 +0200 Subject: [PATCH 257/281] add delete_node_in_a_bst onn ruby version --- .../Delete-Node-in-a-BST.rb | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.rb diff --git a/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.rb b/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.rb new file mode 100644 index 0000000..7d3c0d2 --- /dev/null +++ b/August-LeetCoding-Challenge/31-Delete-Node-in-a-BST/Delete-Node-in-a-BST.rb @@ -0,0 +1,49 @@ +# Definition for a binary tree node. +# class TreeNode +# attr_accessor :val, :left, :right +# def initialize(val = 0, left = nil, right = nil) +# @val = val +# @left = left +# @right = right +# end +# end +# @param {TreeNode} root +# @param {Integer} key +# @return {TreeNode} +def delete_node(root, key) + if root == nil + return root + elsif root.val > key + root.left = delete_node(root.left, key) + + elsif root.val < key + root.right = delete_node(root.right, key) + + else + if root.left == nil && root.right == nil + root = nil + return nil + elsif root.left == nil + tmp = root.right + root = nil + return tmp + elsif root.right == nil + tmp = root.left + root = nil + return tmp + else + tmp = min_value(root.right) + root.val = tmp.val + root.right = delete_node(root.right, tmp.val) + end + end + return root +end + +def min_value(node) + current = node + while current.left != nil + current = current.left + end + current +end \ No newline at end of file From 967256911213ca09b7534e6f072a70a54910cac6 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Tue, 1 Sep 2020 21:41:10 +0200 Subject: [PATCH 258/281] Add Largest Time for Given Digits C# --- README.md | 7 ++++++ .../Largest-Time-for-Given-Digits.cs | 25 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-for-Given-Digits.cs diff --git a/README.md b/README.md index 53a6b2b..19555eb 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,13 @@ https://leetcode.com +## September LeetCoding Challenge +Click [here](https://leetcode.com/explore/challenge/card/september-leetcoding-challenge) for problem descriptions. + +Solutions in various programming languages are provided. Enjoy it. + +1. [Largest Time for Given Digits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits) + ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. diff --git a/September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-for-Given-Digits.cs b/September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-for-Given-Digits.cs new file mode 100644 index 0000000..5fdc94e --- /dev/null +++ b/September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-for-Given-Digits.cs @@ -0,0 +1,25 @@ +public class Solution { + public string LargestTimeFromDigits(int[] A) { + var l = new Queue(); + l.Enqueue(""); + + for(int n=0; n0; size--){ + var s = l.Dequeue(); + for(int i=0; i<=s.Length; i++){ + l.Enqueue(s.Substring(0,i) + A[n] + s.Substring(i)); + } + } + } + + var largest = ""; + foreach(var s in l){ + var t = s.Substring(0, 2) + ":" + s.Substring(2); + if(t[3] < '6' && t.CompareTo("24:00") <0 && t.CompareTo(largest)>0){ + largest = t; + } + } + + return largest; + } +} From 215774e28459c09631f3cf1ac5cc4d85988f11c0 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 6 Sep 2020 19:05:26 +0200 Subject: [PATCH 259/281] Add C# solutions --- README.md | 5 ++ .../Contains-Duplicate-III.cs | 23 ++++++++ .../Repeated-Substring-Pattern.cs | 33 ++++++++++++ .../04-Partition-Labels/Partition-Labels.cs | 22 ++++++++ ...All-Elements-in-Two-Binary-Search-Trees.cs | 54 +++++++++++++++++++ .../06-Image-Overlap/Image-Overlap.cs | 40 ++++++++++++++ 6 files changed, 177 insertions(+) create mode 100644 September-LeetCoding-Challenge/02-Contains-Duplicate-III/Contains-Duplicate-III.cs create mode 100644 September-LeetCoding-Challenge/03-Repeated-Substring-Pattern/Repeated-Substring-Pattern.cs create mode 100644 September-LeetCoding-Challenge/04-Partition-Labels/Partition-Labels.cs create mode 100644 September-LeetCoding-Challenge/05-All-Elements-in-Two-Binary-Search-Trees/All-Elements-in-Two-Binary-Search-Trees.cs create mode 100644 September-LeetCoding-Challenge/06-Image-Overlap/Image-Overlap.cs diff --git a/README.md b/README.md index 19555eb..f79e858 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,11 @@ Click [here](https://leetcode.com/explore/challenge/card/september-leetcoding-ch Solutions in various programming languages are provided. Enjoy it. 1. [Largest Time for Given Digits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits) +2. [Contains Duplicate III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/02-Contains-Duplicate-III) +3. [Repeated Substring Pattern](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/03-Repeated-Substring-Pattern) +4. [Partition Labels](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/04-Partition-Labels) +5. [All Elements in Two Binary Search Trees](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/05-All-Elements-in-Two-Binary-Search-Trees) +6. [Image Overlap](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/06-Image-Overlap) ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. diff --git a/September-LeetCoding-Challenge/02-Contains-Duplicate-III/Contains-Duplicate-III.cs b/September-LeetCoding-Challenge/02-Contains-Duplicate-III/Contains-Duplicate-III.cs new file mode 100644 index 0000000..4381bf2 --- /dev/null +++ b/September-LeetCoding-Challenge/02-Contains-Duplicate-III/Contains-Duplicate-III.cs @@ -0,0 +1,23 @@ +public class Solution { + public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) { + if (t < 0) return false; + var d = new Dictionary(); + long w = (long)t + 1; + for (int i = 0; i < nums.Length; ++i) { + long m = getID(nums[i], w); + if (d.ContainsKey(m)) + return true; + if (d.ContainsKey(m - 1) && Math.Abs(nums[i] - d[m - 1]) < w) + return true; + if (d.ContainsKey(m + 1) && Math.Abs(nums[i] - d[m + 1]) < w) + return true; + d.Add(m, (long)nums[i]); + if (i >= k) d.Remove(getID(nums[i - k], w)); + } + return false; + } + + private long getID(long i, long w) { + return i < 0 ? (i + 1) / w - 1 : i / w; + } +} \ No newline at end of file diff --git a/September-LeetCoding-Challenge/03-Repeated-Substring-Pattern/Repeated-Substring-Pattern.cs b/September-LeetCoding-Challenge/03-Repeated-Substring-Pattern/Repeated-Substring-Pattern.cs new file mode 100644 index 0000000..fc0040b --- /dev/null +++ b/September-LeetCoding-Challenge/03-Repeated-Substring-Pattern/Repeated-Substring-Pattern.cs @@ -0,0 +1,33 @@ +public class Solution { + public bool RepeatedSubstringPattern(string s) { + var len = s.Length; + for (int i = len / 2; i >= 1; i--) + { + // Dividable + if (len % i == 0) + { + int m = len / i; + var sub = s.Substring(0, i); + int j; + + //Check sub is repeated in each round, until m rounds. + for (j = 1; j < m; j++) + { + if (!sub.Equals(s.Substring(j * i, i))) break; + } + + //If sub is repeated m rounds, then it's a repeated substring + if (j == m) + return true; + } + } + return false; + } + + public void Test() + { + var s = "abcdabcdabcd"; + var r = RepeatedSubstringPattern(s); + Console.WriteLine(r); + } +} \ No newline at end of file diff --git a/September-LeetCoding-Challenge/04-Partition-Labels/Partition-Labels.cs b/September-LeetCoding-Challenge/04-Partition-Labels/Partition-Labels.cs new file mode 100644 index 0000000..e637d29 --- /dev/null +++ b/September-LeetCoding-Challenge/04-Partition-Labels/Partition-Labels.cs @@ -0,0 +1,22 @@ +public class Solution { + public IList PartitionLabels(string S) { + if(string.IsNullOrEmpty(S)) return null; + + int[] largestPositionByValue = new int[26]; + for(int i=0; i(); + var start = 0; + var end=0; + for(int i=0; i GetAllElements(TreeNode root1, TreeNode root2) { + var l1 = new List(); + Traversal(root1, l1); + var l2 = new List(); + Traversal(root2, l2); + + var res = Merge(l1, l2); + return res; + } + + private void Traversal(TreeNode node, List l){ + if(node == null) return; + Traversal(node.left, l); + l.Add(node.val); + Traversal(node.right, l); + } + + private List Merge(List l1, List l2){ + var res = new List(); + int i=0, j=0; + while(i al = new List(), bl = new List(); + + for (int i = 0; i < rows; i++) + { + for (int j = 0; j < cols; j++) + { + if(A[i][j] == 1) al.Add(new int[]{i, j}); + if(B[i][j] == 1) bl.Add(new int[]{i, j }); + } + } + + var dict = new Dictionary(); + foreach (int[] a in al) + { + foreach (int[] b in bl) + { + var s = (a[0] - b[0]) + " " + (a[1] - b[1]); + if (dict.ContainsKey(s)) + { + dict[s]++; + } + else + { + dict.Add(s, 1); + } + } + } + + int c = 0; + foreach(var v in dict.Values){ + c = Math.Max(c, v); + } + return c; + } +} \ No newline at end of file From 98d7b74d97e39f91e81a42eb2706d65a9bb5338c Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 9 Sep 2020 19:50:32 +0200 Subject: [PATCH 260/281] Add C# solutions --- README.md | 3 ++ .../07-Word-Pattern/Word-Pattern.cs | 29 +++++++++++++++++ .../Sum-of-Root-To-Leaf-Binary-Numbers.cs | 30 ++++++++++++++++++ .../Compare-Version-Numbers.cs | 31 +++++++++++++++++++ 4 files changed, 93 insertions(+) create mode 100644 September-LeetCoding-Challenge/07-Word-Pattern/Word-Pattern.cs create mode 100644 September-LeetCoding-Challenge/08-Sum-of-Root-To-Leaf-Binary-Numbers/Sum-of-Root-To-Leaf-Binary-Numbers.cs create mode 100644 September-LeetCoding-Challenge/09-Compare-Version-Numbers/Compare-Version-Numbers.cs diff --git a/README.md b/README.md index f79e858..a4be82c 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,9 @@ Solutions in various programming languages are provided. Enjoy it. 4. [Partition Labels](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/04-Partition-Labels) 5. [All Elements in Two Binary Search Trees](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/05-All-Elements-in-Two-Binary-Search-Trees) 6. [Image Overlap](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/06-Image-Overlap) +7. [Word Pattern](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/07-Word-Pattern) +8. [Sum of Root To Leaf Binary Numbers](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/08-Sum-of-Root-To-Leaf-Binary-Numbers) +9. [Compare Version Numbers](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/09-Compare-Version-Numbers) ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. diff --git a/September-LeetCoding-Challenge/07-Word-Pattern/Word-Pattern.cs b/September-LeetCoding-Challenge/07-Word-Pattern/Word-Pattern.cs new file mode 100644 index 0000000..e7773d4 --- /dev/null +++ b/September-LeetCoding-Challenge/07-Word-Pattern/Word-Pattern.cs @@ -0,0 +1,29 @@ +public class Solution { + public bool WordPattern(string pattern, string str) { + var words = str.Split(" "); + + if (pattern.Length != words.Length) return false; + + var dict = new Dictionary(); + + for (int i = 0; i < words.Length; i++) + { + char c = pattern[i]; //Positionning char + + if (dict.ContainsKey(c)) + { + if (dict[c] != words[i]) + return false; + } + else + { + if (dict.ContainsValue(words[i])) + return false; + + dict.Add(c, words[i]); + } + } + + return true; + } +} \ No newline at end of file diff --git a/September-LeetCoding-Challenge/08-Sum-of-Root-To-Leaf-Binary-Numbers/Sum-of-Root-To-Leaf-Binary-Numbers.cs b/September-LeetCoding-Challenge/08-Sum-of-Root-To-Leaf-Binary-Numbers/Sum-of-Root-To-Leaf-Binary-Numbers.cs new file mode 100644 index 0000000..7f27986 --- /dev/null +++ b/September-LeetCoding-Challenge/08-Sum-of-Root-To-Leaf-Binary-Numbers/Sum-of-Root-To-Leaf-Binary-Numbers.cs @@ -0,0 +1,30 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +public class Solution { + public int SumRootToLeaf(TreeNode root) { + if(root == null) return 0; + + return Traverse(root, 0); + } + + private int Traverse(TreeNode node, int v){ + if(node == null) { + return 0; + } + + v = v * 2 + node.val; + + return node.left == node.right ? v : Traverse(node.left, v) + Traverse(node.right, v); + } +} \ No newline at end of file diff --git a/September-LeetCoding-Challenge/09-Compare-Version-Numbers/Compare-Version-Numbers.cs b/September-LeetCoding-Challenge/09-Compare-Version-Numbers/Compare-Version-Numbers.cs new file mode 100644 index 0000000..91aea79 --- /dev/null +++ b/September-LeetCoding-Challenge/09-Compare-Version-Numbers/Compare-Version-Numbers.cs @@ -0,0 +1,31 @@ +public class Solution { + public int CompareVersion(string version1, string version2) { + var v1parts = version1.Split(".").ToList(); + var v2parts = version2.Split(".").ToList(); + + if(v1parts.Count != v2parts.Count){ + while(v1parts.Count < v2parts.Count) + { + v1parts.Add("0"); + } + while(v1parts.Count > v2parts.Count) + { + v2parts.Add("0"); + } + } + + for(int i=0; i v2){ + return 1; + }else if(v1 == v2){ + continue; + }else if(v1 < v2){ + return -1; + } + } + + return 0; + } +} \ No newline at end of file From 34364863e64aed472298eb472fd598f57de22f20 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sat, 12 Sep 2020 11:33:20 +0200 Subject: [PATCH 261/281] Add C# solutions --- .../10-Bulls-and-Cows/Bulls-and-Cows.cs | 20 ++++++++++++++ .../Maximum-Product-Subarray.cs | 17 ++++++++++++ .../Combination-Sum-III.cs | 26 +++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 September-LeetCoding-Challenge/10-Bulls-and-Cows/Bulls-and-Cows.cs create mode 100644 September-LeetCoding-Challenge/11-Maximum-Product-Subarray/Maximum-Product-Subarray.cs create mode 100644 September-LeetCoding-Challenge/12-Combination-Sum-III/Combination-Sum-III.cs diff --git a/September-LeetCoding-Challenge/10-Bulls-and-Cows/Bulls-and-Cows.cs b/September-LeetCoding-Challenge/10-Bulls-and-Cows/Bulls-and-Cows.cs new file mode 100644 index 0000000..289ccfb --- /dev/null +++ b/September-LeetCoding-Challenge/10-Bulls-and-Cows/Bulls-and-Cows.cs @@ -0,0 +1,20 @@ +public class Solution { + public string GetHint(string secret, string guess) { + var bulls = 0; + var cows = 0; + int[] secretarr = new int[10]; + int[] guessarr = new int[10]; + for(int i=0; i> CombinationSum3(int k, int n) + { + var res = new List>(); + var tmp = new List(); + Backtrack(res, tmp, k, n, 1); + return res; + } + + public void Backtrack(List> res, List tmp, int k, int n, int idx) + { + if (k == tmp.Count && n == 0) + { + res.Add(new List(tmp)); //Deep clone + return; + } + + for (int i = idx; i <= n && k > 0 && n > 0; i++) + { + if(i>9) break; + tmp.Add(i); + Backtrack(res, tmp, k, n - i, i + 1); + tmp.RemoveAt(tmp.Count - 1); //Remove last item when it doesn't find the correct combo + } + } +} From f520e977f10dc68b446e57f475e274c56eead389 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sat, 12 Sep 2020 11:35:04 +0200 Subject: [PATCH 262/281] update --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index a4be82c..ee3cd4c 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,9 @@ Solutions in various programming languages are provided. Enjoy it. 7. [Word Pattern](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/07-Word-Pattern) 8. [Sum of Root To Leaf Binary Numbers](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/08-Sum-of-Root-To-Leaf-Binary-Numbers) 9. [Compare Version Numbers](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/09-Compare-Version-Numbers) +10. [Bulls and Cows](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/10-Bulls-and-Cows) +11. [Maximum Product Subarray](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/11-Maximum-Product-Subarray) +12. [Combination Sum III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/12-Combination-Sum-III) ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. From ecf0c02800f15a79d51381786d34e66ec31bf44c Mon Sep 17 00:00:00 2001 From: jiangl <> Date: Sat, 12 Sep 2020 23:33:46 +0200 Subject: [PATCH 263/281] add some september's ruby solution --- .../Largest-Time-For-Given-Digest.rb | 6 +++ .../Contains-Duplicate-III.rb | 12 +++++ .../Repeated-Substring-Pattern.rb | 18 ++++++++ .../04-Partition-Labels/Partition-Labels.rb | 22 +++++++++ ...All-Elements-in-Two-Binary-Search-Trees.rb | 46 +++++++++++++++++++ .../06-Image-Overlap/Image-Overlap.rb | 37 +++++++++++++++ .../07-Word-Pattern/Word-Pattern.rb | 17 +++++++ .../Sum-of-Root-To-Leaf-Binary-Numbers.rb | 16 +++++++ .../Compare-Version-Numbers.rb | 23 ++++++++++ .../10-Bulls-and-Cows/Bulls-and-Cows.rb | 30 ++++++++++++ .../Maximum-Product-Subarray.rb | 16 +++++++ .../Combination-Sum-III.rb | 23 ++++++++++ 12 files changed, 266 insertions(+) create mode 100644 September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-For-Given-Digest.rb create mode 100644 September-LeetCoding-Challenge/02-Contains-Duplicate-III/Contains-Duplicate-III.rb create mode 100644 September-LeetCoding-Challenge/03-Repeated-Substring-Pattern/Repeated-Substring-Pattern.rb create mode 100644 September-LeetCoding-Challenge/04-Partition-Labels/Partition-Labels.rb create mode 100644 September-LeetCoding-Challenge/05-All-Elements-in-Two-Binary-Search-Trees/All-Elements-in-Two-Binary-Search-Trees.rb create mode 100644 September-LeetCoding-Challenge/06-Image-Overlap/Image-Overlap.rb create mode 100644 September-LeetCoding-Challenge/07-Word-Pattern/Word-Pattern.rb create mode 100644 September-LeetCoding-Challenge/08-Sum-of-Root-To-Leaf-Binary-Numbers/Sum-of-Root-To-Leaf-Binary-Numbers.rb create mode 100644 September-LeetCoding-Challenge/09-Compare-Version-Numbers/Compare-Version-Numbers.rb create mode 100644 September-LeetCoding-Challenge/10-Bulls-and-Cows/Bulls-and-Cows.rb create mode 100644 September-LeetCoding-Challenge/11-Maximum-Product-Subarray/Maximum-Product-Subarray.rb create mode 100644 September-LeetCoding-Challenge/12-Combination-Sum-III/Combination-Sum-III.rb diff --git a/September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-For-Given-Digest.rb b/September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-For-Given-Digest.rb new file mode 100644 index 0000000..efcbc39 --- /dev/null +++ b/September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-For-Given-Digest.rb @@ -0,0 +1,6 @@ +def largest_time_from_digits(a) + out = a.permutation.to_a.map {|e| e.join("").to_i}.sort.select{|elt| elt < 2359 && elt.to_s[-2..-1] .to_i < 60}.last + + return "" if out == nil + out.to_s.rjust(4, '0').insert(2, ":") +end \ No newline at end of file diff --git a/September-LeetCoding-Challenge/02-Contains-Duplicate-III/Contains-Duplicate-III.rb b/September-LeetCoding-Challenge/02-Contains-Duplicate-III/Contains-Duplicate-III.rb new file mode 100644 index 0000000..230dccf --- /dev/null +++ b/September-LeetCoding-Challenge/02-Contains-Duplicate-III/Contains-Duplicate-III.rb @@ -0,0 +1,12 @@ +def contains_nearby_almost_duplicate(nums, k, t) + length = nums.length + out = false + 0.upto(length-1) do |i| + (i+1).upto([length-1,i+k].min) do |n| + + return true if (nums[n] - nums[i]).abs <= t + + end + end + out +end \ No newline at end of file diff --git a/September-LeetCoding-Challenge/03-Repeated-Substring-Pattern/Repeated-Substring-Pattern.rb b/September-LeetCoding-Challenge/03-Repeated-Substring-Pattern/Repeated-Substring-Pattern.rb new file mode 100644 index 0000000..d063788 --- /dev/null +++ b/September-LeetCoding-Challenge/03-Repeated-Substring-Pattern/Repeated-Substring-Pattern.rb @@ -0,0 +1,18 @@ +def repeated_substring_pattern(s) + out = false + length = s.length / 2 + 0.upto(length) do |n| + out = is_repeated_sub?(s[0..n], s) + return out if out == true + end + out + +end + +def is_repeated_sub?(sub, string) + modulo = string.length % sub.length + return false if modulo != 0 + multiplicator = string.length / sub.length + return false if multiplicator <= 1 + return (sub * multiplicator) == string +end \ No newline at end of file diff --git a/September-LeetCoding-Challenge/04-Partition-Labels/Partition-Labels.rb b/September-LeetCoding-Challenge/04-Partition-Labels/Partition-Labels.rb new file mode 100644 index 0000000..6818551 --- /dev/null +++ b/September-LeetCoding-Challenge/04-Partition-Labels/Partition-Labels.rb @@ -0,0 +1,22 @@ +def partition_labels(s) + last_indices = Array.new(26) + s.each_char.with_index do |val, index| + last_indices[val.ord - "a".ord] = index + end + last_indices + start = 0 + finish = 0 + out = [] + + p last_indices + 0.upto((s.length)-1) do |n| + val = s[n] + finish = [finish, last_indices[val.ord - "a".ord]].max + if finish == n + + out << finish-start + 1 + start = finish + 1 + end + end + out +end \ No newline at end of file diff --git a/September-LeetCoding-Challenge/05-All-Elements-in-Two-Binary-Search-Trees/All-Elements-in-Two-Binary-Search-Trees.rb b/September-LeetCoding-Challenge/05-All-Elements-in-Two-Binary-Search-Trees/All-Elements-in-Two-Binary-Search-Trees.rb new file mode 100644 index 0000000..5ee9682 --- /dev/null +++ b/September-LeetCoding-Challenge/05-All-Elements-in-Two-Binary-Search-Trees/All-Elements-in-Two-Binary-Search-Trees.rb @@ -0,0 +1,46 @@ +def get_all_elements(root1, root2) + + arr_1 = in_order(root1, []) + arr_2 = in_order(root2, []) + res = [] + + len1 = arr_1.length + len2 = arr_2.length + index_1 = 0 + index_2 = 0 + + while (index_1 <= (len1 -1)) || + (index_2 <= (len2 -1)) + + if arr_1[index_1].nil? && !arr_2[index_2].nil? + res << arr_2[index_2] + index_2 += 1 + elsif !arr_1[index_1].nil? && arr_2[index_2].nil? + res << arr_1[index_1] + index_1 += 1 + + elsif arr_1[index_1] < arr_2[index_2] + res << arr_1[index_1] + index_1 += 1 + + else + res << arr_2[index_2] + index_2 += 1 + end + + end + + + res + +end + +def in_order(root, arr) + if root.nil? + return arr + else + in_order(root.left, arr) + arr << root.val + in_order(root.right, arr) + end +end \ No newline at end of file diff --git a/September-LeetCoding-Challenge/06-Image-Overlap/Image-Overlap.rb b/September-LeetCoding-Challenge/06-Image-Overlap/Image-Overlap.rb new file mode 100644 index 0000000..fb4a8d4 --- /dev/null +++ b/September-LeetCoding-Challenge/06-Image-Overlap/Image-Overlap.rb @@ -0,0 +1,37 @@ +def largest_overlap(a, b) + + # c'est une solution que je n'ai pas tout comprise + # pk [max_overlaps, shift_count(x, y, a, b)].max et [max_overlaps, shift_count(x, y, b, a)].max suffisent ?? + max_overlaps = 0 + + len = a.length + + 0.upto(len-1) do |y| + 0.upto(len-1) do |x| + max_overlaps = [max_overlaps, shift_count(x, y, a, b)].max + max_overlaps = [max_overlaps, shift_count(x, y, b, a)].max + end + end + max_overlaps + +end + + + +def shift_count(x, y, m, r) + len = m.length + count = 0 + r_row = 0 + + y.upto(len - 1) do |m_row| + r_col = 0 + + x.upto(len - 1) do |m_col| + count += 1 if m[m_row][m_col] == 1 && m[m_row][m_col] == r[r_row][r_col] + r_col += 1 + end + + r_row +=1 + end + count +end \ No newline at end of file diff --git a/September-LeetCoding-Challenge/07-Word-Pattern/Word-Pattern.rb b/September-LeetCoding-Challenge/07-Word-Pattern/Word-Pattern.rb new file mode 100644 index 0000000..15ce7f4 --- /dev/null +++ b/September-LeetCoding-Challenge/07-Word-Pattern/Word-Pattern.rb @@ -0,0 +1,17 @@ +def word_pattern(pattern, str) + arr = str.split + return false if pattern.length != arr.length + l = pattern.length + h = {} + out = true + 0.upto(l-1) do |n| + + if h.key?(pattern[n]) + return out = false if h[pattern[n]] != arr[n] + else + return false if h.values.include?(arr[n]) + h.merge!(pattern[n] => arr[n]) + end + end + out +end \ No newline at end of file diff --git a/September-LeetCoding-Challenge/08-Sum-of-Root-To-Leaf-Binary-Numbers/Sum-of-Root-To-Leaf-Binary-Numbers.rb b/September-LeetCoding-Challenge/08-Sum-of-Root-To-Leaf-Binary-Numbers/Sum-of-Root-To-Leaf-Binary-Numbers.rb new file mode 100644 index 0000000..5db9c1d --- /dev/null +++ b/September-LeetCoding-Challenge/08-Sum-of-Root-To-Leaf-Binary-Numbers/Sum-of-Root-To-Leaf-Binary-Numbers.rb @@ -0,0 +1,16 @@ +def sum_root_to_leaf(root) + rec(root, 0) +end + +def rec(root, val) + if root.nil? + return 0 + else + val = val * 2 + root.val + if root.left.nil? && root.right.nil? + return val + end + rec(root.left, val) + rec(root.right, val) + + end +end \ No newline at end of file diff --git a/September-LeetCoding-Challenge/09-Compare-Version-Numbers/Compare-Version-Numbers.rb b/September-LeetCoding-Challenge/09-Compare-Version-Numbers/Compare-Version-Numbers.rb new file mode 100644 index 0000000..266ffe8 --- /dev/null +++ b/September-LeetCoding-Challenge/09-Compare-Version-Numbers/Compare-Version-Numbers.rb @@ -0,0 +1,23 @@ +def compare_version(version1, version2) + arr1 = version1.split(".") + arr2 = version2.split(".") + + len = [arr1.length-1, arr2.length-1].max + + 0.upto(len) do |n| + if arr1[n].nil? && arr2[n].nil? + return 0 + else + a = arr1[n] || "0" + b = arr2[n] || "0" + if a.to_i > b.to_i + return 1 + elsif a.to_i < b.to_i + return -1 + else + next + end + end + end + +end \ No newline at end of file diff --git a/September-LeetCoding-Challenge/10-Bulls-and-Cows/Bulls-and-Cows.rb b/September-LeetCoding-Challenge/10-Bulls-and-Cows/Bulls-and-Cows.rb new file mode 100644 index 0000000..611edd4 --- /dev/null +++ b/September-LeetCoding-Challenge/10-Bulls-and-Cows/Bulls-and-Cows.rb @@ -0,0 +1,30 @@ +def get_hint(secret, guess) + new_guess = [] + new_secret = [] + count_a = 0 + count_b = 0 + + guess.chars.to_a.each_with_index do |val, index| + if val == secret[index] + count_a += 1 + else + new_guess << val + new_secret << secret[index] + end + end + + new_guess.sort! + new_secret.sort! + while new_guess != [] && new_secret != [] + s = new_secret.pop + g = new_guess.pop + if s == g + count_b += 1 + elsif s.to_i > g.to_i + new_guess << g + elsif s.to_i < g.to_i + new_secret < n + path << i + bt(k-1, n-i, i+1, path, res) + path.pop + end +end \ No newline at end of file From 9d6044f1fd43e703b3e026591edb1e9675db1d9e Mon Sep 17 00:00:00 2001 From: jiangl <> Date: Sat, 12 Sep 2020 23:41:24 +0200 Subject: [PATCH 264/281] naming errors --- ...-Time-For-Given-Digest.rb => Largest-Time-for-Given-Digits.rb} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/{Largest-Time-For-Given-Digest.rb => Largest-Time-for-Given-Digits.rb} (100%) diff --git a/September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-For-Given-Digest.rb b/September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-for-Given-Digits.rb similarity index 100% rename from September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-For-Given-Digest.rb rename to September-LeetCoding-Challenge/01-Largest-Time-for-Given-Digits/Largest-Time-for-Given-Digits.rb From d2b06135f6cbb0fd251cd2e55707e64673149b8b Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 13 Sep 2020 19:54:43 +0200 Subject: [PATCH 265/281] Add Insert Interval --- README.md | 1 + .../13-Insert-Interval/Insert-Interval.cs | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 September-LeetCoding-Challenge/13-Insert-Interval/Insert-Interval.cs diff --git a/README.md b/README.md index ee3cd4c..03be1ac 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ Solutions in various programming languages are provided. Enjoy it. 10. [Bulls and Cows](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/10-Bulls-and-Cows) 11. [Maximum Product Subarray](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/11-Maximum-Product-Subarray) 12. [Combination Sum III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/12-Combination-Sum-III) +13. [Insert Interval](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/13-Insert-Interval) ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. diff --git a/September-LeetCoding-Challenge/13-Insert-Interval/Insert-Interval.cs b/September-LeetCoding-Challenge/13-Insert-Interval/Insert-Interval.cs new file mode 100644 index 0000000..cdbe556 --- /dev/null +++ b/September-LeetCoding-Challenge/13-Insert-Interval/Insert-Interval.cs @@ -0,0 +1,23 @@ +public class Solution { + public int[][] Insert(int[][] intervals, int[] newInterval) { + var res = new List(); + foreach(int[] i in intervals){ + if(newInterval == null || i[1] < newInterval[0]){ + res.Add(i); + } + else if(i[0] > newInterval[1]){ + res.Add(newInterval); + res.Add(i); + newInterval = null; + } + else{ + newInterval[0] = Math.Min(newInterval[0], i[0]); + newInterval[1] = Math.Max(newInterval[1], i[1]); + } + } + if(newInterval != null){ + res.Add(newInterval); + } + return res.ToArray(); + } +} From 6cafde28df8e208bc1aef3485fabce0ad4359238 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 14 Sep 2020 22:05:35 +0200 Subject: [PATCH 266/281] Add House Robber --- README.md | 1 + .../14-House-Robber/House-Robber.cs | 12 ++++++++++++ 2 files changed, 13 insertions(+) create mode 100644 September-LeetCoding-Challenge/14-House-Robber/House-Robber.cs diff --git a/README.md b/README.md index 03be1ac..e4da82c 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Solutions in various programming languages are provided. Enjoy it. 11. [Maximum Product Subarray](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/11-Maximum-Product-Subarray) 12. [Combination Sum III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/12-Combination-Sum-III) 13. [Insert Interval](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/13-Insert-Interval) +14. [House Robber](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/14-House-Robber) ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. diff --git a/September-LeetCoding-Challenge/14-House-Robber/House-Robber.cs b/September-LeetCoding-Challenge/14-House-Robber/House-Robber.cs new file mode 100644 index 0000000..7dfdbaf --- /dev/null +++ b/September-LeetCoding-Challenge/14-House-Robber/House-Robber.cs @@ -0,0 +1,12 @@ +public class Solution { + public int Rob(int[] nums) { + if(nums.Length == 0) return 0; + + var dp = new int[nums.Length+1]; + dp[1] = nums[0]; + for(int i=1; i Date: Tue, 15 Sep 2020 21:29:04 +0200 Subject: [PATCH 267/281] Add Length of Last Word C# --- README.md | 1 + .../Length-of-Last-Word.cs | 74 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 September-LeetCoding-Challenge/15-Length-of-Last-Word/Length-of-Last-Word.cs diff --git a/README.md b/README.md index e4da82c..f033250 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ Solutions in various programming languages are provided. Enjoy it. 12. [Combination Sum III](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/12-Combination-Sum-III) 13. [Insert Interval](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/13-Insert-Interval) 14. [House Robber](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/14-House-Robber) +15. [Length of Last Word](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/15-Length-of-Last-Word) ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. diff --git a/September-LeetCoding-Challenge/15-Length-of-Last-Word/Length-of-Last-Word.cs b/September-LeetCoding-Challenge/15-Length-of-Last-Word/Length-of-Last-Word.cs new file mode 100644 index 0000000..a032ca7 --- /dev/null +++ b/September-LeetCoding-Challenge/15-Length-of-Last-Word/Length-of-Last-Word.cs @@ -0,0 +1,74 @@ +public class Solution { + + //Solution 1 + public class Solution { + public int LengthOfLastWord(string s) { + if(s.Length == 0) return 0; + + var l = s.Split(' ').ToList(); + var i = l.Count - 1; + while(i >= 0){ + if(l[i] == ""){ + i--; + } + else{ + return l[i].Length; + } + } + + return 0; + } +} + + + //Solution 2 + public int LengthOfLastWord(string s) + { + if (s.Length == 0) return 0; + + int beginPosition = 0; + int endPosition = 0; + bool hasWord = false; + bool hasSpaceBeforeLastWord = false; + + //Start by the end of string + for (int i = s.Length - 1; i >= 0; i--) + { + if (s[i] == ' ' && !hasWord) + { + //This condition improves performance + continue; + } + else if (s[i] != ' ' && !hasWord) + { + hasWord = true; + endPosition = i; + continue; + } + else if (s[i] == ' ' && hasWord) + { + beginPosition = i; + hasSpaceBeforeLastWord = true; + break; + } + } + + //One word case + if (endPosition - beginPosition == 0 && hasWord) + return 1; + + //No words case + if (endPosition - beginPosition == 0 && !hasWord) + return 0; + + //Has word and has spaces before last words + if (endPosition - beginPosition != 0 && hasWord && hasSpaceBeforeLastWord) + return endPosition - beginPosition; + + //Has word and has no space before last words + if (endPosition - beginPosition != 0 && hasWord && !hasSpaceBeforeLastWord) + return endPosition - beginPosition + 1; + + return 0; + } +} From 77d7b5a79eedd6aaf6e2a9a66e824cea3a189fc4 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Thu, 17 Sep 2020 22:43:24 +0200 Subject: [PATCH 268/281] Add C# solutions --- README.md | 2 ++ .../Maximum-XOR-of-Two-Numbers-in-an-Array.cs | 22 +++++++++++++++++++ .../Robot-Bounded-In-Circle.cs | 21 ++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 September-LeetCoding-Challenge/16-Maximum-XOR-of-Two-Numbers-in-an-Array/Maximum-XOR-of-Two-Numbers-in-an-Array.cs create mode 100644 September-LeetCoding-Challenge/17-Robot-Bounded-In-Circle/Robot-Bounded-In-Circle.cs diff --git a/README.md b/README.md index f033250..c143974 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ Solutions in various programming languages are provided. Enjoy it. 13. [Insert Interval](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/13-Insert-Interval) 14. [House Robber](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/14-House-Robber) 15. [Length of Last Word](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/15-Length-of-Last-Word) +16. [Maximum XOR of Two Numbers in an Array](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/16-Maximum-XOR-of-Two-Numbers-in-an-Array) +17. [Robot Bounded In Circle](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/17-Robot-Bounded-In-Circle) ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. diff --git a/September-LeetCoding-Challenge/16-Maximum-XOR-of-Two-Numbers-in-an-Array/Maximum-XOR-of-Two-Numbers-in-an-Array.cs b/September-LeetCoding-Challenge/16-Maximum-XOR-of-Two-Numbers-in-an-Array/Maximum-XOR-of-Two-Numbers-in-an-Array.cs new file mode 100644 index 0000000..c31fcfa --- /dev/null +++ b/September-LeetCoding-Challenge/16-Maximum-XOR-of-Two-Numbers-in-an-Array/Maximum-XOR-of-Two-Numbers-in-an-Array.cs @@ -0,0 +1,22 @@ +public class Solution { + public int FindMaximumXOR(int[] nums) { + int max = 0, mask=0; + for(int i=31; i>=0; i--){ + mask |= (1 << i); + + var hs = new HashSet(); + foreach(int num in nums){ + hs.Add(num & mask); + } + + int tmp = max | (1 << i); + foreach(int prefix in hs){ + if(hs.Contains(tmp ^ prefix)){ + max = tmp; + break; + } + } + } + return max; + } +} diff --git a/September-LeetCoding-Challenge/17-Robot-Bounded-In-Circle/Robot-Bounded-In-Circle.cs b/September-LeetCoding-Challenge/17-Robot-Bounded-In-Circle/Robot-Bounded-In-Circle.cs new file mode 100644 index 0000000..ecbe82f --- /dev/null +++ b/September-LeetCoding-Challenge/17-Robot-Bounded-In-Circle/Robot-Bounded-In-Circle.cs @@ -0,0 +1,21 @@ +public class Solution { + public bool IsRobotBounded(string instructions) { + int x = 0; + int y = 0; + var dirs = new int[4][]{new int[]{0,1}, new int[]{1, 0}, new int[]{0,-1}, new int[]{-1,0}}; + int d = 0; + + foreach(char c in instructions){ + if(c == 'L'){ + d = (d+3)%4; + }else if(c == 'R'){ + d = (d+1)%4; + }else{ + x += dirs[d][0]; + y += dirs[d][1]; + } + } + + return x == 0 && y == 0 || d > 0; + } +} \ No newline at end of file From c5fd3de6e8994fe682256bf68fc4db8de971d0b4 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Sun, 20 Sep 2020 08:09:17 +0200 Subject: [PATCH 269/281] Add C# solutions --- README.md | 2 ++ .../Best-Time-to-Buy-and-Sell-Stock.cs | 11 ++++++++++ .../19-Sequential-Digits/Sequential-Digits.cs | 20 +++++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 September-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock/Best-Time-to-Buy-and-Sell-Stock.cs create mode 100644 September-LeetCoding-Challenge/19-Sequential-Digits/Sequential-Digits.cs diff --git a/README.md b/README.md index c143974..dc8f5ce 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ Solutions in various programming languages are provided. Enjoy it. 15. [Length of Last Word](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/15-Length-of-Last-Word) 16. [Maximum XOR of Two Numbers in an Array](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/16-Maximum-XOR-of-Two-Numbers-in-an-Array) 17. [Robot Bounded In Circle](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/17-Robot-Bounded-In-Circle) +18. [Best Time to Buy and Sell Stock](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock) +19. [Sequential Digits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/19-Sequential-Digits) ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. diff --git a/September-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock/Best-Time-to-Buy-and-Sell-Stock.cs b/September-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock/Best-Time-to-Buy-and-Sell-Stock.cs new file mode 100644 index 0000000..e5877f1 --- /dev/null +++ b/September-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock/Best-Time-to-Buy-and-Sell-Stock.cs @@ -0,0 +1,11 @@ +public class Solution { + public int MaxProfit(int[] prices) { + if(prices == null || prices.Length == 0) return 0; + int min=prices[0],max=0; + for (int i=1;i SequentialDigits(int low, int high) { + int[] allNums = {12,23,34,45,56,67,78,89, + 123,234,345,456,567,678,789, + 1234,2345,3456,4567,5678,6789, + 12345,23456,34567,45678,56789, + 123456,234567,345678,456789, + 1234567,2345678,3456789, + 12345678,23456789, + 123456789}; + var res = new List(); + int n = allNums.Length; + for (int i = 0; i < n; i++) { + if (allNums[i] < low) continue; + if (allNums[i] > high) break; + res.Add(allNums[i]); + } + return res; + } +} From b83f1c28ade8bc0c23bcb0d20c4599a0f8a31fdd Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Wed, 23 Sep 2020 23:02:50 +0200 Subject: [PATCH 270/281] Add Gas Station C# --- .../23-Gas-Station/Gas-Station.cs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 September-LeetCoding-Challenge/23-Gas-Station/Gas-Station.cs diff --git a/September-LeetCoding-Challenge/23-Gas-Station/Gas-Station.cs b/September-LeetCoding-Challenge/23-Gas-Station/Gas-Station.cs new file mode 100644 index 0000000..a85afba --- /dev/null +++ b/September-LeetCoding-Challenge/23-Gas-Station/Gas-Station.cs @@ -0,0 +1,21 @@ +public class Solution { + public int CanCompleteCircuit(int[] gas, int[] cost) { + int sumGas = 0, sumCost = 0, tank = 0, pos = 0; + + for(int i = 0; i= sumCost){ + return pos; + } + + return -1; + } +} \ No newline at end of file From 63130b5e371277999b7568e989de7d73d126f336 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 28 Sep 2020 21:20:13 +0200 Subject: [PATCH 271/281] Add Subarray Product Less Than K --- README.md | 2 ++ .../Subarray-Product-Less-Than-K.cs | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 September-LeetCoding-Challenge/28-Subarray-Product-Less-Than-K/Subarray-Product-Less-Than-K.cs diff --git a/README.md b/README.md index dc8f5ce..bfcf8ca 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,8 @@ Solutions in various programming languages are provided. Enjoy it. 17. [Robot Bounded In Circle](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/17-Robot-Bounded-In-Circle) 18. [Best Time to Buy and Sell Stock](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock) 19. [Sequential Digits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/19-Sequential-Digits) +23. [Gas Station](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/23-Gas-Station) +28. [Subarray Product Less Than K](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/28-Subarray-Product-Less-Than-K) ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. diff --git a/September-LeetCoding-Challenge/28-Subarray-Product-Less-Than-K/Subarray-Product-Less-Than-K.cs b/September-LeetCoding-Challenge/28-Subarray-Product-Less-Than-K/Subarray-Product-Less-Than-K.cs new file mode 100644 index 0000000..abf7444 --- /dev/null +++ b/September-LeetCoding-Challenge/28-Subarray-Product-Less-Than-K/Subarray-Product-Less-Than-K.cs @@ -0,0 +1,17 @@ +public class Solution { + public int NumSubarrayProductLessThanK(int[] nums, int k) { + int len = nums.Length; + int p = 1; + int i=0, j=0, total=0; + while(j < len){ + p *= nums[j]; + while(i<=j && p>=k){ + p /= nums[i]; + i++; + } + total += (j-i+1); + j++; + } + return total; + } +} From 1243c6fea4fda7217f705de3371ccc47936d9c4e Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 2 Oct 2020 07:45:55 +0200 Subject: [PATCH 272/281] Add C# solutions --- .../Number-of-Recent-Calls.cs | 24 +++++++++++ README.md | 10 +++++ .../First-Missing-Positive.cs | 43 +++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 October-LeetCoding-Challenge/01-Number-of-Recent-Calls/Number-of-Recent-Calls.cs create mode 100644 September-LeetCoding-Challenge/30-First-Missing-Positive/First-Missing-Positive.cs diff --git a/October-LeetCoding-Challenge/01-Number-of-Recent-Calls/Number-of-Recent-Calls.cs b/October-LeetCoding-Challenge/01-Number-of-Recent-Calls/Number-of-Recent-Calls.cs new file mode 100644 index 0000000..1e7b1f3 --- /dev/null +++ b/October-LeetCoding-Challenge/01-Number-of-Recent-Calls/Number-of-Recent-Calls.cs @@ -0,0 +1,24 @@ +public class RecentCounter { + + private Queue queue; + private int count; + public RecentCounter() { + count = 0; + queue = new Queue(); + } + + public int Ping(int t) { + queue.Enqueue(t); + while(t - queue.FirstOrDefault() > 3000) + { + queue.Dequeue(); + } + return queue.Count(); + } +} + +/** + * Your RecentCounter object will be instantiated and called as such: + * RecentCounter obj = new RecentCounter(); + * int param_1 = obj.Ping(t); + */ \ No newline at end of file diff --git a/README.md b/README.md index bfcf8ca..da09af3 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,15 @@ https://leetcode.com + +## October LeetCoding Challenge +Click [here](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/) for problem descriptions. + +Solutions in various programming languages are provided. Enjoy it. + +1. [Number of Recent Calls](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/01-Number-of-Recent-Calls) : Queue + + ## September LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/september-leetcoding-challenge) for problem descriptions. @@ -28,6 +37,7 @@ Solutions in various programming languages are provided. Enjoy it. 19. [Sequential Digits](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/19-Sequential-Digits) 23. [Gas Station](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/23-Gas-Station) 28. [Subarray Product Less Than K](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/28-Subarray-Product-Less-Than-K) +30. [First Missing Positive](https://github.com/AlgoStudyGroup/Leetcode/tree/master/September-LeetCoding-Challenge/30-First-Missing-Positive) ## August LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/) for problem descriptions. diff --git a/September-LeetCoding-Challenge/30-First-Missing-Positive/First-Missing-Positive.cs b/September-LeetCoding-Challenge/30-First-Missing-Positive/First-Missing-Positive.cs new file mode 100644 index 0000000..5235212 --- /dev/null +++ b/September-LeetCoding-Challenge/30-First-Missing-Positive/First-Missing-Positive.cs @@ -0,0 +1,43 @@ +public class Solution { + public int FirstMissingPositive(int[] nums) { + int n = nums.Length; + + // 1. mark numbers (num < 0) and (num > n) with a special marker number (n+1) + // (we can ignore those because if all number are > n then we'll simply return 1) + for (int i = 0; i < n; i++) + { + if (nums[i] <= 0 || nums[i] > n) + { + nums[i] = n + 1; + } + } + // note: all number in the array are now positive, and on the range 1..n+1 + + // 2. mark each cell appearing in the array, by converting the index for that number to negative + for (int i = 0; i < n; i++) + { + int num = Math.Abs(nums[i]); + if (num > n) + { + continue; + } + num--; // -1 for zero index based array (so the number 1 will be at pos 0) + if (nums[num] > 0) + { // prevents double negative operations + nums[num] = -1 * nums[num]; + } + } + + // 3. find the first cell which isn't negative (doesn't appear in the array) + for (int i = 0; i < n; i++) + { + if (nums[i] >= 0) + { + return i + 1; + } + } + + // 4. no positive numbers were found, which means the array contains all numbers 1..n + return n + 1; + } +} \ No newline at end of file From 58ca119a1786eff1e35462ae10cef98c9fb8880d Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Mon, 5 Oct 2020 08:57:40 +0200 Subject: [PATCH 273/281] Add C# solutions --- .../Remove-Covered-Intervals.cs | 14 ++++++++++++++ README.md | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 October-LeetCoding-Challenge/04-Remove-Covered-Intervals/Remove-Covered-Intervals.cs diff --git a/October-LeetCoding-Challenge/04-Remove-Covered-Intervals/Remove-Covered-Intervals.cs b/October-LeetCoding-Challenge/04-Remove-Covered-Intervals/Remove-Covered-Intervals.cs new file mode 100644 index 0000000..79b8db2 --- /dev/null +++ b/October-LeetCoding-Challenge/04-Remove-Covered-Intervals/Remove-Covered-Intervals.cs @@ -0,0 +1,14 @@ +public class Solution { + public int RemoveCoveredIntervals(int[][] intervals) { + Array.Sort(intervals, (x, y) => x[0]==y[0] ? y[1]-x[1] : x[0]-y[0]); + int count = 0; + int curr = 0; + foreach(int[] interval in intervals){ + if(curr < interval[1]){ + curr = interval[1]; + count++; + } + } + return count; + } +} \ No newline at end of file diff --git a/README.md b/README.md index da09af3..59ac251 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Click [here](https://leetcode.com/explore/challenge/card/october-leetcoding-chal Solutions in various programming languages are provided. Enjoy it. 1. [Number of Recent Calls](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/01-Number-of-Recent-Calls) : Queue - +4. [Remove Covered Intervals](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/04-Remove-Covered-Intervals) ## September LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/september-leetcoding-challenge) for problem descriptions. From 9bb31e9b1d5a0bae7ca60245f325c645af9a3936 Mon Sep 17 00:00:00 2001 From: hellomrsun Date: Fri, 16 Oct 2020 23:22:17 +0200 Subject: [PATCH 274/281] Add C# solutions --- .../12-Buddy-Strings/Buddy-Strings.cs | 22 +++++++++ .../14-House-Robber-II/House-Robber-II.cs | 18 +++++++ .../15-Rotate-Array/Rotate-Array.cs | 23 +++++++++ .../Search-a-2D-Matrix.cs | 47 +++++++++++++++++++ 4 files changed, 110 insertions(+) create mode 100644 October-LeetCoding-Challenge/12-Buddy-Strings/Buddy-Strings.cs create mode 100644 October-LeetCoding-Challenge/14-House-Robber-II/House-Robber-II.cs create mode 100644 October-LeetCoding-Challenge/15-Rotate-Array/Rotate-Array.cs create mode 100644 October-LeetCoding-Challenge/16-Search-a-2D-Matrix/Search-a-2D-Matrix.cs diff --git a/October-LeetCoding-Challenge/12-Buddy-Strings/Buddy-Strings.cs b/October-LeetCoding-Challenge/12-Buddy-Strings/Buddy-Strings.cs new file mode 100644 index 0000000..935f207 --- /dev/null +++ b/October-LeetCoding-Challenge/12-Buddy-Strings/Buddy-Strings.cs @@ -0,0 +1,22 @@ +public class Solution { + public bool BuddyStrings(string A, string B) { + if((A == null && B != null) || (A != null && B == null)) return false; + if(A.Length != B.Length) return false; + int diffCount = 0; + int a = -1, b = -1; + bool canSwitch = false; + int[] count = new int[26]; + + for(int i=0; i= 2) canSwitch = true; + + if(A[i] != B[i]) + { + diffCount++; + if (a == -1) a = i; + else if (b == -1) b = i; + } + } + return (diffCount == 0 && canSwitch) || (diffCount == 2 && A[a] == B[b] && A[b] == B[a]); + } +} diff --git a/October-LeetCoding-Challenge/14-House-Robber-II/House-Robber-II.cs b/October-LeetCoding-Challenge/14-House-Robber-II/House-Robber-II.cs new file mode 100644 index 0000000..3eef2a6 --- /dev/null +++ b/October-LeetCoding-Challenge/14-House-Robber-II/House-Robber-II.cs @@ -0,0 +1,18 @@ +public class Solution { + public int Rob(int[] nums) { + if(nums == null || nums.Length == 0) return 0; + if(nums.Length == 1) return nums[0]; + + return Math.Max(rob(nums, 1, nums.Length-1), rob(nums, 0, nums.Length-2)); + } + + private int rob(int[] nums, int lo, int hi){ + int include = 0, exclude = 0; + for(int x=lo; x<=hi; x++){ + int i=include, e=exclude; + include = e + nums[x]; + exclude = Math.Max(i, e); + } + return Math.Max(include, exclude); + } +} diff --git a/October-LeetCoding-Challenge/15-Rotate-Array/Rotate-Array.cs b/October-LeetCoding-Challenge/15-Rotate-Array/Rotate-Array.cs new file mode 100644 index 0000000..0352ac5 --- /dev/null +++ b/October-LeetCoding-Challenge/15-Rotate-Array/Rotate-Array.cs @@ -0,0 +1,23 @@ +public class Solution { + public void Rotate(int[] nums, int k) { + if(nums == null || nums.Length < 2) return; + var length = nums.Length; + int n = k % length; + //Reverse left part + Reverse(nums, 0, length - 1 - n); + //Reverse right part + Reverse(nums, length - n, length-1); + //Reverse whole array + Reverse(nums, 0, length-1); + } + private void Reverse(int[] nums, int b, int e){ + int tmp = 0; + while(b < e){ + tmp = nums[b]; + nums[b] = nums[e]; + nums[e] = tmp; + b++; + e--; + } + } +} \ No newline at end of file diff --git a/October-LeetCoding-Challenge/16-Search-a-2D-Matrix/Search-a-2D-Matrix.cs b/October-LeetCoding-Challenge/16-Search-a-2D-Matrix/Search-a-2D-Matrix.cs new file mode 100644 index 0000000..8853423 --- /dev/null +++ b/October-LeetCoding-Challenge/16-Search-a-2D-Matrix/Search-a-2D-Matrix.cs @@ -0,0 +1,47 @@ +public class Solution { + public bool SearchMatrix(int[][] matrix, int target) + { + if (matrix == null || matrix.Length == 0) return false; + var levelLen = matrix[0].Length; + if(levelLen == 0) return false; + + bool result = false; + for (int i = 0; i <= matrix.Length-1; i++) + { + if (target <= matrix[i][levelLen - 1]) + { + return BinarySearch(target, matrix[i]); + } + } + + return false; + } + + private bool BinarySearch(int target, int[] nums) + { + int lo = 0, hi = nums.Length - 1; + int mid = 0; + while (lo <= hi) + { + mid = lo + (hi - lo) / 2; + + if (nums[mid] > target) + { + hi = mid-1; + } + else if (nums[mid] < target) + { + lo = mid+1; + } + else if (nums[mid] == target) + { + return true; + } + else + { + return false; + } + } + return false; + } +} \ No newline at end of file From 8b8e04547b79cea2491cf9f837cf9dcf7a540f5f Mon Sep 17 00:00:00 2001 From: hellomrsun <23157401+hellomrsun@users.noreply.github.com> Date: Sat, 17 Oct 2020 19:46:05 +0200 Subject: [PATCH 275/281] Add C# solutions --- .../Repeated-DNA-Sequences.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 October-LeetCoding-Challenge/17-Repeated-DNA-Sequences/Repeated-DNA-Sequences.cs diff --git a/October-LeetCoding-Challenge/17-Repeated-DNA-Sequences/Repeated-DNA-Sequences.cs b/October-LeetCoding-Challenge/17-Repeated-DNA-Sequences/Repeated-DNA-Sequences.cs new file mode 100644 index 0000000..26503ca --- /dev/null +++ b/October-LeetCoding-Challenge/17-Repeated-DNA-Sequences/Repeated-DNA-Sequences.cs @@ -0,0 +1,14 @@ +public class Solution { + public IList FindRepeatedDnaSequences(string s) { + if(s == null || s.Length == 0) return new List(); + var seen = new HashSet(); + var repeated = new HashSet(); + for(int i=0; i(repeated); + } +} From e9eec6cda520542f3dee87c2b4f1fcb3b3d02d14 Mon Sep 17 00:00:00 2001 From: hellomrsun <23157401+hellomrsun@users.noreply.github.com> Date: Sun, 22 Nov 2020 12:26:54 +0100 Subject: [PATCH 276/281] Add October algos --- .../Best_Time_to_Buy_and_Sell_Stock_IV.cs | 41 +++++++++++++++ .../Minimum_Domino_Rotations_For_Equal_Row.cs | 34 +++++++++++++ .../20-Clone-Graph/Clone-Graph.cs | 49 ++++++++++++++++++ .../Asteroid-Collision.cs | 51 +++++++++++++++++++ .../Minimum-Depth-of-Binary-Tree.cs | 48 +++++++++++++++++ .../23-132-Pattern/132-Pattern.cs | 30 +++++++++++ .../24-Bag-of-Tokens/Bag-of-Tokens.cs | 22 ++++++++ .../25-Stone-Game-IV/Stone-Game-IV.cs | 19 +++++++ .../26-Champagne-Tower/Champgane-Tower.cs | 24 +++++++++ .../Linked-List-Cycle-II.cs | 39 ++++++++++++++ .../28-Summary-Ranges/Summary-Ranges.cs | 34 +++++++++++++ .../Maximize-Distance-to-Closest-Person.cs | 22 ++++++++ ...umber-of-Longest-Increasing-Subsequence.cs | 24 +++++++++ README.md | 30 +++++++++++ 14 files changed, 467 insertions(+) create mode 100644 October-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock-IV/Best_Time_to_Buy_and_Sell_Stock_IV.cs create mode 100644 October-LeetCoding-Challenge/19-Minimum-Domino-Rotations-For-Equal-Row/Minimum_Domino_Rotations_For_Equal_Row.cs create mode 100644 October-LeetCoding-Challenge/20-Clone-Graph/Clone-Graph.cs create mode 100644 October-LeetCoding-Challenge/21-Asteroid-Collision/Asteroid-Collision.cs create mode 100644 October-LeetCoding-Challenge/22-Minimum-Depth-of-Binary-Tree/Minimum-Depth-of-Binary-Tree.cs create mode 100644 October-LeetCoding-Challenge/23-132-Pattern/132-Pattern.cs create mode 100644 October-LeetCoding-Challenge/24-Bag-of-Tokens/Bag-of-Tokens.cs create mode 100644 October-LeetCoding-Challenge/25-Stone-Game-IV/Stone-Game-IV.cs create mode 100644 October-LeetCoding-Challenge/26-Champagne-Tower/Champgane-Tower.cs create mode 100644 October-LeetCoding-Challenge/27-Linked-List-Cycle-II/Linked-List-Cycle-II.cs create mode 100644 October-LeetCoding-Challenge/28-Summary-Ranges/Summary-Ranges.cs create mode 100644 October-LeetCoding-Challenge/29-Maximum-Distance-to-Closest-Person/Maximize-Distance-to-Closest-Person.cs create mode 100644 October-LeetCoding-Challenge/30-Number-of-Longest-Increasing-Subsequence/Number-of-Longest-Increasing-Subsequence.cs diff --git a/October-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock-IV/Best_Time_to_Buy_and_Sell_Stock_IV.cs b/October-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock-IV/Best_Time_to_Buy_and_Sell_Stock_IV.cs new file mode 100644 index 0000000..9816bd4 --- /dev/null +++ b/October-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock-IV/Best_Time_to_Buy_and_Sell_Stock_IV.cs @@ -0,0 +1,41 @@ +using System; + +namespace _188_Best_Time_to_Buy_and_Sell_Stock_IV +{ + public class Solution + { + public int MaxProfit(int k, int[] prices) + { + if (prices == null || prices.Length <= 1) return 0; + + int len = prices.Length; + + //You can make as many as operations on array prices + if (k >= len / 2) + { + int max = 0; + for (int i = 1; i < len; i++) + { + if (prices[i] > prices[i - 1]) + { + max += prices[i] - prices[i - 1]; + } + } + return max; + } + + int[,] dp = new int[k + 1, len]; + + for (int i = 1; i <= k; i++) + { + int localMax = dp[i - 1, 0] - prices[0]; + for (int j = 1; j < len; j++) + { + dp[i, j] = Math.Max(dp[i, j - 1], prices[j] + localMax); + localMax = Math.Max(localMax, dp[i - 1, j] - prices[j]); + } + } + return dp[k, len - 1]; + } + } +} \ No newline at end of file diff --git a/October-LeetCoding-Challenge/19-Minimum-Domino-Rotations-For-Equal-Row/Minimum_Domino_Rotations_For_Equal_Row.cs b/October-LeetCoding-Challenge/19-Minimum-Domino-Rotations-For-Equal-Row/Minimum_Domino_Rotations_For_Equal_Row.cs new file mode 100644 index 0000000..5f765d8 --- /dev/null +++ b/October-LeetCoding-Challenge/19-Minimum-Domino-Rotations-For-Equal-Row/Minimum_Domino_Rotations_For_Equal_Row.cs @@ -0,0 +1,34 @@ +using System; + +namespace _1007_Minimum_Domino_Rotations_For_Equal_Row +{ + public class Solution + { + public int MinDominoRotations(int[] A, int[] B) + { + int[] countA = new int[7], countB = new int[7], same = new int[7]; + int len = A.Length; + + //Count the occurence times of each number + for (int i = 0; i < len; i++) + { + countA[A[i]]++; + countB[B[i]]++; + if (A[i] == B[i]) + { + same[A[i]]++; + } + } + + for (int i = 1; i < 7; i++) + { + if (countA[i] + countB[i] - same[i] == len) + { + return len - Math.Max(countA[i], countB[i]); + } + } + + return -1; + } + } +} \ No newline at end of file diff --git a/October-LeetCoding-Challenge/20-Clone-Graph/Clone-Graph.cs b/October-LeetCoding-Challenge/20-Clone-Graph/Clone-Graph.cs new file mode 100644 index 0000000..4b458d5 --- /dev/null +++ b/October-LeetCoding-Challenge/20-Clone-Graph/Clone-Graph.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Collections; + +namespace _133_Clone_Graph +{ + public class Solution + { + Dictionary map = new Dictionary(); + public Node CloneGraph(Node node) + { + if (node == null) return null; + if (!map.ContainsKey(node)) + { + map.Add(node, new Node(node.val)); + foreach (var nei in node.neighbors) + { + map[node].neighbors.Add(CloneGraph(nei)); + } + } + return map[node]; + } + } + + public class Node + { + public int val; + public IList neighbors; + + public Node() + { + val = 0; + neighbors = new List(); + } + + public Node(int _val) + { + val = _val; + neighbors = new List(); + } + + public Node(int _val, List _neighbors) + { + val = _val; + neighbors = _neighbors; + } + } + +} \ No newline at end of file diff --git a/October-LeetCoding-Challenge/21-Asteroid-Collision/Asteroid-Collision.cs b/October-LeetCoding-Challenge/21-Asteroid-Collision/Asteroid-Collision.cs new file mode 100644 index 0000000..9ddcb97 --- /dev/null +++ b/October-LeetCoding-Challenge/21-Asteroid-Collision/Asteroid-Collision.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Collections; + +namespace _735_Asteroid_Collision +{ + public class Solution + { + public int[] AsteroidCollision(int[] asteroids) + { + var stack = new Stack(); + + for (int i = 0; i < asteroids.Length; i++) + { + if (asteroids[i] > 0) + { + //If element is positive, just push it into the stack + stack.Push(asteroids[i]); + } + //element is negative + else + { + //While the last element is positive, and it is smaller than absolute value of current element, then Pop the last element in the stack + while (stack.Count > 0 && stack.Peek() > 0 && stack.Peek() < Math.Abs(asteroids[i])) + { + stack.Pop(); + } + + //When the stack is empty or the last element is negative + if (stack.Count == 0 || stack.Peek() < 0) + { + stack.Push(asteroids[i]); + } + //When the last element + current element equals 0 + else if (asteroids[i] + stack.Peek() == 0) + { + stack.Pop(); + } + } + } + + var res = new int[stack.Count]; + for (int i = stack.Count - 1; i >= 0; i--) + { + res[i] = stack.Pop(); + } + + return res; + } + } +} \ No newline at end of file diff --git a/October-LeetCoding-Challenge/22-Minimum-Depth-of-Binary-Tree/Minimum-Depth-of-Binary-Tree.cs b/October-LeetCoding-Challenge/22-Minimum-Depth-of-Binary-Tree/Minimum-Depth-of-Binary-Tree.cs new file mode 100644 index 0000000..786d0e7 --- /dev/null +++ b/October-LeetCoding-Challenge/22-Minimum-Depth-of-Binary-Tree/Minimum-Depth-of-Binary-Tree.cs @@ -0,0 +1,48 @@ +using System.Collections; +using System.Collections.Generic; +using System; + +namespace _111_Minimum_Depth_of_Binary_Tree +{ + public class Solution + { + public int MinDepth(TreeNode root) + { + if (root == null) return 0; + var queue = new Queue(); + queue.Enqueue(root); + int layer = 1; + while (queue.Count > 0) + { + int size = queue.Count; + //each tree layer + for (int i = 0; i < size; i++) + { + var node = queue.Dequeue(); + if (node != null) + { + if (node.left == null && node.right == null) return layer; + if (node.left != null) queue.Enqueue(node.left); + if (node.right != null) queue.Enqueue(node.right); + } + } + layer++; + } + + return layer; + } + } + + public class TreeNode + { + public int val; + public TreeNode left; + public TreeNode right; + public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) + { + this.val = val; + this.left = left; + this.right = right; + } + } +} \ No newline at end of file diff --git a/October-LeetCoding-Challenge/23-132-Pattern/132-Pattern.cs b/October-LeetCoding-Challenge/23-132-Pattern/132-Pattern.cs new file mode 100644 index 0000000..4838391 --- /dev/null +++ b/October-LeetCoding-Challenge/23-132-Pattern/132-Pattern.cs @@ -0,0 +1,30 @@ +using System.Collections; +using System.Collections.Generic; + +namespace _456_132_Pattern +{ + public class Solution + { + public bool Find132pattern(int[] nums) + { + int n3 = int.MinValue; + var stack = new Stack(); + //Loop from the end of array + for (int i = nums.Length - 1; i >= 0; i--) + { + if (nums[i] < n3) return true; + else + { + //Pop all elements smaller than nums[i] from stack + while (stack.Count > 0 && nums[i] > stack.Peek()) + { + n3 = stack.Pop(); + } + } + //Push current element + stack.Push(nums[i]); + } + return false; + } + } +} diff --git a/October-LeetCoding-Challenge/24-Bag-of-Tokens/Bag-of-Tokens.cs b/October-LeetCoding-Challenge/24-Bag-of-Tokens/Bag-of-Tokens.cs new file mode 100644 index 0000000..51ff7af --- /dev/null +++ b/October-LeetCoding-Challenge/24-Bag-of-Tokens/Bag-of-Tokens.cs @@ -0,0 +1,22 @@ +public class Solution { + public int BagOfTokensScore(int[] tokens, int P) { + Array.Sort(tokens); + int lo=0, hi=tokens.Length-1, res=0, points=0; + while(lo = hi){ + if(P = tokens[lo]){ + P -= tokens[lo]; + res = Math.Max(res, ++points); + lo++; + } + else if(points0){ + points--; + P += tokens[hi]; + hi--; + } + else{ + break; + } + } + return res; + } +} diff --git a/October-LeetCoding-Challenge/25-Stone-Game-IV/Stone-Game-IV.cs b/October-LeetCoding-Challenge/25-Stone-Game-IV/Stone-Game-IV.cs new file mode 100644 index 0000000..ded6efc --- /dev/null +++ b/October-LeetCoding-Challenge/25-Stone-Game-IV/Stone-Game-IV.cs @@ -0,0 +1,19 @@ +namespace _1510_Stone_Game_IV +{ + public class Solution + { + public bool WinnerSquareGame(int n) + { + bool[] dp = new bool[n+1]; + for(int i=1; i<=n; i++){ + for(int j=1; j*j<=i; j++){ + if(!dp[i -j*j]){ + dp[i] = true; + break; + } + } + } + return dp[n]; + } + } +} \ No newline at end of file diff --git a/October-LeetCoding-Challenge/26-Champagne-Tower/Champgane-Tower.cs b/October-LeetCoding-Challenge/26-Champagne-Tower/Champgane-Tower.cs new file mode 100644 index 0000000..1471dbf --- /dev/null +++ b/October-LeetCoding-Challenge/26-Champagne-Tower/Champgane-Tower.cs @@ -0,0 +1,24 @@ +using System; + +namespace _799_Champgane_Tower +{ + public class Solution + { + public double ChampagneTower(int poured, int query_row, int query_glass) + { + var res = new double[query_row + 2]; + res[0] = poured; + + for (int row = 1; row <= query_row; row++) + { + for (int i = row; i >= 0; i--) + { + res[i] = Math.Max(0.0, (res[i] - 1) / 2); + res[i + 1] += res[i]; + } + } + + return Math.Min(res[query_glass], 1.0); + } + } +} diff --git a/October-LeetCoding-Challenge/27-Linked-List-Cycle-II/Linked-List-Cycle-II.cs b/October-LeetCoding-Challenge/27-Linked-List-Cycle-II/Linked-List-Cycle-II.cs new file mode 100644 index 0000000..05dd684 --- /dev/null +++ b/October-LeetCoding-Challenge/27-Linked-List-Cycle-II/Linked-List-Cycle-II.cs @@ -0,0 +1,39 @@ +namespace _142_Linked_List_Cycle_II +{ + public class Solution + { + public ListNode DetectCycle(ListNode head) + { + var fast = head; + var slow = head; + while (fast != null && fast.next != null) + { + fast = fast.next.next; + slow = slow.next; + if (fast == slow) + { + var slow2 = head; + while (slow != slow2) + { + slow = slow.next; + slow2 = slow2.next; + } + return slow; + } + } + return null; + } + } + + /* Definition for singly-linked list.*/ + public class ListNode + { + public int val; + public ListNode next; + public ListNode(int x) + { + val = x; + next = null; + } + } +} \ No newline at end of file diff --git a/October-LeetCoding-Challenge/28-Summary-Ranges/Summary-Ranges.cs b/October-LeetCoding-Challenge/28-Summary-Ranges/Summary-Ranges.cs new file mode 100644 index 0000000..7976caf --- /dev/null +++ b/October-LeetCoding-Challenge/28-Summary-Ranges/Summary-Ranges.cs @@ -0,0 +1,34 @@ +using System.Collections.Generic; + +namespace _228_Summary_Ranges +{ + public class Solution + { + public IList SummaryRanges(int[] nums) + { + if (nums == null) return null; + if (nums.Length == 0) return new List(); + if (nums.Length == 1) return new List { nums[0].ToString() }; + + var res = new List(); + for (int i = 0; i < nums.Length; i++) + { + int v = nums[i]; + while (i < nums.Length - 1 && nums[i] + 1 == nums[i + 1]) + { + i++; + } + if (v != nums[i]) + { + res.Add(v + "->" + nums[i]); + } + else + { + res.Add(v.ToString()); + } + } + + return res; + } + } +} diff --git a/October-LeetCoding-Challenge/29-Maximum-Distance-to-Closest-Person/Maximize-Distance-to-Closest-Person.cs b/October-LeetCoding-Challenge/29-Maximum-Distance-to-Closest-Person/Maximize-Distance-to-Closest-Person.cs new file mode 100644 index 0000000..1c1cbd2 --- /dev/null +++ b/October-LeetCoding-Challenge/29-Maximum-Distance-to-Closest-Person/Maximize-Distance-to-Closest-Person.cs @@ -0,0 +1,22 @@ +using System; + +namespace _849_Maximize_Distance_to_Closest_Person +{ + public class Solution + { + public int MaxDistToClosest(int[] seats) + { + int res = 0, last = -1, len = seats.Length; + for (int i = 0; i < len; i++) + { + if (seats[i] == 1) + { + res = last < 0 ? i : Math.Max(res, (i - last) / 2); + last = i; + } + } + res = Math.Max(res, len - last - 1); + return res; + } + } +} \ No newline at end of file diff --git a/October-LeetCoding-Challenge/30-Number-of-Longest-Increasing-Subsequence/Number-of-Longest-Increasing-Subsequence.cs b/October-LeetCoding-Challenge/30-Number-of-Longest-Increasing-Subsequence/Number-of-Longest-Increasing-Subsequence.cs new file mode 100644 index 0000000..e936b77 --- /dev/null +++ b/October-LeetCoding-Challenge/30-Number-of-Longest-Increasing-Subsequence/Number-of-Longest-Increasing-Subsequence.cs @@ -0,0 +1,24 @@ +public class Solution { + public int FindNumberOfLIS(int[] nums) { + int n = nums.Length, res = 0, max_len = 0; + int[] len = new int[n], cnt = new int[n]; + for(int i = 0; i nums[j]){ + if(len[i] == len[j] + 1)cnt[i] += cnt[j]; + else if(len[i] < len[j] + 1){ + len[i] = len[j] + 1; + cnt[i] = cnt[j]; + } + } + } + if(max_len == len[i])res += cnt[i]; + if(max_len < len[i]){ + max_len = len[i]; + res = cnt[i]; + } + } + return res; + } +} \ No newline at end of file diff --git a/README.md b/README.md index 59ac251..af9ab97 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,37 @@ Click [here](https://leetcode.com/explore/challenge/card/october-leetcoding-chal Solutions in various programming languages are provided. Enjoy it. 1. [Number of Recent Calls](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/01-Number-of-Recent-Calls) : Queue +2. [Combination Sum](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/02-Combination-Sum) +3. [K-diff Pairs in an Array](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/03-K-diff-Pairs-in-an-Array) 4. [Remove Covered Intervals](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/04-Remove-Covered-Intervals) +5. [Complement of Base 10 Integer](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/05-Complement-of-Base-10-Integer) +6. [Insert into a Binary Search Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/06-Insert-into-a-Binary-Search-Tree) +7. [Rotate List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/07-Rotate-List) +8. [Binary Search](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/08-Binary-Search) +9. [Serialize and Deserialize BST](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/09-Serialize-and-Deserialize-BST) +10. [Minimum Number of Arrows to Burst Balloons](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/10-Minimum-Number-of-Arrows-to-Burst-Balloons) +11. [Remove Duplicate Letters](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/11-Remove-Duplicate-Letters) +12. [Buddy Strings](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/12-Buddy-Strings) +13. [Sort List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/13-Sort-List) +14. [House Robber II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/14-House-Robber-II) +15. [Rotate Array](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/15-Rotate-Array) +16. [Search a 2D Matrix](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/16-Search-a-2D-Matrix) +17. [Repeated DNA Sequences](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/17-Repeated-DNA-Sequences) +18. [Best Time to Buy and Sell Stock IV](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock-IV) +19. [Minimum Domino Rotations For Equal Row](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/19-Minimum-Domino-Rotations-For-Equal-Row) +20. [Clone Graph](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/20-Clone-Graph) +21. [Asteroid Collision](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/21-Asteroid-Collision) +22. [Minimum Depth of Binary Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/22-Minimum-Depth-of-Binary-Tree) +23. [132 Pattern](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/23-132-Pattern) +24. [Bag of Tokens](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/24-Bag-of-Tokens) +25. [Stone Game IV](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/25-Stone-Game-IV) +26. [Champagne Tower](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/26-Champagne-Tower) +27. [Linked List Cycle II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/27-Linked-List-Cycle-II) +28. [Summary Ranges](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/28-Summary-Ranges) +29. [Maximum Distance to Closest Person](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/29-Maximum-Distance-to-Closest-Person) +30. [Number of Longest Increasing Subsequence](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/30-Number-of-Longest-Increasing-Subsequence) +31. [Recover Binary Search Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/October-LeetCoding-Challenge/31-Recover-Binary-Search-Tree) + ## September LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/september-leetcoding-challenge) for problem descriptions. From c59cae0e62d7ec9ec44f9c356e469879d4d5496c Mon Sep 17 00:00:00 2001 From: hellomrsun <23157401+hellomrsun@users.noreply.github.com> Date: Sun, 22 Nov 2020 12:38:11 +0100 Subject: [PATCH 277/281] Initialize c# empty solutions --- .../02-Combination-Sum/Combination-Sum.cs | 0 .../03-K-diff-Pairs-in-an-Array/K-diff-Pairs-in-an-Array.cs | 0 .../Complement-of-Base-10-Integer.cs | 0 .../Insert-into-a-Binary-Search-Tree.cs | 0 October-LeetCoding-Challenge/07-Rotate-List/Rotate-List.cs | 0 .../08-Binary-Search/Binary-Search.cs | 0 .../Serialize-and-Deserialize-BST.cs | 0 .../Minimum-Number-of-Arrows-to-Burst-Balloons.cs | 0 .../11-Remove-Duplicate-Letters/Remove-Duplicate-Letters.cs | 0 October-LeetCoding-Challenge/13-Sort-List/Sort-List.cs | 0 .../Recover-Binary-Search-Tree.cs | 0 README.md | 6 ++++++ 12 files changed, 6 insertions(+) create mode 100644 October-LeetCoding-Challenge/02-Combination-Sum/Combination-Sum.cs create mode 100644 October-LeetCoding-Challenge/03-K-diff-Pairs-in-an-Array/K-diff-Pairs-in-an-Array.cs create mode 100644 October-LeetCoding-Challenge/05-Complement-of-Base-10-Integer/Complement-of-Base-10-Integer.cs create mode 100644 October-LeetCoding-Challenge/06-Insert-into-a-Binary-Search-Tree/Insert-into-a-Binary-Search-Tree.cs create mode 100644 October-LeetCoding-Challenge/07-Rotate-List/Rotate-List.cs create mode 100644 October-LeetCoding-Challenge/08-Binary-Search/Binary-Search.cs create mode 100644 October-LeetCoding-Challenge/09-Serialize-and-Deserialize-BST/Serialize-and-Deserialize-BST.cs create mode 100644 October-LeetCoding-Challenge/10-Minimum-Number-of-Arrows-to-Burst-Balloons/Minimum-Number-of-Arrows-to-Burst-Balloons.cs create mode 100644 October-LeetCoding-Challenge/11-Remove-Duplicate-Letters/Remove-Duplicate-Letters.cs create mode 100644 October-LeetCoding-Challenge/13-Sort-List/Sort-List.cs create mode 100644 October-LeetCoding-Challenge/31-Recover-Binary-Search-Tree/Recover-Binary-Search-Tree.cs diff --git a/October-LeetCoding-Challenge/02-Combination-Sum/Combination-Sum.cs b/October-LeetCoding-Challenge/02-Combination-Sum/Combination-Sum.cs new file mode 100644 index 0000000..e69de29 diff --git a/October-LeetCoding-Challenge/03-K-diff-Pairs-in-an-Array/K-diff-Pairs-in-an-Array.cs b/October-LeetCoding-Challenge/03-K-diff-Pairs-in-an-Array/K-diff-Pairs-in-an-Array.cs new file mode 100644 index 0000000..e69de29 diff --git a/October-LeetCoding-Challenge/05-Complement-of-Base-10-Integer/Complement-of-Base-10-Integer.cs b/October-LeetCoding-Challenge/05-Complement-of-Base-10-Integer/Complement-of-Base-10-Integer.cs new file mode 100644 index 0000000..e69de29 diff --git a/October-LeetCoding-Challenge/06-Insert-into-a-Binary-Search-Tree/Insert-into-a-Binary-Search-Tree.cs b/October-LeetCoding-Challenge/06-Insert-into-a-Binary-Search-Tree/Insert-into-a-Binary-Search-Tree.cs new file mode 100644 index 0000000..e69de29 diff --git a/October-LeetCoding-Challenge/07-Rotate-List/Rotate-List.cs b/October-LeetCoding-Challenge/07-Rotate-List/Rotate-List.cs new file mode 100644 index 0000000..e69de29 diff --git a/October-LeetCoding-Challenge/08-Binary-Search/Binary-Search.cs b/October-LeetCoding-Challenge/08-Binary-Search/Binary-Search.cs new file mode 100644 index 0000000..e69de29 diff --git a/October-LeetCoding-Challenge/09-Serialize-and-Deserialize-BST/Serialize-and-Deserialize-BST.cs b/October-LeetCoding-Challenge/09-Serialize-and-Deserialize-BST/Serialize-and-Deserialize-BST.cs new file mode 100644 index 0000000..e69de29 diff --git a/October-LeetCoding-Challenge/10-Minimum-Number-of-Arrows-to-Burst-Balloons/Minimum-Number-of-Arrows-to-Burst-Balloons.cs b/October-LeetCoding-Challenge/10-Minimum-Number-of-Arrows-to-Burst-Balloons/Minimum-Number-of-Arrows-to-Burst-Balloons.cs new file mode 100644 index 0000000..e69de29 diff --git a/October-LeetCoding-Challenge/11-Remove-Duplicate-Letters/Remove-Duplicate-Letters.cs b/October-LeetCoding-Challenge/11-Remove-Duplicate-Letters/Remove-Duplicate-Letters.cs new file mode 100644 index 0000000..e69de29 diff --git a/October-LeetCoding-Challenge/13-Sort-List/Sort-List.cs b/October-LeetCoding-Challenge/13-Sort-List/Sort-List.cs new file mode 100644 index 0000000..e69de29 diff --git a/October-LeetCoding-Challenge/31-Recover-Binary-Search-Tree/Recover-Binary-Search-Tree.cs b/October-LeetCoding-Challenge/31-Recover-Binary-Search-Tree/Recover-Binary-Search-Tree.cs new file mode 100644 index 0000000..e69de29 diff --git a/README.md b/README.md index af9ab97..8a4234f 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,12 @@ https://leetcode.com +## November LeetCoding Challenge +Click [here](https://leetcode.com/explore/challenge/card/november-leetcoding-challenge/) for problem descriptions. + +Solutions in various programming languages are provided. Enjoy it. + + ## October LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/) for problem descriptions. From 5a12b244566e3170707920af2028d6e8e06604d6 Mon Sep 17 00:00:00 2001 From: hellomrsun <23157401+hellomrsun@users.noreply.github.com> Date: Sun, 22 Nov 2020 13:07:24 +0100 Subject: [PATCH 278/281] Add solutions --- ...nary-Number-in-a-Linked-List-to-Integer.cs | 48 ++++++++++++++++ .../Insertion-Sort-List.cs | 41 ++++++++++++++ .../Consecutive-Characters.cs | 25 +++++++++ .../Minimum-Height-Trees.cs | 0 ...Cost-to-Move-Chips-to-The-Same-Position.cs | 14 +++++ ...-the-Smallest-Divisor-Given-a-Threshold.cs | 0 .../Add-Two-Numbers-II.cs | 50 +++++++++++++++++ .../08-Binary-Tree-Tilt/Binary-Tree-Tilt.cs | 36 ++++++++++++ ...um-Difference-Between-Node-and-Ancestor.cs | 35 ++++++++++++ .../10-Flipping-an-Image/Flipping-an-Image.cs | 27 +++++++++ .../11-Valid-Square/Valid-Square.cs | 28 ++++++++++ .../12-Permutations-II/Permutations-II.cs | 38 +++++++++++++ ...lating-Next-Right-Pointers-in-Each-Node.cs | 50 +++++++++++++++++ .../14-Poor-Pigs/Poor-Pigs.cs | 17 ++++++ .../15-Range-Sum-of-BST/Range-Sum-of-BST.cs | 40 +++++++++++++ .../Longest-Mountain-in-Array.cs | 20 +++++++ .../17-Mirror-Reflection/Mirror-Reflection.cs | 22 ++++++++ .../18-Merge-Intervals/Merge-Intervals.cs | 41 ++++++++++++++ .../19-Decode-String/Decode-String.cs | 50 +++++++++++++++++ .../Search-in-Rotated-Sorted-Array-II.cs | 51 +++++++++++++++++ .../Numbers-At-Most-N-Given-Digit-Set.cs | 0 .../Unique-Morse-Code-Words.cs | 56 +++++++++++++++++++ README.md | 23 ++++++++ 23 files changed, 712 insertions(+) create mode 100644 November-LeetCoding-Challenge/01-Convert-Binary-Number-in-a-Linked-List-to-Integer/Convert-Binary-Number-in-a-Linked-List-to-Integer.cs create mode 100644 November-LeetCoding-Challenge/02-Insertion-Sort-List/Insertion-Sort-List.cs create mode 100644 November-LeetCoding-Challenge/03-Consecutive-Characters/Consecutive-Characters.cs create mode 100644 November-LeetCoding-Challenge/04-Minimum-Height-Trees/Minimum-Height-Trees.cs create mode 100644 November-LeetCoding-Challenge/05-Minimum-Cost-to-Move-Chips-to-The-Same-Position/Minimum-Cost-to-Move-Chips-to-The-Same-Position.cs create mode 100644 November-LeetCoding-Challenge/06-Find-the-Smallest-Divisor-Given-a-Threshold/Find-the-Smallest-Divisor-Given-a-Threshold.cs create mode 100644 November-LeetCoding-Challenge/07-Add-Two-Numbers-II/Add-Two-Numbers-II.cs create mode 100644 November-LeetCoding-Challenge/08-Binary-Tree-Tilt/Binary-Tree-Tilt.cs create mode 100644 November-LeetCoding-Challenge/09-Maximum-Difference-Between-Node-and-Ancestor/Maximum-Difference-Between-Node-and-Ancestor.cs create mode 100644 November-LeetCoding-Challenge/10-Flipping-an-Image/Flipping-an-Image.cs create mode 100644 November-LeetCoding-Challenge/11-Valid-Square/Valid-Square.cs create mode 100644 November-LeetCoding-Challenge/12-Permutations-II/Permutations-II.cs create mode 100644 November-LeetCoding-Challenge/13-Populating-Next-Right-Pointers-in-Each-Node/Populating-Next-Right-Pointers-in-Each-Node.cs create mode 100644 November-LeetCoding-Challenge/14-Poor-Pigs/Poor-Pigs.cs create mode 100644 November-LeetCoding-Challenge/15-Range-Sum-of-BST/Range-Sum-of-BST.cs create mode 100644 November-LeetCoding-Challenge/16-Longest-Mountain-in-Array/Longest-Mountain-in-Array.cs create mode 100644 November-LeetCoding-Challenge/17-Mirror-Reflection/Mirror-Reflection.cs create mode 100644 November-LeetCoding-Challenge/18-Merge-Intervals/Merge-Intervals.cs create mode 100644 November-LeetCoding-Challenge/19-Decode-String/Decode-String.cs create mode 100644 November-LeetCoding-Challenge/20-Search-in-Rotated-Sorted-Array-II/Search-in-Rotated-Sorted-Array-II.cs create mode 100644 November-LeetCoding-Challenge/21-Numbers-At-Most-N-Given-Digit-Set/Numbers-At-Most-N-Given-Digit-Set.cs create mode 100644 November-LeetCoding-Challenge/22-Unique-Morse-Code-Words/Unique-Morse-Code-Words.cs diff --git a/November-LeetCoding-Challenge/01-Convert-Binary-Number-in-a-Linked-List-to-Integer/Convert-Binary-Number-in-a-Linked-List-to-Integer.cs b/November-LeetCoding-Challenge/01-Convert-Binary-Number-in-a-Linked-List-to-Integer/Convert-Binary-Number-in-a-Linked-List-to-Integer.cs new file mode 100644 index 0000000..6b02f75 --- /dev/null +++ b/November-LeetCoding-Challenge/01-Convert-Binary-Number-in-a-Linked-List-to-Integer/Convert-Binary-Number-in-a-Linked-List-to-Integer.cs @@ -0,0 +1,48 @@ +namespace _1290_Convert_Binary_Number_in_a_Linked_List_to_Integer +{ + public class Solution + { + public int GetDecimalValue(ListNode head) + { + //Solution 1 + var res = 0; + while (head != null) + { + res = res * 2 + head.val; + head = head.next; + } + return res; + + //Solution 2: Stack, from end to beginning + /* + var stack = new Stack(); + while(head != null){ + stack.Push(head.val); + head = head.next; + } + + var res = 0; + var lvl = 1; + res += stack.Pop(); + + while(stack.Count > 0){ + lvl *= 2; + res += lvl * stack.Pop(); + } + + return res; + */ + } + } + + public class ListNode + { + public int val; + public ListNode next; + public ListNode(int val = 0, ListNode next = null) + { + this.val = val; + this.next = next; + } + } +} \ No newline at end of file diff --git a/November-LeetCoding-Challenge/02-Insertion-Sort-List/Insertion-Sort-List.cs b/November-LeetCoding-Challenge/02-Insertion-Sort-List/Insertion-Sort-List.cs new file mode 100644 index 0000000..8bd3927 --- /dev/null +++ b/November-LeetCoding-Challenge/02-Insertion-Sort-List/Insertion-Sort-List.cs @@ -0,0 +1,41 @@ +namespace _147_Insertion_Sort_List +{ + public class Solution + { + public ListNode InsertionSortList(ListNode head) + { + ListNode dummy = new ListNode(0); + ListNode prev = dummy; + while (head != null) + { + ListNode temp = head.next; + + /* Before insert, the prev is at the last node of the sorted list. + Only the last node's value is larger than the current inserting node + should we move the temp back to the head*/ + if (prev.val >= head.val) prev = dummy; + + while (prev.next != null && prev.next.val < head.val) + { + prev = prev.next; + } + + head.next = prev.next; + prev.next = head; + // prev = dummy; // Don't set prev to the head of the list after insert + head = temp; + } + return dummy.next; + } + } + public class ListNode + { + public int val; + public ListNode next; + public ListNode(int val = 0, ListNode next = null) + { + this.val = val; + this.next = next; + } + } +} \ No newline at end of file diff --git a/November-LeetCoding-Challenge/03-Consecutive-Characters/Consecutive-Characters.cs b/November-LeetCoding-Challenge/03-Consecutive-Characters/Consecutive-Characters.cs new file mode 100644 index 0000000..a38c8e2 --- /dev/null +++ b/November-LeetCoding-Challenge/03-Consecutive-Characters/Consecutive-Characters.cs @@ -0,0 +1,25 @@ +using System; + +namespace _1446_Consecutive_Characters +{ + public class Solution + { + public int MaxPower(string s) + { + int res = 1, cnt = 1; + for (int i = 1; i < s.Length; i++) + { + if (s[i] == s[i - 1]) + { + cnt++; + res = Math.Max(res, cnt); + } + else + { + cnt = 1; + } + } + return res; + } + } +} diff --git a/November-LeetCoding-Challenge/04-Minimum-Height-Trees/Minimum-Height-Trees.cs b/November-LeetCoding-Challenge/04-Minimum-Height-Trees/Minimum-Height-Trees.cs new file mode 100644 index 0000000..e69de29 diff --git a/November-LeetCoding-Challenge/05-Minimum-Cost-to-Move-Chips-to-The-Same-Position/Minimum-Cost-to-Move-Chips-to-The-Same-Position.cs b/November-LeetCoding-Challenge/05-Minimum-Cost-to-Move-Chips-to-The-Same-Position/Minimum-Cost-to-Move-Chips-to-The-Same-Position.cs new file mode 100644 index 0000000..a6c084c --- /dev/null +++ b/November-LeetCoding-Challenge/05-Minimum-Cost-to-Move-Chips-to-The-Same-Position/Minimum-Cost-to-Move-Chips-to-The-Same-Position.cs @@ -0,0 +1,14 @@ +public class Solution { + public int MinCostToMoveChips(int[] position) { + int even = 0, odd = 0; + for(int i=0; i s1 = new Stack(), s2 = new Stack(); + while (l1 != null) + { + s1.Push(l1.val); + l1 = l1.next; + } + while (l2 != null) + { + s2.Push(l2.val); + l2 = l2.next; + } + + var sum = 0; + var node = new ListNode(0); + while (s1.Count > 0 || s2.Count > 0) + { + if (s1.Count > 0) sum += s1.Pop(); + if (s2.Count > 0) sum += s2.Pop(); + node.val = sum % 10; + + var head = new ListNode(sum / 10); + head.next = node; + node = head; + + sum /= 10; + } + + return node.val == 0 ? node.next : node; + } + } + + public class ListNode + { + public int val; + public ListNode next; + public ListNode(int val = 0, ListNode next = null) + { + this.val = val; + this.next = next; + } + } +} \ No newline at end of file diff --git a/November-LeetCoding-Challenge/08-Binary-Tree-Tilt/Binary-Tree-Tilt.cs b/November-LeetCoding-Challenge/08-Binary-Tree-Tilt/Binary-Tree-Tilt.cs new file mode 100644 index 0000000..46d6ab5 --- /dev/null +++ b/November-LeetCoding-Challenge/08-Binary-Tree-Tilt/Binary-Tree-Tilt.cs @@ -0,0 +1,36 @@ +using System; + +namespace _563_Binary_Tree_Tilt +{ + public class Solution + { + private int diff = 0; + + public int FindTilt(TreeNode root) { + PostOrder(root); + return diff; + } + + private int PostOrder(TreeNode node){ + if(node == null) return 0; + + var l = PostOrder(node.left); + var r = PostOrder(node.right); + + diff += Math.Abs(l - r); + + return l + r + node.val; + } + } + + public class TreeNode { + public int val; + public TreeNode left; + public TreeNode right; + public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { + this.val = val; + this.left = left; + this.right = right; + } + } +} \ No newline at end of file diff --git a/November-LeetCoding-Challenge/09-Maximum-Difference-Between-Node-and-Ancestor/Maximum-Difference-Between-Node-and-Ancestor.cs b/November-LeetCoding-Challenge/09-Maximum-Difference-Between-Node-and-Ancestor/Maximum-Difference-Between-Node-and-Ancestor.cs new file mode 100644 index 0000000..5a4da71 --- /dev/null +++ b/November-LeetCoding-Challenge/09-Maximum-Difference-Between-Node-and-Ancestor/Maximum-Difference-Between-Node-and-Ancestor.cs @@ -0,0 +1,35 @@ +using System; + +namespace _1026_Maximum_Difference_Between_Node_and_Ancestor +{ + public class Solution + { + public int MaxAncestorDiff(TreeNode root) + { + return Dfs(root, root.val, root.val); + } + + public int Dfs(TreeNode node, int min, int max) + { + if (node == null) return max - min; + + min = Math.Min(min, node.val); + max = Math.Max(max, node.val); + + return Math.Max(Dfs(node.left, min, max), Dfs(node.right, min, max)); + } + } + + public class TreeNode + { + public int val; + public TreeNode left; + public TreeNode right; + public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) + { + this.val = val; + this.left = left; + this.right = right; + } + } +} diff --git a/November-LeetCoding-Challenge/10-Flipping-an-Image/Flipping-an-Image.cs b/November-LeetCoding-Challenge/10-Flipping-an-Image/Flipping-an-Image.cs new file mode 100644 index 0000000..d077965 --- /dev/null +++ b/November-LeetCoding-Challenge/10-Flipping-an-Image/Flipping-an-Image.cs @@ -0,0 +1,27 @@ +namespace _832_Flipping_an_Image +{ + public class Solution + { + public int[][] FlipAndInvertImage(int[][] A) { + if(A == null || A.Length == 0) return new int[0][]; + var levelLength = A[0].Length-1; + int b =0; + int e = levelLength; + for(int i=0; i<=A.Length-1; i++){ + b = 0; + e = levelLength; + while(b < e){ + int temp = A[i][b]; + A[i][b] = A[i][e]; + A[i][e] = temp; + b++; + e--; + } + for(int j=0; j<=levelLength; j++){ + A[i][j] = 1 - A[i][j]; + } + } + return A; + } + } +} \ No newline at end of file diff --git a/November-LeetCoding-Challenge/11-Valid-Square/Valid-Square.cs b/November-LeetCoding-Challenge/11-Valid-Square/Valid-Square.cs new file mode 100644 index 0000000..bacf012 --- /dev/null +++ b/November-LeetCoding-Challenge/11-Valid-Square/Valid-Square.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; + +namespace _593_Valid_Square +{ + public class Solution + { + public bool ValidSquare(int[] p1, int[] p2, int[] p3, int[] p4) + { + var arr = + new int[] { + Cal(p1, p2), + Cal(p1, p3), + Cal(p1, p4), + Cal(p2, p3), + Cal(p2, p4), + Cal(p3, p4) + }; + HashSet hs = new HashSet(arr); + return !hs.Contains(0) && hs.Count == 2; + } + + private int Cal(int[] a, int[] b) + { + return (a[0] - b[0]) * (a[0] - b[0]) + + (a[1] - b[1]) * (a[1] - b[1]); + } + } +} diff --git a/November-LeetCoding-Challenge/12-Permutations-II/Permutations-II.cs b/November-LeetCoding-Challenge/12-Permutations-II/Permutations-II.cs new file mode 100644 index 0000000..ad28979 --- /dev/null +++ b/November-LeetCoding-Challenge/12-Permutations-II/Permutations-II.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; +using System.Linq; + +namespace _47_Permutations_II +{ + public class Solution + { + public IList> PermuteUnique(int[] nums) { + var res = new List>(); + if(nums == null || nums.Length == 0) return res; + + Recursion(nums, 0, res); + return res; + } + + private void Recursion(int[] nums, int idx, List> li){ + if(idx == nums.Length){ + li.Add(nums.ToList()); + return; + } + + var hs = new HashSet(); + for(int i=idx; i= low && root.val <= high) res += root.val; + PreOrder(root.right, low, high, ref res); + } + } + + public class TreeNode + { + public int val; + + public TreeNode left; + + public TreeNode right; + + public TreeNode( + int val = 0, + TreeNode left = null, + TreeNode right = null + ) + { + this.val = val; + this.left = left; + this.right = right; + } + } +} diff --git a/November-LeetCoding-Challenge/16-Longest-Mountain-in-Array/Longest-Mountain-in-Array.cs b/November-LeetCoding-Challenge/16-Longest-Mountain-in-Array/Longest-Mountain-in-Array.cs new file mode 100644 index 0000000..d218a5e --- /dev/null +++ b/November-LeetCoding-Challenge/16-Longest-Mountain-in-Array/Longest-Mountain-in-Array.cs @@ -0,0 +1,20 @@ +namespace _845_Longest_Mountain_in_Array +{ + public class Solution + { + public int LongestMountain(int[] A) + { + int res = 0, up = 0, down = 0; + for (int i = 1; i < A.Length; i++) + { + if (down > 0 && A[i - 1] < A[i] || A[i - 1] == A[i]) + up = down = 0; + if (A[i - 1] < A[i]) up++; + if (A[i - 1] > A[i]) down++; + if (up > 0 && down > 0 && up + down + 1 > res) + res = up + down + 1; + } + return res; + } + } +} diff --git a/November-LeetCoding-Challenge/17-Mirror-Reflection/Mirror-Reflection.cs b/November-LeetCoding-Challenge/17-Mirror-Reflection/Mirror-Reflection.cs new file mode 100644 index 0000000..e804c4b --- /dev/null +++ b/November-LeetCoding-Challenge/17-Mirror-Reflection/Mirror-Reflection.cs @@ -0,0 +1,22 @@ +namespace _858_Mirror_Reflection +{ + public class Solution + { + public int MirrorReflection(int p, int q) + { + int m = q, n = p; + + while (m % 2 == 0 && n % 2 == 0) + { + m /= 2; + n /= 2; + } + + if (m % 2 == 0 && n % 2 == 1) return 0; + if (m % 2 == 1 && n % 2 == 1) return 1; + if (m % 2 == 1 && n % 2 == 0) return 2; + + return -1; + } + } +} diff --git a/November-LeetCoding-Challenge/18-Merge-Intervals/Merge-Intervals.cs b/November-LeetCoding-Challenge/18-Merge-Intervals/Merge-Intervals.cs new file mode 100644 index 0000000..dd7a050 --- /dev/null +++ b/November-LeetCoding-Challenge/18-Merge-Intervals/Merge-Intervals.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace _56_Merge_Intervals +{ + public class Solution + { + public int[][] Merge(int[][] intervals) + { + if (intervals == null || intervals.Length < 2) return intervals; + + Array.Sort(intervals, (x, y) => new ArrayComparer().Compare(x, y)); + + var prev = new int[2] { -1, -1 }; + var res = new List(); + for (int i = 0; i < intervals.Length; i++) + { + var curr = intervals[i]; + if (prev[0] == -1 || curr[0] > prev[1]) + { + res.Add (curr); + prev = curr; + } + else if (curr[1] > prev[1]) + { + prev[1] = curr[1]; + } + } + return res.ToArray(); + } + + public class ArrayComparer : IComparer + { + public int Compare(int[] x, int[] y) + { + return x[0] - y[0]; + } + } + } +} diff --git a/November-LeetCoding-Challenge/19-Decode-String/Decode-String.cs b/November-LeetCoding-Challenge/19-Decode-String/Decode-String.cs new file mode 100644 index 0000000..fea108a --- /dev/null +++ b/November-LeetCoding-Challenge/19-Decode-String/Decode-String.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using System; +using System.Text; + +namespace _394_Decode_String +{ + public class Solution + { + public string DecodeString(string s) + { + var numStack = new Stack(); + var resStack = new Stack(); + resStack.Push(""); + + var len = s.Length; + + for (int i = 0; i < len; i++) + { + var c = s[i]; + if (c >= '0' && c <= '9') + { + int start = i; + while (s[i + 1] >= '0' && s[i + 1] <= '9') i++; + numStack.Push(int.Parse(s.Substring(start, i - start + 1))); + } + else if (c == '[') + { + resStack.Push(""); + } + else if (c == ']') + { + string str = resStack.Pop(); + var sb = new StringBuilder(); + var times = numStack.Pop(); + for (int b = 0; b < times; b++) + { + sb.Append (str); + } + resStack.Push(resStack.Pop() + sb.ToString()); + } + else + { + var curr = resStack.Pop(); + resStack.Push(curr + c); + } + } + return resStack.Pop(); + } + } +} diff --git a/November-LeetCoding-Challenge/20-Search-in-Rotated-Sorted-Array-II/Search-in-Rotated-Sorted-Array-II.cs b/November-LeetCoding-Challenge/20-Search-in-Rotated-Sorted-Array-II/Search-in-Rotated-Sorted-Array-II.cs new file mode 100644 index 0000000..1e70bac --- /dev/null +++ b/November-LeetCoding-Challenge/20-Search-in-Rotated-Sorted-Array-II/Search-in-Rotated-Sorted-Array-II.cs @@ -0,0 +1,51 @@ +namespace _81_Search_in_Rotated_Sorted_Array_II +{ + public class Solution + { + public bool Search(int[] nums, int target) + { + int + begin = 0, + end = nums.Length - 1; + + while (begin <= end) + { + int mid = begin + (end - begin) / 2; + if (nums[mid] == target) return true; + + //left part is sorted + if (nums[begin] < nums[mid]) + { + if (target < nums[begin] || target > nums[mid]) + { + //target is in rotated part + begin = mid + 1; + } + else + { + end = mid - 1; + } + } + else //right part is sorted + if (nums[begin] > nums[mid]) + { + if (target < nums[mid] || target > nums[end]) + { + //target is in rotated part + end = mid - 1; + } + else + { + begin = mid + 1; + } + } + else + //duplicates + { + begin++; + } + } + return false; + } + } +} diff --git a/November-LeetCoding-Challenge/21-Numbers-At-Most-N-Given-Digit-Set/Numbers-At-Most-N-Given-Digit-Set.cs b/November-LeetCoding-Challenge/21-Numbers-At-Most-N-Given-Digit-Set/Numbers-At-Most-N-Given-Digit-Set.cs new file mode 100644 index 0000000..e69de29 diff --git a/November-LeetCoding-Challenge/22-Unique-Morse-Code-Words/Unique-Morse-Code-Words.cs b/November-LeetCoding-Challenge/22-Unique-Morse-Code-Words/Unique-Morse-Code-Words.cs new file mode 100644 index 0000000..2944b70 --- /dev/null +++ b/November-LeetCoding-Challenge/22-Unique-Morse-Code-Words/Unique-Morse-Code-Words.cs @@ -0,0 +1,56 @@ +using System.Collections.Generic; +using System.Text; + +namespace _804_Unique_Morse_Code_Words +{ + public class Solution + { + public int UniqueMorseRepresentations(string[] words) + { + var arr = + new string[26] + { + ".-", + "-...", + "-.-.", + "-..", + ".", + "..-.", + "--.", + "....", + "..", + ".---", + "-.-", + ".-..", + "--", + "-.", + "---", + ".--.", + "--.-", + ".-.", + "...", + "-", + "..-", + "...-", + ".--", + "-..-", + "-.--", + "--.." + }; + + var hs = new HashSet(); + + foreach (string word in words) + { + var sb = new StringBuilder(); + for (int i = 0; i < word.Length; i++) + { + sb.Append(arr[word[i] - 'a']); + } + hs.Add(sb.ToString()); + } + + return hs.Count; + } + } +} diff --git a/README.md b/README.md index 8a4234f..e21dead 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,29 @@ Click [here](https://leetcode.com/explore/challenge/card/november-leetcoding-cha Solutions in various programming languages are provided. Enjoy it. +1. [Convert Binary Number in a Linked List to Integer](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/01-Convert-Binary-Number-in-a-Linked-List-to-Integer) +2. [Insertion Sort List](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/02-Insertion-Sort-List) +3. [Consecutive Characters](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/03-Consecutive-Characters) +4. [Minimum Height Trees](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/04-Minimum-Height-Trees) +5. [Minimum Cost to Move Chips to The Same Position](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/05-Minimum-Cost-to-Move-Chips-to-The-Same-Position) +6. [Find the Smallest Divisor Given a Threshold](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/06-Find-the-Smallest-Divisor-Given-a-Threshold) +7. [Add Two Numbers II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/07-Add-Two-Numbers-II) +8. [Binary Tree Tilt](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/08-Binary-Tree-Tilt) +9. [Maximum Difference Between Node and Ancestor](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/09-Maximum-Difference-Between-Node-and-Ancestor) +10. [Flipping an Image](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/10-Flipping-an-Image) +11. [Valid Square](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/11-Valid-Square) +12. [Permutations II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/12-Permutations-II) +13. [Populating Next Right Pointers in Each Node](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/13-Populating-Next-Right-Pointers-in-Each-Node) +14. [Poor Pigs](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/14-Poor-Pigs) +15. [Range Sum of BST](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/15-Range-Sum-of-BST) +16. [Longest Mountain in Array](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/16-Longest-Mountain-in-Array) +17. [Mirror Reflection](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/17-Mirror-Reflection) +18. [Merge Intervals](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/18-Merge-Intervals) +19. [Decode String](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/19-Decode-String) +20. [Search in Rotated Sorted Array II](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/20-Search-in-Rotated-Sorted-Array-II) +21. [Numbers At Most N Given Digit Set](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/21-Numbers-At-Most-N-Given-Digit-Set) +22. [Unique Morse Code Words](https://github.com/AlgoStudyGroup/Leetcode/tree/master/November-LeetCoding-Challenge/22-Unique-Morse-Code-Words) + ## October LeetCoding Challenge Click [here](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/) for problem descriptions. From bce16fa0fe95cc83af646fc63cf4d5c2dd9fe8f0 Mon Sep 17 00:00:00 2001 From: hellomrsun <23157401+hellomrsun@users.noreply.github.com> Date: Sun, 22 Nov 2020 19:21:30 +0100 Subject: [PATCH 279/281] file names --- ...and_Sell_Stock_IV.cs => Best-Time-to-Buy-and-Sell-Stock-IV.cs} | 0 ...For_Equal_Row.cs => Minimum-Domino-Rotations-For-Equal-Row.cs} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename October-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock-IV/{Best_Time_to_Buy_and_Sell_Stock_IV.cs => Best-Time-to-Buy-and-Sell-Stock-IV.cs} (100%) rename October-LeetCoding-Challenge/19-Minimum-Domino-Rotations-For-Equal-Row/{Minimum_Domino_Rotations_For_Equal_Row.cs => Minimum-Domino-Rotations-For-Equal-Row.cs} (100%) diff --git a/October-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock-IV/Best_Time_to_Buy_and_Sell_Stock_IV.cs b/October-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock-IV/Best-Time-to-Buy-and-Sell-Stock-IV.cs similarity index 100% rename from October-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock-IV/Best_Time_to_Buy_and_Sell_Stock_IV.cs rename to October-LeetCoding-Challenge/18-Best-Time-to-Buy-and-Sell-Stock-IV/Best-Time-to-Buy-and-Sell-Stock-IV.cs diff --git a/October-LeetCoding-Challenge/19-Minimum-Domino-Rotations-For-Equal-Row/Minimum_Domino_Rotations_For_Equal_Row.cs b/October-LeetCoding-Challenge/19-Minimum-Domino-Rotations-For-Equal-Row/Minimum-Domino-Rotations-For-Equal-Row.cs similarity index 100% rename from October-LeetCoding-Challenge/19-Minimum-Domino-Rotations-For-Equal-Row/Minimum_Domino_Rotations_For_Equal_Row.cs rename to October-LeetCoding-Challenge/19-Minimum-Domino-Rotations-For-Equal-Row/Minimum-Domino-Rotations-For-Equal-Row.cs From 3617f1e12baf7761599065e87835713d495603c9 Mon Sep 17 00:00:00 2001 From: hellomrsun <23157401+hellomrsun@users.noreply.github.com> Date: Sun, 22 Nov 2020 19:34:57 +0100 Subject: [PATCH 280/281] Fix names --- .../26-Champagne-Tower/{Champgane-Tower.cs => Champagne-Tower.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename October-LeetCoding-Challenge/26-Champagne-Tower/{Champgane-Tower.cs => Champagne-Tower.cs} (100%) diff --git a/October-LeetCoding-Challenge/26-Champagne-Tower/Champgane-Tower.cs b/October-LeetCoding-Challenge/26-Champagne-Tower/Champagne-Tower.cs similarity index 100% rename from October-LeetCoding-Challenge/26-Champagne-Tower/Champgane-Tower.cs rename to October-LeetCoding-Challenge/26-Champagne-Tower/Champagne-Tower.cs From 39f978c37c2608517582a25d4959ffaa59c93002 Mon Sep 17 00:00:00 2001 From: hellomrsun <23157401+hellomrsun@users.noreply.github.com> Date: Sun, 22 Nov 2020 19:42:32 +0100 Subject: [PATCH 281/281] Fix names --- ...to-Closest-Person.cs => Maximum-Distance-to-Closest-Person.cs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename October-LeetCoding-Challenge/29-Maximum-Distance-to-Closest-Person/{Maximize-Distance-to-Closest-Person.cs => Maximum-Distance-to-Closest-Person.cs} (100%) diff --git a/October-LeetCoding-Challenge/29-Maximum-Distance-to-Closest-Person/Maximize-Distance-to-Closest-Person.cs b/October-LeetCoding-Challenge/29-Maximum-Distance-to-Closest-Person/Maximum-Distance-to-Closest-Person.cs similarity index 100% rename from October-LeetCoding-Challenge/29-Maximum-Distance-to-Closest-Person/Maximize-Distance-to-Closest-Person.cs rename to October-LeetCoding-Challenge/29-Maximum-Distance-to-Closest-Person/Maximum-Distance-to-Closest-Person.cs