From 0d4447d0b51ffd9fa3f14313c2237b75b444e429 Mon Sep 17 00:00:00 2001 From: Charies Gavin Date: Sun, 29 Sep 2019 14:31:43 +0800 Subject: [PATCH] add java solutions of 822 ~ 840 --- README.md | 20 +-- .../com/hit/basmath/learn/others/_822.java | 54 ++++++++ .../com/hit/basmath/learn/others/_823.java | 48 +++++++ .../com/hit/basmath/learn/others/_824.java | 53 ++++++++ .../com/hit/basmath/learn/others/_825.java | 59 ++++++++ .../com/hit/basmath/learn/others/_826.java | 62 +++++++++ .../com/hit/basmath/learn/others/_827.java | 126 ++++++++++++++++++ .../com/hit/basmath/learn/others/_828.java | 55 ++++++++ .../com/hit/basmath/learn/others/_829.java | 36 +++++ .../com/hit/basmath/learn/others/_830.java | 50 +++++++ .../com/hit/basmath/learn/others/_831.java | 97 ++++++++++++++ .../com/hit/basmath/learn/others/_832.java | 47 +++++++ .../com/hit/basmath/learn/others/_833.java | 68 ++++++++++ .../com/hit/basmath/learn/others/_834.java | 68 ++++++++++ .../com/hit/basmath/learn/others/_835.java | 53 ++++++++ .../com/hit/basmath/learn/others/_836.java | 39 ++++++ .../com/hit/basmath/learn/others/_837.java | 63 +++++++++ .../com/hit/basmath/learn/others/_838.java | 62 +++++++++ .../com/hit/basmath/learn/others/_839.java | 84 ++++++++++++ .../com/hit/basmath/learn/others/_840.java | 76 +++++++++++ 20 files changed, 1210 insertions(+), 10 deletions(-) create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_822.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_823.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_824.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_825.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_826.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_827.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_828.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_829.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_830.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_831.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_832.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_833.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_834.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_835.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_836.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_837.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_838.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_839.java create mode 100644 codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_840.java diff --git a/README.md b/README.md index a9089e4..576fbb6 100644 --- a/README.md +++ b/README.md @@ -713,16 +713,16 @@ My LeetCode Solutions! |828|[Unique Letter String](https://leetcode.com/problems/unique-letter-string/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_828.java) & Python |![hard](https://github.com/guobinhit/myleetcode/blob/master/images/hard.png)| Others |829|[Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_829.java) & Python |![hard](https://github.com/guobinhit/myleetcode/blob/master/images/hard.png)| Others |830|[Positions of Large Groups](https://leetcode.com/problems/positions-of-large-groups/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_830.java) & Python |![easy](https://github.com/guobinhit/myleetcode/blob/master/images/easy.png)| Others -|831|[Masking Personal Information]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_831.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others -|832|[Flipping an Image]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_832.java) & Python |![easy](https://github.com/guobinhit/myleetcode/blob/master/images/easy.png)| Others -|833|[Find And Replace in String]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_833.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others -|834|[Sum of Distances in Tree]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_834.java) & Python |![hard](https://github.com/guobinhit/myleetcode/blob/master/images/hard.png)| Others -|835|[Image Overlap]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_835.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others -|836|[Rectangle Overlap]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_836.java) & Python |![easy](https://github.com/guobinhit/myleetcode/blob/master/images/easy.png)| Others -|837|[New 21 Game]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_837.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others -|838|[Push Dominoes]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_838.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others -|839|[Similar String Groups]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_839.java) & Python |![hard](https://github.com/guobinhit/myleetcode/blob/master/images/hard.png)| Others -|840|[Magic Squares In Grid]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_840.java) & Python |![easy](https://github.com/guobinhit/myleetcode/blob/master/images/easy.png)| Others +|831|[Masking Personal Information](https://leetcode.com/problems/masking-personal-information/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_831.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others +|832|[Flipping an Image](https://leetcode.com/problems/flipping-an-image/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_832.java) & Python |![easy](https://github.com/guobinhit/myleetcode/blob/master/images/easy.png)| Others +|833|[Find And Replace in String](https://leetcode.com/problems/find-and-replace-in-string/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_833.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others +|834|[Sum of Distances in Tree](https://leetcode.com/problems/sum-of-distances-in-tree/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_834.java) & Python |![hard](https://github.com/guobinhit/myleetcode/blob/master/images/hard.png)| Others +|835|[Image Overlap](https://leetcode.com/problems/image-overlap/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_835.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others +|836|[Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_836.java) & Python |![easy](https://github.com/guobinhit/myleetcode/blob/master/images/easy.png)| Others +|837|[New 21 Game](https://leetcode.com/problems/new-21-game/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_837.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others +|838|[Push Dominoes](https://leetcode.com/problems/push-dominoes/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_838.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others +|839|[Similar String Groups](https://leetcode.com/problems/similar-string-groups/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_839.java) & Python |![hard](https://github.com/guobinhit/myleetcode/blob/master/images/hard.png)| Others +|840|[Magic Squares In Grid](https://leetcode.com/problems/magic-squares-in-grid/)|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_840.java) & Python |![easy](https://github.com/guobinhit/myleetcode/blob/master/images/easy.png)| Others |842|[Split Array into Fibonacci Sequence]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_842.java) & Python |![medium](https://github.com/guobinhit/myleetcode/blob/master/images/medium.png)| Others |843|[Guess the Word]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_843.java) & Python |![hard](https://github.com/guobinhit/myleetcode/blob/master/images/hard.png)| Others |844|[Backspace String Compare]()|[Java](https://github.com/guobinhit/myleetcode/blob/master/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_844.java) & Python |![easy](https://github.com/guobinhit/myleetcode/blob/master/images/easy.png)| Others diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_822.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_822.java new file mode 100644 index 0000000..7e87612 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_822.java @@ -0,0 +1,54 @@ +package com.hit.basmath.learn.others; + +import java.util.HashSet; +import java.util.Set; + +/** + * 822. Card Flipping Game + *

+ * On a table are N cards, with a positive integer printed on the front and back of each card (possibly different). + *

+ * We flip any number of cards, and after we choose one card. + *

+ * If the number X on the back of the chosen card is not on the front of any card, then this number X is good. + *

+ * What is the smallest number that is good? If no number is good, output 0. + *

+ * Here, fronts[i] and backs[i] represent the number on the front and back of card i. + *

+ * A flip swaps the front and back numbers, so the value on the front is now on the back and vice versa. + *

+ * Example: + *

+ * Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3] + * Output: 2 + * Explanation: If we flip the second card, the fronts are [1,3,4,4,7] and the backs are [1,2,4,1,3]. + * We choose the second card, which has number 2 on the back, and it isn't on the front of any card, so 2 is good. + *

+ * Note: + *

+ * 1 <= fronts.length == backs.length <= 1000. + * 1 <= fronts[i] <= 2000. + * 1 <= backs[i] <= 2000. + */ +public class _822 { + public int flipgame(int[] fronts, int[] backs) { + Set set = new HashSet<>(); + int n = fronts.length; + for (int i = 0; i < n; i++) { + if (fronts[i] == backs[i]) { + set.add(fronts[i]); + } + } + int min = Integer.MAX_VALUE; + for (int i = 0; i < n; i++) { + if (!set.contains(backs[i])) { + min = Math.min(min, backs[i]); + } + if (!set.contains(fronts[i])) { + min = Math.min(min, fronts[i]); + } + } + return min == Integer.MAX_VALUE ? 0 : min; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_823.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_823.java new file mode 100644 index 0000000..f2b3302 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_823.java @@ -0,0 +1,48 @@ +package com.hit.basmath.learn.others; + +import java.util.Arrays; +import java.util.HashMap; + +/** + * 823. Binary Trees With Factors + *

+ * Given an array of unique integers, each integer is strictly greater than 1. + *

+ * We make a binary tree using these integers and each number may be used for any number of times. + *

+ * Each non-leaf node's value should be equal to the product of the values of it's children. + *

+ * How many binary trees can we make? Return the answer modulo 10 ** 9 + 7. + *

+ * Example 1: + *

+ * Input: A = [2, 4] + * Output: 3 + * Explanation: We can make these trees: [2], [4], [4, 2, 2] + *

+ * Example 2: + *

+ * Input: A = [2, 4, 5, 10] + * Output: 7 + * Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]. + *

+ * Note: + *

+ * 1 <= A.length <= 1000. + * 2 <= A[i] <= 10 ^ 9. + */ +public class _823 { + public int numFactoredBinaryTrees(int[] A) { + long res = 0L, mod = (long) 1e9 + 7; + Arrays.sort(A); + HashMap dp = new HashMap<>(); + for (int i = 0; i < A.length; ++i) { + dp.put(A[i], 1L); + for (int j = 0; j < i; ++j) + if (A[i] % A[j] == 0) + dp.put(A[i], (dp.get(A[i]) + dp.get(A[j]) * dp.getOrDefault(A[i] / A[j], 0L)) % mod); + res = (res + dp.get(A[i])) % mod; + } + return (int) res; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_824.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_824.java new file mode 100644 index 0000000..76d5c2f --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_824.java @@ -0,0 +1,53 @@ +package com.hit.basmath.learn.others; + +import java.util.HashSet; +import java.util.Set; + +/** + * 824. Goat Latin + *

+ * A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only. + *

+ * We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) + *

+ * The rules of Goat Latin are as follows: + *

+ * If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of the word. + * For example, the word 'apple' becomes 'applema'. + *

+ * If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add "ma". + * For example, the word "goat" becomes "oatgma". + *

+ * Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1. + * For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on. + * Return the final sentence representing the conversion from S to Goat Latin. + *

+ * Example 1: + *

+ * Input: "I speak Goat Latin" + * Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" + *

+ * Example 2: + *

+ * Input: "The quick brown fox jumped over the lazy dog" + * Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa" + *

+ * Notes: + *

+ * S contains only uppercase, lowercase and spaces. Exactly one space between each word. + * 1 <= S.length <= 150. + */ +public class _824 { + public String toGoatLatin(String S) { + Set vowel = new HashSet(); + for (char c : "aeiouAEIOU".toCharArray()) vowel.add(c); + String res = ""; + int i = 0, j = 0; + for (String w : S.split("\\s")) { + res += ' ' + (vowel.contains(w.charAt(0)) ? w : w.substring(1) + w.charAt(0)) + "ma"; + for (j = 0, ++i; j < i; ++j) res += "a"; + } + ; + return res.substring(1); + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_825.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_825.java new file mode 100644 index 0000000..8f6386f --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_825.java @@ -0,0 +1,59 @@ +package com.hit.basmath.learn.others; + +import java.util.HashMap; +import java.util.Map; + +/** + * 825. Friends Of Appropriate Ages + *

+ * Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person. + *

+ * Person A will NOT friend request person B (B != A) if any of the following conditions are true: + *

+ * age[B] <= 0.5 * age[A] + 7 + * age[B] > age[A] + * age[B] > 100 && age[A] < 100 + * Otherwise, A will friend request B. + *

+ * Note that if A requests B, B does not necessarily request A. Also, people will not friend request themselves. + *

+ * How many total friend requests are made? + *

+ * Example 1: + *

+ * Input: [16,16] + * Output: 2 + * Explanation: 2 people friend request each other. + *

+ * Example 2: + *

+ * Input: [16,17,18] + * Output: 2 + * Explanation: Friend requests are made 17 -> 16, 18 -> 17. + *

+ * Example 3: + *

+ * Input: [20,30,100,110,120] + * Output: + * Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. + *

+ * Notes: + *

+ * 1 <= ages.length <= 20000. + * 1 <= ages[i] <= 120. + */ +public class _825 { + public int numFriendRequests(int[] ages) { + Map count = new HashMap<>(); + for (int age : ages) count.put(age, count.getOrDefault(age, 0) + 1); + int res = 0; + for (Integer a : count.keySet()) + for (Integer b : count.keySet()) + if (request(a, b)) res += count.get(a) * (count.get(b) - (a == b ? 1 : 0)); + return res; + } + + private boolean request(int a, int b) { + return !(b <= 0.5 * a + 7 || b > a || (b > 100 && a < 100)); + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_826.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_826.java new file mode 100644 index 0000000..05e9e85 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_826.java @@ -0,0 +1,62 @@ +package com.hit.basmath.learn.others; + +import java.util.Map; +import java.util.TreeMap; + +/** + * 826. Most Profit Assigning Work + *

+ * We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job. + *

+ * Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i]. + *

+ * Every worker can be assigned at most one job, but one job can be completed multiple times. + *

+ * For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0. + *

+ * What is the most profit we can make? + *

+ * Example 1: + *

+ * Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7] + * Output: 100 + * Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately. + *

+ * Notes: + *

+ * 1 <= difficulty.length = profit.length <= 10000 + * 1 <= worker.length <= 10000 + * difficulty[i], profit[i], worker[i] are in range [1, 10^5] + */ +public class _826 { + public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) { + + TreeMap tmap = new TreeMap<>(); + // in case two jobs have same difficulty but different profit, we want to count + // the higher profit + for (int i = 0; i < difficulty.length; i++) { + tmap.put(difficulty[i], Math.max(profit[i], tmap.getOrDefault(difficulty[i], 0))); + } + + int max = 0, res = 0; + // maximum profit at this difficulty or below in case + // lower difficulty job offers higher profit + for (Integer key : tmap.keySet()) { + max = Math.max(tmap.get(key), max); + tmap.put(key, max); + } + + Map.Entry entry = null; + for (int i = 0; i < worker.length; i++) { + if (tmap.containsKey(worker[i])) { + res += tmap.get(worker[i]); + } else { + entry = tmap.floorEntry(worker[i]); + if (entry != null) { + res += entry.getValue(); + } + } + } + return res; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_827.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_827.java new file mode 100644 index 0000000..9039423 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_827.java @@ -0,0 +1,126 @@ +package com.hit.basmath.learn.others; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * 827. Making A Large Island + *

+ * In a 2D grid of 0s and 1s, we change at most one 0 to a 1. + *

+ * After, what is the size of the largest island? (An island is a 4-directionally connected group of 1s). + *

+ * Example 1: + *

+ * Input: [[1, 0], [0, 1]] + * Output: 3 + * Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3. + *

+ * Example 2: + *

+ * Input: [[1, 1], [1, 0]] + * Output: 4 + * Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4. + *

+ * Example 3: + *

+ * Input: [[1, 1], [1, 1]] + * Output: 4 + * Explanation: Can't change any 0 to 1, only one island with area = 4. + *

+ * Notes: + *

+ * 1 <= grid.length = grid[0].length <= 50. + * 0 <= grid[i][j] <= 1. + */ +public class _827 { + public int largestIsland(int[][] grid) { + int rows = grid.length; + int cols = grid[0].length; + + // create father array and size array, and initialize them + int[] father = new int[rows * cols]; + for (int i = 0; i < rows * cols; i++) { + father[i] = i; + } + int[] size = new int[rows * cols]; + Arrays.fill(size, 1); + + int[] dx = {0, 1, -1, 0}; + int[] dy = {1, 0, 0, -1}; + + // scan grid, update father array and size array + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (grid[i][j] == 1) { + int id = i * cols + j; + for (int k = 0; k < 4; k++) { + int newi = i + dx[k]; + int newj = j + dy[k]; + int newid = newi * cols + newj; + if (isValid(rows, cols, newi, newj) && grid[newi][newj] == 1) { + union(father, size, id, newid); + } + } + } + } + } + + // find current max component size + int max = 0; + for (int i = 0; i < size.length; i++) { + max = Math.max(max, size[i]); + } + + // find max component size if we set any 0 to 1 + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + if (grid[i][j] == 0) { + int id = i * cols + j; + int combinedSize = 1; + Set prevFather = new HashSet<>(); + for (int k = 0; k < 4; k++) { + int newi = i + dx[k]; + int newj = j + dy[k]; + int newid = newi * cols + newj; + if (isValid(rows, cols, newi, newj) && grid[newi][newj] == 1) { + int currFather = find(father, newid); + if (prevFather.isEmpty() || !prevFather.contains(currFather)) { + combinedSize += size[currFather]; + prevFather.add(currFather); + } + } + } + max = Math.max(max, combinedSize); + } + } + } + + // return whole size if the grid is an all 1 matrix, otherwise return the value of max + return max == 0 ? rows * cols : max; + } + + private int find(int[] father, int id) { + if (father[id] == id) { + return id; + } + return father[id] = find(father, father[id]); + } + + private void union(int[] father, int[] size, int id1, int id2) { + int fa1 = find(father, id1); + int fa2 = find(father, id2); + if (fa1 != fa2) { + father[fa1] = fa2; + size[fa2] += size[fa1]; + } + } + + private boolean isValid(int rows, int cols, int i, int j) { + if (i >= 0 && i < rows && j >= 0 && j < cols) { + return true; + } + return false; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_828.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_828.java new file mode 100644 index 0000000..c66a65f --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_828.java @@ -0,0 +1,55 @@ +package com.hit.basmath.learn.others; + +/** + * 828. Unique Letter String + *

+ * A character is unique in string S if it occurs exactly once in it. + *

+ * For example, in string S = "LETTER", the only unique characters are "L" and "R". + *

+ * Let's define UNIQ(S) as the number of unique characters in string S. + *

+ * For example, UNIQ("LETTER") = 2. + *

+ * Given a string S with only uppercases, calculate the sum of UNIQ(substring) over all non-empty substrings of S. + *

+ * If there are two or more equal substrings at different positions in S, we consider them different. + *

+ * Since the answer can be very large, return the answer modulo 10 ^ 9 + 7. + *

+ * Example 1: + *

+ * Input: "ABC" + * Output: 10 + * Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC". + * Evey substring is composed with only unique letters. + * Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10 + *

+ * Example 2: + *

+ * Input: "ABA" + * Output: 8 + * Explanation: The same as example 1, except uni("ABA") = 1. + *

+ * Note: 0 <= S.length <= 10000. + */ +public class _828 { + public int uniqueLetterString(String S) { + + int res = 0; + if (S == null || S.length() == 0) + return res; + int[] showLastPosition = new int[128]; + int[] contribution = new int[128]; + int cur = 0; + for (int i = 0; i < S.length(); i++) { + char x = S.charAt(i); + cur -= contribution[x]; + contribution[x] = (i - (showLastPosition[x] - 1)); + cur += contribution[x]; + showLastPosition[x] = i + 1; + res += cur; + } + return res; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_829.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_829.java new file mode 100644 index 0000000..ee18f64 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_829.java @@ -0,0 +1,36 @@ +package com.hit.basmath.learn.others; + +/** + * 829. Consecutive Numbers Sum + *

+ * Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers? + *

+ * Example 1: + *

+ * Input: 5 + * Output: 2 + * Explanation: 5 = 5 = 2 + 3 + *

+ * Example 2: + *

+ * Input: 9 + * Output: 3 + * Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4 + *

+ * Example 3: + *

+ * Input: 15 + * Output: 4 + * Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5 + *

+ * Note: 1 <= N <= 10 ^ 9. + */ +public class _829 { + public int consecutiveNumbersSum(int N) { + int ans = 1; + for (int i = 2; i * (i + 1) / 2 <= N; ++i) { + if ((N - i * (i + 1) / 2) % i == 0) ++ans; + } + return ans; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_830.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_830.java new file mode 100644 index 0000000..a969393 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_830.java @@ -0,0 +1,50 @@ +package com.hit.basmath.learn.others; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * 830. Positions of Large Groups + *

+ * In a string S of lowercase letters, these letters form consecutive groups of the same character. + *

+ * For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy". + *

+ * Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group. + *

+ * The final answer should be in lexicographic order. + *

+ * Example 1: + *

+ * Input: "abbxxxxzzy" + * Output: [[3,6]] + * Explanation: "xxxx" is the single large group with starting 3 and ending positions 6. + *

+ * Example 2: + *

+ * Input: "abc" + * Output: [] + * Explanation: We have "a","b" and "c" but no large group. + * Example 3: + *

+ * Input: "abcdddeeeeaabbbcd" + * Output: [[3,5],[6,9],[12,14]] + *

+ * Note: 1 <= S.length <= 1000 + */ +public class _830 { + public List> largeGroupPositions(String S) { + List> ans = new ArrayList<>(); + int start = 0; + for (int i = 1; i <= S.length(); i++) { + if (i == S.length() || S.charAt(i) != S.charAt(start)) { + if (i - start >= 3) { + ans.add(Arrays.asList(start, i - 1)); + } + start = i; + } + } + return ans; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_831.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_831.java new file mode 100644 index 0000000..8c8ae1c --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_831.java @@ -0,0 +1,97 @@ +package com.hit.basmath.learn.others; + +/** + * 831. Masking Personal Information + *

+ * We are given a personal information string S, which may represent either an email address or a phone number. + *

+ * We would like to mask this personal information according to the following rules: + *

+ * 1. Email address: + *

+ * We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-Z. + *

+ * An email address starts with a name, followed by the symbol '@', followed by a name, followed by the dot '.' and followed by a name. + *

+ * All email addresses are guaranteed to be valid and in the format of "name1@name2.name3". + *

+ * To mask an email, all names must be converted to lowercase and all letters between the first and last letter of the first name must be replaced by 5 asterisks '*'. + *

+ * 2. Phone number: + *

+ * A phone number is a string consisting of only the digits 0-9 or the characters from the set {'+', '-', '(', ')', ' '}. You may assume a phone number contains 10 to 13 digits. + *

+ * The last 10 digits make up the local number, while the digits before those make up the country code. Note that the country code is optional. We want to expose only the last 4 digits and mask all other digits. + *

+ * The local number should be formatted and masked as "***-***-1111", where 1 represents the exposed digits. + *

+ * To mask a phone number with country code like "+111 111 111 1111", we write it in the form "+***-***-***-1111". The '+' sign and the first '-' sign before the local number should only exist if there is a country code. For example, a 12 digit phone number mask should start with "+**-". + *

+ * Note that extraneous characters like "(", ")", " ", as well as extra dashes or plus signs not part of the above formatting scheme should be removed. + *

+ * Return the correct "mask" of the information provided. + *

+ * Example 1: + *

+ * Input: "LeetCode@LeetCode.com" + * Output: "l*****e@leetcode.com" + * Explanation: All names are converted to lowercase, and the letters between the + * first and last letter of the first name is replaced by 5 asterisks. + * Therefore, "leetcode" -> "l*****e". + *

+ * Example 2: + *

+ * Input: "AB@qq.com" + * Output: "a*****b@qq.com" + * Explanation: There must be 5 asterisks between the first and last letter + * of the first name "ab". Therefore, "ab" -> "a*****b". + *

+ * Example 3: + *

+ * Input: "1(234)567-890" + * Output: "***-***-7890" + * Explanation: 10 digits in the phone number, which means all digits make up the local number. + *

+ * Example 4: + *

+ * Input: "86-(10)12345678" + * Output: "+**-***-***-5678" + * Explanation: 12 digits, 2 digits for country code and 10 digits for local number. + *

+ * Notes: + *

+ * S.length <= 40. + * Emails have length at least 8. + * Phone numbers have length at least 10. + */ +public class _831 { + public String maskPII(String S) { + S = S.toLowerCase(); + StringBuilder str = null; + int index = S.indexOf('@'); + if (index != -1) { + str = new StringBuilder(S); + str.replace(1, index - 1, "*****"); + } else { + str = new StringBuilder(); + for (char ch : S.toCharArray()) { + int d = ch - '0'; + if (d >= 0 && d <= 9) { + str.append(ch); + } + } + if (str.length() > 10) { + if (str.length() == 11) { + str.replace(0, str.length() - 4, "+*-***-***-"); + } else if (str.length() == 12) { + str.replace(0, str.length() - 4, "+**-***-***-"); + } else if (str.length() == 13) { + str.replace(0, str.length() - 4, "+***-***-***-"); + } + } else { + str.replace(0, str.length() - 4, "***-***-"); + } + } + return str.toString(); + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_832.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_832.java new file mode 100644 index 0000000..db7159a --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_832.java @@ -0,0 +1,47 @@ +package com.hit.basmath.learn.others; + +/** + * 832. Flipping an Image + *

+ * Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image. + *

+ * To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. + *

+ * To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. + *

+ * Example 1: + *

+ * Input: [[1,1,0],[1,0,1],[0,0,0]] + * Output: [[1,0,0],[0,1,0],[1,1,1]] + * Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. + * Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] + *

+ * Example 2: + *

+ * Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] + * Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] + * Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. + * Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] + *

+ * Notes: + *

+ * 1 <= A.length = A[0].length <= 20 + * 0 <= A[i][j] <= 1 + */ +public class _832 { + public int[][] flipAndInvertImage(int[][] A) { + for (int i = 0; i < A.length; i++) { + int lo = 0, hi = A[0].length - 1; + while (lo <= hi) { + if (A[i][lo] == A[i][hi]) { + A[i][lo] = 1 - A[i][lo]; + A[i][hi] = A[i][lo]; + } + lo++; + hi--; + } + } + + return A; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_833.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_833.java new file mode 100644 index 0000000..5f1ed4e --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_833.java @@ -0,0 +1,68 @@ +package com.hit.basmath.learn.others; + +import java.util.Arrays; + +/** + * 833. Find And Replace in String + *

+ * To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size). + *

+ * Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. The rule is that if x starts at position i in the original string S, then we will replace that occurrence of x with y. If not, we do nothing. + *

+ * For example, if we have S = "abcd" and we have some replacement operation i = 2, x = "cd", y = "ffff", then because "cd" starts at position 2 in the original string S, we will replace it with "ffff". + *

+ * Using another example on S = "abcd", if we have both the replacement operation i = 0, x = "ab", y = "eee", as well as another replacement operation i = 2, x = "ec", y = "ffff", this second operation does nothing because in the original string S[2] = 'c', which doesn't match x[0] = 'e'. + *

+ * All these operations occur simultaneously. It's guaranteed that there won't be any overlap in replacement: for example, S = "abc", indexes = [0, 1], sources = ["ab","bc"] is not a valid test case. + *

+ * Example 1: + *

+ * Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"] + * Output: "eeebffff" + * Explanation: "a" starts at index 0 in S, so it's replaced by "eee". + * "cd" starts at index 2 in S, so it's replaced by "ffff". + *

+ * Example 2: + *

+ * Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"] + * Output: "eeecd" + * Explanation: "ab" starts at index 0 in S, so it's replaced by "eee". + * "ec" doesn't starts at index 2 in the original S, so we do nothing. + *

+ * Notes: + *

+ * 0 <= indexes.length = sources.length = targets.length <= 100 + * 0 < indexes[i] < S.length <= 1000 + * All characters in given inputs are lowercase letters. + */ +public class _833 { + public String findReplaceString(String S, int[] indexes, String[] sources, String[] targets) { + int n = S.length(); + int[] match = new int[n]; + Arrays.fill(match, -1); + // Mark expected matching position with + // its corresponding index in the replacement arrays + for (int i = 0; i < indexes.length; i++) { + match[indexes[i]] = i; + } + // Build output + StringBuilder sb = new StringBuilder(); + int start = 0; + for (int i = 0; i < n; i++) { + if (match[i] == -1) continue; + + int j = match[i]; // index of replacement array + int end = i + sources[j].length(); + String sub = S.substring(i, end); + + // If match found then replace + if (sub.equals(sources[j])) { + sb.append(S.substring(start, i)); // keep non-replace part + sb.append(targets[j]); // replace matching part + start = end; + } + } + sb.append(S.substring(start)); // remaining part + return sb.toString(); + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_834.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_834.java new file mode 100644 index 0000000..85ee576 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_834.java @@ -0,0 +1,68 @@ +package com.hit.basmath.learn.others; + +import java.util.ArrayList; +import java.util.HashSet; + +/** + * 834. Sum of Distances in Tree + *

+ * An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given. + *

+ * The ith edge connects nodes edges[i][0] and edges[i][1] together. + *

+ * Return a list ans, where ans[i] is the sum of the distances between node i and all other nodes. + *

+ * Example 1: + *

+ * Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] + * Output: [8,12,6,10,10,10] + * Explanation: + * Here is a diagram of the given tree: + * 0 + * / \ + * 1 2 + * /|\ + * 3 4 5 + * We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) + * equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer[0] = 8, and so on. + *

+ * Note: 1 <= N <= 10000 + */ +public class _834 { + private int[] res, count; + private ArrayList> tree; + + public int[] sumOfDistancesInTree(int N, int[][] edges) { + tree = new ArrayList>(); + res = new int[N]; + count = new int[N]; + for (int i = 0; i < N; ++i) + tree.add(new HashSet()); + for (int[] e : edges) { + tree.get(e[0]).add(e[1]); + tree.get(e[1]).add(e[0]); + } + dfs(0, -1); + dfs2(0, -1); + return res; + } + + public void dfs(int root, int pre) { + for (int i : tree.get(root)) { + if (i == pre) continue; + dfs(i, root); + count[root] += count[i]; + res[root] += res[i] + count[i]; + } + count[root]++; + } + + + private void dfs2(int root, int pre) { + for (int i : tree.get(root)) { + if (i == pre) continue; + res[i] = res[root] - count[i] + count.length - count[i]; + dfs2(i, root); + } + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_835.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_835.java new file mode 100644 index 0000000..25315c6 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_835.java @@ -0,0 +1,53 @@ +package com.hit.basmath.learn.others; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * 835. Image Overlap + *

+ * Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.) + *

+ * We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images. + *

+ * (Note also that a translation does not include any kind of rotation.) + *

+ * What is the largest possible overlap? + *

+ * Example 1: + *

+ * Input: A = [[1,1,0], + * [0,1,0], + * [0,1,0]] + * B = [[0,0,0], + * [0,1,1], + * [0,0,1]] + * Output: 3 + * Explanation: We slide A to right by 1 unit and down by 1 unit. + *

+ * Notes: + *

+ * 1 <= A.length = A[0].length = B.length = B[0].length <= 30 + * 0 <= A[i][j], B[i][j] <= 1 + */ +public class _835 { + public int largestOverlap(int[][] A, int[][] B) { + int N = A.length; + List LA = new ArrayList<>(), LB = new ArrayList<>(); + HashMap count = new HashMap<>(); + for (int i = 0; i < N * N; ++i) + if (A[i / N][i % N] == 1) + LA.add(i / N * 100 + i % N); + for (int i = 0; i < N * N; ++i) + if (B[i / N][i % N] == 1) + LB.add(i / N * 100 + i % N); + for (int i : LA) + for (int j : LB) + count.put(i - j, count.getOrDefault(i - j, 0) + 1); + int res = 0; + for (int i : count.values()) + res = Math.max(res, i); + return res; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_836.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_836.java new file mode 100644 index 0000000..d6fda3b --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_836.java @@ -0,0 +1,39 @@ +package com.hit.basmath.learn.others; + +/** + * 836. Rectangle Overlap + *

+ * A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the coordinates of its top-right corner. + *

+ * Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap. + *

+ * Given two (axis-aligned) rectangles, return whether they overlap. + *

+ * Example 1: + *

+ * Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3] + * Output: true + *

+ * Example 2: + *

+ * Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1] + * Output: false + *

+ * Notes: + *

+ * Both rectangles rec1 and rec2 are lists of 4 integers. + * All coordinates in rectangles will be between -10^9 and 10^9. + */ +public class _836 { + public boolean isRectangleOverlap(int[] rec1, int[] rec2) { + if (rec2[1] >= rec1[3] || rec2[3] <= rec1[1]) { + return false; + } + + if (rec2[0] >= rec1[2] || rec2[2] <= rec1[0]) { + return false; + } + + return true; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_837.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_837.java new file mode 100644 index 0000000..ce16586 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_837.java @@ -0,0 +1,63 @@ +package com.hit.basmath.learn.others; + +/** + * 837. New 21 Game + *

+ * Alice plays the following game, loosely based on the card game "21". + *

+ * Alice starts with 0 points, and draws numbers while she has less than K points. During each draw, she gains an integer number of points randomly from the range [1, W], where W is an integer. Each draw is independent and the outcomes have equal probabilities. + *

+ * Alice stops drawing numbers when she gets K or more points. What is the probability that she has N or less points? + *

+ * Example 1: + *

+ * Input: N = 10, K = 1, W = 10 + * Output: 1.00000 + * Explanation: Alice gets a single card, then stops. + *

+ * Example 2: + *

+ * Input: N = 6, K = 1, W = 10 + * Output: 0.60000 + * Explanation: Alice gets a single card, then stops. + * In 6 out of W = 10 possibilities, she is at or below N = 6 points. + *

+ * Example 3: + *

+ * Input: N = 21, K = 17, W = 10 + * Output: 0.73278 + *

+ * Note: + *

+ * 0 <= K <= N <= 10000 + * 1 <= W <= 10000 + * Answers will be accepted as correct if they are within 10^-5 of the correct answer. + * The judging time limit has been reduced for this question. + */ +public class _837 { + public double new21Game(int N, int K, int W) { + if (K == 0 || K + W <= N) { + return 1; + } + if (N < K) { + return 0; + } + double base = 1.0 / W; + double[] dp = new double[N + 1]; + double sum = 0; + double res = 0; + for (int i = 1; i <= N; ++i) { + dp[i] = sum * base + (i <= W ? base : 0); + if (i < K) { + sum += dp[i]; + } + if (i > W) { + sum -= dp[i - W]; + } + if (i >= K) { + res += dp[i]; + } + } + return res; + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_838.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_838.java new file mode 100644 index 0000000..bb99b95 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_838.java @@ -0,0 +1,62 @@ +package com.hit.basmath.learn.others; + +/** + * 838. Push Dominoes + *

+ * There are N dominoes in a line, and we place each domino vertically upright. + *

+ * In the beginning, we simultaneously push some of the dominoes either to the left or to the right. + *

+ * After each second, each domino that is falling to the left pushes the adjacent domino on the left. + *

+ * Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. + *

+ * When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. + *

+ * For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. + *

+ * Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed. + *

+ * Return a string representing the final state. + *

+ * Example 1: + *

+ * Input: ".L.R...LR..L.." + * Output: "LL.RR.LLRRLL.." + *

+ * Example 2: + *

+ * Input: "RR.L" + * Output: "RR.L" + * Explanation: The first domino expends no additional force on the second domino. + *

+ * Note: + *

+ * 0 <= N <= 10^5 + * String dominoes contains only 'L', 'R' and '.' + */ +public class _838 { + public String pushDominoes(String dominoes) { + char[] a = dominoes.toCharArray(); + int L = -1, R = -1;//positions of last seen L and R + for (int i = 0; i <= dominoes.length(); i++) + if (i == a.length || a[i] == 'R') { + if (R > L)//R..R, turn all to R + while (R < i) + a[R++] = 'R'; + R = i; + } else if (a[i] == 'L') + if (L > R || (R == -1 && L == -1))//L..L, turn all to L + while (++L < i) + a[L] = 'L'; + else { //R...L + L = i; + int lo = R + 1, hi = L - 1; + while (lo < hi) { //one in the middle stays '.' + a[lo++] = 'R'; + a[hi--] = 'L'; + } + } + return new String(a); + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_839.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_839.java new file mode 100644 index 0000000..463a856 --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_839.java @@ -0,0 +1,84 @@ +package com.hit.basmath.learn.others; + +/** + * 839. Similar String Groups + *

+ * Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. + *

+ * For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts". + *

+ * Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group. + *

+ * We are given a list A of strings. Every string in A is an anagram of every other string in A. How many groups are there? + *

+ * Example 1: + *

+ * Input: ["tars","rats","arts","star"] + * Output: 2 + *

+ * Note: + *

+ * A.length <= 2000 + * A[i].length <= 1000 + * A.length * A[i].length <= 20000 + * All words in A consist of lowercase letters only. + * All words in A have the same length and are anagrams of each other. + * The judging time limit has been increased for this question. + */ +public class _839 { + public int numSimilarGroups(String[] A) { + final int n = A.length; + + final UnionFind uf = new UnionFind(n); + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + if (uf.find(i) == uf.find(j)) continue; + + String a = A[i], b = A[j]; + if (isSimilar(a, b)) uf.union(i, j); + } + } + + return uf.groups; + } + + private boolean isSimilar(String a, String b) { + int count = 0; + for (int i = 0; i < a.length(); i++) { + if (a.charAt(i) != b.charAt(i) && ++count > 2) return false; + } + + return true; + } + + private class UnionFind { + int n, groups; + int[] parent; + + UnionFind(int n) { + this.n = n; + + groups = n; + parent = new int[n]; + for (int i = 0; i < n; i++) parent[i] = i; + } + + int find(int x) { + while (x != parent[x]) { + parent[x] = parent[parent[x]]; + x = parent[x]; + } + + return x; + } + + void union(int a, int b) { + int p = find(a), q = find(b); + + if (p != q) { + parent[p] = q; + groups--; + } + } + } +} diff --git a/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_840.java b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_840.java new file mode 100644 index 0000000..323681d --- /dev/null +++ b/codes/java/leetcodes/src/main/java/com/hit/basmath/learn/others/_840.java @@ -0,0 +1,76 @@ +package com.hit.basmath.learn.others; + +/** + * 840. Magic Squares In Grid + *

+ * A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum. + *

+ * Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous). + *

+ * Example 1: + *

+ * Input: [[4,3,8,4], + * [9,5,1,9], + * [2,7,6,2]] + * Output: 1 + * Explanation: + *

+ * The following subgrid is a 3 x 3 magic square: + * 438 + * 951 + * 276 + *

+ * while this one is not: + * 384 + * 519 + * 762 + *

+ * In total, there is only one magic square inside the given grid. + *

+ * Note: + *

+ * 1 <= grid.length <= 10 + * 1 <= grid[0].length <= 10 + * 0 <= grid[i][j] <= 15 + */ +public class _840 { + public int numMagicSquaresInside(int[][] grid) { + //Assuming each row have the same length + if (grid.length < 3 || grid[0].length < 3) return 0; + + int magicBoxCount = 0; + for (int i = 0; i <= (grid.length - 3); i++) { + for (int j = 0; (j <= grid[0].length - 3); j++) { + if (isAMagicBox(grid, i, j)) + magicBoxCount++; + } + } + + return magicBoxCount; + } + + private boolean isAMagicBox(int[][] grid, int x, int y) { + if (grid[x + 1][y + 1] != 5) return false; + + //corner are even + if (grid[x][y] % 2 != 0 || grid[x + 2][y] % 2 != 0 || + grid[x][y + 2] % 2 != 0 || grid[x + 2][y + 2] % 2 != 0) { + return false; + } + + //not-corner are odd + if (grid[x + 1][y] % 2 == 0 || grid[x][y + 1] % 2 == 0 || + grid[x + 1][y + 2] % 2 == 0 || grid[x + 2][y + 1] % 2 == 0) { + return false; + } + + if ((grid[x][y] + grid[x][y + 1] + grid[x][y + 2]) != 15 || //row1 + (grid[x + 2][y] + grid[x + 2][y + 1] + grid[x + 2][y + 2]) != 15 || //row2 + (grid[x][y] + grid[x + 1][y] + grid[x + 2][y]) != 15) //column 1 + { + return false; + } + + return true; + } +}