From 03f9355de0c25f41fa5ed78b81b0fd0ee988a117 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 24 Oct 2017 22:19:39 +0800 Subject: [PATCH 001/220] Add py solution for 215. Kth Largest Element in an Array 215. Kth Largest Element in an Array: https://leetcode.com/problems/kth-largest-element-in-an-array/ --- py/kth-largest-element-in-an-array.py | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 py/kth-largest-element-in-an-array.py diff --git a/py/kth-largest-element-in-an-array.py b/py/kth-largest-element-in-an-array.py new file mode 100644 index 0000000..cc85cfc --- /dev/null +++ b/py/kth-largest-element-in-an-array.py @@ -0,0 +1,35 @@ +import random +class Solution(object): + def findKthLargest(self, nums, k, start=0, end=None): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + l = len(nums) + if end is None: + end = l + + if end == start + 1: + return nums[start] + + pivot = nums[random.randint(start, end - 1)] + i, j, n = start, start, end - 1 + while j <= n: + if nums[j] < pivot: + if i != j: + nums[i], nums[j] = nums[j], nums[i] + i += 1 + j += 1 + elif nums[j] > pivot: + if j != n: + nums[j], nums[n] = nums[n], nums[j] + n -= 1 + else: + j += 1 + if i <= l - k < j: + return nums[-k] + if l - k < i: + return self.findKthLargest(nums, k, start, i) + else: + return self.findKthLargest(nums, k, j, end) From 0224af7414bdfff6b4bd3118ba50cfc08ed60215 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Oct 2017 00:04:19 +0800 Subject: [PATCH 002/220] Add py solution for 282. Expression Add Operators 282. Expression Add Operators: https://leetcode.com/problems/expression-add-operators/ Way too ugly... --- py/expression-add-operators.py | 63 ++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 py/expression-add-operators.py diff --git a/py/expression-add-operators.py b/py/expression-add-operators.py new file mode 100644 index 0000000..c59943d --- /dev/null +++ b/py/expression-add-operators.py @@ -0,0 +1,63 @@ +from collections import defaultdict +class Solution(object): + def dfs_ans(self, ans, depth, lans, ans_list): + if depth == lans: + yield ''.join(ans_list) + else: + if isinstance(ans[depth], set): + for x in ans[depth]: + ans_list.append(x) + for y in self.dfs_ans(ans, depth + 1, lans, ans_list): + yield y + ans_list.pop() + else: + ans_list.append(ans[depth]) + for y in self.dfs_ans(ans, depth + 1, lans, ans_list): + yield y + ans_list.pop() + + + def dfs(self, dp, end, target, depth, cur, ans): + if end == depth and cur == target: + for x in self.dfs_ans(ans, 0, len(ans), []): + yield x + else: + for nd in xrange(depth + 1, end + 1): + for possible_v, possible_set in dp[depth, nd].iteritems(): + if depth > 0: + ans.append('+') + ans.append(possible_set) + for x in self.dfs(dp, end, target, nd, cur + possible_v, ans): + yield x + ans.pop() + if depth > 0: + ans.pop() + for x in self.dfs(dp, end, target, nd, cur - possible_v, ans + ['-', possible_set]): + yield x + + def addOperators(self, num, target): + """ + :type num: str + :type target: int + :rtype: List[str] + """ + dp = defaultdict(lambda:defaultdict(set)) + + # merge phase + lnum = len(num) + for i in xrange(1, lnum + 1): + for j in xrange(i): + if num[j] != '0' or j + 1 == i: + dp[j, i][int(num[j:i])].add(num[j:i]) + + # multiple phase + for l in xrange(2, lnum + 1): + for i in xrange(lnum - l + 1): + for j in xrange(i + 1, i + l): + for a, a_set in dp[i, j].iteritems(): + for b, b_set in dp[j, i + l].iteritems(): + for a_ in a_set: + if '*' not in a_: + for b_ in b_set: + dp[i, i + l][a * b].add(a_ + '*' + b_) + return list(self.dfs(dp, lnum, target, 0, 0, [])) From cb159032856c4409187154cc0ec3d6ffae1fc4db Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Oct 2017 00:42:59 +0800 Subject: [PATCH 003/220] Add py solution for 692. Top K Frequent Words 692. Top K Frequent Words: https://leetcode.com/problems/top-k-frequent-words/ O(nlgk) and O(klgn) approaches --- py/top-k-frequent-words.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 py/top-k-frequent-words.py diff --git a/py/top-k-frequent-words.py b/py/top-k-frequent-words.py new file mode 100644 index 0000000..e5da006 --- /dev/null +++ b/py/top-k-frequent-words.py @@ -0,0 +1,38 @@ +from collections import Counter +import heapq +class Neg(): + def __init__(self, x): + self.x = x + + def __cmp__(self, other): + return -cmp(self.x, other.x) + +class Solution(object): + def topKFrequent_nlogk(self, words, k): + """ + :type words: List[str] + :type k: int + :rtype: List[str] + """ + c = Counter(words) + ary = [Neg((-cnt, w)) for w, cnt in c.iteritems()] + heap = ary[:k] + heapq.heapify(heap) + for i in xrange(k, len(ary)): + heapq.heappush(heap, ary[i]) + heapq.heappop(heap) + heap.sort(key=lambda x:(x.x[0], x.x[1])) + return [x.x[1] for x in heap] + + + def topKFrequent_klogn(self, words, k): + """ + :type words: List[str] + :type k: int + :rtype: List[str] + """ + c = Counter(words) + ary = [(-cnt, w) for w, cnt in c.iteritems()] + return [x[1] for x in heapq.nsmallest(k, ary)] + + topKFrequent = topKFrequent_nlogk From 45e78bd7cbfa93a96255df9b5144ce25a609eb9b Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Sun, 29 Oct 2017 01:17:17 +0800 Subject: [PATCH 004/220] Add py solution for 638. Shopping Offers 638. Shopping Offers: https://leetcode.com/problems/shopping-offers/ --- py/shopping-offers.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 py/shopping-offers.py diff --git a/py/shopping-offers.py b/py/shopping-offers.py new file mode 100644 index 0000000..5c2aa70 --- /dev/null +++ b/py/shopping-offers.py @@ -0,0 +1,43 @@ +from collections import Counter +from operator import mul +class Solution(object): + def shoppingOffers(self, price, special, needs): + """ + :type price: List[int] + :type special: List[List[int]] + :type needs: List[int] + :rtype: int + """ + c = Counter() + c[tuple(needs)] = 0 + + q = [(tuple(needs), 0)] + + min_offer = 0 + for need, depth in q: + if depth < len(special): + sp, p = special[depth][:-1], special[depth][-1] + m = c[need] + max_group = None + q.append((need, depth + 1)) + for nv, sv in zip(need, sp): + if nv < sv: + break + if sv > 0: + if max_group is None or nv / sv < max_group: + max_group = nv / sv + else: + for i in xrange(1, max_group + 1): + s_need = list(need) + orig = 0 + for j, s in enumerate(sp): + s_need[j] -= s * i + orig += price[j] * s * i + used = p * i - orig + if c[tuple(s_need)] > m + used: + c[tuple(s_need)] = m + used + q.append((tuple(s_need), 1)) + min_offer = min(min_offer, m + used) + return sum(map(mul, price, needs)) + min_offer + +print Solution().shoppingOffers([2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1]) From 52d736e154f74342dde91acb069c0ea7cb9068ec Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Sun, 29 Oct 2017 02:25:22 +0800 Subject: [PATCH 005/220] Add py solution for 381. Insert Delete GetRandom O(1) - Duplicates allowed 381. Insert Delete GetRandom O(1) - Duplicates allowed: https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/ getRandom may not be O(1). I'm not sure.. --- ...-delete-getrandom-o1-duplicates-allowed.py | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 py/insert-delete-getrandom-o1-duplicates-allowed.py diff --git a/py/insert-delete-getrandom-o1-duplicates-allowed.py b/py/insert-delete-getrandom-o1-duplicates-allowed.py new file mode 100644 index 0000000..791dc00 --- /dev/null +++ b/py/insert-delete-getrandom-o1-duplicates-allowed.py @@ -0,0 +1,63 @@ +from collections import Counter +import random +class RandomizedCollection(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.counter = Counter() + self.redundant = Counter() + self.array = [] + + + def insert(self, val): + """ + Inserts a value to the collection. Returns true if the collection did not already contain the specified element. + :type val: int + :rtype: bool + """ + self.counter[val] += 1 + if self.redundant[val] == 0: + self.array.append(val) + else: + self.redundant[val] -= 1 + return self.counter[val] == 1 + + def remove(self, val): + """ + Removes a value from the collection. Returns true if the collection contained the specified element. + :type val: int + :rtype: bool + """ + ret = False + if self.counter[val]: + ret = True + self.counter[val] -= 1 + self.redundant[val] += 1 + return ret + + + def getRandom(self): + """ + Get a random element from the collection. + :rtype: int + """ + while True: + idx = random.randint(0, len(self.array) - 1) + v = self.array[idx] + if self.counter[v] and (self.redundant[v] == 0 or random.random() * (self.counter[v] + self.redundant[v]) < self.counter[v]): + break + else: + self.array[idx] = self.array[-1] + self.array.pop() + self.redundant[v] -= 1 + return v + + + +# Your RandomizedCollection object will be instantiated and called as such: +# obj = RandomizedCollection() +# param_1 = obj.insert(val) +# param_2 = obj.remove(val) +# param_3 = obj.getRandom() From 8c71a177c16762ab50dafe2528d24fab4ccf0925 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Sun, 29 Oct 2017 03:10:59 +0800 Subject: [PATCH 006/220] Add py solution for 462. Minimum Moves to Equal Array Elements II 462. Minimum Moves to Equal Array Elements II: https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/ Could be optimized to O(n) by q-select --- py/minimum-moves-to-equal-array-elements-ii.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 py/minimum-moves-to-equal-array-elements-ii.py diff --git a/py/minimum-moves-to-equal-array-elements-ii.py b/py/minimum-moves-to-equal-array-elements-ii.py new file mode 100644 index 0000000..c503012 --- /dev/null +++ b/py/minimum-moves-to-equal-array-elements-ii.py @@ -0,0 +1,9 @@ +class Solution(object): + def minMoves2(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums.sort() + median = nums[len(nums) / 2] + return sum(abs(x - median) for x in nums) From f629b836aad3c06a387416c9a407df722d65d89a Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 14:14:42 +0800 Subject: [PATCH 007/220] Add py solution for 713. Subarray Product Less Than K 713. Subarray Product Less Than K: https://leetcode.com/problems/subarray-product-less-than-k/ --- py/subarray-product-less-than-k.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 py/subarray-product-less-than-k.py diff --git a/py/subarray-product-less-than-k.py b/py/subarray-product-less-than-k.py new file mode 100644 index 0000000..159b168 --- /dev/null +++ b/py/subarray-product-less-than-k.py @@ -0,0 +1,24 @@ +class Solution(object): + def numSubarrayProductLessThanK(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + ans = 0 + subproduct = 1 + if k <= 1: + return 0 + start, end = 0, 0 + while start < len(nums) or end < len(nums): + if subproduct < k: + ans += end - start + if end < len(nums): + subproduct *= nums[end] + end += 1 + else: + break + else: + subproduct /= nums[start] + start += 1 + return ans From 7b179e4a420a3cd7a27f0f438a6eac462048bb93 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 14:44:46 +0800 Subject: [PATCH 008/220] Add py solution for 554. Brick Wall 554. Brick Wall: https://leetcode.com/problems/brick-wall/ Approach1: O(n_brick * log(n_row)) Use heap to find the least length of accumulated row and find how many rows can match such length --- py/brick-wall.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 py/brick-wall.py diff --git a/py/brick-wall.py b/py/brick-wall.py new file mode 100644 index 0000000..a2ad43c --- /dev/null +++ b/py/brick-wall.py @@ -0,0 +1,28 @@ +import heapq +class Solution(object): + def leastBricks(self, wall): + """ + :type wall: List[List[int]] + :rtype: int + """ + n_row = len(wall) + heap = [(wall[i][0], i, 0) for i in xrange(n_row)] + heapq.heapify(heap) + max_noncross = 0 + while True: + l, idx, offset = heapq.heappop(heap) + cur_l = l + if offset == len(wall[idx]) - 1: + break + heapq.heappush(heap, (l + wall[idx][offset + 1], idx, offset + 1)) + cnt = 1 + while True: + ol, oidx, ooffset = heapq.heappop(heap) + if ol == l: + cnt += 1 + heapq.heappush(heap, (ol + wall[oidx][ooffset + 1], oidx, ooffset + 1)) + elif ol > l: + heapq.heappush(heap, (ol, oidx, ooffset)) + break + max_noncross = max(max_noncross, cnt) + return n_row - max_noncross From 5d519c31b17a60441d522ab2a5c17c944c376afd Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 14:55:49 +0800 Subject: [PATCH 009/220] Add py solution for 554. Brick Wall 554. Brick Wall: https://leetcode.com/problems/brick-wall/ Approach2: O(n_brick): Count # of every length can formed by any row --- py/brick-wall.py | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/py/brick-wall.py b/py/brick-wall.py index a2ad43c..df97ef5 100644 --- a/py/brick-wall.py +++ b/py/brick-wall.py @@ -1,28 +1,18 @@ -import heapq +from collections import Counter class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ - n_row = len(wall) - heap = [(wall[i][0], i, 0) for i in xrange(n_row)] - heapq.heapify(heap) - max_noncross = 0 - while True: - l, idx, offset = heapq.heappop(heap) - cur_l = l - if offset == len(wall[idx]) - 1: - break - heapq.heappush(heap, (l + wall[idx][offset + 1], idx, offset + 1)) - cnt = 1 - while True: - ol, oidx, ooffset = heapq.heappop(heap) - if ol == l: - cnt += 1 - heapq.heappush(heap, (ol + wall[oidx][ooffset + 1], oidx, ooffset + 1)) - elif ol > l: - heapq.heappush(heap, (ol, oidx, ooffset)) - break - max_noncross = max(max_noncross, cnt) - return n_row - max_noncross + c = Counter() + wall_width = sum(wall[0]) + max_non_cut = 0 + for row in wall: + subsum = 0 + for n in row: + subsum += n + c[subsum] += 1 + if subsum < wall_width: + max_non_cut = max(c[subsum], max_non_cut) + return len(wall) - max_non_cut From b5c6e37bdcb88545d187ad1e3adbbbe1d466f874 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 15:40:17 +0800 Subject: [PATCH 010/220] Add py solution for 688. Knight Probability in Chessboard 688. Knight Probability in Chessboard: https://leetcode.com/problems/knight-probability-in-chessboard/ --- py/knight-probability-in-chessboard.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 py/knight-probability-in-chessboard.py diff --git a/py/knight-probability-in-chessboard.py b/py/knight-probability-in-chessboard.py new file mode 100644 index 0000000..4f35180 --- /dev/null +++ b/py/knight-probability-in-chessboard.py @@ -0,0 +1,24 @@ +from collections import Counter +from math import log, exp +class Solution(object): + def knightProbability(self, N, K, r, c): + """ + :type N: int + :type K: int + :type r: int + :type c: int + :rtype: float + """ + p = Counter() + p[r, c] += 1 + ds = [(-1, -2), (-2, -1), (1, -2), (2, -1), (1, 2), (2, 1), (-1, 2), (-2, 1)] + for i in xrange(K): + np = Counter() + for (px, py), prev_p in p.iteritems(): + for dx, dy in ds: + nx, ny = px + dx, py + dy + if 0 <= nx < N and 0 <= ny < N: + np[nx, ny] += prev_p + p = np + s = sum(p.values()) + return 0 if s == 0 else exp(log(sum(p.values())) - K * log(8)) From 5daad1d1db64082fb0e5ec11089ee37187ab9f03 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 15:53:51 +0800 Subject: [PATCH 011/220] Add py solution for 343. Integer Break 343. Integer Break: https://leetcode.com/problems/integer-break/ --- py/integer-break.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 py/integer-break.py diff --git a/py/integer-break.py b/py/integer-break.py new file mode 100644 index 0000000..b7e9ab6 --- /dev/null +++ b/py/integer-break.py @@ -0,0 +1,13 @@ +class Solution(object): + def integerBreak(self, n): + """ + :type n: int + :rtype: int + """ + d = {1: 1, 2:2, 3: 3, 4: 4} + d[1] = 1 + if n <= 3: + return n - 1 + for i in xrange(5, n + 1): + d[i] = max(d[a] * d[i - a] for a in xrange(1, i / 2 + 1)) + return d[n] From 47cb213be2071ad77f75d350ead4cfd7c7dc2d62 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 16:29:08 +0800 Subject: [PATCH 012/220] Add py solution for 334. Increasing Triplet Subsequence 334. Increasing Triplet Subsequence: https://leetcode.com/problems/increasing-triplet-subsequence/ --- py/increasing-triplet-subsequence.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 py/increasing-triplet-subsequence.py diff --git a/py/increasing-triplet-subsequence.py b/py/increasing-triplet-subsequence.py new file mode 100644 index 0000000..10752e0 --- /dev/null +++ b/py/increasing-triplet-subsequence.py @@ -0,0 +1,16 @@ +class Solution(object): + def increasingTriplet(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + first, second = None, None + for n in nums: + if first is None or n <= first: + first = n + elif second is None or n <= second: + second = n + else: + return True + return False + From 68b5e3438b771afe4a70019a12fdd6d60a587c7e Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 17:17:05 +0800 Subject: [PATCH 013/220] Add py solution for 717. 1-bit and 2-bit Characters 717. 1-bit and 2-bit Characters: https://leetcode.com/problems/1-bit-and-2-bit-characters/ --- py/1-bit-and-2-bit-characters.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 py/1-bit-and-2-bit-characters.py diff --git a/py/1-bit-and-2-bit-characters.py b/py/1-bit-and-2-bit-characters.py new file mode 100644 index 0000000..da7bb23 --- /dev/null +++ b/py/1-bit-and-2-bit-characters.py @@ -0,0 +1,14 @@ +class Solution(object): + def isOneBitCharacter(self, bits): + """ + :type bits: List[int] + :rtype: bool + """ + s0, s1 = True, False + for i, b in enumerate(bits[:-1]): + if b == 1: + s0, s1 = s1 and bits[i - 1] == 1, s0 + else: + s0, s1 = True, False + return s0 + From 1102db025fd41b91d9cfa1ce93dddd72da47926c Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 17:52:53 +0800 Subject: [PATCH 014/220] Add py solution for 508. Most Frequent Subtree Sum 508. Most Frequent Subtree Sum: https://leetcode.com/problems/most-frequent-subtree-sum/ --- py/most-frequent-subtree-sum.py | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 py/most-frequent-subtree-sum.py diff --git a/py/most-frequent-subtree-sum.py b/py/most-frequent-subtree-sum.py new file mode 100644 index 0000000..25fa3d7 --- /dev/null +++ b/py/most-frequent-subtree-sum.py @@ -0,0 +1,35 @@ +from collections import Counter +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def top_down(self, cur, c): + if cur: + lsum = self.top_down(cur.left, c) + rsum = self.top_down(cur.right, c) + s = lsum + rsum + cur.val + c[s] += 1 + if c[s] > self.freq: + self.freq = c[s] + self.most_freq = [s] + elif c[s] == self.freq: + self.most_freq.append(s) + return s + else: + return 0 + + + def findFrequentTreeSum(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ + c = Counter() + self.most_freq = [] + self.freq = 0 + self.top_down(root, c) + return self.most_freq From 79723a38a1905da020effe0b5b1edf98b9a5351b Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 18:17:00 +0800 Subject: [PATCH 015/220] Add py solution for 600. Non-negative Integers without Consecutive Ones 600. Non-negative Integers without Consecutive Ones: https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/ --- ...ative-integers-without-consecutive-ones.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 py/non-negative-integers-without-consecutive-ones.py diff --git a/py/non-negative-integers-without-consecutive-ones.py b/py/non-negative-integers-without-consecutive-ones.py new file mode 100644 index 0000000..b7e29cf --- /dev/null +++ b/py/non-negative-integers-without-consecutive-ones.py @@ -0,0 +1,25 @@ +class Solution(object): + def findIntegers(self, num): + """ + :type num: int + :rtype: int + """ + for t in xrange(num.bit_length() - 1, 0, -1): + if ((1 << t) & num) and (1 << (t - 1) & num): + flag = True + for i in xrange(t, -1, -1): + if flag: + num |= (1 << i) + else: + num &= ~(1 << i) + flag = not flag + break + + a, b = 1, 1 + ans = 0 + while num > 0: + if num & 1: + ans += a + num >>= 1 + a, b = a + b, a + return ans + 1 From b584731ece48468345be8bdeceb0f1f574d9b443 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 18:27:16 +0800 Subject: [PATCH 016/220] Add py solution for 495. Teemo Attacking 495. Teemo Attacking: https://leetcode.com/problems/teemo-attacking/ --- py/teemo-attacking.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 py/teemo-attacking.py diff --git a/py/teemo-attacking.py b/py/teemo-attacking.py new file mode 100644 index 0000000..851ac7e --- /dev/null +++ b/py/teemo-attacking.py @@ -0,0 +1,15 @@ +class Solution(object): + def findPoisonedDuration(self, timeSeries, duration): + """ + :type timeSeries: List[int] + :type duration: int + :rtype: int + """ + prev_end = None + ans = 0 + for t in timeSeries: + end = t + duration + t = max(prev_end, t) + ans += end - t + prev_end = end + return ans From fe79933c028d55a6ad2d8f203d33c9ca7939afbe Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Oct 2017 23:42:24 +0800 Subject: [PATCH 017/220] Add py solution for 477. Total Hamming Distance 477. Total Hamming Distance: https://leetcode.com/problems/total-hamming-distance/ --- py/total-hamming-distance.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 py/total-hamming-distance.py diff --git a/py/total-hamming-distance.py b/py/total-hamming-distance.py new file mode 100644 index 0000000..5832230 --- /dev/null +++ b/py/total-hamming-distance.py @@ -0,0 +1,17 @@ +from collections import Counter +class Solution(object): + def totalHammingDistance(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + c = Counter() + for n in nums: + for i in xrange(n.bit_length()): + if n & (1 << i): + c[i] += 1 + ans = 0 + for k, v in c.iteritems(): + ans += v * (len(nums) - v) + return ans + From 670df024302a30ccf8be42ec869143e1f3d4457f Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 31 Oct 2017 01:43:03 +0800 Subject: [PATCH 018/220] Add py solution for 382. Linked List Random Node 382. Linked List Random Node: https://leetcode.com/problems/linked-list-random-node/ --- py/linked-list-random-node.py | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 py/linked-list-random-node.py diff --git a/py/linked-list-random-node.py b/py/linked-list-random-node.py new file mode 100644 index 0000000..0ccdac0 --- /dev/null +++ b/py/linked-list-random-node.py @@ -0,0 +1,36 @@ +import random +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + + def __init__(self, head): + """ + @param head The linked list's head. + Note that the head is guaranteed to be not null, so it contains at least one node. + :type head: ListNode + """ + self.head = head + + def getRandom(self): + """ + Returns a random node's value. + :rtype: int + """ + t = self.head + val = None + n = 0 + while t is not None: + n += 1 + if random.random() * n < 1: + val = t.val + t = t.next + return val + + +# Your Solution object will be instantiated and called as such: +# obj = Solution(head) +# param_1 = obj.getRandom() From d692508e9c6fba847f3bb179bbfd3684e6ebcef0 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 31 Oct 2017 01:50:22 +0800 Subject: [PATCH 019/220] Add py solution for 384. Shuffle an Array 384. Shuffle an Array: https://leetcode.com/problems/shuffle-an-array/ --- py/shuffle-an-array.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 py/shuffle-an-array.py diff --git a/py/shuffle-an-array.py b/py/shuffle-an-array.py new file mode 100644 index 0000000..40ba97f --- /dev/null +++ b/py/shuffle-an-array.py @@ -0,0 +1,35 @@ +from random import randint +class Solution(object): + + def __init__(self, nums): + """ + :type nums: List[int] + """ + self.nums = nums + + def reset(self): + """ + Resets the array to its original configuration and return it. + :rtype: List[int] + """ + return self.nums + + def shuffle(self): + """ + Returns a random shuffling of the array. + :rtype: List[int] + """ + out = self.nums[:] + n = len(self.nums) + for i in xrange(n - 1): + r = randint(i, n - 1) + if r != i: + out[r], out[i] = out[i], out[r] + return out + + + +# Your Solution object will be instantiated and called as such: +# obj = Solution(nums) +# param_1 = obj.reset() +# param_2 = obj.shuffle() From 52ca0942faaa52138805f966cb0b242009516a06 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 01:01:03 +0800 Subject: [PATCH 020/220] Add py solution for 322. Coin Change 322. Coin Change: https://leetcode.com/problems/coin-change/ --- py/coin-change.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 py/coin-change.py diff --git a/py/coin-change.py b/py/coin-change.py new file mode 100644 index 0000000..b9214fb --- /dev/null +++ b/py/coin-change.py @@ -0,0 +1,25 @@ +class Solution(object): + def coinChange(self, coins, amount): + """ + :type coins: List[int] + :type amount: int + :rtype: int + """ + min_count = [0] * (amount + 1) + for c in coins: + if c <= amount: + min_count[c] = 1 + for i in xrange(min(coins), amount + 1): + next_min = None + for c in coins: + if i == c or (i > c and min_count[i - c] > 0): + t = min_count[i - c] + 1 + if next_min is None or t < next_min: + next_min = t + if next_min is not None: + min_count[i] = next_min + + if min_count[amount] == 0 and amount > 0: + return -1 + else: + return min_count[amount] From e77957398f78f905c6b8ac881b621c67c1352d0a Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 11:16:55 +0800 Subject: [PATCH 021/220] Add py solution for 494. Target Sum 494. Target Sum: https://leetcode.com/problems/target-sum/ --- py/target-sum.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 py/target-sum.py diff --git a/py/target-sum.py b/py/target-sum.py new file mode 100644 index 0000000..0f53be8 --- /dev/null +++ b/py/target-sum.py @@ -0,0 +1,18 @@ +from collections import Counter +class Solution(object): + def findTargetSumWays(self, nums, S): + """ + :type nums: List[int] + :type S: int + :rtype: int + """ + c = Counter() + c[0] = 1 + for n in nums: + nc = Counter() + for k, v in c.iteritems(): + nc[k + n] += v + nc[k - n] += v + c = nc + return c[S] + From cc9536bf3775f7e7af8fc74cbf810049e5a3fda6 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 11:42:36 +0800 Subject: [PATCH 022/220] Add py solution for 547. Friend Circles 547. Friend Circles: https://leetcode.com/problems/friend-circles/ --- py/friend-circles.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 py/friend-circles.py diff --git a/py/friend-circles.py b/py/friend-circles.py new file mode 100644 index 0000000..1d8d988 --- /dev/null +++ b/py/friend-circles.py @@ -0,0 +1,31 @@ +class Solution(object): + def find_root(self, parent, n): + if parent[n][0] != n: + parent[n][0] = self.find_root(parent, parent[n][0]) + return parent[n][0] + + def link(self, parent, a, b): + if parent[a][1] > parent[b][1]: + parent[b][0] = a + parent[a][1] += parent[b][1] + else: + parent[a][0] = b + parent[b][1] += parent[a][1] + self.groups -= 1 + + def findCircleNum(self, M): + """ + :type M: List[List[int]] + :rtype: int + """ + n = len(M) + parent = [[i, 1] for i in xrange(n)] + self.groups = n + for a in xrange(n): + for b in xrange(i): + if M[a][b]: + ra = self.find_root(parent, a) + rb = self.find_root(parent, b) + if ra != rb: + self.link(parent, ra, rb) + return self.groups From a11ed2f8db4d755764a94f9e71bd28e4e3cf582b Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 12:03:39 +0800 Subject: [PATCH 023/220] Add py solution for 560. Subarray Sum Equals K 560. Subarray Sum Equals K: https://leetcode.com/problems/subarray-sum-equals-k/ --- py/subarray-sum-equals-k.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 py/subarray-sum-equals-k.py diff --git a/py/subarray-sum-equals-k.py b/py/subarray-sum-equals-k.py new file mode 100644 index 0000000..29a4f5f --- /dev/null +++ b/py/subarray-sum-equals-k.py @@ -0,0 +1,19 @@ +from collections import Counter +class Solution(object): + def subarraySum(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + subsum = [0] + for i, n in enumerate(nums): + subsum.append(subsum[-1] + n) + + c = Counter() + ans = 0 + for i, n in enumerate(subsum): + if n - k in c: + ans += c[n - k] + c[n] += 1 + return ans From e3ca94a89e52b9a734009f05e1c88e3de9941587 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 12:57:33 +0800 Subject: [PATCH 024/220] Add py solution for 371. Sum of Two Integers 371. Sum of Two Integers: https://leetcode.com/problems/sum-of-two-integers/ --- py/sum-of-two-integers.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 py/sum-of-two-integers.py diff --git a/py/sum-of-two-integers.py b/py/sum-of-two-integers.py new file mode 100644 index 0000000..f008fa3 --- /dev/null +++ b/py/sum-of-two-integers.py @@ -0,0 +1,18 @@ +class Solution(object): + def getSum(self, a, b): + """ + :type a: int + :type b: int + :rtype: int + """ + if a == 0: + return b + elif a == -b: + return 0 + else: + if a < b: + a, b = b, a + if (a > -b and b < 0) or (b > -a and a < 0): + return -self.getSum((-a & -b) << 1, -a ^ -b) + else: + return self.getSum((a & b) << 1, a ^ b) From d9c9ba576fda54e22c9292ce43f0fb895d8eb371 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 13:53:46 +0800 Subject: [PATCH 025/220] Add py solution for 329. Longest Increasing Path in a Matrix 329. Longest Increasing Path in a Matrix: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ Approach 1: Topological sort and find the maximum chain length --- py/longest-increasing-path-in-a-matrix.py | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 py/longest-increasing-path-in-a-matrix.py diff --git a/py/longest-increasing-path-in-a-matrix.py b/py/longest-increasing-path-in-a-matrix.py new file mode 100644 index 0000000..2d643f3 --- /dev/null +++ b/py/longest-increasing-path-in-a-matrix.py @@ -0,0 +1,39 @@ +from collections import defaultdict, Counter +class Solution(object): + def longestIncreasingPath(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: int + """ + if not matrix: + return 0 + h = len(matrix) + w = len(matrix[0]) + neighbors = defaultdict(list) + in_deg = Counter() + longest_length = Counter() + + ds = [(0, -1), (0, 1), (1, 0), (-1, 0)] + starts = set(xrange(h * w)) + for x, row in enumerate(matrix): + for y, v in enumerate(row): + for dx, dy in ds: + nx, ny = x + dx, y + dy + if 0 <= nx < h and 0 <= ny < w: + if matrix[nx][ny] > v: + neighbors[x * w + y].append(nx * w + ny) + in_deg[nx * w + ny] += 1 + starts.discard(nx * w + ny) + for start in starts: + longest_length[start] = 1 + + q = list(starts) + ans = 1 + for v in q: + for neighbor in neighbors[v]: + longest_length[neighbor] = max(longest_length[neighbor], longest_length[v] + 1) + ans = max(longest_length[neighbor], ans) + in_deg[neighbor] -= 1 + if in_deg[neighbor] == 0: + q.append(neighbor) + return ans From 6b36639cc7ff17f4d74aa0239311867b3937da87 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 14:02:03 +0800 Subject: [PATCH 026/220] Add py solution for 329. Longest Increasing Path in a Matrix 329. Longest Increasing Path in a Matrix: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ Approach 2: Top down search --- py/longest-increasing-path-in-a-matrix.py | 41 +++++++++-------------- 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/py/longest-increasing-path-in-a-matrix.py b/py/longest-increasing-path-in-a-matrix.py index 2d643f3..e159c8a 100644 --- a/py/longest-increasing-path-in-a-matrix.py +++ b/py/longest-increasing-path-in-a-matrix.py @@ -1,5 +1,17 @@ -from collections import defaultdict, Counter +from collections import Counter class Solution(object): + def dfs(self, dp, matrix, x, y, w, h): + v = matrix[x][y] + if dp[x, y] == 0: + dp[x, y] = 1 + max( + 0 if x == 0 or matrix[x - 1][y] <= v else self.dfs(dp, matrix, x - 1, y, w, h), + 0 if y == 0 or matrix[x][y - 1] <= v else self.dfs(dp, matrix, x, y - 1, w, h), + 0 if x == h - 1 or matrix[x + 1][y] <= v else self.dfs(dp, matrix, x + 1, y, w, h), + 0 if y == w - 1 or matrix[x][y + 1] <= v else self.dfs(dp, matrix, x, y + 1, w, h) + ) + + return dp[x, y] + def longestIncreasingPath(self, matrix): """ :type matrix: List[List[int]] @@ -9,31 +21,10 @@ def longestIncreasingPath(self, matrix): return 0 h = len(matrix) w = len(matrix[0]) - neighbors = defaultdict(list) - in_deg = Counter() - longest_length = Counter() - - ds = [(0, -1), (0, 1), (1, 0), (-1, 0)] + ans = 1 starts = set(xrange(h * w)) + dp = Counter() for x, row in enumerate(matrix): for y, v in enumerate(row): - for dx, dy in ds: - nx, ny = x + dx, y + dy - if 0 <= nx < h and 0 <= ny < w: - if matrix[nx][ny] > v: - neighbors[x * w + y].append(nx * w + ny) - in_deg[nx * w + ny] += 1 - starts.discard(nx * w + ny) - for start in starts: - longest_length[start] = 1 - - q = list(starts) - ans = 1 - for v in q: - for neighbor in neighbors[v]: - longest_length[neighbor] = max(longest_length[neighbor], longest_length[v] + 1) - ans = max(longest_length[neighbor], ans) - in_deg[neighbor] -= 1 - if in_deg[neighbor] == 0: - q.append(neighbor) + ans = max(ans, self.dfs(dp, matrix, x, y, w, h)) return ans From 118edbb78d2d56ccc41cb3c65346d4f3d59f5647 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 14:35:59 +0800 Subject: [PATCH 027/220] Add py solution for 380. Insert Delete GetRandom O(1) 380. Insert Delete GetRandom O(1): https://leetcode.com/problems/insert-delete-getrandom-o1/ --- py/insert-delete-getrandom-o1.py | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 py/insert-delete-getrandom-o1.py diff --git a/py/insert-delete-getrandom-o1.py b/py/insert-delete-getrandom-o1.py new file mode 100644 index 0000000..7a3f2fb --- /dev/null +++ b/py/insert-delete-getrandom-o1.py @@ -0,0 +1,49 @@ +class RandomizedSet(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.pos = dict() + self.lst = [] + + def insert(self, val): + """ + Inserts a value to the set. Returns true if the set did not already contain the specified element. + :type val: int + :rtype: bool + """ + if val not in self.pos: + self.pos[val] = len(self.lst) + self.lst.append(val) + return True + return False + + def remove(self, val): + """ + Removes a value from the set. Returns true if the set contained the specified element. + :type val: int + :rtype: bool + """ + if val in self.pos: + idx = self.pos[val] + self.pos[self.lst[-1]] = idx + self.lst[idx] = self.lst[-1] + self.lst.pop() + self.pos.pop(val) + return True + return False + + def getRandom(self): + """ + Get a random element from the set. + :rtype: int + """ + return random.choice(self.lst) + + +# Your RandomizedSet object will be instantiated and called as such: +# obj = RandomizedSet() +# param_1 = obj.insert(val) +# param_2 = obj.remove(val) +# param_3 = obj.getRandom() From 4cd919e5301880895d1c05ac1bb19cee2c2443ec Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 15:54:26 +0800 Subject: [PATCH 028/220] Add py solution for 443. String Compression 443. String Compression: https://leetcode.com/problems/string-compression/ --- py/string-compression.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 py/string-compression.py diff --git a/py/string-compression.py b/py/string-compression.py new file mode 100644 index 0000000..1441deb --- /dev/null +++ b/py/string-compression.py @@ -0,0 +1,31 @@ +class Solution(object): + def compress(self, chars): + """ + :type chars: List[str] + :rtype: int + """ + idx = 0 + prev = None + cnt = 0 + for c in chars: + if c == prev: + cnt += 1 + else: + if prev is not None: + chars[idx] = prev + idx += 1 + if cnt > 1: + for cnt_c in str(cnt): + chars[idx] = cnt_c + idx += 1 + cnt = 1 + prev = c + + if prev is not None: + chars[idx] = prev + idx += 1 + if cnt > 1: + for cnt_c in str(cnt): + chars[idx] = cnt_c + idx += 1 + return idx From 3a235e25ac3f5d76eb4030e01afbe7b716ec6d91 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 16:08:50 +0800 Subject: [PATCH 029/220] Add py solution for 331. Verify Preorder Serialization of a Binary Tree 331. Verify Preorder Serialization of a Binary Tree: https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/ --- ...preorder-serialization-of-a-binary-tree.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 py/verify-preorder-serialization-of-a-binary-tree.py diff --git a/py/verify-preorder-serialization-of-a-binary-tree.py b/py/verify-preorder-serialization-of-a-binary-tree.py new file mode 100644 index 0000000..a676b36 --- /dev/null +++ b/py/verify-preorder-serialization-of-a-binary-tree.py @@ -0,0 +1,20 @@ +class Solution(object): + def isValidSerialization(self, preorder): + """ + :type preorder: str + :rtype: bool + """ + def get_tree(nodes, offset): + if nodes[offset] == '#': + return offset + 1 + else: + left = get_tree(nodes, offset + 1) + right = get_tree(nodes, left) + return right + + nodes = preorder.split(',') + try: + ret = get_tree(nodes, 0) + return ret == len(nodes) + except IndexError: + return False From 374dc84359bb41bbc94116b3a7662255fa5d147a Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 16:19:09 +0800 Subject: [PATCH 030/220] Add py solution for 372. Super Pow 372. Super Pow: https://leetcode.com/problems/super-pow/ --- py/super-pow.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 py/super-pow.py diff --git a/py/super-pow.py b/py/super-pow.py new file mode 100644 index 0000000..abf614b --- /dev/null +++ b/py/super-pow.py @@ -0,0 +1,15 @@ +class Solution(object): + def superPow(self, a, b): + """ + :type a: int + :type b: List[int] + :rtype: int + """ + MODULI = 1337 + if a == 0: + return 0 + ans = 1 + for n in b: + ans = pow(ans, 10, MODULI) + ans = (ans * pow(a, n, MODULI)) % MODULI + return ans From d5f4a57d3be9f27d80ca037aa7ce6d4576852cfb Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 16:53:40 +0800 Subject: [PATCH 031/220] Add py solution for 373. Find K Pairs with Smallest Sums 373. Find K Pairs with Smallest Sums: https://leetcode.com/problems/find-k-pairs-with-smallest-sums/ --- py/find-k-pairs-with-smallest-sums.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 py/find-k-pairs-with-smallest-sums.py diff --git a/py/find-k-pairs-with-smallest-sums.py b/py/find-k-pairs-with-smallest-sums.py new file mode 100644 index 0000000..7c6edb9 --- /dev/null +++ b/py/find-k-pairs-with-smallest-sums.py @@ -0,0 +1,27 @@ +import heapq +class Solution(object): + def kSmallestPairs(self, nums1, nums2, k): + """ + :type nums1: List[int] + :type nums2: List[int] + :type k: int + :rtype: List[List[int]] + """ + l1, l2 = len(nums1), len(nums2) + if l1 * l2 <= k: + return sorted([[n1, n2] for n1 in nums1 for n2 in nums2], key=lambda x:x[0] + x[1]) + swapped = False + heap = [] + for i in xrange(min(l1, k)): + heap.append([nums1[i] + nums2[0], [i, 0]]) + ans = [] + heapq.heapify(heap) + while len(ans) < k: + s, idx = heapq.heappop(heap) + idx1, idx2 = idx + ans.append([nums1[idx1], nums2[idx2]]) + if idx2 + 1 < l2: + idx2 += 1 + s = nums1[idx1] + nums2[idx2] + heapq.heappush(heap, [s, [idx1, idx2]]) + return ans From 229cd1c8dec92010074bad6c6081142f3e551026 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 18:03:50 +0800 Subject: [PATCH 032/220] Add py solution for 375. Guess Number Higher or Lower II 375. Guess Number Higher or Lower II: https://leetcode.com/problems/guess-number-higher-or-lower-ii/ --- py/guess-number-higher-or-lower-ii.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 py/guess-number-higher-or-lower-ii.py diff --git a/py/guess-number-higher-or-lower-ii.py b/py/guess-number-higher-or-lower-ii.py new file mode 100644 index 0000000..8666c53 --- /dev/null +++ b/py/guess-number-higher-or-lower-ii.py @@ -0,0 +1,14 @@ +class Solution(object): + def getMoneyAmount(self, n, table=dict()): + """ + :type n: int + :rtype: int + """ + def dp(L, U): + if (L, U) not in table: + if L + 1 >= U: + table[L, U] = 0 + else: + table[L, U] = min(j + max(dp(L, j), dp(j + 1, U)) for j in xrange(L, U)) + return table[L, U] + return dp(1, n + 1) From 884ae74bb75e5a0c60da74791a2e6fad9e4b83e5 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 1 Nov 2017 23:47:42 +0800 Subject: [PATCH 033/220] Add py solution for 436. Find Right Interval 436. Find Right Interval: https://leetcode.com/problems/find-right-interval/ --- py/find-right-interval.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 py/find-right-interval.py diff --git a/py/find-right-interval.py b/py/find-right-interval.py new file mode 100644 index 0000000..1f94748 --- /dev/null +++ b/py/find-right-interval.py @@ -0,0 +1,29 @@ +from operator import itemgetter +# Definition for an interval. +# class Interval(object): +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class Solution(object): + def findRightInterval(self, intervals): + """ + :type intervals: List[Interval] + :rtype: List[int] + """ + sorted_itv = map(itemgetter(1, 2), sorted((x.start, i, x) for i, x in enumerate(intervals))) + size = len(intervals) + ans = [] + for itv in intervals: + L, U = -1, size + while L + 1 < U: + mid = (L + U) / 2 + if sorted_itv[mid][1].start >= itv.end: + U = mid + else: + L = mid + if U == size: + ans.append(-1) + else: + ans.append(sorted_itv[U][0]) + return ans From 119196cc7d3932c09d5125d1d2f02fd0e6964b43 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Nov 2017 12:38:17 +0800 Subject: [PATCH 034/220] Add py solution for 525. Contiguous Array 525. Contiguous Array: https://leetcode.com/problems/contiguous-array/ --- py/contiguous-array.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 py/contiguous-array.py diff --git a/py/contiguous-array.py b/py/contiguous-array.py new file mode 100644 index 0000000..b4b108b --- /dev/null +++ b/py/contiguous-array.py @@ -0,0 +1,16 @@ +class Solution(object): + def findMaxLength(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + pos = {0: -1} + v = 0 + ans = 0 + for i, n in enumerate(nums): + v += n * 2 - 1 + if v in pos: + ans = max(ans, i - pos[v]) + else: + pos[v] = i + return ans From f6b0fbc208012610e7658c02318226d0085ed7a0 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Nov 2017 12:52:45 +0800 Subject: [PATCH 035/220] Add py solution for 593. Valid Square 593. Valid Square: https://leetcode.com/problems/valid-square/ --- py/valid-square.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 py/valid-square.py diff --git a/py/valid-square.py b/py/valid-square.py new file mode 100644 index 0000000..2c39341 --- /dev/null +++ b/py/valid-square.py @@ -0,0 +1,23 @@ +from operator import itemgetter +class Solution(object): + def validSquare(self, p1, p2, p3, p4): + """ + :type p1: List[int] + :type p2: List[int] + :type p3: List[int] + :type p4: List[int] + :rtype: bool + """ + mid = [sum(map(itemgetter(0), [p1, p2, p3, p4])), sum(map(itemgetter(1), [p1, p2, p3, p4]))] + v1 = [p1[0] * 4 - mid[0], p1[1] * 4 - mid[1]] + for p in [p2, p3, p4]: + if p1 == p: + return False + v = [p[0] * 4 - mid[0], p[1] * 4 - mid[1]] + # perpendicular or parallel + if v[0] * v1[0] + v[1] * v1[1] != 0 and v[0] * v1[1] != v[1] * v1[0]: + return False + # same length + if v[0] * v[0] + v[1] * v[1] != v1[0] * v1[0] + v1[1] * v1[1]: + return False + return True From 3fdd2de650c24933ae32eb07b85ede34165702fc Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Nov 2017 13:09:46 +0800 Subject: [PATCH 036/220] Add py solution for 718. Maximum Length of Repeated Subarray 718. Maximum Length of Repeated Subarray: https://leetcode.com/problems/maximum-length-of-repeated-subarray/ --- py/maximum-length-of-repeated-subarray.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 py/maximum-length-of-repeated-subarray.py diff --git a/py/maximum-length-of-repeated-subarray.py b/py/maximum-length-of-repeated-subarray.py new file mode 100644 index 0000000..324ec8d --- /dev/null +++ b/py/maximum-length-of-repeated-subarray.py @@ -0,0 +1,21 @@ +class Solution(object): + def findLength(self, A, B): + """ + :type A: List[int] + :type B: List[int] + :rtype: int + """ + lA, lB = len(A), len(B) + if lA > lB: + lA, lB = lB, lA + A, B = B, A + ans = 0 + prev = [0] * (lA + 1) + for b in B: + ary = [0] * (lA + 1) + for j, a in enumerate(A, 1): + if a == b: + ary[j] = prev[j - 1] + 1 + ans = max(ans, ary[j]) + prev = ary + return ans From 00f9a05f651c4c51c8c2a3c359f6eecc3faca699 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Nov 2017 13:27:26 +0800 Subject: [PATCH 037/220] Add py solution for 474. Ones and Zeroes 474. Ones and Zeroes: https://leetcode.com/problems/ones-and-zeroes/ --- py/ones-and-zeroes.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 py/ones-and-zeroes.py diff --git a/py/ones-and-zeroes.py b/py/ones-and-zeroes.py new file mode 100644 index 0000000..8a6499c --- /dev/null +++ b/py/ones-and-zeroes.py @@ -0,0 +1,23 @@ +from collections import Counter +class Solution(object): + def findMaxForm(self, strs, m, n): + """ + :type strs: List[str] + :type m: int + :type n: int + :rtype: int + """ + str_counter = [] + for s in strs: + c0 = s.count('0') + str_counter.append((c0, len(s) - c0)) + table = Counter() + table[m, n] = 0 + ans = 0 + for c0, c1 in str_counter: + for (remm, remn), cnt in table.items(): + if c0 <= remm and c1 <= remn: + nxtm, nxtn = remm - c0, remn - c1 + table[nxtm, nxtn] = max(table[nxtm, nxtn], cnt + 1) + ans = max(table[nxtm, nxtn], ans) + return ans From bb60309dc207f388c3f84837041d1f0115521049 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Nov 2017 14:13:33 +0800 Subject: [PATCH 038/220] Add py solution for 491. Increasing Subsequences 491. Increasing Subsequences: https://leetcode.com/problems/increasing-subsequences/ --- py/increasing-subsequences.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 py/increasing-subsequences.py diff --git a/py/increasing-subsequences.py b/py/increasing-subsequences.py new file mode 100644 index 0000000..e360614 --- /dev/null +++ b/py/increasing-subsequences.py @@ -0,0 +1,20 @@ +class Solution(object): + def findSubsequences(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + lnums = len(nums) + def dfs(idx, cur): + if idx == lnums: + if len(cur) > 1: + yield tuple(cur) + else: + for x in dfs(idx + 1, cur): + yield x + if not cur or nums[idx] >= cur[-1]: + cur.append(nums[idx]) + for x in dfs(idx + 1, cur): + yield x + cur.pop() + return map(list, set(dfs(0, []))) From 77cb10ac2d524c43f43387d6c62f757c3e37fbbe Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Nov 2017 14:29:28 +0800 Subject: [PATCH 039/220] Add py solution for 670. Maximum Swap 670. Maximum Swap: https://leetcode.com/problems/maximum-swap/ --- py/maximum-swap.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 py/maximum-swap.py diff --git a/py/maximum-swap.py b/py/maximum-swap.py new file mode 100644 index 0000000..b06f3bf --- /dev/null +++ b/py/maximum-swap.py @@ -0,0 +1,19 @@ +class Solution(object): + def maximumSwap(self, num): + """ + :type num: int + :rtype: int + """ + counter = [0] * 10 + snum = str(num) + lnum = len(snum) + for d in map(int, snum): + counter[d] += 1 + for i, d in enumerate(map(int, snum)): + for di in xrange(9, d, -1): + if counter[di] > 0: + for j in xrange(lnum - 1, i, -1): + if int(snum[j]) == di: + return int(snum[:i] + snum[j] + snum[i + 1:j] + snum[i] + snum[j + 1:]) + counter[d] -= 1 + return num From 80ee01e15ec62b4286b98ecc85c13c398154d7ac Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Nov 2017 14:58:02 +0800 Subject: [PATCH 040/220] Add py solution for 684. Redundant Connection 684. Redundant Connection: https://leetcode.com/problems/redundant-connection/ --- py/redundant-connection.py | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 py/redundant-connection.py diff --git a/py/redundant-connection.py b/py/redundant-connection.py new file mode 100644 index 0000000..ab5fad8 --- /dev/null +++ b/py/redundant-connection.py @@ -0,0 +1,39 @@ +from collections import defaultdict +class Solution(object): + def findRedundantConnection(self, edges): + """ + :type edges: List[List[int]] + :rtype: List[int] + """ + visited = set() + parent = dict() + neighbors = defaultdict(list) + edge_idx = {tuple(sorted(e)): i for i, e in enumerate(edges)} + def cycle_edge(v1, v2): + e = tuple(sorted([v1, v2])) + max_idx, ans = edge_idx[e], e + v = v1 + while v != v2: + e = tuple(sorted([v, parent[v]])) + if edge_idx[e] > max_idx: + max_idx = edge_idx[e] + ans = e + v = parent[v] + return list(ans) + + def dfs(cur): + visited.add(cur) + for neighbor in neighbors[cur]: + if neighbor != parent[cur]: + if neighbor in visited: + yield cycle_edge(cur, neighbor) + else: + parent[neighbor] = cur + for x in dfs(neighbor): + yield x + + for v1, v2 in edges: + neighbors[v1].append(v2) + neighbors[v2].append(v1) + parent[v1] = -1 + return next(dfs(v1)) From 89612a126b7df58022554df439bef2988e504643 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Nov 2017 15:42:21 +0800 Subject: [PATCH 041/220] Add py solution for 450. Delete Node in a BST 450. Delete Node in a BST: https://leetcode.com/problems/delete-node-in-a-bst/ --- py/delete-node-in-a-bst.py | 59 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 py/delete-node-in-a-bst.py diff --git a/py/delete-node-in-a-bst.py b/py/delete-node-in-a-bst.py new file mode 100644 index 0000000..8345864 --- /dev/null +++ b/py/delete-node-in-a-bst.py @@ -0,0 +1,59 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def deleteNode(self, root, key): + """ + :type root: TreeNode + :type key: int + :rtype: TreeNode + """ + def remove(node, parent): + ret = root + if node.left is None and node.right is None: + if parent is None: + ret = None + else: + if parent.val > node.val: + parent.left = None + else: + parent.right = None + elif node.left is not None and node.right is not None: + p, to_remove = node, node.right + while to_remove.left is not None: + p, to_remove = to_remove, to_remove.left + node.val = to_remove.val + ret = remove(to_remove, p) + else: + if node.left is not None: + up = node.left + else: + up = node.right + if parent is None: + ret = up + else: + if parent.val > node.val: + parent.left = up + else: + parent.right = up + return ret + + def dfs(cur, parent): + if cur: + if cur.val == key: + return remove(cur, parent) + elif cur.val < key: + return dfs(cur.right, cur) + else: + return dfs(cur.left, cur) + return None + + ret = dfs(root, None) + if root is None or (ret is None and root.val == key): + return None + else: + return ret or root From 385e7194e8cf7db736001e50023cc13fbba27366 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Nov 2017 18:33:23 +0800 Subject: [PATCH 042/220] Add py solution for 672. Bulb Switcher II 672. Bulb Switcher II: https://leetcode.com/problems/bulb-switcher-ii/ --- py/bulb-switcher-ii.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 py/bulb-switcher-ii.py diff --git a/py/bulb-switcher-ii.py b/py/bulb-switcher-ii.py new file mode 100644 index 0000000..de624b1 --- /dev/null +++ b/py/bulb-switcher-ii.py @@ -0,0 +1,28 @@ +from itertools import combinations, cycle, islice +class Solution(object): + def flipLights(self, n, m): + """ + :type n: int + :type m: int + :rtype: int + """ + if m > 4: + return self.flipLights(n, 4 - m % 2) + if n > 6: + return self.flipLights(6, m) + + ans = set() + for i in xrange(m % 2, m + 1, 2): + for comb in combinations(xrange(4), i): + orig = [True] * n + for flip in comb: + if flip == 0: + orig = [not x for x in orig] + elif flip == 1: + orig = [not x if i % 2 == 0 else x for i, x in enumerate(orig)] + elif flip == 2: + orig = [not x if i % 2 == 1 else x for i, x in enumerate(orig)] + elif flip == 3: + orig = [not x if i % 3 == 0 else x for i, x in enumerate(orig)] + ans.add(tuple(orig)) + return len(ans) From 07fdaf648ac290438c91413a69fc77235bf691de Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Nov 2017 18:56:24 +0800 Subject: [PATCH 043/220] Add py solution for 486. Predict the Winner 486. Predict the Winner: https://leetcode.com/problems/predict-the-winner/ --- py/predict-the-winner.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 py/predict-the-winner.py diff --git a/py/predict-the-winner.py b/py/predict-the-winner.py new file mode 100644 index 0000000..49e357f --- /dev/null +++ b/py/predict-the-winner.py @@ -0,0 +1,15 @@ +class Solution(object): + def PredictTheWinner(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + dp = dict() + def top_down(start, end): + if start == end: + dp[start, end] = 0 + elif (start, end) not in dp: + dp[start, end] = max(nums[start] - top_down(start + 1, end), nums[end - 1] - top_down(start, end - 1)) + return dp[start, end] + + return top_down(0, len(nums)) >= 0 From d76809021c99f841cd8d123058d307404b7c025c Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 13:30:47 +0800 Subject: [PATCH 044/220] Add py solution for 659. Split Array into Consecutive Subsequences 659. Split Array into Consecutive Subsequences: https://leetcode.com/problems/split-array-into-consecutive-subsequences/ --- ...lit-array-into-consecutive-subsequences.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 py/split-array-into-consecutive-subsequences.py diff --git a/py/split-array-into-consecutive-subsequences.py b/py/split-array-into-consecutive-subsequences.py new file mode 100644 index 0000000..b79bda1 --- /dev/null +++ b/py/split-array-into-consecutive-subsequences.py @@ -0,0 +1,27 @@ +from itertools import groupby +class Solution(object): + def isPossible(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + prev = None + not_full_1, not_full_2, attach = 0, 0, 0 + for n, items in groupby(nums): + cnt = len(list(items)) + if prev is None: + not_full_1 = cnt + elif prev + 1 == n: + if not_full_1 + not_full_2 > cnt: + return False + else: + cnt -= not_full_1 + not_full_2 + attach = min(attach, cnt) + cnt -= attach + not_full_1, not_full_2, attach = cnt, not_full_1, not_full_2 + attach + else: + if not_full_1 + not_full_2 > 0: + return False + not_full_1, not_full_2, attach = cnt, 0, 0 + prev = n + return not_full_1 + not_full_2 == 0 From 5898822218500487419256676ac57c70a7d40367 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 13:54:50 +0800 Subject: [PATCH 045/220] Add py solution for 650. 2 Keys Keyboard 650. 2 Keys Keyboard: https://leetcode.com/problems/2-keys-keyboard/ --- py/2-keys-keyboard.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 py/2-keys-keyboard.py diff --git a/py/2-keys-keyboard.py b/py/2-keys-keyboard.py new file mode 100644 index 0000000..00a371b --- /dev/null +++ b/py/2-keys-keyboard.py @@ -0,0 +1,12 @@ +class Solution(object): + def minSteps(self, n): + """ + :type n: int + :rtype: int + """ + ans = [n] * (n + 1) + ans[1] = 0 + for i in xrange(1, n + 1): + for j in xrange(2, n / i + 1): + ans[j * i] = min(ans[i] + j, ans[j * i]) + return ans[n] From e42718a59d9c0bffed524f5764ee119cb616085e Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 14:13:40 +0800 Subject: [PATCH 046/220] Add py solution for 721. Accounts Merge 721. Accounts Merge: https://leetcode.com/problems/accounts-merge/ --- py/accounts-merge.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 py/accounts-merge.py diff --git a/py/accounts-merge.py b/py/accounts-merge.py new file mode 100644 index 0000000..38bfb3c --- /dev/null +++ b/py/accounts-merge.py @@ -0,0 +1,33 @@ +from collections import defaultdict +class Solution(object): + def accountsMerge(self, accounts): + """ + :type accounts: List[List[str]] + :rtype: List[List[str]] + """ + parent = dict() + def find_root(a): + if parent[a] != a: + parent[a] = find_root(parent[a]) + return parent[a] + + def link(ra, rb): + parent[ra] = rb + + for acct in accounts: + name = acct[0] + for email in acct[1:]: + parent.setdefault((email, name), (email, name)) + for email in acct[2:]: + ra, rb = find_root((email, name)), find_root((acct[1], name)) + if ra != rb: + link(ra, rb) + ans_mapping = defaultdict(list) + for email, name in parent: + ans_mapping[find_root((email, name))].append(email) + ans = [] + for (email, name), l in ans_mapping.iteritems(): + acct = [name] + sorted(l) + ans.append(acct) + + return ans From dbaccbddfe36c32444c61df5ac6ffd238d3d022b Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 14:21:43 +0800 Subject: [PATCH 047/220] Add py solution for 720. Longest Word in Dictionary 720. Longest Word in Dictionary: https://leetcode.com/problems/longest-word-in-dictionary/ --- py/longest-word-in-dictionary.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 py/longest-word-in-dictionary.py diff --git a/py/longest-word-in-dictionary.py b/py/longest-word-in-dictionary.py new file mode 100644 index 0000000..564e773 --- /dev/null +++ b/py/longest-word-in-dictionary.py @@ -0,0 +1,15 @@ +class Solution(object): + def longestWord(self, words): + """ + :type words: List[str] + :rtype: str + """ + words = sorted(words, key=lambda w:(len(w), w)) + prefix_dict = set() + max_word = '' + for w in words: + if len(w) == 1 or w[:-1] in prefix_dict: + prefix_dict.add(w) + if len(w) > len(max_word) or w < max_word: + max_word = w + return max_word From 45132f541d9d72ab02a94dfbcdfe06c7736aac3e Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 14:37:09 +0800 Subject: [PATCH 048/220] Add py solution for 669. Trim a Binary Search Tree 669. Trim a Binary Search Tree: https://leetcode.com/problems/trim-a-binary-search-tree/ --- py/trim-a-binary-search-tree.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 py/trim-a-binary-search-tree.py diff --git a/py/trim-a-binary-search-tree.py b/py/trim-a-binary-search-tree.py new file mode 100644 index 0000000..6836bd9 --- /dev/null +++ b/py/trim-a-binary-search-tree.py @@ -0,0 +1,24 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def trimBST(self, root, L, R): + """ + :type root: TreeNode + :type L: int + :type R: int + :rtype: TreeNode + """ + if not root: + return root + if root.val > R: + return self.trimBST(root.left, L, R) + if root.val < L: + return self.trimBST(root.right, L, R) + root.left = self.trimBST(root.left, L, R) + root.right = self.trimBST(root.right, L, R) + return root From dfdfe3d713fa55825f3ec4b3a9f19b923963e558 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 15:11:44 +0800 Subject: [PATCH 049/220] Add py solution for 526. Beautiful Arrangement 526. Beautiful Arrangement: https://leetcode.com/problems/beautiful-arrangement/ --- py/beautiful-arrangement.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 py/beautiful-arrangement.py diff --git a/py/beautiful-arrangement.py b/py/beautiful-arrangement.py new file mode 100644 index 0000000..9997120 --- /dev/null +++ b/py/beautiful-arrangement.py @@ -0,0 +1,22 @@ +class Solution(object): + def countArrangement(self, N): + """ + :type N: int + :rtype: int + """ + table = dict() + def dfs(cur, s): + fs = frozenset(s) + if (cur, fs) not in table: + if not s: + table[cur, fs] = 1 + else: + ans = 0 + for n in s: + if n % cur == 0 or cur % n == 0: + s.remove(n) + ans += dfs(cur + 1, s) + s.add(n) + table[cur, fs] = ans + return table[cur, fs] + return dfs(1, set(xrange(1, N + 1))) From a097bbd8fdc94d19f37077d65b619ffa74d50bcc Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 15:26:08 +0800 Subject: [PATCH 050/220] Add py solution for 677. Map Sum Pairs 677. Map Sum Pairs: https://leetcode.com/problems/map-sum-pairs/ --- py/map-sum-pairs.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 py/map-sum-pairs.py diff --git a/py/map-sum-pairs.py b/py/map-sum-pairs.py new file mode 100644 index 0000000..0c5b689 --- /dev/null +++ b/py/map-sum-pairs.py @@ -0,0 +1,45 @@ +from collections import defaultdict +class Node(object): + def __init__(self): + self.children = defaultdict(Node) + self.val = 0 + +class MapSum(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.appeared = dict() + self.root = Node() + + + def insert(self, key, val): + """ + :type key: str + :type val: int + :rtype: void + """ + diff = val - self.appeared.get(key, 0) + cur = self.root + for c in key: + node = cur.children[c] + node.val += diff + cur = node + self.appeared[key] = val + + def sum(self, prefix): + """ + :type prefix: str + :rtype: int + """ + cur = self.root + for c in prefix: + cur = cur.children[c] + return cur.val + + +# Your MapSum object will be instantiated and called as such: +# obj = MapSum() +# obj.insert(key,val) +# param_2 = obj.sum(prefix) From 37b175b6a6ac3f0fd7fdaa5c2ed6435c159a29c2 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 16:12:34 +0800 Subject: [PATCH 051/220] Add py solution for 553. Optimal Division 553. Optimal Division: https://leetcode.com/problems/optimal-division/ Approach1 Bottom-up DP --- py/optimal-division.py | 45 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 py/optimal-division.py diff --git a/py/optimal-division.py b/py/optimal-division.py new file mode 100644 index 0000000..e48bcaf --- /dev/null +++ b/py/optimal-division.py @@ -0,0 +1,45 @@ +from fractions import Fraction +class Solution(object): + def optimalDivision(self, nums): + """ + :type nums: List[int] + :rtype: str + """ + min_result, max_result = dict(), dict() + min_offset, max_offset = dict(), dict() + lnums = len(nums) + def print_ans(start, end, need_max=True): + if start + 1 == end: + return str(nums[start]) + + if need_max: + cut = max_offset[start, end] + else: + cut = min_offset[start, end] + ans = print_ans(start, cut, need_max) + "/" + if end - cut > 1: + ans += "(" + ans += print_ans(cut, end, not need_max) + if end - cut > 1: + ans += ")" + return ans + + for i, n in enumerate(nums): + min_result[i, i + 1] = max_result[i, i + 1] = Fraction(n) + + for l in xrange(2, lnums + 1): + for i in xrange(lnums - l + 1): + m, M = None, None + mj, Mj = None, None + for j in xrange(1, l): + tm = min_result[i, i + j] / max_result[i + j, i + l] + tM = max_result[i, i + j] / min_result[i + j, i + l] + if m is None or m > tm: + m, mj = tm, i + j + if M is None or M < tM: + M, Mj = tM, i + j + min_result[i, i + l] = m + max_result[i, i + l] = M + min_offset[i, i + l] = mj + max_offset[i, i + l] = Mj + return print_ans(0, lnums) From 75bafd44ebcd9bd0413dc1fea67c3815c58071d3 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 16:38:33 +0800 Subject: [PATCH 052/220] Add py solution for 553. Optimal Division 553. Optimal Division: https://leetcode.com/problems/optimal-division/ Approach2 Top-down DP, still slow --- py/optimal-division.py | 55 +++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/py/optimal-division.py b/py/optimal-division.py index e48bcaf..5bc44c3 100644 --- a/py/optimal-division.py +++ b/py/optimal-division.py @@ -1,4 +1,3 @@ -from fractions import Fraction class Solution(object): def optimalDivision(self, nums): """ @@ -6,16 +5,40 @@ def optimalDivision(self, nums): :rtype: str """ min_result, max_result = dict(), dict() - min_offset, max_offset = dict(), dict() lnums = len(nums) - def print_ans(start, end, need_max=True): + + def find_cut(start, end, need_max): if start + 1 == end: - return str(nums[start]) + return 0, (nums[start], 1) + if need_max and (start, end) in max_result: + return max_result[start, end] + if not need_max and (start, end) in min_result: + return min_result[start, end] if need_max: - cut = max_offset[start, end] + M, Mcut = None, None + for cut in xrange(start + 1, end): + c1, v1 = find_cut(start, cut, True) + c2, v2 = find_cut(cut, end, False) + if M is None or v1[0] * v2[1] * M[1] > M[0] * v1[1] * v2[0]: + M, Mcut = (v1[0] * v2[1], v1[1] * v2[0]), cut + max_result[start, end] = Mcut, M + return max_result[start, end] else: - cut = min_offset[start, end] + m, mcut = None, None + for cut in xrange(start + 1, end): + c1, v1 = find_cut(start, cut, False) + c2, v2 = find_cut(cut, end, True) + if m is None or v1[0] * v2[1] * m[1] < m[0] * v1[1] * v2[0]: + m, mcut = (v1[0] * v2[1], v1[1] * v2[0]), cut + min_result[start, end] = mcut, m + return min_result[start, end] + + def print_ans(start, end, need_max): + if start + 1 == end: + return str(nums[start]) + + cut, val = find_cut(start, end, need_max) ans = print_ans(start, cut, need_max) + "/" if end - cut > 1: ans += "(" @@ -24,22 +47,4 @@ def print_ans(start, end, need_max=True): ans += ")" return ans - for i, n in enumerate(nums): - min_result[i, i + 1] = max_result[i, i + 1] = Fraction(n) - - for l in xrange(2, lnums + 1): - for i in xrange(lnums - l + 1): - m, M = None, None - mj, Mj = None, None - for j in xrange(1, l): - tm = min_result[i, i + j] / max_result[i + j, i + l] - tM = max_result[i, i + j] / min_result[i + j, i + l] - if m is None or m > tm: - m, mj = tm, i + j - if M is None or M < tM: - M, Mj = tM, i + j - min_result[i, i + l] = m - max_result[i, i + l] = M - min_offset[i, i + l] = mj - max_offset[i, i + l] = Mj - return print_ans(0, lnums) + return print_ans(0, lnums, True) From fb490678db67fa360ea9e242d04de573050056ae Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 16:51:05 +0800 Subject: [PATCH 053/220] Add py solution for 609. Find Duplicate File in System 609. Find Duplicate File in System: https://leetcode.com/problems/find-duplicate-file-in-system/ --- py/find-duplicate-file-in-system.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 py/find-duplicate-file-in-system.py diff --git a/py/find-duplicate-file-in-system.py b/py/find-duplicate-file-in-system.py new file mode 100644 index 0000000..9f742f1 --- /dev/null +++ b/py/find-duplicate-file-in-system.py @@ -0,0 +1,15 @@ +from collections import defaultdict +class Solution(object): + def findDuplicate(self, paths): + """ + :type paths: List[str] + :rtype: List[List[str]] + """ + content_mapping = defaultdict(list) + for s in paths: + sp = s.split() + dirpath = sp[0] + for name_content in sp[1:]: + name, content = name_content.split('(') + content_mapping[content].append(dirpath + '/' + name) + return [x for x in content_mapping.values() if len(x) > 1] From 5c3cdc7a23fc1b0733b8b8bb9266c6d8c419dcd4 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 17:25:16 +0800 Subject: [PATCH 054/220] Add py solution for 712. Minimum ASCII Delete Sum for Two Strings 712. Minimum ASCII Delete Sum for Two Strings: https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/ --- ...inimum-ascii-delete-sum-for-two-strings.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 py/minimum-ascii-delete-sum-for-two-strings.py diff --git a/py/minimum-ascii-delete-sum-for-two-strings.py b/py/minimum-ascii-delete-sum-for-two-strings.py new file mode 100644 index 0000000..20ea7ea --- /dev/null +++ b/py/minimum-ascii-delete-sum-for-two-strings.py @@ -0,0 +1,22 @@ +class Solution(object): + def minimumDeleteSum(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: int + """ + prev = [0] + for c in s2: + prev.append(prev[-1] + ord(c)) + for i1, c1 in enumerate(s1, 1): + nxtRow = [0] * (len(s2) + 1) + o1 = ord(c1) + nxtRow[0] = o1 + prev[0] + for i2, c2 in enumerate(s2, 1): + if c1 == c2: + nxtRow[i2] = prev[i2 - 1] + else: + o2 = ord(c2) + nxtRow[i2] = min(prev[i2] + o1, nxtRow[i2 - 1] + o2) + prev = nxtRow + return nxtRow[len(s2)] From 93df9699c1ac06d35a72532b0e36f9d687f5fb67 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Nov 2017 18:21:11 +0800 Subject: [PATCH 055/220] Add py solution for 676. Implement Magic Dictionary 676. Implement Magic Dictionary: https://leetcode.com/problems/implement-magic-dictionary/ --- py/implement-magic-dictionary.py | 79 ++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 py/implement-magic-dictionary.py diff --git a/py/implement-magic-dictionary.py b/py/implement-magic-dictionary.py new file mode 100644 index 0000000..bf665fd --- /dev/null +++ b/py/implement-magic-dictionary.py @@ -0,0 +1,79 @@ +from collections import defaultdict +class Node(object): + def __init__(self): + self.end = False + self._not = defaultdict(set) + self.children = defaultdict(Node) + +class MagicDictionary(object): + + def __init__(self): + """ + Initialize your data structure here. + """ + self.root = Node() + + def buildDict(self, dict): + """ + Build a dictionary through a list of words + :type dict: List[str] + :rtype: void + """ + def dfs(depth, s, rem, out): + if depth == len(s): + if rem == 0: + yield out + else: + if rem: + out.append(s[depth].upper()) + for x in dfs(depth + 1, s, 0, out): + yield x + out.pop() + out.append(s[depth]) + for x in dfs(depth + 1, s, rem, out): + yield x + out.pop() + + def insert_word(w): + cur = self.root + for i, c in enumerate(w): + if c.isupper(): + cur = cur.children['?'] + cur._not[c.lower()].add(''.join(w[i + 1:])) + break + else: + cur = cur.children[c] + cur.end = True + + for d in dict: + for word in dfs(0, d, 1, []): + insert_word(word) + + + def search(self, word): + """ + Returns if there is any word in the trie that equals to the given word after modifying exactly one character + :type word: str + :rtype: bool + """ + def do_search(cur, depth, w): + if depth == len(w): + return cur.end + c = w[depth] + nxt = cur.children.get(c) + if nxt and do_search(nxt, depth + 1, w): + return True + nxt = cur.children.get('?') + if nxt: + for k, s in nxt._not.iteritems(): + if k != c and w[depth + 1:] in s: + return True + return False + + return do_search(self.root, 0, word) + + +# Your MagicDictionary object will be instantiated and called as such: +# obj = MagicDictionary() +# obj.buildDict(dict) +# param_2 = obj.search(word) From 73666cdc83e55aefcf4796c286d5d11fe2cac956 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 10:21:41 +0800 Subject: [PATCH 056/220] Add py solution for 503. Next Greater Element II 503. Next Greater Element II: https://leetcode.com/problems/next-greater-element-ii/ --- py/next-greater-element-ii.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 py/next-greater-element-ii.py diff --git a/py/next-greater-element-ii.py b/py/next-greater-element-ii.py new file mode 100644 index 0000000..8ce637a --- /dev/null +++ b/py/next-greater-element-ii.py @@ -0,0 +1,25 @@ +class Solution(object): + def nextGreaterElements(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + stack = [] + lnum = len(nums) + for i in xrange(lnum - 1, -1, -1): + n = nums[i] + while stack and stack[-1] <= n: + stack.pop() + stack.append(n) + + ans = [None] * lnum + for i in xrange(lnum - 1, -1, -1): + n = nums[i] + while stack and stack[-1] <= n: + stack.pop() + if not stack: + ans[i] = -1 + else: + ans[i] = stack[-1] + stack.append(n) + return ans From b763ddb93c273f8641344866aa004c1798cf7234 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 10:41:43 +0800 Subject: [PATCH 057/220] Add py solution for 529. Minesweeper 529. Minesweeper: https://leetcode.com/problems/minesweeper/ --- py/minesweeper.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 py/minesweeper.py diff --git a/py/minesweeper.py b/py/minesweeper.py new file mode 100644 index 0000000..a27661f --- /dev/null +++ b/py/minesweeper.py @@ -0,0 +1,40 @@ +class Solution(object): + def updateBoard(self, board, click): + """ + :type board: List[List[str]] + :type click: List[int] + :rtype: List[List[str]] + """ + r = len(board) + if r == 0: + return board + c = len(board[0]) + if board[click[0]][click[1]] == 'M': + board[click[0]][click[1]] = 'X' + return board + else: + cnt = [[0] * len(board[0]) for _ in xrange(len(board))] + for x, row in enumerate(board): + for y, v in enumerate(row): + if v == 'M': + for i in xrange(-1, 2): + for j in xrange(-1, 2): + if i or j: + if 0 <= x + i < r and 0 <= y + j < c: + cnt[x + i][y + j] += 1 + visited = set() + q = [tuple(click)] + for v in q: + if v not in visited: + visited.add(v) + if cnt[v[0]][v[1]] > 0: + board[v[0]][v[1]] = str(cnt[v[0]][v[1]]) + else: + board[v[0]][v[1]] = 'B' + for i in xrange(-1, 2): + for j in xrange(-1, 2): + if i or j: + nx, ny = v[0] + i, v[1] + j + if 0 <= nx < r and 0 <= ny < c: + q.append((nx, ny)) + return board From 0f174aac0b8fc99e7c7666f4a2958ae048ef62cb Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 11:01:55 +0800 Subject: [PATCH 058/220] Add py solution for 646. Maximum Length of Pair Chain 646. Maximum Length of Pair Chain: https://leetcode.com/problems/maximum-length-of-pair-chain/ --- py/maximum-length-of-pair-chain.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 py/maximum-length-of-pair-chain.py diff --git a/py/maximum-length-of-pair-chain.py b/py/maximum-length-of-pair-chain.py new file mode 100644 index 0000000..39080cc --- /dev/null +++ b/py/maximum-length-of-pair-chain.py @@ -0,0 +1,21 @@ +class Solution(object): + def findLongestChain(self, pairs): + """ + :type pairs: List[List[int]] + :rtype: int + """ + pairs.sort() + LIS = [] + for p in pairs: + L, U = -1, len(LIS) + while L + 1 < U: + mid = (L + U) / 2 + if LIS[mid] < p[0]: + L = mid + else: + U = mid + if len(LIS) == U: + LIS.append(p[1]) + else: + LIS[L + 1] = min(LIS[L + 1], p[1]) + return len(LIS) From b540a1ebc6b389c1be6cba2bb6b01836ad517d6c Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 11:35:19 +0800 Subject: [PATCH 059/220] Add py solution for 648. Replace Words 648. Replace Words: https://leetcode.com/problems/replace-words/ --- py/replace-words.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 py/replace-words.py diff --git a/py/replace-words.py b/py/replace-words.py new file mode 100644 index 0000000..e501d63 --- /dev/null +++ b/py/replace-words.py @@ -0,0 +1,37 @@ +from collections import defaultdict +class Node(object): + def __init__(self): + self.children = defaultdict(Node) + self.end = False + +class Solution(object): + def replaceWords(self, dict, sentence): + """ + :type dict: List[str] + :type sentence: str + :rtype: str + """ + root = Node() + for w in dict: + cur = root + for c in w: + cur = cur.children[c] + cur.end = True + + ans = [] + for w in sentence.split(): + w_tmp = [] + cur = root + for c in w: + w_tmp.append(c) + if c not in cur.children: + ans.append(w) + break + else: + cur = cur.children[c] + if cur.end: + ans.append(''.join(w_tmp)) + break + else: + ans.append(w) + return ' '.join(ans) From d2ff3f0905ded1dcbffd7ebd9cada423d44767d6 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 11:56:25 +0800 Subject: [PATCH 060/220] Add py solution for 454. 4Sum II 454. 4Sum II: https://leetcode.com/problems/4sum-ii/ --- py/4sum-ii.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 py/4sum-ii.py diff --git a/py/4sum-ii.py b/py/4sum-ii.py new file mode 100644 index 0000000..6c04039 --- /dev/null +++ b/py/4sum-ii.py @@ -0,0 +1,19 @@ +from collections import Counter +class Solution(object): + def fourSumCount(self, A, B, C, D): + """ + :type A: List[int] + :type B: List[int] + :type C: List[int] + :type D: List[int] + :rtype: int + """ + count1 = Counter() + for a in A: + for b in B: + count1[a + b] += 1 + ans = 0 + for c in C: + for d in D: + ans += count1[-(c + d)] + return ans From b715b0def9eefa0cde9ac57564fee6ea54d7d92c Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 12:10:48 +0800 Subject: [PATCH 061/220] Add py solution for 623. Add One Row to Tree 623. Add One Row to Tree: https://leetcode.com/problems/add-one-row-to-tree/ --- py/add-one-row-to-tree.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 py/add-one-row-to-tree.py diff --git a/py/add-one-row-to-tree.py b/py/add-one-row-to-tree.py new file mode 100644 index 0000000..8d05da3 --- /dev/null +++ b/py/add-one-row-to-tree.py @@ -0,0 +1,33 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def addOneRow(self, root, v, d): + """ + :type root: TreeNode + :type v: int + :type d: int + :rtype: TreeNode + """ + if d == 1: + new_root = TreeNode(v) + new_root.left = root + return new_root + q = [(root, 2)] + for node, nxt_depth in q: + if nxt_depth == d: + left = TreeNode(v) + right = TreeNode(v) + left.left = node.left + right.right = node.right + node.left, node.right = left, right + else: + if node.left: + q.append((node.left, nxt_depth + 1)) + if node.right: + q.append((node.right, nxt_depth + 1)) + return root From df586ef873d93031444a57baf055837d746f62a1 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 12:33:13 +0800 Subject: [PATCH 062/220] Add py solution for 498. Diagonal Traverse 498. Diagonal Traverse: https://leetcode.com/problems/diagonal-traverse/ --- py/diagonal-traverse.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 py/diagonal-traverse.py diff --git a/py/diagonal-traverse.py b/py/diagonal-traverse.py new file mode 100644 index 0000000..8af0003 --- /dev/null +++ b/py/diagonal-traverse.py @@ -0,0 +1,19 @@ +class Solution(object): + def findDiagonalOrder(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: List[int] + """ + M = len(matrix) + if M == 0: + return [] + N = len(matrix[0]) + ans = [] + for i in xrange(M + N - 1): + if i % 2 == 0: + for x in xrange(min(i, M - 1), max(i - N + 1, 0) - 1, -1): + ans.append(matrix[x][i - x]) + else: + for x in xrange(max(i - N + 1, 0), min(i, M - 1) + 1): + ans.append(matrix[x][i - x]) + return ans From 0aafd10663f42c02d290949453946afe9f1e2f88 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 12:48:07 +0800 Subject: [PATCH 063/220] Add py solution for 592. Fraction Addition and Subtraction 592. Fraction Addition and Subtraction: https://leetcode.com/problems/fraction-addition-and-subtraction/ --- py/fraction-addition-and-subtraction.py | 27 +++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 py/fraction-addition-and-subtraction.py diff --git a/py/fraction-addition-and-subtraction.py b/py/fraction-addition-and-subtraction.py new file mode 100644 index 0000000..9a2cbc5 --- /dev/null +++ b/py/fraction-addition-and-subtraction.py @@ -0,0 +1,27 @@ +import re +class Solution(object): + def fractionAddition(self, expression): + """ + :type expression: str + :rtype: str + """ + expression = expression.replace('-+', '-') + expression = expression.replace('+-', '-') + matches = re.findall(r'([+-]?)(\d+)/(\d+)', expression) + ans = (0, 1) + for m in matches: + if m[0] == '-': + v = -int(m[1]), int(m[2]) + else: + v = int(m[1]), int(m[2]) + ans = ans[0] * v[1] + ans[1] * v[0], ans[1] * v[1] + def gcd(a, b): + while b != 0: + a, b = b, a % b + return a + neg = 1 + if ans[0] * ans[1] < 0: + neg = -1 + g = gcd(abs(ans[0]), abs(ans[1])) + return '{}/{}'.format(neg * abs(ans[0]) / g, abs(ans[1]) / g) + From 32a02c58a67813417eaa49c80edbdd77f8b2569f Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 14:31:51 +0800 Subject: [PATCH 064/220] Add py solution for 539. Minimum Time Difference 539. Minimum Time Difference: https://leetcode.com/problems/minimum-time-difference/ --- py/minimum-time-difference.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 py/minimum-time-difference.py diff --git a/py/minimum-time-difference.py b/py/minimum-time-difference.py new file mode 100644 index 0000000..14aaa18 --- /dev/null +++ b/py/minimum-time-difference.py @@ -0,0 +1,13 @@ +class Solution(object): + def findMinDifference(self, timePoints): + """ + :type timePoints: List[str] + :rtype: int + """ + timePoints = map(lambda x:int(x.split(':')[0]) * 60 + int(x.split(':')[1]), timePoints) + MINUTES_IN_A_DAY = 24 * 60 + timePoints.sort() + m = timePoints[0] + MINUTES_IN_A_DAY - timePoints[-1] + it1, it2 = iter(timePoints), iter(timePoints) + it2.next() + return min(m, min(t2 - t1 for (t1, t2) in zip(it1, it2))) From 1bb34ccef2f5c622f258a7dbe375e3a62b6cf63d Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 14:45:43 +0800 Subject: [PATCH 065/220] Add py solution for 481. Magical String 481. Magical String: https://leetcode.com/problems/magical-string/ --- py/magical-string.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 py/magical-string.py diff --git a/py/magical-string.py b/py/magical-string.py new file mode 100644 index 0000000..0fa8692 --- /dev/null +++ b/py/magical-string.py @@ -0,0 +1,26 @@ +class Solution(object): + def magicalString(self, n): + """ + :type n: int + :rtype: int + """ + if n == 0: + return 0 + elif n <= 3: + return 1 + q = [1, 2, 2] + cur = 1 + skip = 2 + cnt_1 = 1 + total_cnt = 3 + for v in q: + if skip <= 0: + q += [cur] * v + v = min(n - total_cnt, v) + total_cnt += v + if cur == 1: + cnt_1 += v + if total_cnt == n: + return cnt_1 + cur = 3 - cur + skip -= 1 From b2bc2f08d69ea42f9cecf6f994b1ed3c8e9f8022 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 15:31:14 +0800 Subject: [PATCH 066/220] Add py solution for 452. Minimum Number of Arrows to Burst Balloons 452. Minimum Number of Arrows to Burst Balloons: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/ --- py/minimum-number-of-arrows-to-burst-balloons.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 py/minimum-number-of-arrows-to-burst-balloons.py diff --git a/py/minimum-number-of-arrows-to-burst-balloons.py b/py/minimum-number-of-arrows-to-burst-balloons.py new file mode 100644 index 0000000..046038c --- /dev/null +++ b/py/minimum-number-of-arrows-to-burst-balloons.py @@ -0,0 +1,15 @@ +from operator import itemgetter +class Solution(object): + def findMinArrowShots(self, points): + """ + :type points: List[List[int]] + :rtype: int + """ + points.sort(key=itemgetter(1)) + end = None + ans = 0 + for p in points: + if end is None or end < p[0]: + end = p[1] + ans += 1 + return ans From d362aad24282f158aee4c8178f2f32a757658e11 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 15:36:07 +0800 Subject: [PATCH 067/220] Add py solution for 583. Delete Operation for Two Strings 583. Delete Operation for Two Strings: https://leetcode.com/problems/delete-operation-for-two-strings/ --- py/delete-operation-for-two-strings.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 py/delete-operation-for-two-strings.py diff --git a/py/delete-operation-for-two-strings.py b/py/delete-operation-for-two-strings.py new file mode 100644 index 0000000..4770edd --- /dev/null +++ b/py/delete-operation-for-two-strings.py @@ -0,0 +1,17 @@ +class Solution(object): + def minDistance(self, word1, word2): + """ + :type word1: str + :type word2: str + :rtype: int + """ + prev = [0] * (len(word2) + 1) + for i, c1 in enumerate(word1, 1): + nxt = [0] * (len(word2) + 1) + for j, c2 in enumerate(word2, 1): + if c1 == c2: + nxt[j] = prev[j - 1] + 1 + else: + nxt[j] = max(nxt[j - 1], prev[j]) + prev = nxt + return len(word2) + len(word1) - 2 * prev[len(word2)] From 43d5c85a1b91719cabbc4a92bfd65feceb6cedfc Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 16:07:08 +0800 Subject: [PATCH 068/220] Add py solution for 398. Random Pick Index 398. Random Pick Index: https://leetcode.com/problems/random-pick-index/ --- py/random-pick-index.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 py/random-pick-index.py diff --git a/py/random-pick-index.py b/py/random-pick-index.py new file mode 100644 index 0000000..8863a17 --- /dev/null +++ b/py/random-pick-index.py @@ -0,0 +1,29 @@ +from random import random +class Solution(object): + + def __init__(self, nums): + """ + :type nums: List[int] + :type numsSize: int + """ + self.nums = nums + + def pick(self, target): + """ + :type target: int + :rtype: int + """ + meet = 0 + choice = None + for i, n in enumerate(self.nums): + if n == target: + meet += 1 + if random() * meet < 1: + choice = i + return choice + + + +# Your Solution object will be instantiated and called as such: +# obj = Solution(nums) +# param_1 = obj.pick(target) From e2159264bf9c5849044f9a6df1d5545ba85efbe2 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 16:31:03 +0800 Subject: [PATCH 069/220] Add py solution for 636. Exclusive Time of Functions 636. Exclusive Time of Functions: https://leetcode.com/problems/exclusive-time-of-functions/ --- py/exclusive-time-of-functions.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 py/exclusive-time-of-functions.py diff --git a/py/exclusive-time-of-functions.py b/py/exclusive-time-of-functions.py new file mode 100644 index 0000000..ca10d9a --- /dev/null +++ b/py/exclusive-time-of-functions.py @@ -0,0 +1,23 @@ +from collections import Counter +class Solution(object): + def exclusiveTime(self, n, logs): + """ + :type n: int + :type logs: List[str] + :rtype: List[int] + """ + exec_time = Counter() + stack = [] + for log in logs: + id, type, t = log.split(':') + id, t = int(id), int(t) + if type == 'start': + stack.append((id, t, t)) + else: + cur_id, cur_start, cur_real_start = stack.pop() + exec_time[cur_id] += t - cur_start + 1 + if stack: + nxt_id, nxt_start, real_start = stack.pop() + exec_time[nxt_id] += cur_real_start - nxt_start + stack.append((nxt_id, t + 1, real_start)) + return [exec_time[i] for i in xrange(n)] From 3ad97790d078d50839d8a0c50775d8a75e04ff9e Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 17:36:18 +0800 Subject: [PATCH 070/220] Add py solution for 516. Longest Palindromic Subsequence 516. Longest Palindromic Subsequence: https://leetcode.com/problems/longest-palindromic-subsequence/ --- py/longest-palindromic-subsequence.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 py/longest-palindromic-subsequence.py diff --git a/py/longest-palindromic-subsequence.py b/py/longest-palindromic-subsequence.py new file mode 100644 index 0000000..62697b1 --- /dev/null +++ b/py/longest-palindromic-subsequence.py @@ -0,0 +1,17 @@ +class Solution(object): + def longestPalindromeSubseq(self, s): + """ + :type s: str + :rtype: int + """ + prev2 = [0] * len(s) + prev = [1] * len(s) + for l in xrange(2, len(s) + 1): + nxt = [0] * (len(s) - l + 1) + for i in xrange(len(s) - l + 1): + if s[i] == s[i + l - 1]: + nxt[i] = prev2[i + 1] + 2 + else: + nxt[i] = max(prev[i + 1], prev[i]) + prev2, prev = prev, nxt + return prev[0] From 198b9972c4fd89f95660dd2cf71a6eb983dae76a Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 18:40:51 +0800 Subject: [PATCH 071/220] Add py solution for 424. Longest Repeating Character Replacement 424. Longest Repeating Character Replacement: https://leetcode.com/problems/longest-repeating-character-replacement/ --- py/longest-repeating-character-replacement.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 py/longest-repeating-character-replacement.py diff --git a/py/longest-repeating-character-replacement.py b/py/longest-repeating-character-replacement.py new file mode 100644 index 0000000..a3c7a57 --- /dev/null +++ b/py/longest-repeating-character-replacement.py @@ -0,0 +1,20 @@ +from collections import Counter +class Solution(object): + def characterReplacement(self, s, k): + """ + :type s: str + :type k: int + :rtype: int + """ + c = Counter() + lo = 0 + M = 0 + for hi, char in enumerate(s): + c[char] += 1 + most_common_count = c.most_common(1)[0][1] + if (hi - lo + 1) - most_common_count > k: + c[s[lo]] -= 1 + lo += 1 + M = max(M, hi - lo + 1) + return M + From 8bd86656ca589c3da1b4da078b5cd9633c018c3c Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Nov 2017 23:57:17 +0800 Subject: [PATCH 072/220] Add py solution for 449. Serialize and Deserialize BST 449. Serialize and Deserialize BST: https://leetcode.com/problems/serialize-and-deserialize-bst/ --- py/serialize-and-deserialize-bst.py | 43 +++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 py/serialize-and-deserialize-bst.py diff --git a/py/serialize-and-deserialize-bst.py b/py/serialize-and-deserialize-bst.py new file mode 100644 index 0000000..9dd005e --- /dev/null +++ b/py/serialize-and-deserialize-bst.py @@ -0,0 +1,43 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Codec: + + def serialize(self, root): + """Encodes a tree to a single string. + :type root: TreeNode + :rtype: str + """ + ans = [] + if root: + ans.append(str(root.val)) + ans.append(self.serialize(root.left)) + ans.append(self.serialize(root.right)) + return ' '.join(ans) + + def deserialize(self, data): + """Decodes your encoded data to tree. + :type data: str + :rtype: TreeNode + """ + return self.do_deserialize(data)[0] + + def do_deserialize(self, data): + ans = None + if data: + val, data = data.split(' ', 1) + if val: + ans = TreeNode(int(val)) + ans.left, data = self.do_deserialize(data) + ans.right, data = self.do_deserialize(data) + return ans, data + + + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.deserialize(codec.serialize(root)) From f1d9339e91c679e631b29ad2be7266e3a90d1d47 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 8 Nov 2017 00:19:57 +0800 Subject: [PATCH 073/220] Add py solution for 377. Combination Sum IV 377. Combination Sum IV: https://leetcode.com/problems/combination-sum-iv/ --- py/combination-sum-iv.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 py/combination-sum-iv.py diff --git a/py/combination-sum-iv.py b/py/combination-sum-iv.py new file mode 100644 index 0000000..ab245e5 --- /dev/null +++ b/py/combination-sum-iv.py @@ -0,0 +1,19 @@ +class Solution(object): + def combinationSum4(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + table = dict() + def dp(n): + if n not in table: + ans = 0 + for num in nums: + if num < n: + ans += dp(n - num) + if num == n: + ans += 1 + table[n] = ans + return table[n] + return dp(target) From df17568e00d1b0adbd327d58918d71b3bf195ced Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 8 Nov 2017 01:00:35 +0800 Subject: [PATCH 074/220] Add py solution for 611. Valid Triangle Number 611. Valid Triangle Number: https://leetcode.com/problems/valid-triangle-number/ --- py/valid-triangle-number.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 py/valid-triangle-number.py diff --git a/py/valid-triangle-number.py b/py/valid-triangle-number.py new file mode 100644 index 0000000..7d992d8 --- /dev/null +++ b/py/valid-triangle-number.py @@ -0,0 +1,29 @@ +from collections import Counter +class Solution(object): + def triangleNumber(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums = filter(None, nums) + if not nums: + return 0 + c = Counter(nums) + N = max(nums) + buckets = [0] * (N + 1) + for k, cnt in c.iteritems(): + buckets[k] += cnt + for i in xrange(1, N + 1): + buckets[i] += buckets[i - 1] + + s = sorted(c) + ans = 0 + for i, n1 in enumerate(s): + for j in xrange(i): + n2 = s[j] + n1_n2 = n1 + n2 + ans += c[n1] * c[n2] * (buckets[min(n1_n2 - 1, N)] - buckets[n1]) + ans += c[n2] * (c[n1] - 1) * c[n1] / 2 + ans += c[n1] * (c[n1] - 1) * (c[n1] - 2) / 6 + ans += c[n1] * (c[n1] - 1) / 2 * (buckets[min(n1 * 2 - 1, N)] - buckets[n1]) + return ans From d265071055d0671212683b9edbb64d313f49ff8d Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 8 Nov 2017 01:16:21 +0800 Subject: [PATCH 075/220] Add py solution for 482. License Key Formatting 482. License Key Formatting: https://leetcode.com/problems/license-key-formatting/ --- py/license-key-formatting.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 py/license-key-formatting.py diff --git a/py/license-key-formatting.py b/py/license-key-formatting.py new file mode 100644 index 0000000..16c9697 --- /dev/null +++ b/py/license-key-formatting.py @@ -0,0 +1,9 @@ +class Solution(object): + def licenseKeyFormatting(self, S, K): + """ + :type S: str + :type K: int + :rtype: str + """ + S = S.replace('-', '').upper() + return '-'.join(S[max(0, i):i + K] for i in xrange(-((K - len(S)) % K), len(S), K)) From 497f8e09c7b92bd06c960b4f23bd8cabcc429d3d Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 8 Nov 2017 18:06:43 +0800 Subject: [PATCH 076/220] Add py solution for 435. Non-overlapping Intervals 435. Non-overlapping Intervals: https://leetcode.com/problems/non-overlapping-intervals/ --- py/non-overlapping-intervals.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 py/non-overlapping-intervals.py diff --git a/py/non-overlapping-intervals.py b/py/non-overlapping-intervals.py new file mode 100644 index 0000000..82480ce --- /dev/null +++ b/py/non-overlapping-intervals.py @@ -0,0 +1,27 @@ +from operator import attrgetter +# Definition for an interval. +# class Interval(object): +# def __init__(self, s=0, e=0): +# self.start = s +# self.end = e + +class Solution(object): + def eraseOverlapIntervals(self, intervals): + """ + :type intervals: List[Interval] + :rtype: int + """ + intervals.sort(key=attrgetter('end', 'start')) + if not intervals: + return 0 + end = None + ans = 0 + for itv in intervals: + if end is None: + end = itv.end + else: + if itv.start < end: + ans += 1 + else: + end = itv.end + return ans From 0682925763edab138008a392e57140416471fdee Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 8 Nov 2017 18:15:15 +0800 Subject: [PATCH 077/220] Add py solution for 399. Evaluate Division 399. Evaluate Division: https://leetcode.com/problems/evaluate-division/ --- py/evaluate-division.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 py/evaluate-division.py diff --git a/py/evaluate-division.py b/py/evaluate-division.py new file mode 100644 index 0000000..90721a2 --- /dev/null +++ b/py/evaluate-division.py @@ -0,0 +1,25 @@ +class Solution(object): + def calcEquation(self, equations, values, queries): + """ + :type equations: List[List[str]] + :type values: List[float] + :type queries: List[List[str]] + :rtype: List[float] + """ + var = set() + distance = dict() + for (a, b), val in zip(equations, values): + var.add(a) + var.add(b) + distance[a, b] = val + distance[b, a] = 1 / val + for v in var: + distance[v, v] = 1. + + for k in var: + for i in var: + for j in var: + if (i, j) not in distance: + if (i, k) in distance and (k, j) in distance: + distance[i, j] = distance[i, k] * distance[k, j] + return map(lambda q:distance.get(tuple(q), -1.), queries) From 7031126f3839a389b16d48404e5ad085d815fe83 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 8 Nov 2017 18:34:30 +0800 Subject: [PATCH 078/220] Add py solution for 640. Solve the Equation 640. Solve the Equation: https://leetcode.com/problems/solve-the-equation/ --- py/solve-the-equation.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 py/solve-the-equation.py diff --git a/py/solve-the-equation.py b/py/solve-the-equation.py new file mode 100644 index 0000000..119a539 --- /dev/null +++ b/py/solve-the-equation.py @@ -0,0 +1,20 @@ +import re +class Solution(object): + def solveEquation(self, equation): + """ + :type equation: str + :rtype: str + """ + lhs, rhs = equation.split('=') + lcoef = sum(int(m + "1" if m in ["-", "+", ""] else m) for m in re.findall(r'([+-]?\d*)x', lhs)) + rcoef = sum(int(m + "1" if m in ["-", "+", ""] else m) for m in re.findall(r'([+-]?\d*)x', rhs)) + lconst = sum(int(m) for m in re.findall(r'([+-]?\d+)(?![0-9x])', lhs)) + rconst = sum(int(m) for m in re.findall(r'([+-]?\d+)(?![0-9x])', rhs)) + print lcoef, rcoef, lconst, rconst + if lcoef == rcoef: + if lconst == rconst: + return "Infinite solutions" + else: + return "No solution" + else: + return 'x={ans}'.format(ans=(lconst - rconst) / (rcoef - lcoef)) From ecf6b04821d2d46a1144530fde240c042f301e24 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 10 Nov 2017 16:17:08 +0800 Subject: [PATCH 079/220] Add py solution for 368. Largest Divisible Subset 368. Largest Divisible Subset: https://leetcode.com/problems/largest-divisible-subset/ --- py/largest-divisible-subset.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 py/largest-divisible-subset.py diff --git a/py/largest-divisible-subset.py b/py/largest-divisible-subset.py new file mode 100644 index 0000000..94ecfb8 --- /dev/null +++ b/py/largest-divisible-subset.py @@ -0,0 +1,25 @@ +class Solution(object): + def largestDivisibleSubset(self, nums): + """ + :type nums: List[int] + :rtype: List[int] + """ + if not nums: + return [] + nums.sort(reverse=True) + lnums = len(nums) + dp = [(-1, 1)] * lnums + max_length, max_end = 1, 0 + for i, n in enumerate(nums): + for j in xrange(i + 1, lnums): + if n % nums[j] == 0: + if dp[j][1] < dp[i][1] + 1: + dp[j] = i, dp[i][1] + 1 + if dp[j][1] > max_length: + max_length, max_end = dp[j][1], j + cur = max_end + ans = [] + while cur != -1: + ans.append(nums[cur]) + cur = dp[cur][0] + return ans From d067d9937ff34787e6f632d86075af29c27d98f8 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 10 Nov 2017 16:50:11 +0800 Subject: [PATCH 080/220] Add py solution for 714. Best Time to Buy and Sell Stock with Transaction Fee 714. Best Time to Buy and Sell Stock with Transaction Fee: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ --- ...time-to-buy-and-sell-stock-with-transaction-fee.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 py/best-time-to-buy-and-sell-stock-with-transaction-fee.py diff --git a/py/best-time-to-buy-and-sell-stock-with-transaction-fee.py b/py/best-time-to-buy-and-sell-stock-with-transaction-fee.py new file mode 100644 index 0000000..be308ed --- /dev/null +++ b/py/best-time-to-buy-and-sell-stock-with-transaction-fee.py @@ -0,0 +1,11 @@ +class Solution(object): + def maxProfit(self, prices, fee): + """ + :type prices: List[int] + :type fee: int + :rtype: int + """ + hold, not_hold = None, 0 + for p in prices: + hold, not_hold = max(hold, not_hold - p - fee), max(not_hold, None if hold is None else hold + p) + return max(hold, not_hold) From fd059ce3e00953d855afd166cbafb58ddecd7626 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 10 Nov 2017 17:49:45 +0800 Subject: [PATCH 081/220] Add py solution for 567. Permutation in String 567. Permutation in String: https://leetcode.com/problems/permutation-in-string/ --- py/permutation-in-string.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 py/permutation-in-string.py diff --git a/py/permutation-in-string.py b/py/permutation-in-string.py new file mode 100644 index 0000000..993b6df --- /dev/null +++ b/py/permutation-in-string.py @@ -0,0 +1,30 @@ +from collections import Counter +class Solution(object): + def checkInclusion(self, s1, s2): + """ + :type s1: str + :type s2: str + :rtype: bool + """ + P = 10 ** 9 + 7 + Q = 65535 + inv = lambda x: pow(x % P, P - 2, P) + ls1, ls2 = len(s1), len(s2) + + if ls2 < ls1: + return False + + match = 0 + for c, cnt in Counter(s1).iteritems(): + match = (match + cnt * pow(Q, ord(c) - ord('a') + 1, P)) % P + + window = 0 + for i in xrange(ls1 - 1): + window = (window + pow(Q, ord(s2[i]) - ord('a') + 1, P)) % P + + for i in xrange(ls1 - 1, ls2): + window = (window + pow(Q, ord(s2[i]) - ord('a') + 1, P)) % P + if window == match: + return True + window = (window + (P - pow(Q, ord(s2[i - ls1 + 1]) - ord('a') + 1, P))) % P + return False From f342ce1ee57b0fdc6847d80a7453f575e4301299 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 10 Nov 2017 18:53:05 +0800 Subject: [PATCH 082/220] Add py solution for 698. Partition to K Equal Sum Subsets 698. Partition to K Equal Sum Subsets: https://leetcode.com/problems/partition-to-k-equal-sum-subsets/ --- py/partition-to-k-equal-sum-subsets.py | 27 ++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 py/partition-to-k-equal-sum-subsets.py diff --git a/py/partition-to-k-equal-sum-subsets.py b/py/partition-to-k-equal-sum-subsets.py new file mode 100644 index 0000000..f993d7b --- /dev/null +++ b/py/partition-to-k-equal-sum-subsets.py @@ -0,0 +1,27 @@ +class Solution(object): + def canPartitionKSubsets(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: bool + """ + s = sum(nums) + if s % k != 0: + return False + target = s / k + lnums = len(nums) + fail = set() + nums.sort(reverse=True) + def dfs(groups, cur, flag): + if groups == k - 1: + return True + for i in xrange(lnums): + n = nums[i] + if (1 << i) & flag == 0 and flag | (1 << i) not in fail: + if cur + n <= target: + if dfs(groups + (cur + n) / target, (cur + n) % target, flag | (1 << i)): + return True + fail.add(flag) + return False + + return dfs(0, 0, 0) From 3135e75954fa5aa91e1cd0970167f3699a04dcd0 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 13 Nov 2017 14:45:32 +0800 Subject: [PATCH 083/220] Add py solution for 725. Split Linked List in Parts 725. Split Linked List in Parts: https://leetcode.com/problems/split-linked-list-in-parts/ --- py/split-linked-list-in-parts.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 py/split-linked-list-in-parts.py diff --git a/py/split-linked-list-in-parts.py b/py/split-linked-list-in-parts.py new file mode 100644 index 0000000..c60ff1a --- /dev/null +++ b/py/split-linked-list-in-parts.py @@ -0,0 +1,31 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def splitListToParts(self, root, k): + """ + :type root: ListNode + :type k: int + :rtype: List[ListNode] + """ + n = 0 + cur = root + while cur: + n += 1 + cur = cur.next + group_size, rem = n / k, n % k + ans = [] + cur = root + prev = None + for group in xrange(k): + gs = group_size + int(group < rem) + ans.append(cur) + while gs > 0: + prev, cur = cur, cur.next + gs -= 1 + if prev: + prev.next = None + return ans From 7113374b0eab84769fe452ad124d8e082bb11923 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 22 Nov 2017 00:53:56 +0800 Subject: [PATCH 084/220] Add py solution for 4. Median of Two Sorted Arrays 4. Median of Two Sorted Arrays: https://leetcode.com/problems/median-of-two-sorted-arrays/ Reference: https://discuss.leetcode.com/topic/16797/very-concise-o-log-min-m-n-iterative-solution-with-detailed-explanation --- py/median-of-two-sorted-arrays.py | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 py/median-of-two-sorted-arrays.py diff --git a/py/median-of-two-sorted-arrays.py b/py/median-of-two-sorted-arrays.py new file mode 100644 index 0000000..651f4e9 --- /dev/null +++ b/py/median-of-two-sorted-arrays.py @@ -0,0 +1,36 @@ +class Solution(object): + def findMedianSortedArrays(self, nums1, nums2): + """ + :type nums1: List[int] + :type nums2: List[int] + :rtype: float + """ + if len(nums1) > len(nums2): + nums1, nums2 = nums2, nums1 + l1, l2 = len(nums1), len(nums2) + + m = min(nums1[:1] + nums2[:1]) + M = max(nums1[-1:] + nums2[-1:]) + + + # 0123456789 + # .4.5.6. + # .1.2.3. + L, U = 0, l1 * 2 + 1 + while L + 1 < U: + mid1 = (L + U) / 2 + mid2 = l1 + l2 - mid1 + L1 = m if mid1 == 0 else nums1[(mid1 - 1) / 2] + R1 = M if mid1 == 2 * l1 else nums1[mid1 / 2] + L2 = m if mid2 == 0 else nums2[(mid2 - 1) / 2] + R2 = M if mid2 == 2 * l2 else nums2[mid2 / 2] + if L1 > R2: + U = mid1 + else: + L = mid1 + C1, C2 = L, l1 + l2 - L + L1 = m if C1 == 0 else nums1[(C1 - 1) / 2] + R1 = M if C1 == 2 * l1 else nums1[C1 / 2] + L2 = m if C2 == 0 else nums2[(C2 - 1) / 2] + R2 = M if C2 == 2 * l2 else nums2[C2 / 2] + return (max(L1, L2) + min(R1, R2)) / 2. From 6885eb0cb50f2af39075f6bec13e95c648f3a19f Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 23 Jan 2018 18:20:52 +0800 Subject: [PATCH 085/220] Add py solution for 105. Construct Binary Tree from Preorder and Inorder Traversal 105. Construct Binary Tree from Preorder and Inorder Traversal: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ --- ...ree-from-preorder-and-inorder-traversal.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 py/construct-binary-tree-from-preorder-and-inorder-traversal.py diff --git a/py/construct-binary-tree-from-preorder-and-inorder-traversal.py b/py/construct-binary-tree-from-preorder-and-inorder-traversal.py new file mode 100644 index 0000000..22b39bd --- /dev/null +++ b/py/construct-binary-tree-from-preorder-and-inorder-traversal.py @@ -0,0 +1,26 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def buildTree(self, preorder, inorder): + """ + :type preorder: List[int] + :type inorder: List[int] + :rtype: TreeNode + """ + def build(pre, pre_start, pre_end, in_pos, in_start, in_end): + if pre_start == pre_end: + return + cur_root = pre[pre_start] + root_pos = in_pos[cur_root] + left_size = root_pos - in_start + cur = TreeNode(cur_root) + cur.left = build(pre, pre_start + 1, pre_start + 1 + left_size, in_pos, in_start, root_pos) + cur.right = build(pre, pre_start + 1 + left_size, pre_end, in_pos, root_pos + 1, in_end) + return cur + in_pos = {v: pos for (pos, v) in enumerate(inorder)} + return build(preorder, 0, len(preorder), in_pos, 0, len(inorder)) From 1314fc91a5d9f3a8e035e92a6da162ca74ca1a71 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 22 Feb 2018 17:31:56 +0800 Subject: [PATCH 086/220] Add py solution for 23. Merge k Sorted Lists 23. Merge k Sorted Lists: https://leetcode.com/problems/merge-k-sorted-lists/ --- py/merge-k-sorted-lists.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 py/merge-k-sorted-lists.py diff --git a/py/merge-k-sorted-lists.py b/py/merge-k-sorted-lists.py new file mode 100644 index 0000000..0b1e827 --- /dev/null +++ b/py/merge-k-sorted-lists.py @@ -0,0 +1,34 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None +import heapq + +class Solution(object): + def mergeKLists(self, lists): + """ + :type lists: List[ListNode] + :rtype: ListNode + """ + h = [] + for i, l in enumerate(lists): + if l: + node = l + h.append((node.val, node, i)) + lists[i] = lists[i].next + heapq.heapify(h) + ret = None + cur = ret + while h: + _, node, idx = heapq.heappop(h) + if ret is None: + ret = cur = node + else: + cur.next = node + cur = node + if lists[idx]: + heapq.heappush(h, (lists[idx].val, lists[idx], idx)) + lists[idx] = lists[idx].next + return ret + From 2ae585068ea0ba0501e28c27c56bf45359459540 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 2 Mar 2018 16:29:19 +0800 Subject: [PATCH 087/220] Add py solution for 546. Remove Boxes 546. Remove Boxes: https://leetcode.com/problems/remove-boxes/ --- py/remove-boxes.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 py/remove-boxes.py diff --git a/py/remove-boxes.py b/py/remove-boxes.py new file mode 100644 index 0000000..6ed1de3 --- /dev/null +++ b/py/remove-boxes.py @@ -0,0 +1,46 @@ +from collections import defaultdict, Counter +from itertools import groupby +class Solution(object): + def removeBoxes(self, boxes): + """ + :type boxes: List[int] + :rtype: int + """ + table = defaultdict(Counter) + table_max = Counter() + B = [] + for k, l in groupby(boxes): + B.append((k, len(list(l)))) + lB = len(B) + for i in xrange(lB): + table[i, i + 1][B[i][1]] = 0 + table_max[i, i + 1] = B[i][1] ** 2 + for l in xrange(2, lB + 1): + for i in xrange(lB - l + 1): + fr, to = i, i + l + table_fr_to = table[fr, to] + + size = B[fr][1] + table_fr_to[size] = max(table_fr_to[size], table_max[fr + 1, to]) + table_max[fr, to] = max(table_max[fr, to], table_fr_to[size] + size ** 2) + + for sp in xrange(fr + 1, to): + if B[fr][0] == B[sp][0]: + size_score_l = table[fr, sp] + size_score_r = table[sp, to] + max_size, max_score = 0, 0 + size_scores = [] + for size_l, score_l in size_score_l.iteritems(): + for size_r, score_r in size_score_r.iteritems(): + size_scores.append((size_l + size_r, score_l + score_r)) + size_scores.sort(key=lambda (size, score): (-size, -score)) + out_size_scores = [] + for size, score in size_scores: + if not out_size_scores: + out_size_scores.append((size, score)) + elif score > out_size_scores[-1][1]: + out_size_scores.append((size, score)) + for size, score in out_size_scores: + table_fr_to[size] = max(table_fr_to[size], score) + table_max[fr, to] = max(table_max[fr, to], table_fr_to[size] + size ** 2) + return table_max[0, lB] From eb5c22a423d83c48dcc4a47687363b7dd4c713c0 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Sat, 28 Dec 2019 01:54:20 +0800 Subject: [PATCH 088/220] Add go.mod --- go/go.mod | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 go/go.mod diff --git a/go/go.mod b/go/go.mod new file mode 100644 index 0000000..c9e1624 --- /dev/null +++ b/go/go.mod @@ -0,0 +1,3 @@ +module leetcode + +go 1.13 From 7c578a864e5bcaa11c0535a48e5d1b1d60bd5342 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 12:51:01 +0800 Subject: [PATCH 089/220] Add go solution for 1. Two Sum 1. Two Sum: https://leetcode.com/problems/two-sum/ --- go/two-sum.go | 13 +++++++++++++ go/two-sum_test.go | 21 +++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 go/two-sum.go create mode 100644 go/two-sum_test.go diff --git a/go/two-sum.go b/go/two-sum.go new file mode 100644 index 0000000..213d3c4 --- /dev/null +++ b/go/two-sum.go @@ -0,0 +1,13 @@ +package leetcode + +func twoSum(nums []int, target int) []int { + m := make(map[int]int) + for i, v := range nums { + if idx, ok := m[target-v]; ok { + return []int{idx, i} + } else { + m[v] = i + } + } + return []int{} +} diff --git a/go/two-sum_test.go b/go/two-sum_test.go new file mode 100644 index 0000000..bf184d7 --- /dev/null +++ b/go/two-sum_test.go @@ -0,0 +1,21 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +type Prob struct { + arr []int + target int +} + +type Expected []int + +func TestTwoSum(t *testing.T) { + q := Prob{[]int{1, 2, 3}, 5} + e := Expected([]int{1, 2}) + if !reflect.DeepEqual(twoSum(q.arr, q.target), []int(e)) { + t.Fatalf("%v %v", q, e) + } +} From f16ec7acc57bd314b339833a82c9dd474f1752fa Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 13:33:35 +0800 Subject: [PATCH 090/220] Add go solution for 1295. Find Numbers with Even Number of Digits 1295. Find Numbers with Even Number of Digits: https://leetcode.com/problems/find-numbers-with-even-number-of-digits/ --- go/find-numbers-with-even-number-of-digits.go | 13 +++++++++++++ go/find-numbers-with-even-number-of-digits_test.go | 11 +++++++++++ 2 files changed, 24 insertions(+) create mode 100644 go/find-numbers-with-even-number-of-digits.go create mode 100644 go/find-numbers-with-even-number-of-digits_test.go diff --git a/go/find-numbers-with-even-number-of-digits.go b/go/find-numbers-with-even-number-of-digits.go new file mode 100644 index 0000000..35f123d --- /dev/null +++ b/go/find-numbers-with-even-number-of-digits.go @@ -0,0 +1,13 @@ +package leetcode + +import ( + "strconv" +) + +func findNumbers(nums []int) int { + ans := 0 + for _, v := range nums { + ans += (len(strconv.Itoa(v)) & 1) ^ 1 + } + return ans +} diff --git a/go/find-numbers-with-even-number-of-digits_test.go b/go/find-numbers-with-even-number-of-digits_test.go new file mode 100644 index 0000000..152821b --- /dev/null +++ b/go/find-numbers-with-even-number-of-digits_test.go @@ -0,0 +1,11 @@ +package leetcode + +import ( + "fmt" + "testing" +) + +func TestFindNumbers(t *testing.T) { + fmt.Println(findNumbers([]int{12, 345, 2, 6, 7896}) == 2) + fmt.Println(findNumbers([]int{555, 901, 482, 1771}) == 1) +} From 9194d6d960bbdbec55ab24ebae631aca28fa198a Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 14:45:51 +0800 Subject: [PATCH 091/220] Add go solution for 1108. Defanging an IP Address 1108. Defanging an IP Address: https://leetcode.com/problems/defanging-an-ip-address/ --- go/defanging-an-ip-address.go | 7 +++++++ go/defanging-an-ip-address_test.go | 13 +++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 go/defanging-an-ip-address.go create mode 100644 go/defanging-an-ip-address_test.go diff --git a/go/defanging-an-ip-address.go b/go/defanging-an-ip-address.go new file mode 100644 index 0000000..cad90a4 --- /dev/null +++ b/go/defanging-an-ip-address.go @@ -0,0 +1,7 @@ +package leetcode + +import "strings" + +func defangIPaddr(address string) string { + return strings.Replace(address, ".", "[.]", -1) +} diff --git a/go/defanging-an-ip-address_test.go b/go/defanging-an-ip-address_test.go new file mode 100644 index 0000000..5e541aa --- /dev/null +++ b/go/defanging-an-ip-address_test.go @@ -0,0 +1,13 @@ +package leetcode + +import "testing" + +func TestDefangIPaddr(t *testing.T) { + if defangIPaddr("1.1.1.1") != "1[.]1[.]1[.]1" { + t.Fatal() + } + + if defangIPaddr("255.100.50.0") != "255[.]100[.]50[.]0" { + t.Fatal() + } +} From 187e2b584dd1fc2282f0e2bc2c258f0a8640bc00 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 15:45:10 +0800 Subject: [PATCH 092/220] Add go solution for 771. Jewels and Stones 771. Jewels and Stones: https://leetcode.com/problems/jewels-and-stones/ --- go/jewels-and-stones.go | 15 +++++++++++++++ go/jewels-and-stones_test.go | 12 ++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 go/jewels-and-stones.go create mode 100644 go/jewels-and-stones_test.go diff --git a/go/jewels-and-stones.go b/go/jewels-and-stones.go new file mode 100644 index 0000000..a25c3a9 --- /dev/null +++ b/go/jewels-and-stones.go @@ -0,0 +1,15 @@ +package leetcode + +func numJewelsInStones(J string, S string) int { + isJewel := make(map[rune]struct{}) + for _, c := range J { + isJewel[c] = struct{}{} + } + ans := 0 + for _, c := range S { + if _, ok := isJewel[c]; ok { + ans++ + } + } + return ans +} diff --git a/go/jewels-and-stones_test.go b/go/jewels-and-stones_test.go new file mode 100644 index 0000000..4a1185a --- /dev/null +++ b/go/jewels-and-stones_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestNumJewelsInStones(t *testing.T) { + if numJewelsInStones("aA", "aAAbbbb") != 3 { + t.Fatal() + } + if numJewelsInStones("z", "ZZ") != 0 { + t.Fatal() + } +} From a3b89f67340e851de5ea2d656b14887290590732 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 15:53:22 +0800 Subject: [PATCH 093/220] Add go solution for 1281. Subtract the Product and Sum of Digits of an Integer 1281. Subtract the Product and Sum of Digits of an Integer: https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ --- ...the-product-and-sum-of-digits-of-an-integer.go | 12 ++++++++++++ ...roduct-and-sum-of-digits-of-an-integer_test.go | 15 +++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 go/subtract-the-product-and-sum-of-digits-of-an-integer.go create mode 100644 go/subtract-the-product-and-sum-of-digits-of-an-integer_test.go diff --git a/go/subtract-the-product-and-sum-of-digits-of-an-integer.go b/go/subtract-the-product-and-sum-of-digits-of-an-integer.go new file mode 100644 index 0000000..fe9cbe3 --- /dev/null +++ b/go/subtract-the-product-and-sum-of-digits-of-an-integer.go @@ -0,0 +1,12 @@ +package leetcode + +func subtractProductAndSum(n int) int { + p, s := 1, 0 + for n > 0 { + v := n % 10 + p *= v + s += v + n /= 10 + } + return p - s +} diff --git a/go/subtract-the-product-and-sum-of-digits-of-an-integer_test.go b/go/subtract-the-product-and-sum-of-digits-of-an-integer_test.go new file mode 100644 index 0000000..208a1cc --- /dev/null +++ b/go/subtract-the-product-and-sum-of-digits-of-an-integer_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestSubtractProductAndSum(t *testing.T) { + if subtractProductAndSum(234) != 15 { + t.Fatal() + } + if subtractProductAndSum(4421) != 21 { + t.Fatal() + } + if subtractProductAndSum(114) != -2 { + t.Fatal() + } +} From 138ef34291b4185c53939ae4b68305c4d531b771 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 15:59:30 +0800 Subject: [PATCH 094/220] Add go solution for 1290. Convert Binary Number in a Linked List to Integer 1290. Convert Binary Number in a Linked List to Integer: https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/ --- ...ert-binary-number-in-a-linked-list-to-integer.go | 12 ++++++++++++ ...inary-number-in-a-linked-list-to-integer_test.go | 13 +++++++++++++ go/listNode.go | 6 ++++++ 3 files changed, 31 insertions(+) create mode 100644 go/convert-binary-number-in-a-linked-list-to-integer.go create mode 100644 go/convert-binary-number-in-a-linked-list-to-integer_test.go create mode 100644 go/listNode.go diff --git a/go/convert-binary-number-in-a-linked-list-to-integer.go b/go/convert-binary-number-in-a-linked-list-to-integer.go new file mode 100644 index 0000000..af4a078 --- /dev/null +++ b/go/convert-binary-number-in-a-linked-list-to-integer.go @@ -0,0 +1,12 @@ +package leetcode + +func getDecimalValue(head *ListNode) int { + t := head + ans := 0 + for t != nil { + ans <<= 1 + ans |= t.Val + t = t.Next + } + return ans +} diff --git a/go/convert-binary-number-in-a-linked-list-to-integer_test.go b/go/convert-binary-number-in-a-linked-list-to-integer_test.go new file mode 100644 index 0000000..8cc6cc7 --- /dev/null +++ b/go/convert-binary-number-in-a-linked-list-to-integer_test.go @@ -0,0 +1,13 @@ +package leetcode + +import "testing" + +func TestGetDecimalValue(t *testing.T) { + if getDecimalValue(nil) != 0 { + t.Fatal() + } + r := ListNode{1, &ListNode{0, &ListNode{1, nil}}} + if getDecimalValue(&r) != 5 { + t.Fatal() + } +} diff --git a/go/listNode.go b/go/listNode.go new file mode 100644 index 0000000..d853f04 --- /dev/null +++ b/go/listNode.go @@ -0,0 +1,6 @@ +package leetcode + +type ListNode struct { + Val int + Next *ListNode +} From 2e77552c798caee2a84bb9bbacd6416c64c3c104 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 16:03:53 +0800 Subject: [PATCH 095/220] Add go solution for 1221. Split a String in Balanced Strings 1221. Split a String in Balanced Strings: https://leetcode.com/problems/split-a-string-in-balanced-strings/ --- go/split-a-string-in-balanced-strings.go | 17 +++++++++++++++++ go/split-a-string-in-balanced-strings_test.go | 9 +++++++++ 2 files changed, 26 insertions(+) create mode 100644 go/split-a-string-in-balanced-strings.go create mode 100644 go/split-a-string-in-balanced-strings_test.go diff --git a/go/split-a-string-in-balanced-strings.go b/go/split-a-string-in-balanced-strings.go new file mode 100644 index 0000000..a1ede09 --- /dev/null +++ b/go/split-a-string-in-balanced-strings.go @@ -0,0 +1,17 @@ +package leetcode + +func balancedStringSplit(s string) int { + r, l := 0, 0 + ans := 0 + for _, c := range s { + if c == 'R' { + r += 1 + } else if c == 'L' { + l += 1 + } + if r == l { + ans += 1 + } + } + return ans +} diff --git a/go/split-a-string-in-balanced-strings_test.go b/go/split-a-string-in-balanced-strings_test.go new file mode 100644 index 0000000..f8c9cb0 --- /dev/null +++ b/go/split-a-string-in-balanced-strings_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestBalancedStringSplit(t *testing.T) { + if balancedStringSplit("RLRRLLRLRL") != 4 { + t.Fatal() + } +} From 283431c0e5be12156c107277b34cb389e390de04 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 16:15:45 +0800 Subject: [PATCH 096/220] Add go solution for 1266. Minimum Time Visiting All Points 1266. Minimum Time Visiting All Points: https://leetcode.com/problems/minimum-time-visiting-all-points/ --- go/minimum-time-visiting-all-points.go | 27 +++++++++++++++++++++ go/minimum-time-visiting-all-points_test.go | 9 +++++++ 2 files changed, 36 insertions(+) create mode 100644 go/minimum-time-visiting-all-points.go create mode 100644 go/minimum-time-visiting-all-points_test.go diff --git a/go/minimum-time-visiting-all-points.go b/go/minimum-time-visiting-all-points.go new file mode 100644 index 0000000..4a4f788 --- /dev/null +++ b/go/minimum-time-visiting-all-points.go @@ -0,0 +1,27 @@ +package leetcode + +func abs(v int) int { + if v < 0 { + return -v + } + return v +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func minTimeToVisitAllPoints(points [][]int) int { + var prev *[]int + ans := 0 + for _, p := range points { + if prev != nil { + ans += max(abs((*prev)[0]-p[0]), abs((*prev)[1]-p[1])) + } + prev = &[]int{p[0], p[1]} + } + return ans +} diff --git a/go/minimum-time-visiting-all-points_test.go b/go/minimum-time-visiting-all-points_test.go new file mode 100644 index 0000000..f44ab43 --- /dev/null +++ b/go/minimum-time-visiting-all-points_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestMinTimeToVisitAllPoints(t *testing.T) { + if minTimeToVisitAllPoints([][]int{[]int{1, 1}, []int{3, 4}, []int{-1, 0}}) != 7 { + t.Fatal() + } +} From 82fd0452f31ae88887866ec923ded04fd0c7a210 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 16:28:47 +0800 Subject: [PATCH 097/220] Add go solution for 938. Range Sum of BST 938. Range Sum of BST: https://leetcode.com/problems/range-sum-of-bst/ --- go/range-sum-of-bst.go | 14 ++++++++++++++ go/range-sum-of-bst_test.go | 18 ++++++++++++++++++ go/treeNode.go | 7 +++++++ 3 files changed, 39 insertions(+) create mode 100644 go/range-sum-of-bst.go create mode 100644 go/range-sum-of-bst_test.go create mode 100644 go/treeNode.go diff --git a/go/range-sum-of-bst.go b/go/range-sum-of-bst.go new file mode 100644 index 0000000..8ea8c09 --- /dev/null +++ b/go/range-sum-of-bst.go @@ -0,0 +1,14 @@ +package leetcode + +func rangeSumBST(root *TreeNode, L int, R int) int { + if root == nil { + return 0 + } + if root.Val < L { + return rangeSumBST(root.Right, L, R) + } else if root.Val > R { + return rangeSumBST(root.Left, L, R) + } else { + return rangeSumBST(root.Left, L, R) + root.Val + rangeSumBST(root.Right, L, R) + } +} diff --git a/go/range-sum-of-bst_test.go b/go/range-sum-of-bst_test.go new file mode 100644 index 0000000..7bc98f9 --- /dev/null +++ b/go/range-sum-of-bst_test.go @@ -0,0 +1,18 @@ +package leetcode + +import "testing" + +func TestRangeSumBST(t *testing.T) { + root := TreeNode{ + Val: 3, + Left: &TreeNode{ + Val: 1, + }, + Right: &TreeNode{ + Val: 4, + }, + } + if rangeSumBST(&root, 2, 5) != 7 { + t.Fatal() + } +} diff --git a/go/treeNode.go b/go/treeNode.go new file mode 100644 index 0000000..d575c3a --- /dev/null +++ b/go/treeNode.go @@ -0,0 +1,7 @@ +package leetcode + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} From 6a97514695031d9b73b5b079ee7d800a43caa466 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 16:33:23 +0800 Subject: [PATCH 098/220] Add go solution for 709. To Lower Case 709. To Lower Case: https://leetcode.com/problems/to-lower-case/ --- go/to-lower-case.go | 11 +++++++++++ go/to-lower-case_test.go | 15 +++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 go/to-lower-case.go create mode 100644 go/to-lower-case_test.go diff --git a/go/to-lower-case.go b/go/to-lower-case.go new file mode 100644 index 0000000..4bf878b --- /dev/null +++ b/go/to-lower-case.go @@ -0,0 +1,11 @@ +package leetcode + +func toLowerCase(str string) string { + out := []rune(str) + for i, v := range out { + if 'A' <= v && v <= 'Z' { + out[i] = v | 0x20 + } + } + return string(out) +} diff --git a/go/to-lower-case_test.go b/go/to-lower-case_test.go new file mode 100644 index 0000000..c85d1bb --- /dev/null +++ b/go/to-lower-case_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestToLowerCase(t *testing.T) { + if toLowerCase("Hello") != "hello" { + t.Fatal() + } + if toLowerCase("here") != "here" { + t.Fatal() + } + if toLowerCase("LOVELY") != "lovely" { + t.Fatal() + } +} From 993d5e0d96743d2b6669b11aea34d0cc65d6285a Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 16:59:14 +0800 Subject: [PATCH 099/220] Add go solution for 1252. Cells with Odd Values in a Matrix 1252. Cells with Odd Values in a Matrix: https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ --- go/cells-with-odd-values-in-a-matrix.go | 22 ++++++++++++++++++++ go/cells-with-odd-values-in-a-matrix_test.go | 12 +++++++++++ 2 files changed, 34 insertions(+) create mode 100644 go/cells-with-odd-values-in-a-matrix.go create mode 100644 go/cells-with-odd-values-in-a-matrix_test.go diff --git a/go/cells-with-odd-values-in-a-matrix.go b/go/cells-with-odd-values-in-a-matrix.go new file mode 100644 index 0000000..56123bb --- /dev/null +++ b/go/cells-with-odd-values-in-a-matrix.go @@ -0,0 +1,22 @@ +package leetcode + +func oddCells(n int, m int, indices [][]int) int { + rows := make([]int, n) + cols := make([]int, m) + nrow, ncol := 0, 0 + for _, idx := range indices { + rows[idx[0]] ^= 1 + if rows[idx[0]] == 1 { + nrow++ + } else { + nrow-- + } + cols[idx[1]] ^= 1 + if cols[idx[1]] == 1 { + ncol++ + } else { + ncol-- + } + } + return nrow*m + ncol*n - nrow*ncol*2 +} diff --git a/go/cells-with-odd-values-in-a-matrix_test.go b/go/cells-with-odd-values-in-a-matrix_test.go new file mode 100644 index 0000000..2b2d00e --- /dev/null +++ b/go/cells-with-odd-values-in-a-matrix_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestOddCells(t *testing.T) { + if oddCells(2, 3, [][]int{[]int{0, 1}, []int{1, 1}}) != 6 { + t.Fatal() + } + if oddCells(2, 2, [][]int{[]int{1, 1}, []int{0, 0}}) != 0 { + t.Fatal() + } +} From 6bebf152db8855c2c6683ddbfff2b24cf847e196 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 17:26:47 +0800 Subject: [PATCH 100/220] Add go solution for 1021. Remove Outermost Parentheses 1021. Remove Outermost Parentheses: https://leetcode.com/problems/remove-outermost-parentheses/ --- go/remove-outermost-parentheses.go | 19 +++++++++++++++++++ go/remove-outermost-parentheses_test.go | 14 ++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 go/remove-outermost-parentheses.go create mode 100644 go/remove-outermost-parentheses_test.go diff --git a/go/remove-outermost-parentheses.go b/go/remove-outermost-parentheses.go new file mode 100644 index 0000000..0d19288 --- /dev/null +++ b/go/remove-outermost-parentheses.go @@ -0,0 +1,19 @@ +package leetcode + +func removeOuterParentheses(S string) string { + stack, s_stack := make([]rune, 0, len(S)), 0 + for _, c := range S { + if c == '(' { + if s_stack > 0 { + stack = append(stack, c) + } + s_stack++ + } else if c == ')' { + if s_stack > 1 { + stack = append(stack, c) + } + s_stack-- + } + } + return string(stack) +} diff --git a/go/remove-outermost-parentheses_test.go b/go/remove-outermost-parentheses_test.go new file mode 100644 index 0000000..9a443e7 --- /dev/null +++ b/go/remove-outermost-parentheses_test.go @@ -0,0 +1,14 @@ +package leetcode + +import ( + "testing" +) + +func TestRemoveOuterParentheses(t *testing.T) { + if removeOuterParentheses("(()())(())") != "()()()" { + t.Fatal() + } + if removeOuterParentheses("(()())(())(()(()))") != "()()()()(())" { + t.Fatal() + } +} From 2fac38834d25b0af8bcae7dbb641f455cc196e24 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 17:35:28 +0800 Subject: [PATCH 101/220] Add go solution for 804. Unique Morse Code Words 804. Unique Morse Code Words: https://leetcode.com/problems/unique-morse-code-words/ --- go/unique-morse-code-words.go | 16 ++++++++++++++++ go/unique-morse-code-words_test.go | 9 +++++++++ 2 files changed, 25 insertions(+) create mode 100644 go/unique-morse-code-words.go create mode 100644 go/unique-morse-code-words_test.go diff --git a/go/unique-morse-code-words.go b/go/unique-morse-code-words.go new file mode 100644 index 0000000..b062b4a --- /dev/null +++ b/go/unique-morse-code-words.go @@ -0,0 +1,16 @@ +package leetcode + +import "strings" + +func uniqueMorseRepresentations(words []string) int { + morse := []string{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."} + set := make(map[string]struct{}) + for _, w := range words { + b := strings.Builder{} + for _, c := range w { + b.WriteString(morse[c-'a']) + } + set[b.String()] = struct{}{} + } + return len(set) +} diff --git a/go/unique-morse-code-words_test.go b/go/unique-morse-code-words_test.go new file mode 100644 index 0000000..f97be70 --- /dev/null +++ b/go/unique-morse-code-words_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestUniqueMorseRepresentations(t *testing.T) { + if uniqueMorseRepresentations([]string{"gin", "zen", "gig", "msg"}) != 2 { + t.Fatal() + } +} From 628a2d8a6aa8e84a2f23a892d18791a886c6fdd5 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 17:44:36 +0800 Subject: [PATCH 102/220] Add go solution for 832. Flipping an Image 832. Flipping an Image: https://leetcode.com/problems/flipping-an-image/ --- go/flipping-an-image.go | 17 +++++++++++++++++ go/flipping-an-image_test.go | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 go/flipping-an-image.go create mode 100644 go/flipping-an-image_test.go diff --git a/go/flipping-an-image.go b/go/flipping-an-image.go new file mode 100644 index 0000000..fb686ab --- /dev/null +++ b/go/flipping-an-image.go @@ -0,0 +1,17 @@ +package leetcode + +func flipAndInvertImage(A [][]int) [][]int { + for _, row := range A { + l := len(row) + i, j := 0, l-1 + for i < j { + row[i], row[j] = row[j]^1, row[i]^1 + i++ + j-- + } + if i == j { + row[i] ^= 1 + } + } + return A +} diff --git a/go/flipping-an-image_test.go b/go/flipping-an-image_test.go new file mode 100644 index 0000000..42db77a --- /dev/null +++ b/go/flipping-an-image_test.go @@ -0,0 +1,19 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestFlipAndInvertImage(t *testing.T) { + prob1 := [][]int{[]int{1, 1, 0}, []int{1, 0, 1}, []int{0, 0, 0}} + ans1 := [][]int{[]int{1, 0, 0}, []int{0, 1, 0}, []int{1, 1, 1}} + if !reflect.DeepEqual(flipAndInvertImage(prob1), ans1) { + t.Fatal() + } + prob2 := [][]int{[]int{1, 1, 0, 0}, []int{1, 0, 0, 1}, []int{0, 1, 1, 1}, []int{1, 0, 1, 0}} + ans2 := [][]int{[]int{1, 1, 0, 0}, []int{0, 1, 1, 0}, []int{0, 0, 0, 1}, []int{1, 0, 1, 0}} + if !reflect.DeepEqual(flipAndInvertImage(prob2), ans2) { + t.Fatal() + } +} From 2d2aad6c2939425dd4a8703cedfd7761026d1d50 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 18:04:20 +0800 Subject: [PATCH 103/220] Add go solution for 905. Sort Array By Parity 905. Sort Array By Parity: https://leetcode.com/problems/sort-array-by-parity/ --- go/sort-array-by-parity.go | 14 ++++++++++++++ go/sort-array-by-parity_test.go | 12 ++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 go/sort-array-by-parity.go create mode 100644 go/sort-array-by-parity_test.go diff --git a/go/sort-array-by-parity.go b/go/sort-array-by-parity.go new file mode 100644 index 0000000..d9ee732 --- /dev/null +++ b/go/sort-array-by-parity.go @@ -0,0 +1,14 @@ +package leetcode + +func sortArrayByParity(A []int) []int { + i, j := 0, len(A)-1 + for i < j { + if A[i]&1 == 1 { + A[i], A[j] = A[j], A[i] + j-- + } else { + i++ + } + } + return A +} diff --git a/go/sort-array-by-parity_test.go b/go/sort-array-by-parity_test.go new file mode 100644 index 0000000..cc4f458 --- /dev/null +++ b/go/sort-array-by-parity_test.go @@ -0,0 +1,12 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestSortArrayByParity(t *testing.T) { + if !reflect.DeepEqual(sortArrayByParity([]int{3, 1, 2, 4}), []int{4, 2, 1, 3}) { + t.Fatal() + } +} From 2921a4608abc8df966e8a5469ae5186f57ff9e18 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 18:37:42 +0800 Subject: [PATCH 104/220] Add go solution for 961. N-Repeated Element in Size 2N Array 961. N-Repeated Element in Size 2N Array: https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ --- go/n-repeated-element-in-size-2n-array.go | 17 +++++++++++++++++ ...-repeated-element-in-size-2n-array_test.go | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 go/n-repeated-element-in-size-2n-array.go create mode 100644 go/n-repeated-element-in-size-2n-array_test.go diff --git a/go/n-repeated-element-in-size-2n-array.go b/go/n-repeated-element-in-size-2n-array.go new file mode 100644 index 0000000..5fd0364 --- /dev/null +++ b/go/n-repeated-element-in-size-2n-array.go @@ -0,0 +1,17 @@ +package leetcode + +func repeatedNTimes(A []int) int { + l := len(A) + if A[0] == A[2] { + return A[0] + } + if A[1] == A[3] { + return A[1] + } + for i := 0; i < l-1; i++ { + if A[i] == A[i+1] { + return A[i] + } + } + return A[0] +} diff --git a/go/n-repeated-element-in-size-2n-array_test.go b/go/n-repeated-element-in-size-2n-array_test.go new file mode 100644 index 0000000..81ba7c3 --- /dev/null +++ b/go/n-repeated-element-in-size-2n-array_test.go @@ -0,0 +1,19 @@ +package leetcode + +import ( + "fmt" + "testing" +) + +func TestRepeatedNTimes(t *testing.T) { + fmt.Println(repeatedNTimes([]int{1, 2, 3, 3})) + if repeatedNTimes([]int{1, 2, 3, 3}) != 3 { + t.Fatal() + } + if repeatedNTimes([]int{2, 1, 2, 5, 3, 2}) != 2 { + t.Fatal() + } + if repeatedNTimes([]int{5, 1, 5, 2, 5, 3, 5, 4}) != 5 { + t.Fatal() + } +} From 723d010c7d079d7dca4131a53f96796e9f5c30fb Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 18:43:46 +0800 Subject: [PATCH 105/220] Add go solution for 657. Robot Return to Origin 657. Robot Return to Origin: https://leetcode.com/problems/robot-return-to-origin/ --- go/robot-return-to-origin.go | 18 ++++++++++++++++++ go/robot-return-to-origin_test.go | 12 ++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 go/robot-return-to-origin.go create mode 100644 go/robot-return-to-origin_test.go diff --git a/go/robot-return-to-origin.go b/go/robot-return-to-origin.go new file mode 100644 index 0000000..4de2b5e --- /dev/null +++ b/go/robot-return-to-origin.go @@ -0,0 +1,18 @@ +package leetcode + +func judgeCircle(moves string) bool { + h, v := 0, 0 + for _, c := range moves { + switch c { + case 'U': + v++ + case 'D': + v-- + case 'L': + h-- + case 'R': + h++ + } + } + return h == 0 && v == 0 +} diff --git a/go/robot-return-to-origin_test.go b/go/robot-return-to-origin_test.go new file mode 100644 index 0000000..fb1aed4 --- /dev/null +++ b/go/robot-return-to-origin_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestJudgeCircle(t *testing.T) { + if judgeCircle("UD") != true { + t.Fatal() + } + if judgeCircle("LL") != false { + t.Fatal() + } +} From 539ff514bfb4a7ab8d512cd3b5b20906c07ebb9c Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 18:56:41 +0800 Subject: [PATCH 106/220] Add go solution for 728. Self Dividing Numbers 728. Self Dividing Numbers: https://leetcode.com/problems/self-dividing-numbers/ --- go/self-dividing-numbers.go | 19 +++++++++++++++++++ go/self-dividing-numbers_test.go | 12 ++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 go/self-dividing-numbers.go create mode 100644 go/self-dividing-numbers_test.go diff --git a/go/self-dividing-numbers.go b/go/self-dividing-numbers.go new file mode 100644 index 0000000..4c46c49 --- /dev/null +++ b/go/self-dividing-numbers.go @@ -0,0 +1,19 @@ +package leetcode + +func selfDividingNumbers(left int, right int) []int { + ans := make([]int, 0, right-left+1) + for n := left; n <= right; n++ { + t := n + for t > 0 { + v := t % 10 + if v == 0 || n%v != 0 { + break + } + t /= 10 + } + if t == 0 { + ans = append(ans, n) + } + } + return ans +} diff --git a/go/self-dividing-numbers_test.go b/go/self-dividing-numbers_test.go new file mode 100644 index 0000000..da60521 --- /dev/null +++ b/go/self-dividing-numbers_test.go @@ -0,0 +1,12 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestSelfDividingNumbers(t *testing.T) { + if !reflect.DeepEqual(selfDividingNumbers(1, 22), []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22}) { + t.Fatal() + } +} From 94a68d403350ba3bd9af10f56a27b86d37d4fb8c Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 19:11:14 +0800 Subject: [PATCH 107/220] Add go solution for 617. Merge Two Binary Trees 617. Merge Two Binary Trees: https://leetcode.com/problems/merge-two-binary-trees/ --- go/merge-two-binary-trees.go | 19 ++++++++++ go/merge-two-binary-trees_test.go | 58 +++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 go/merge-two-binary-trees.go create mode 100644 go/merge-two-binary-trees_test.go diff --git a/go/merge-two-binary-trees.go b/go/merge-two-binary-trees.go new file mode 100644 index 0000000..bc9bed9 --- /dev/null +++ b/go/merge-two-binary-trees.go @@ -0,0 +1,19 @@ +package leetcode + +func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode { + if t1 == nil && t2 == nil { + return nil + } + if t1 != nil && t2 != nil { + ans := &TreeNode{} + ans.Val = t1.Val + t2.Val + ans.Left = mergeTrees(t1.Left, t2.Left) + ans.Right = mergeTrees(t1.Right, t2.Right) + return ans + } else if t1 != nil { + return t1 + } else if t2 != nil { + return t2 + } + return nil +} diff --git a/go/merge-two-binary-trees_test.go b/go/merge-two-binary-trees_test.go new file mode 100644 index 0000000..0bf9027 --- /dev/null +++ b/go/merge-two-binary-trees_test.go @@ -0,0 +1,58 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestMergeTrees(t *testing.T) { + t1 := &TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 3, + Left: &TreeNode{ + Val: 5, + }, + }, + Right: &TreeNode{ + Val: 2, + }, + } + t2 := &TreeNode{ + Val: 2, + Left: &TreeNode{ + Val: 1, + Right: &TreeNode{ + Val: 4, + }, + }, + Right: &TreeNode{ + Val: 3, + Right: &TreeNode{ + Val: 7, + }, + }, + } + merged := mergeTrees(t1, t2) + if !reflect.DeepEqual(merged, &TreeNode{ + Val: 3, + Left: &TreeNode{ + Val: 4, + Left: &TreeNode{ + Val: 5, + }, + Right: &TreeNode{ + Val: 4, + }, + }, + Right: &TreeNode{ + Val: 5, + Right: &TreeNode{ + Val: 7, + }, + }, + }) { + t.Logf("%v", merged) + t.Fatal() + } +} From 47a8caa862733ee36b7e00173ec7c16c4ccd8f55 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Wed, 25 Dec 2019 19:25:21 +0800 Subject: [PATCH 108/220] Add go solution for 977. Squares of a Sorted Array 977. Squares of a Sorted Array: https://leetcode.com/problems/squares-of-a-sorted-array/ --- go/squares-of-a-sorted-array.go | 19 +++++++++++++++++++ go/squares-of-a-sorted-array_test.go | 15 +++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 go/squares-of-a-sorted-array.go create mode 100644 go/squares-of-a-sorted-array_test.go diff --git a/go/squares-of-a-sorted-array.go b/go/squares-of-a-sorted-array.go new file mode 100644 index 0000000..8343d4d --- /dev/null +++ b/go/squares-of-a-sorted-array.go @@ -0,0 +1,19 @@ +package leetcode + +func sortedSquares(A []int) []int { + ans := make([]int, len(A)) + i, j := 0, len(A)-1 + p := len(A) - 1 + for p >= 0 { + i2, j2 := A[i]*A[i], A[j]*A[j] + if i2 > j2 { + ans[p] = i2 + i++ + } else { + ans[p] = j2 + j-- + } + p-- + } + return ans +} diff --git a/go/squares-of-a-sorted-array_test.go b/go/squares-of-a-sorted-array_test.go new file mode 100644 index 0000000..23d48b0 --- /dev/null +++ b/go/squares-of-a-sorted-array_test.go @@ -0,0 +1,15 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestSortedSquares(t *testing.T) { + if !reflect.DeepEqual(sortedSquares([]int{-4, -1, 0, 3, 10}), []int{0, 1, 9, 16, 100}) { + t.Fatal() + } + if !reflect.DeepEqual(sortedSquares([]int{-7, -3, 2, 3, 11}), []int{4, 9, 9, 49, 121}) { + t.Fatal() + } +} From cacfc0e9c623609f1d6d011922621e8594992664 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 15:09:49 +0800 Subject: [PATCH 109/220] Add go solution for 1207. Unique Number of Occurrences 1207. Unique Number of Occurrences: https://leetcode.com/problems/unique-number-of-occurrences/ --- go/unique-number-of-occurrences.go | 16 ++++++++++++++++ go/unique-number-of-occurrences_test.go | 15 +++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 go/unique-number-of-occurrences.go create mode 100644 go/unique-number-of-occurrences_test.go diff --git a/go/unique-number-of-occurrences.go b/go/unique-number-of-occurrences.go new file mode 100644 index 0000000..0193c27 --- /dev/null +++ b/go/unique-number-of-occurrences.go @@ -0,0 +1,16 @@ +package leetcode + +func uniqueOccurrences(arr []int) bool { + counter := make(map[int]int) + for _, v := range arr { + counter[v]++ + } + vals := make(map[int]struct{}) + for _, v := range counter { + if _, ok := vals[v]; ok { + return false + } + vals[v] = struct{}{} + } + return true +} diff --git a/go/unique-number-of-occurrences_test.go b/go/unique-number-of-occurrences_test.go new file mode 100644 index 0000000..7b5f992 --- /dev/null +++ b/go/unique-number-of-occurrences_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestUniqueOccurrences(t *testing.T) { + if uniqueOccurrences([]int{1, 2, 2, 1, 1, 3}) != true { + t.Fatal() + } + if uniqueOccurrences([]int{1, 2}) != false { + t.Fatal() + } + if uniqueOccurrences([]int{-3, 0, 1, -3, 1, 1, 1, -3, 10, 0}) != true { + t.Fatal() + } +} From 3b85e2e5063c0e50923ea9f80513f20b6a74a78b Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 15:18:41 +0800 Subject: [PATCH 110/220] Add go solution for 461. Hamming Distance 461. Hamming Distance: https://leetcode.com/problems/hamming-distance/ --- go/hamming-distance.go | 11 +++++++++++ go/hamming-distance_test.go | 9 +++++++++ 2 files changed, 20 insertions(+) create mode 100644 go/hamming-distance.go create mode 100644 go/hamming-distance_test.go diff --git a/go/hamming-distance.go b/go/hamming-distance.go new file mode 100644 index 0000000..ab26d29 --- /dev/null +++ b/go/hamming-distance.go @@ -0,0 +1,11 @@ +package leetcode + +func hammingDistance(x int, y int) int { + xor := x ^ y + xor = (xor & 0x55555555) + ((xor >> 1) & 0x55555555) + xor = (xor & 0x33333333) + ((xor >> 2) & 0x33333333) + xor = (xor & 0x0f0f0f0f) + ((xor >> 4) & 0x0f0f0f0f) + xor = (xor & 0x00ff00ff) + ((xor >> 8) & 0x00ff00ff) + xor = (xor & 0x0000ffff) + ((xor >> 16) & 0x0000ffff) + return xor +} diff --git a/go/hamming-distance_test.go b/go/hamming-distance_test.go new file mode 100644 index 0000000..71d9ba2 --- /dev/null +++ b/go/hamming-distance_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestHammingDistance(t *testing.T) { + if hammingDistance(1, 4) != 2 { + t.Fatal() + } +} From fe15027175fe56482c4408d0f0676d6fd9c6d9e7 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 15:22:18 +0800 Subject: [PATCH 111/220] Add go solution for 561. Array Partition I 561. Array Partition I: https://leetcode.com/problems/array-partition-i/ --- go/array-partition-i.go | 13 +++++++++++++ go/array-partition-i_test.go | 9 +++++++++ 2 files changed, 22 insertions(+) create mode 100644 go/array-partition-i.go create mode 100644 go/array-partition-i_test.go diff --git a/go/array-partition-i.go b/go/array-partition-i.go new file mode 100644 index 0000000..e62f3a5 --- /dev/null +++ b/go/array-partition-i.go @@ -0,0 +1,13 @@ +package leetcode + +import "sort" + +func arrayPairSum(nums []int) int { + sort.Ints(nums) + l := len(nums) + ans := 0 + for i := 0; i < l; i += 2 { + ans += nums[i] + } + return ans +} diff --git a/go/array-partition-i_test.go b/go/array-partition-i_test.go new file mode 100644 index 0000000..ec0e623 --- /dev/null +++ b/go/array-partition-i_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestArrayPairSum(t *testing.T) { + if arrayPairSum([]int{1, 4, 3, 2}) != 4 { + t.Fatal() + } +} From 6f4f44f156af9542675798911f7f0660e6349ed7 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 15:32:05 +0800 Subject: [PATCH 112/220] Add go solution for 852. Peak Index in a Mountain Array 852. Peak Index in a Mountain Array: https://leetcode.com/problems/peak-index-in-a-mountain-array/ --- go/peak-index-in-a-mountain-array.go | 22 ++++++++++++++++++++++ go/peak-index-in-a-mountain-array_test.go | 12 ++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 go/peak-index-in-a-mountain-array.go create mode 100644 go/peak-index-in-a-mountain-array_test.go diff --git a/go/peak-index-in-a-mountain-array.go b/go/peak-index-in-a-mountain-array.go new file mode 100644 index 0000000..758878d --- /dev/null +++ b/go/peak-index-in-a-mountain-array.go @@ -0,0 +1,22 @@ +package leetcode + +func peakIndexInMountainArray(A []int) int { + length := len(A) + if A[0] > A[1] { + return 0 + } + if A[length-2] < A[length-1] { + return length - 1 + } + + L, U := 0, len(A)-1 + for L+1 < U { + mid := (L + U) / 2 + if A[mid-1] > A[mid] { + U = mid + } else { + L = mid + } + } + return L +} diff --git a/go/peak-index-in-a-mountain-array_test.go b/go/peak-index-in-a-mountain-array_test.go new file mode 100644 index 0000000..e3269a6 --- /dev/null +++ b/go/peak-index-in-a-mountain-array_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestPeakIndexInMountainArray(t *testing.T) { + if peakIndexInMountainArray([]int{0, 1, 0}) != 1 { + t.Fatal() + } + if peakIndexInMountainArray([]int{0, 2, 1, 0}) != 1 { + t.Fatal() + } +} From 27ee8ac33d89e279b309646c09098b0ed6751f34 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 15:47:38 +0800 Subject: [PATCH 113/220] Add go solution for 942. DI String Match 942. DI String Match: https://leetcode.com/problems/di-string-match/ --- go/di-string-match.go | 22 ++++++++++++++++++++++ go/di-string-match_test.go | 18 ++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 go/di-string-match.go create mode 100644 go/di-string-match_test.go diff --git a/go/di-string-match.go b/go/di-string-match.go new file mode 100644 index 0000000..8ee9ea6 --- /dev/null +++ b/go/di-string-match.go @@ -0,0 +1,22 @@ +package leetcode + +func diStringMatch(S string) []int { + l := len(S) + L, U := 0, 0 + ans := make([]int, l+1) + for i, c := range S { + if c == 'I' { + U += 1 + ans[i+1] = U + } else if c == 'D' { + L -= 1 + ans[i+1] = L + } else { + panic("Impossible") + } + } + for i := 0; i < l+1; i++ { + ans[i] -= L + } + return ans +} diff --git a/go/di-string-match_test.go b/go/di-string-match_test.go new file mode 100644 index 0000000..1bc200b --- /dev/null +++ b/go/di-string-match_test.go @@ -0,0 +1,18 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestDiStringMatch(t *testing.T) { + if !reflect.DeepEqual(diStringMatch("IDID"), []int{2, 3, 1, 4, 0}) { + t.Fatal() + } + if !reflect.DeepEqual(diStringMatch("III"), []int{0, 1, 2, 3}) { + t.Fatal() + } + if !reflect.DeepEqual(diStringMatch("DDI"), []int{2, 1, 0, 3}) { + t.Fatal() + } +} From 771cca5f28ace79212f9d5651097f4a09b9b5f21 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 15:55:44 +0800 Subject: [PATCH 114/220] Add go solution for 700. Search in a Binary Search Tree 700. Search in a Binary Search Tree: https://leetcode.com/problems/search-in-a-binary-search-tree/ --- go/search-in-a-binary-search-tree.go | 14 ++++++++ go/search-in-a-binary-search-tree_test.go | 39 +++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 go/search-in-a-binary-search-tree.go create mode 100644 go/search-in-a-binary-search-tree_test.go diff --git a/go/search-in-a-binary-search-tree.go b/go/search-in-a-binary-search-tree.go new file mode 100644 index 0000000..6b5de89 --- /dev/null +++ b/go/search-in-a-binary-search-tree.go @@ -0,0 +1,14 @@ +package leetcode + +func searchBST(root *TreeNode, val int) *TreeNode { + if root == nil { + return nil + } + if root.Val > val { + return searchBST(root.Left, val) + } else if root.Val < val { + return searchBST(root.Right, val) + } else { + return root + } +} diff --git a/go/search-in-a-binary-search-tree_test.go b/go/search-in-a-binary-search-tree_test.go new file mode 100644 index 0000000..aa074f4 --- /dev/null +++ b/go/search-in-a-binary-search-tree_test.go @@ -0,0 +1,39 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestSearchBST(t *testing.T) { + tree := &TreeNode{ + Val: 4, + Left: &TreeNode{ + Val: 2, + Left: &TreeNode{ + Val: 1, + }, + Right: &TreeNode{ + Val: 3, + }, + }, + Right: &TreeNode{ + Val: 7, + }, + } + if !reflect.DeepEqual(searchBST(tree, 2), &TreeNode{ + Val: 2, + Left: &TreeNode{ + Val: 1, + }, + Right: &TreeNode{ + Val: 3, + }, + }) { + t.Fatal() + } + + if searchBST(tree, 5) != nil { + t.Fatal() + } +} From 641eafd3db250432ae1c65a51315304e8cf202b2 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 16:12:44 +0800 Subject: [PATCH 115/220] Add go solution for 933. Number of Recent Calls 933. Number of Recent Calls: https://leetcode.com/problems/number-of-recent-calls/ --- go/number-of-recent-calls.go | 19 +++++++++++++++++++ go/number-of-recent-calls_test.go | 14 ++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 go/number-of-recent-calls.go create mode 100644 go/number-of-recent-calls_test.go diff --git a/go/number-of-recent-calls.go b/go/number-of-recent-calls.go new file mode 100644 index 0000000..b1656ec --- /dev/null +++ b/go/number-of-recent-calls.go @@ -0,0 +1,19 @@ +package leetcode + +type RecentCounter struct { + buffer []int + offset int +} + +func Constructor() RecentCounter { + return RecentCounter{buffer: []int{}} +} + +func (this *RecentCounter) Ping(t int) int { + for this.offset < len(this.buffer) && this.buffer[this.offset]+3000 < t { + this.offset++ + } + this.buffer = append(this.buffer, t) + ans := len(this.buffer) - this.offset + return ans +} diff --git a/go/number-of-recent-calls_test.go b/go/number-of-recent-calls_test.go new file mode 100644 index 0000000..08d3fd4 --- /dev/null +++ b/go/number-of-recent-calls_test.go @@ -0,0 +1,14 @@ +package leetcode + +import "testing" + +func TestRecentCounter(t *testing.T) { + obj := Constructor() + inputs := []int{1, 100, 3001, 3002} + expected := []int{1, 2, 3, 3} + for i := 0; i < 4; i++ { + if obj.Ping(inputs[i]) != expected[i] { + t.Fatal() + } + } +} From 1c20cfe152b0bcb5e0bec8ea7b112d2987252cf0 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 16:20:13 +0800 Subject: [PATCH 116/220] Add go solution for 944. Delete Columns to Make Sorted 944. Delete Columns to Make Sorted: https://leetcode.com/problems/delete-columns-to-make-sorted/ --- go/delete-columns-to-make-sorted.go | 16 ++++++++++++++++ go/delete-columns-to-make-sorted_test.go | 15 +++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 go/delete-columns-to-make-sorted.go create mode 100644 go/delete-columns-to-make-sorted_test.go diff --git a/go/delete-columns-to-make-sorted.go b/go/delete-columns-to-make-sorted.go new file mode 100644 index 0000000..2cd1917 --- /dev/null +++ b/go/delete-columns-to-make-sorted.go @@ -0,0 +1,16 @@ +package leetcode + +func minDeletionSize(A []string) int { + n := len(A) + l := len(A[0]) + ans := 0 + for i := 0; i < l; i++ { + for j := 1; j < n; j++ { + if A[j][i] < A[j-1][i] { + ans += 1 + break + } + } + } + return ans +} diff --git a/go/delete-columns-to-make-sorted_test.go b/go/delete-columns-to-make-sorted_test.go new file mode 100644 index 0000000..5af2233 --- /dev/null +++ b/go/delete-columns-to-make-sorted_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestMinDeletionSize(t *testing.T) { + if minDeletionSize([]string{"cba", "daf", "ghi"}) != 1 { + t.Fatal() + } + if minDeletionSize([]string{"a", "b"}) != 0 { + t.Fatal() + } + if minDeletionSize([]string{"zyx", "wuv", "tsr"}) != 3 { + t.Fatal() + } +} From 828b0dee0760b3e1bad0801438b4f37cfc4d36ce Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 16:42:56 +0800 Subject: [PATCH 117/220] Add go solution for 1051. Height Checker 1051. Height Checker: https://leetcode.com/problems/height-checker/ --- go/height-checker.go | 19 +++++++++++++++++++ go/height-checker_test.go | 11 +++++++++++ 2 files changed, 30 insertions(+) create mode 100644 go/height-checker.go create mode 100644 go/height-checker_test.go diff --git a/go/height-checker.go b/go/height-checker.go new file mode 100644 index 0000000..56bed78 --- /dev/null +++ b/go/height-checker.go @@ -0,0 +1,19 @@ +package leetcode + +func heightChecker(heights []int) int { + counter := make([]int, 101) + for _, n := range heights { + counter[n]++ + } + offset := 0 + ans := 0 + for i := 1; i <= 100; i++ { + for j := 0; j < counter[i]; j++ { + if heights[offset] != i { + ans++ + } + offset++ + } + } + return ans +} diff --git a/go/height-checker_test.go b/go/height-checker_test.go new file mode 100644 index 0000000..28c9d1a --- /dev/null +++ b/go/height-checker_test.go @@ -0,0 +1,11 @@ +package leetcode + +import ( + "testing" +) + +func TestHeightChecker(t *testing.T) { + if heightChecker([]int{1, 1, 4, 2, 1, 3}) != 3 { + t.Fatal() + } +} From cfdf16b431bf0ee197d8c0167f7038eccd057822 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 16:51:13 +0800 Subject: [PATCH 118/220] Add go solution for 929. Unique Email Addresses 929. Unique Email Addresses: https://leetcode.com/problems/unique-email-addresses/ --- go/unique-email-addresses.go | 17 +++++++++++++++++ go/unique-email-addresses_test.go | 14 ++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 go/unique-email-addresses.go create mode 100644 go/unique-email-addresses_test.go diff --git a/go/unique-email-addresses.go b/go/unique-email-addresses.go new file mode 100644 index 0000000..fdb83e5 --- /dev/null +++ b/go/unique-email-addresses.go @@ -0,0 +1,17 @@ +package leetcode + +import "strings" + +func numUniqueEmails(emails []string) int { + set := make(map[string]struct{}) + for _, email := range emails { + plus := strings.Index(email, "+") + at := strings.Index(email, "@") + if plus == -1 { + plus = at + } + x := strings.Replace(email[:plus], ".", "", -1) + email[at:] + set[x] = struct{}{} + } + return len(set) +} diff --git a/go/unique-email-addresses_test.go b/go/unique-email-addresses_test.go new file mode 100644 index 0000000..94f6f15 --- /dev/null +++ b/go/unique-email-addresses_test.go @@ -0,0 +1,14 @@ +package leetcode + +import "testing" + +func TestNumUniqueEmails(t *testing.T) { + if numUniqueEmails([]string{ + "test.email@leetcode.com", + "test.email+alex@leetcode.com", + "test.e.mail+bob.cathy@leetcode.com", + "testemail+david@lee.tcode.com", + }) != 2 { + t.Fatal() + } +} From 6c8a5c3098f561960a60b82b682f367b98900902 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 17:00:02 +0800 Subject: [PATCH 119/220] Add go solution for 922. Sort Array By Parity II 922. Sort Array By Parity II: https://leetcode.com/problems/sort-array-by-parity-ii/ --- go/sort-array-by-parity-ii.go | 18 ++++++++++++++++++ go/sort-array-by-parity-ii_test.go | 12 ++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 go/sort-array-by-parity-ii.go create mode 100644 go/sort-array-by-parity-ii_test.go diff --git a/go/sort-array-by-parity-ii.go b/go/sort-array-by-parity-ii.go new file mode 100644 index 0000000..35880fc --- /dev/null +++ b/go/sort-array-by-parity-ii.go @@ -0,0 +1,18 @@ +package leetcode + +func sortArrayByParityII(A []int) []int { + l := len(A) + i, j := 0, 1 + for i < l && j < l { + if A[i]&1 == 0 { + i += 2 + } else if A[j]&1 == 1 { + j += 2 + } else { + A[i], A[j] = A[j], A[i] + i += 2 + j += 2 + } + } + return A +} diff --git a/go/sort-array-by-parity-ii_test.go b/go/sort-array-by-parity-ii_test.go new file mode 100644 index 0000000..e990693 --- /dev/null +++ b/go/sort-array-by-parity-ii_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestSortArrayByParityII(t *testing.T) { + ans := sortArrayByParityII([]int{4, 2, 5, 7}) + for i, v := range ans { + if (i^v)&1 != 0 { + t.Fatal() + } + } +} From 8771c0055246023a61dad5a13fc74ac7d48ea76b Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 17:36:49 +0800 Subject: [PATCH 120/220] Add go solution for 811. Subdomain Visit Count 811. Subdomain Visit Count: https://leetcode.com/problems/subdomain-visit-count/ --- go/subdomain-visit-count.go | 33 +++++++++++++++++++++++++++ go/subdomain-visit-count_test.go | 39 ++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 go/subdomain-visit-count.go create mode 100644 go/subdomain-visit-count_test.go diff --git a/go/subdomain-visit-count.go b/go/subdomain-visit-count.go new file mode 100644 index 0000000..84a60da --- /dev/null +++ b/go/subdomain-visit-count.go @@ -0,0 +1,33 @@ +package leetcode + +import ( + "fmt" + "strconv" + "strings" +) + +func subdomainVisits(cpdomains []string) []string { + counter := make(map[string]int) + for _, s := range cpdomains { + sp := strings.Split(s, " ") + n, err := strconv.Atoi(sp[0]) + if err != nil { + panic("Impossible") + } + url := sp[1] + idx := 0 + for { + counter[url[idx:]] += n + nxtIdx := strings.IndexRune(url[idx:], '.') + if nxtIdx == -1 { + break + } + idx += nxtIdx + 1 + } + } + ans := make([]string, 0, len(counter)) + for k, v := range counter { + ans = append(ans, fmt.Sprintf("%d %s", v, k)) + } + return ans +} diff --git a/go/subdomain-visit-count_test.go b/go/subdomain-visit-count_test.go new file mode 100644 index 0000000..c52d128 --- /dev/null +++ b/go/subdomain-visit-count_test.go @@ -0,0 +1,39 @@ +package leetcode + +import ( + "reflect" + "sort" + "testing" +) + +func TestSubdomainVisits(t *testing.T) { + ans1 := subdomainVisits([]string{"9001 discuss.leetcode.com"}) + sort.Strings(ans1) + if !reflect.DeepEqual(ans1, + []string{ + "9001 com", + "9001 discuss.leetcode.com", + "9001 leetcode.com", + }) { + t.Fatal() + } + ans2 := subdomainVisits([]string{ + "900 google.mail.com", + "50 yahoo.com", + "1 intel.mail.com", + "5 wiki.org", + }) + sort.Strings(ans2) + if !reflect.DeepEqual(ans2, + []string{ + "1 intel.mail.com", + "5 org", + "5 wiki.org", + "50 yahoo.com", + "900 google.mail.com", + "901 mail.com", + "951 com", + }) { + t.Fatal() + } +} From 48ef53b68d71e5ff5bc359891da75e04a42372b9 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 17:43:28 +0800 Subject: [PATCH 121/220] Add go solution for 965. Univalued Binary Tree 965. Univalued Binary Tree: https://leetcode.com/problems/univalued-binary-tree/ --- go/univalued-binary-tree.go | 18 +++++++++++++ go/univalued-binary-tree_test.go | 45 ++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 go/univalued-binary-tree.go create mode 100644 go/univalued-binary-tree_test.go diff --git a/go/univalued-binary-tree.go b/go/univalued-binary-tree.go new file mode 100644 index 0000000..2b59de6 --- /dev/null +++ b/go/univalued-binary-tree.go @@ -0,0 +1,18 @@ +package leetcode + +func isUnivalTree(root *TreeNode) bool { + if root == nil { + return true + } + if root.Left != nil { + if root.Left.Val != root.Val || !isUnivalTree(root.Left) { + return false + } + } + if root.Right != nil { + if root.Right.Val != root.Val || !isUnivalTree(root.Right) { + return false + } + } + return true +} diff --git a/go/univalued-binary-tree_test.go b/go/univalued-binary-tree_test.go new file mode 100644 index 0000000..d4961a3 --- /dev/null +++ b/go/univalued-binary-tree_test.go @@ -0,0 +1,45 @@ +package leetcode + +import "testing" + +func TestIsUnivalTree(t *testing.T) { + tree1 := &TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 1, + }, + Right: &TreeNode{ + Val: 1, + }, + }, + Right: &TreeNode{ + Val: 1, + Right: &TreeNode{ + Val: 1, + }, + }, + } + if isUnivalTree(tree1) != true { + t.Fatal() + } + tree2 := &TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 5, + }, + Right: &TreeNode{ + Val: 1, + }, + }, + Right: &TreeNode{ + Val: 1, + }, + } + if isUnivalTree(tree2) != false { + t.Fatal() + } +} From 023fa2043ff2f73f7b37839655a08bb5274f3c24 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 18:08:37 +0800 Subject: [PATCH 122/220] Add go solution for 1160. Find Words That Can Be Formed by Characters 1160. Find Words That Can Be Formed by Characters: https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/ --- ...-words-that-can-be-formed-by-characters.go | 21 +++++++++++++++++++ ...s-that-can-be-formed-by-characters_test.go | 12 +++++++++++ 2 files changed, 33 insertions(+) create mode 100644 go/find-words-that-can-be-formed-by-characters.go create mode 100644 go/find-words-that-can-be-formed-by-characters_test.go diff --git a/go/find-words-that-can-be-formed-by-characters.go b/go/find-words-that-can-be-formed-by-characters.go new file mode 100644 index 0000000..5589d6d --- /dev/null +++ b/go/find-words-that-can-be-formed-by-characters.go @@ -0,0 +1,21 @@ +package leetcode + +func countCharacters(words []string, chars string) int { + counter := make(map[rune]int) + for _, c := range chars { + counter[c] += 1 + } + ans := 0 + for _, w := range words { + ans += len(w) + c2 := make(map[rune]int) + for _, c := range w { + c2[c] += 1 + if c2[c] > counter[c] { + ans -= len(w) + break + } + } + } + return ans +} diff --git a/go/find-words-that-can-be-formed-by-characters_test.go b/go/find-words-that-can-be-formed-by-characters_test.go new file mode 100644 index 0000000..7de2226 --- /dev/null +++ b/go/find-words-that-can-be-formed-by-characters_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestCountCharacters(t *testing.T) { + if countCharacters([]string{"cat", "bt", "hat", "tree"}, "atach") != 6 { + t.Fatal() + } + if countCharacters([]string{"hello", "world", "leetcode"}, "welldonehoneyr") != 10 { + t.Fatal() + } +} From 4c31f088c5bb555889ed6bf146c37dce411d26e5 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 18:21:39 +0800 Subject: [PATCH 123/220] Add go solution for 883. Projection Area of 3D Shapes 883. Projection Area of 3D Shapes: https://leetcode.com/problems/projection-area-of-3d-shapes/ --- go/projection-area-of-3d-shapes.go | 29 +++++++++++++++++++++++++ go/projection-area-of-3d-shapes_test.go | 24 ++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 go/projection-area-of-3d-shapes.go create mode 100644 go/projection-area-of-3d-shapes_test.go diff --git a/go/projection-area-of-3d-shapes.go b/go/projection-area-of-3d-shapes.go new file mode 100644 index 0000000..35c7764 --- /dev/null +++ b/go/projection-area-of-3d-shapes.go @@ -0,0 +1,29 @@ +package leetcode + +import "math" + +func projectionArea(grid [][]int) int { + if len(grid) == 0 { + return 0 + } + ans := 0 + rmax := make([]int, len(grid)) + cmax := make([]int, len(grid[0])) + + for i, row := range grid { + for j, v := range row { + rmax[i] = int(math.Max(float64(v), float64(rmax[i]))) + cmax[j] = int(math.Max(float64(v), float64(cmax[j]))) + if v > 0 { + ans++ + } + } + } + for _, v := range rmax { + ans += v + } + for _, v := range cmax { + ans += v + } + return ans +} diff --git a/go/projection-area-of-3d-shapes_test.go b/go/projection-area-of-3d-shapes_test.go new file mode 100644 index 0000000..6cc1ad0 --- /dev/null +++ b/go/projection-area-of-3d-shapes_test.go @@ -0,0 +1,24 @@ +package leetcode + +import "testing" + +func TestProjectionArea(t *testing.T) { + if projectionArea([][]int{[]int{1, 0}, []int{0, 2}}) != 8 { + t.Fatal() + } + if projectionArea([][]int{ + []int{1, 1, 1}, + []int{1, 0, 1}, + []int{1, 1, 1}, + }) != 14 { + t.Fatal() + } + + if projectionArea([][]int{ + []int{2, 2, 2}, + []int{2, 1, 2}, + []int{2, 2, 2}, + }) != 21 { + t.Fatal() + } +} From 7e454d21b282e6a3774749cb93ef7a58bb288703 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 18:59:51 +0800 Subject: [PATCH 124/220] Add go solution for 897. Increasing Order Search Tree 897. Increasing Order Search Tree: https://leetcode.com/problems/increasing-order-search-tree/ --- go/increasing-order-search-tree.go | 19 ++++++ go/increasing-order-search-tree_test.go | 84 +++++++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 go/increasing-order-search-tree.go create mode 100644 go/increasing-order-search-tree_test.go diff --git a/go/increasing-order-search-tree.go b/go/increasing-order-search-tree.go new file mode 100644 index 0000000..9e00963 --- /dev/null +++ b/go/increasing-order-search-tree.go @@ -0,0 +1,19 @@ +package leetcode + +func InOrder(cur *TreeNode, tail **TreeNode) { + if cur != nil { + InOrder(cur.Left, tail) + (**tail).Right = cur + (**tail).Left = nil + *tail = cur + InOrder(cur.Right, tail) + } +} + +func increasingBST(root *TreeNode) *TreeNode { + tmp := &TreeNode{} + out := tmp + InOrder(root, &tmp) + tmp.Left = nil + return out.Right +} diff --git a/go/increasing-order-search-tree_test.go b/go/increasing-order-search-tree_test.go new file mode 100644 index 0000000..953d2b0 --- /dev/null +++ b/go/increasing-order-search-tree_test.go @@ -0,0 +1,84 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestIncreasingBST(t *testing.T) { + tree := &TreeNode{ + Val: 5, + Left: &TreeNode{ + Val: 3, + Left: &TreeNode{ + Val: 2, + Left: &TreeNode{ + Val: 1, + }, + }, + Right: &TreeNode{ + Val: 4, + }, + }, + Right: &TreeNode{ + Val: 6, + Right: &TreeNode{ + Val: 8, + Left: &TreeNode{ + Val: 7, + }, + Right: &TreeNode{ + Val: 9, + }, + }, + }, + } + ans := increasingBST(tree) + if !reflect.DeepEqual(ans, &TreeNode{ + Val: 1, + Right: &TreeNode{ + Val: 2, + Right: &TreeNode{ + Val: 3, + Right: &TreeNode{ + Val: 4, + Right: &TreeNode{ + Val: 5, + Right: &TreeNode{ + Val: 6, + Right: &TreeNode{ + Val: 7, + Right: &TreeNode{ + Val: 8, + Right: &TreeNode{ + Val: 9, + }, + }, + }, + }, + }, + }, + }, + }, + }) { + t.Fatal() + } + + tree2 := &TreeNode{ + Val: 826, + Left: &TreeNode{ + Val: 379, + }, + } + + ans2 := increasingBST(tree2) + + if !reflect.DeepEqual(ans2, &TreeNode{ + Val: 379, + Right: &TreeNode{ + Val: 826, + }, + }) { + t.Fatal() + } +} From e1f201faf1e41e370ea222f362d24a261be20c4f Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 19:04:08 +0800 Subject: [PATCH 125/220] Add go solution for 509. Fibonacci Number 509. Fibonacci Number: https://leetcode.com/problems/fibonacci-number/ --- go/fibonacci-number.go | 11 +++++++++++ go/fibonacci-number_test.go | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 go/fibonacci-number.go create mode 100644 go/fibonacci-number_test.go diff --git a/go/fibonacci-number.go b/go/fibonacci-number.go new file mode 100644 index 0000000..25f3f2a --- /dev/null +++ b/go/fibonacci-number.go @@ -0,0 +1,11 @@ +package leetcode + +func fib(N int) int { + a, b := 0, 1 + fib_ary := make([]int, 31) + for i := 0; i <= 30; i++ { + fib_ary[i] = a + a, b = b, a+b + } + return fib_ary[N] +} diff --git a/go/fibonacci-number_test.go b/go/fibonacci-number_test.go new file mode 100644 index 0000000..0faf560 --- /dev/null +++ b/go/fibonacci-number_test.go @@ -0,0 +1,18 @@ +package leetcode + +import "testing" + +func TestFib(t *testing.T) { + if fib(0) != 0 { + t.Fatal() + } + if fib(2) != 1 { + t.Fatal() + } + if fib(3) != 2 { + t.Fatal() + } + if fib(4) != 3 { + t.Fatal() + } +} From 25aa3a5a6ae5870486f3421d7c29d1929885106d Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 19:24:21 +0800 Subject: [PATCH 126/220] Add go solution for 1122. Relative Sort Array 1122. Relative Sort Array: https://leetcode.com/problems/relative-sort-array/ --- go/relative-sort-array.go | 26 ++++++++++++++++++++++++++ go/relative-sort-array_test.go | 15 +++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 go/relative-sort-array.go create mode 100644 go/relative-sort-array_test.go diff --git a/go/relative-sort-array.go b/go/relative-sort-array.go new file mode 100644 index 0000000..8a7a7e6 --- /dev/null +++ b/go/relative-sort-array.go @@ -0,0 +1,26 @@ +package leetcode + +import "sort" + +func relativeSortArray(arr1 []int, arr2 []int) []int { + inv := make(map[int]int) + for idx, v := range arr2 { + inv[v] = idx + } + + sort.Slice(arr1, func(i, j int) bool { + idx1, ok1 := inv[arr1[i]] + idx2, ok2 := inv[arr1[j]] + switch { + case ok1 && ok2: + return idx1 < idx2 + case ok1: + return true + case ok2: + return false + default: + return arr1[i] < arr1[j] + } + }) + return arr1 +} diff --git a/go/relative-sort-array_test.go b/go/relative-sort-array_test.go new file mode 100644 index 0000000..9b2d8c0 --- /dev/null +++ b/go/relative-sort-array_test.go @@ -0,0 +1,15 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestRelativeSortArray(t *testing.T) { + if !reflect.DeepEqual(relativeSortArray( + []int{2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19}, + []int{2, 1, 4, 3, 9, 6}), + []int{2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19}) { + t.Fatal() + } +} From 1ffe76bb279dffc9c5bcd516ac042948e3431bd9 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 19:38:55 +0800 Subject: [PATCH 127/220] Add go solution for 1002. Find Common Characters 1002. Find Common Characters: https://leetcode.com/problems/find-common-characters/ --- go/find-common-characters.go | 23 +++++++++++++++++++++++ go/find-common-characters_test.go | 12 ++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 go/find-common-characters.go create mode 100644 go/find-common-characters_test.go diff --git a/go/find-common-characters.go b/go/find-common-characters.go new file mode 100644 index 0000000..440da73 --- /dev/null +++ b/go/find-common-characters.go @@ -0,0 +1,23 @@ +package leetcode + +func commonChars(A []string) []string { + merge := make([]int, 26) + for i, w := range A { + counter := make([]int, 26) + for _, c := range w { + counter[c-'a']++ + } + for j := 0; j < 26; j++ { + if i == 0 || merge[j] > counter[j] { + merge[j] = counter[j] + } + } + } + ans := []string{} + for i, v := range merge { + for j := 0; j < v; j++ { + ans = append(ans, string('a'+i)) + } + } + return ans +} diff --git a/go/find-common-characters_test.go b/go/find-common-characters_test.go new file mode 100644 index 0000000..6570b31 --- /dev/null +++ b/go/find-common-characters_test.go @@ -0,0 +1,12 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestCommonChars(t *testing.T) { + if !reflect.DeepEqual(commonChars([]string{"bella", "label", "roller"}), []string{"e", "l", "l"}) { + t.Fatal() + } +} From ee15294a9de4ee72b8f96fe8b1fce262e20387dd Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 26 Dec 2019 19:47:37 +0800 Subject: [PATCH 128/220] Add go solution for 1200. Minimum Absolute Difference 1200. Minimum Absolute Difference: https://leetcode.com/problems/minimum-absolute-difference/ --- go/minimum-absolute-difference.go | 21 +++++++++++++++++ go/minimum-absolute-difference_test.go | 31 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 go/minimum-absolute-difference.go create mode 100644 go/minimum-absolute-difference_test.go diff --git a/go/minimum-absolute-difference.go b/go/minimum-absolute-difference.go new file mode 100644 index 0000000..40d51ef --- /dev/null +++ b/go/minimum-absolute-difference.go @@ -0,0 +1,21 @@ +package leetcode + +import "sort" + +func minimumAbsDifference(arr []int) [][]int { + sort.Ints(arr) + l := len(arr) + diff := arr[l-1] - arr[0] + for i := 1; i < l; i++ { + if arr[i]-arr[i-1] < diff { + diff = arr[i] - arr[i-1] + } + } + ans := make([][]int, 0, l) + for i := 1; i < l; i++ { + if arr[i]-arr[i-1] == diff { + ans = append(ans, []int{arr[i-1], arr[i]}) + } + } + return ans +} diff --git a/go/minimum-absolute-difference_test.go b/go/minimum-absolute-difference_test.go new file mode 100644 index 0000000..8789c81 --- /dev/null +++ b/go/minimum-absolute-difference_test.go @@ -0,0 +1,31 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestMinimumAbsDifference(t *testing.T) { + if !reflect.DeepEqual(minimumAbsDifference([]int{4, 2, 1, 3}), + [][]int{ + []int{1, 2}, + []int{2, 3}, + []int{3, 4}, + }) { + t.Fatal() + } + if !reflect.DeepEqual(minimumAbsDifference([]int{1, 3, 6, 10, 15}), + [][]int{ + []int{1, 3}, + }) { + t.Fatal() + } + if !reflect.DeepEqual(minimumAbsDifference([]int{3, 8, -10, 23, 19, -4, -14, 27}), + [][]int{ + []int{-14, -10}, + []int{19, 23}, + []int{23, 27}, + }) { + t.Fatal() + } +} From 3b36c83c68d0371b36277a06d0bdd98e3b15e04d Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 12:26:04 +0800 Subject: [PATCH 129/220] Add go solution for 999. Available Captures for Rook 999. Available Captures for Rook: https://leetcode.com/problems/available-captures-for-rook/ --- go/available-captures-for-rook.go | 51 ++++++++++++++++++++++++++ go/available-captures-for-rook_test.go | 45 +++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 go/available-captures-for-rook.go create mode 100644 go/available-captures-for-rook_test.go diff --git a/go/available-captures-for-rook.go b/go/available-captures-for-rook.go new file mode 100644 index 0000000..3763cbd --- /dev/null +++ b/go/available-captures-for-rook.go @@ -0,0 +1,51 @@ +package leetcode + +func numRookCaptures(board [][]byte) int { + var x, y int + for i := 0; i < 8; i++ { + var j int + for j = 0; j < 8; j++ { + if board[i][j] == 'R' { + x, y = i, j + break + } + } + if j < 8 { + break + } + } + ans := 0 + for i := x - 1; i >= 0; i-- { + if board[i][y] == 'p' { + ans++ + break + } else if board[i][y] == 'B' { + break + } + } + for i := x + 1; i < 8; i++ { + if board[i][y] == 'p' { + ans++ + break + } else if board[i][y] == 'B' { + break + } + } + for i := y - 1; i >= 0; i-- { + if board[x][i] == 'p' { + ans++ + break + } else if board[x][i] == 'B' { + break + } + } + for i := y + 1; i < 8; i++ { + if board[x][i] == 'p' { + ans++ + break + } else if board[x][i] == 'B' { + break + } + } + return ans +} diff --git a/go/available-captures-for-rook_test.go b/go/available-captures-for-rook_test.go new file mode 100644 index 0000000..372f7fa --- /dev/null +++ b/go/available-captures-for-rook_test.go @@ -0,0 +1,45 @@ +package leetcode + +import "testing" + +func TestNumRookCaptures(t *testing.T) { + q1 := [][]byte{ + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + []byte{'.', '.', '.', 'p', '.', '.', '.', '.'}, + []byte{'.', '.', '.', 'R', '.', '.', '.', 'p'}, + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + []byte{'.', '.', '.', 'p', '.', '.', '.', '.'}, + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + } + if numRookCaptures(q1) != 3 { + t.Fatal() + } + q2 := [][]byte{ + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + []byte{'.', 'p', 'p', 'p', 'p', 'p', '.', '.'}, + []byte{'.', 'p', 'p', 'B', 'p', 'p', '.', '.'}, + []byte{'.', 'p', 'B', 'R', 'B', 'p', '.', '.'}, + []byte{'.', 'p', 'p', 'B', 'p', 'p', '.', '.'}, + []byte{'.', 'p', 'p', 'p', 'p', 'p', '.', '.'}, + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + } + if numRookCaptures(q2) != 0 { + t.Fatal() + } + q3 := [][]byte{ + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + []byte{'.', '.', '.', 'p', '.', '.', '.', '.'}, + []byte{'.', '.', '.', 'p', '.', '.', '.', '.'}, + []byte{'p', 'p', '.', 'R', '.', 'p', 'B', '.'}, + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + []byte{'.', '.', '.', 'B', '.', '.', '.', '.'}, + []byte{'.', '.', '.', 'p', '.', '.', '.', '.'}, + []byte{'.', '.', '.', '.', '.', '.', '.', '.'}, + } + if numRookCaptures(q3) != 3 { + t.Fatal() + } +} From 4d8d5cb2489ed1c479503fbfb96d49e2c7373d09 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 12:33:41 +0800 Subject: [PATCH 130/220] Add go solution for 876. Middle of the Linked List 876. Middle of the Linked List: https://leetcode.com/problems/middle-of-the-linked-list/ --- go/middle-of-the-linked-list.go | 22 ++++++++++ go/middle-of-the-linked-list_test.go | 66 ++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 go/middle-of-the-linked-list.go create mode 100644 go/middle-of-the-linked-list_test.go diff --git a/go/middle-of-the-linked-list.go b/go/middle-of-the-linked-list.go new file mode 100644 index 0000000..d155c7f --- /dev/null +++ b/go/middle-of-the-linked-list.go @@ -0,0 +1,22 @@ +package leetcode + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func middleNode(head *ListNode) *ListNode { + tmp := head + n := 0 + for tmp != nil { + tmp = tmp.Next + n++ + } + n /= 2 + for ; n > 0; n-- { + head = head.Next + } + return head +} diff --git a/go/middle-of-the-linked-list_test.go b/go/middle-of-the-linked-list_test.go new file mode 100644 index 0000000..461d294 --- /dev/null +++ b/go/middle-of-the-linked-list_test.go @@ -0,0 +1,66 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestMiddleNode(t *testing.T) { + q1 := &ListNode{ + Val: 1, + Next: &ListNode{ + Val: 2, + Next: &ListNode{ + Val: 3, + Next: &ListNode{ + Val: 4, + Next: &ListNode{ + Val: 5, + }, + }, + }, + }, + } + if !reflect.DeepEqual(middleNode(q1), &ListNode{ + Val: 3, + Next: &ListNode{ + Val: 4, + Next: &ListNode{ + Val: 5, + }, + }, + }) { + t.Fatal() + } + + q2 := &ListNode{ + Val: 1, + Next: &ListNode{ + Val: 2, + Next: &ListNode{ + Val: 3, + Next: &ListNode{ + Val: 4, + Next: &ListNode{ + Val: 5, + Next: &ListNode{ + Val: 6, + }, + }, + }, + }, + }, + } + + if !reflect.DeepEqual(middleNode(q2), &ListNode{ + Val: 4, + Next: &ListNode{ + Val: 5, + Next: &ListNode{ + Val: 6, + }, + }, + }) { + t.Fatal() + } +} From 32d0a68c709bb468fb656afd09451bd994cfaac1 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 12:41:10 +0800 Subject: [PATCH 131/220] Add go solution for 1047. Remove All Adjacent Duplicates In String 1047. Remove All Adjacent Duplicates In String: https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ --- go/remove-all-adjacent-duplicates-in-string.go | 15 +++++++++++++++ ...move-all-adjacent-duplicates-in-string_test.go | 9 +++++++++ 2 files changed, 24 insertions(+) create mode 100644 go/remove-all-adjacent-duplicates-in-string.go create mode 100644 go/remove-all-adjacent-duplicates-in-string_test.go diff --git a/go/remove-all-adjacent-duplicates-in-string.go b/go/remove-all-adjacent-duplicates-in-string.go new file mode 100644 index 0000000..80fd0a1 --- /dev/null +++ b/go/remove-all-adjacent-duplicates-in-string.go @@ -0,0 +1,15 @@ +package leetcode + +func removeDuplicates(S string) string { + stack := make([]rune, len(S)) + size := 0 + for _, c := range S { + if size > 0 && c == stack[size-1] { + size-- + } else { + stack[size] = c + size++ + } + } + return string(stack[:size]) +} diff --git a/go/remove-all-adjacent-duplicates-in-string_test.go b/go/remove-all-adjacent-duplicates-in-string_test.go new file mode 100644 index 0000000..557c531 --- /dev/null +++ b/go/remove-all-adjacent-duplicates-in-string_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestRemoveDuplicates(t *testing.T) { + if removeDuplicates("abbaca") != "ca" { + t.Fatal() + } +} From 624fb05756e3374ca8d8e66416c4919daac3bf59 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 12:58:55 +0800 Subject: [PATCH 132/220] Add go solution for 1025. Divisor Game 1025. Divisor Game: https://leetcode.com/problems/divisor-game/ --- go/divisor-game.go | 23 +++++++++++++++++++++++ go/divisor-game_test.go | 12 ++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 go/divisor-game.go create mode 100644 go/divisor-game_test.go diff --git a/go/divisor-game.go b/go/divisor-game.go new file mode 100644 index 0000000..8a1da92 --- /dev/null +++ b/go/divisor-game.go @@ -0,0 +1,23 @@ +package leetcode + +func divisorGame(N int) bool { + table := make(map[int]bool) + table[1] = false + for i := 2; i <= 1000; i++ { + win := false + for j := 1; j*j <= i; j++ { + if i%j == 0 { + if !table[i-j] { + win = true + break + } + if j > 1 && !table[i-i/j] { + win = true + break + } + } + } + table[i] = win + } + return table[N] +} diff --git a/go/divisor-game_test.go b/go/divisor-game_test.go new file mode 100644 index 0000000..8746b43 --- /dev/null +++ b/go/divisor-game_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestDivisorGame(t *testing.T) { + if divisorGame(2) != true { + t.Fatal() + } + if divisorGame(3) != false { + t.Fatal() + } +} From 8dae32dd7df3e4410636e39b4a3b0a26db66b09a Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 13:07:27 +0800 Subject: [PATCH 133/220] Add go solution for 908. Smallest Range I 908. Smallest Range I: https://leetcode.com/problems/smallest-range-i/ --- go/smallest-range-i.go | 18 ++++++++++++++++++ go/smallest-range-i_test.go | 15 +++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 go/smallest-range-i.go create mode 100644 go/smallest-range-i_test.go diff --git a/go/smallest-range-i.go b/go/smallest-range-i.go new file mode 100644 index 0000000..d52c11e --- /dev/null +++ b/go/smallest-range-i.go @@ -0,0 +1,18 @@ +package leetcode + +func smallestRangeI(A []int, K int) int { + m, M := A[0], A[0] + for _, v := range A { + if m > v { + m = v + } + if M < v { + M = v + } + } + ans := M - m - 2*K + if ans < 0 { + ans = 0 + } + return ans +} diff --git a/go/smallest-range-i_test.go b/go/smallest-range-i_test.go new file mode 100644 index 0000000..0c90dcc --- /dev/null +++ b/go/smallest-range-i_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestSmallestRangeI(t *testing.T) { + if smallestRangeI([]int{1}, 0) != 0 { + t.Fatal() + } + if smallestRangeI([]int{0, 10}, 2) != 6 { + t.Fatal() + } + if smallestRangeI([]int{1, 3, 6}, 3) != 0 { + t.Fatal() + } +} From ae127d7ae9593b700eb5c3b8dca29919567fff51 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 14:05:35 +0800 Subject: [PATCH 134/220] Add go solution for 821. Shortest Distance to a Character 821. Shortest Distance to a Character: https://leetcode.com/problems/shortest-distance-to-a-character/ --- go/shortest-distance-to-a-character.go | 31 +++++++++++++++++++++ go/shortest-distance-to-a-character_test.go | 15 ++++++++++ 2 files changed, 46 insertions(+) create mode 100644 go/shortest-distance-to-a-character.go create mode 100644 go/shortest-distance-to-a-character_test.go diff --git a/go/shortest-distance-to-a-character.go b/go/shortest-distance-to-a-character.go new file mode 100644 index 0000000..fb8b1b7 --- /dev/null +++ b/go/shortest-distance-to-a-character.go @@ -0,0 +1,31 @@ +package leetcode + +func shortestToChar(S string, C byte) []int { + positions := make([]int, 0, len(S)) + for idx, c := range S { + if c == rune(C) { + positions = append(positions, idx) + } + } + ans := make([]int, len(S)) + x := 0 + for i := 0; i < len(S); i++ { + if x < len(positions) && i > positions[x] { + x++ + } + if x == 0 { + ans[i] = positions[x] - i + } else if x == len(positions) { + ans[i] = i - positions[x-1] + } else { + a := positions[x] - i + b := i - positions[x-1] + if a > b { + ans[i] = b + } else { + ans[i] = a + } + } + } + return ans +} diff --git a/go/shortest-distance-to-a-character_test.go b/go/shortest-distance-to-a-character_test.go new file mode 100644 index 0000000..ebaa853 --- /dev/null +++ b/go/shortest-distance-to-a-character_test.go @@ -0,0 +1,15 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestShortestToChar(t *testing.T) { + if !reflect.DeepEqual(shortestToChar("loveleetcode", byte('e')), []int{3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0}) { + t.Fatal() + } + if !reflect.DeepEqual(shortestToChar("aaba", byte('b')), []int{2, 1, 0, 1}) { + t.Fatal() + } +} From 5ffdc269caee8565d06d02ad12e8d46edd90b132 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 14:31:16 +0800 Subject: [PATCH 135/220] Add go solution for 1078. Occurrences After Bigram 1078. Occurrences After Bigram: https://leetcode.com/problems/occurrences-after-bigram/ --- go/occurrences-after-bigram.go | 15 +++++++++++++++ go/occurrences-after-bigram_test.go | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 go/occurrences-after-bigram.go create mode 100644 go/occurrences-after-bigram_test.go diff --git a/go/occurrences-after-bigram.go b/go/occurrences-after-bigram.go new file mode 100644 index 0000000..31798e2 --- /dev/null +++ b/go/occurrences-after-bigram.go @@ -0,0 +1,15 @@ +package leetcode + +import "strings" + +func findOcurrences(text string, first string, second string) []string { + var prev1, prev2 string + ans := []string{} + for _, s := range strings.Split(text, " ") { + if prev1 == first && prev2 == second { + ans = append(ans, s) + } + prev1, prev2 = prev2, s + } + return ans +} diff --git a/go/occurrences-after-bigram_test.go b/go/occurrences-after-bigram_test.go new file mode 100644 index 0000000..6be57a4 --- /dev/null +++ b/go/occurrences-after-bigram_test.go @@ -0,0 +1,21 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestFindOcurrences(t *testing.T) { + ans1 := findOcurrences("alice is a good girl she is a good student", "a", "good") + if !reflect.DeepEqual(ans1, []string{"girl", "student"}) { + t.Fatal() + } + ans2 := findOcurrences("we will we will rock you", "we", "will") + if !reflect.DeepEqual(ans2, []string{"we", "rock"}) { + t.Fatal() + } + ans3 := findOcurrences("we we we rock you", "we", "we") + if !reflect.DeepEqual(ans3, []string{"we", "rock"}) { + t.Fatal() + } +} From a4f7d46ddddc5a65a3fedafb14af7f9be46529b8 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 14:48:34 +0800 Subject: [PATCH 136/220] Add go solution for 872. Leaf-Similar Trees 872. Leaf-Similar Trees: https://leetcode.com/problems/leaf-similar-trees/ --- go/leaf-similar-trees.go | 38 ++++++++++++++++++++ go/leaf-similar-trees_test.go | 66 +++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 go/leaf-similar-trees.go create mode 100644 go/leaf-similar-trees_test.go diff --git a/go/leaf-similar-trees.go b/go/leaf-similar-trees.go new file mode 100644 index 0000000..e55a7ec --- /dev/null +++ b/go/leaf-similar-trees.go @@ -0,0 +1,38 @@ +package leetcode + +func leaves(cur *TreeNode, c chan int) { + if cur != nil { + if cur.Left == nil && cur.Right == nil { + c <- cur.Val + } else { + leaves(cur.Left, c) + leaves(cur.Right, c) + } + } +} + +func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { + chan1 := make(chan int) + chan2 := make(chan int) + go func() { + leaves(root1, chan1) + close(chan1) + }() + go func() { + leaves(root2, chan2) + close(chan2) + }() + for { + v1, open1 := <-chan1 + v2, open2 := <-chan2 + if !open1 && !open2 { + return true + } + if open1 != open2 { + return false + } + if v1 != v2 { + return false + } + } +} diff --git a/go/leaf-similar-trees_test.go b/go/leaf-similar-trees_test.go new file mode 100644 index 0000000..a5f215b --- /dev/null +++ b/go/leaf-similar-trees_test.go @@ -0,0 +1,66 @@ +package leetcode + +import "testing" + +func TestLeafSimilar(t *testing.T) { + q1 := &TreeNode{ + Val: 3, + Left: &TreeNode{ + Val: 5, + Left: &TreeNode{ + Val: 6, + }, + Right: &TreeNode{ + Val: 2, + Left: &TreeNode{ + Val: 7, + }, + Right: &TreeNode{ + Val: 4, + }, + }, + }, + Right: &TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 9, + }, + Right: &TreeNode{ + Val: 8, + }, + }, + } + q2 := &TreeNode{ + Val: 3, + Left: &TreeNode{ + Val: 5, + Left: &TreeNode{ + Val: 0, + Right: &TreeNode{ + Val: 6, + }, + }, + Right: &TreeNode{ + Val: 2, + Left: &TreeNode{ + Val: 7, + }, + Right: &TreeNode{ + Val: 4, + }, + }, + }, + Right: &TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 9, + }, + Right: &TreeNode{ + Val: 8, + }, + }, + } + if leafSimilar(q1, q2) != true { + t.Fatal() + } +} From 3e660cad67cc26bfa142aa1c4ffdcee91e123d97 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 15:22:20 +0800 Subject: [PATCH 137/220] Add go solution for 1030. Matrix Cells in Distance Order 1030. Matrix Cells in Distance Order: https://leetcode.com/problems/matrix-cells-in-distance-order/ --- go/matrix-cells-in-distance-order.go | 33 +++++++++++++++++++++++ go/matrix-cells-in-distance-order_test.go | 13 +++++++++ 2 files changed, 46 insertions(+) create mode 100644 go/matrix-cells-in-distance-order.go create mode 100644 go/matrix-cells-in-distance-order_test.go diff --git a/go/matrix-cells-in-distance-order.go b/go/matrix-cells-in-distance-order.go new file mode 100644 index 0000000..08c4e4f --- /dev/null +++ b/go/matrix-cells-in-distance-order.go @@ -0,0 +1,33 @@ +package leetcode + +func allCellsDistOrder(R int, C int, r0 int, c0 int) [][]int { + ans := make([][]int, 0, R*C) + ans = append(ans, []int{r0, c0}) + for d := 0; d < R+C-1; d++ { + for i := 0; i < d; i++ { + x, y := r0+i, c0+(d-i) + if 0 <= x && x < R && 0 <= y && y < C { + ans = append(ans, []int{x, y}) + } + } + for i := 0; i < d; i++ { + x, y := r0+(d-i), c0-i + if 0 <= x && x < R && 0 <= y && y < C { + ans = append(ans, []int{x, y}) + } + } + for i := 0; i < d; i++ { + x, y := r0-i, c0-(d-i) + if 0 <= x && x < R && 0 <= y && y < C { + ans = append(ans, []int{x, y}) + } + } + for i := 0; i < d; i++ { + x, y := r0-(d-i), c0+i + if 0 <= x && x < R && 0 <= y && y < C { + ans = append(ans, []int{x, y}) + } + } + } + return ans +} diff --git a/go/matrix-cells-in-distance-order_test.go b/go/matrix-cells-in-distance-order_test.go new file mode 100644 index 0000000..714276e --- /dev/null +++ b/go/matrix-cells-in-distance-order_test.go @@ -0,0 +1,13 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestAllCellsDistOrder(t *testing.T) { + ans1 := allCellsDistOrder(1, 2, 0, 0) + if !reflect.DeepEqual(ans1, [][]int{[]int{0, 0}, []int{0, 1}}) { + t.Fatal() + } +} From ef026c58a6611d4376ce6c71fadb4c26df6b4feb Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 15:45:37 +0800 Subject: [PATCH 138/220] Add go solution for 893. Groups of Special-Equivalent Strings 893. Groups of Special-Equivalent Strings: https://leetcode.com/problems/groups-of-special-equivalent-strings/ --- go/groups-of-special-equivalent-strings.go | 35 +++++++++++++++++++ ...oups-of-special-equivalent-strings_test.go | 12 +++++++ 2 files changed, 47 insertions(+) create mode 100644 go/groups-of-special-equivalent-strings.go create mode 100644 go/groups-of-special-equivalent-strings_test.go diff --git a/go/groups-of-special-equivalent-strings.go b/go/groups-of-special-equivalent-strings.go new file mode 100644 index 0000000..3192f8a --- /dev/null +++ b/go/groups-of-special-equivalent-strings.go @@ -0,0 +1,35 @@ +package leetcode + +import "sort" + +type SortRunes []rune + +func (s SortRunes) Less(i, j int) bool { + return s[i] < s[j] +} + +func (s SortRunes) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} + +func (s SortRunes) Len() int { + return len(s) +} + +func numSpecialEquivGroups(A []string) int { + m := make(map[string]struct{}) + for _, s := range A { + odd, even := make([]rune, 0, len(A)/2), make([]rune, 0, len(A)/2) + for idx, c := range s { + if idx%2 == 1 { + odd = append(odd, c) + } else { + even = append(even, c) + } + } + sort.Sort(SortRunes(odd)) + sort.Sort(SortRunes(even)) + m[string(odd)+string(even)] = struct{}{} + } + return len(m) +} diff --git a/go/groups-of-special-equivalent-strings_test.go b/go/groups-of-special-equivalent-strings_test.go new file mode 100644 index 0000000..ebf9c66 --- /dev/null +++ b/go/groups-of-special-equivalent-strings_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestNumSpecialEquivGroups(t *testing.T) { + if numSpecialEquivGroups([]string{"abcd", "cdab", "cbad", "xyzz", "zzxy", "zzyx"}) != 3 { + t.Fatal() + } + if numSpecialEquivGroups([]string{"abc", "acb", "bac", "bca", "cab", "cba"}) != 3 { + t.Fatal() + } +} From 9aa5795432681555a9d557c3634c63ca2472bdf2 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 15:52:53 +0800 Subject: [PATCH 139/220] Add go solution for 1185. Day of the Week 1185. Day of the Week: https://leetcode.com/problems/day-of-the-week/ --- go/day-of-the-week.go | 8 ++++++++ go/day-of-the-week_test.go | 15 +++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 go/day-of-the-week.go create mode 100644 go/day-of-the-week_test.go diff --git a/go/day-of-the-week.go b/go/day-of-the-week.go new file mode 100644 index 0000000..9d8db0c --- /dev/null +++ b/go/day-of-the-week.go @@ -0,0 +1,8 @@ +package leetcode + +import "time" + +func dayOfTheWeek(day int, month int, year int) string { + t := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) + return t.Weekday().String() +} diff --git a/go/day-of-the-week_test.go b/go/day-of-the-week_test.go new file mode 100644 index 0000000..792050b --- /dev/null +++ b/go/day-of-the-week_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestDayOfTheWeek(t *testing.T) { + if dayOfTheWeek(31, 8, 2019) != "Saturday" { + t.Fatal() + } + if dayOfTheWeek(18, 7, 1999) != "Sunday" { + t.Fatal() + } + if dayOfTheWeek(15, 8, 1993) != "Sunday" { + t.Fatal() + } +} From a5f687d4eb18aac6c7eed258bf72b143476b198c Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 16:01:57 +0800 Subject: [PATCH 140/220] Add go solution for 1217. Play with Chips 1217. Play with Chips: https://leetcode.com/problems/play-with-chips/ --- go/play-with-chips.go | 16 ++++++++++++++++ go/play-with-chips_test.go | 12 ++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 go/play-with-chips.go create mode 100644 go/play-with-chips_test.go diff --git a/go/play-with-chips.go b/go/play-with-chips.go new file mode 100644 index 0000000..c548fcd --- /dev/null +++ b/go/play-with-chips.go @@ -0,0 +1,16 @@ +package leetcode + +func minCostToMoveChips(chips []int) int { + odds, evens := 0, 0 + for _, v := range chips { + if v%2 == 0 { + evens++ + } else { + odds++ + } + } + if evens > odds { + return odds + } + return evens +} diff --git a/go/play-with-chips_test.go b/go/play-with-chips_test.go new file mode 100644 index 0000000..76e8b0c --- /dev/null +++ b/go/play-with-chips_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestMinCostToMoveChips(t *testing.T) { + if minCostToMoveChips([]int{1, 2, 3}) != 1 { + t.Fatal() + } + if minCostToMoveChips([]int{2, 2, 2, 3, 3}) != 2 { + t.Fatal() + } +} From 56efdad9f2bfe0e421437c931aebb26ca3d32b35 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 16:17:12 +0800 Subject: [PATCH 141/220] Add go solution for 806. Number of Lines To Write String 806. Number of Lines To Write String: https://leetcode.com/problems/number-of-lines-to-write-string/ --- go/number-of-lines-to-write-string.go | 17 +++++++++++++++++ go/number-of-lines-to-write-string_test.go | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 go/number-of-lines-to-write-string.go create mode 100644 go/number-of-lines-to-write-string_test.go diff --git a/go/number-of-lines-to-write-string.go b/go/number-of-lines-to-write-string.go new file mode 100644 index 0000000..326129a --- /dev/null +++ b/go/number-of-lines-to-write-string.go @@ -0,0 +1,17 @@ +package leetcode + +func numberOfLines(widths []int, S string) []int { + if len(S) == 0 { + return []int{0, 0} + } + lines := 0 + accu := 0 + for _, c := range S { + if accu+widths[c-'a'] > 100 { + lines++ + accu = 0 + } + accu += widths[c-'a'] + } + return []int{lines + 1, accu} +} diff --git a/go/number-of-lines-to-write-string_test.go b/go/number-of-lines-to-write-string_test.go new file mode 100644 index 0000000..52af2b5 --- /dev/null +++ b/go/number-of-lines-to-write-string_test.go @@ -0,0 +1,18 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestNumberOfLines(t *testing.T) { + w1, s1 := []int{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, "abcdefghijklmnopqrstuvwxyz" + if !reflect.DeepEqual(numberOfLines(w1, s1), []int{3, 60}) { + t.Fatal() + } + + w2, s2 := []int{4, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, "bbbcccdddaaa" + if !reflect.DeepEqual(numberOfLines(w2, s2), []int{2, 4}) { + t.Fatal() + } +} From 2392e5d37a2de63e223e4952a5288bbce1add315 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 16:22:35 +0800 Subject: [PATCH 142/220] Add go solution for 867. Transpose Matrix 867. Transpose Matrix: https://leetcode.com/problems/transpose-matrix/ --- go/transpose-matrix.go | 13 +++++++++++++ go/transpose-matrix_test.go | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 go/transpose-matrix.go create mode 100644 go/transpose-matrix_test.go diff --git a/go/transpose-matrix.go b/go/transpose-matrix.go new file mode 100644 index 0000000..da8b1b1 --- /dev/null +++ b/go/transpose-matrix.go @@ -0,0 +1,13 @@ +package leetcode + +func transpose(A [][]int) [][]int { + R, C := len(A), len(A[0]) + ans := make([][]int, 0, C) + for i := 0; i < C; i++ { + ans = append(ans, make([]int, R)) + for j := 0; j < R; j++ { + ans[i][j] = A[j][i] + } + } + return ans +} diff --git a/go/transpose-matrix_test.go b/go/transpose-matrix_test.go new file mode 100644 index 0000000..9cf3fcc --- /dev/null +++ b/go/transpose-matrix_test.go @@ -0,0 +1,22 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestTranspose(t *testing.T) { + q1 := [][]int{ + []int{1, 2, 3}, + []int{4, 5, 6}, + []int{7, 8, 9}, + } + a1 := [][]int{ + []int{1, 4, 7}, + []int{2, 5, 8}, + []int{3, 6, 9}, + } + if !reflect.DeepEqual(transpose(q1), a1) { + t.Fatal() + } +} From c848a2df4f15d8445cb77b2ad1d02d1442d85738 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 16:34:10 +0800 Subject: [PATCH 143/220] Add go solution for 1022. Sum of Root To Leaf Binary Numbers 1022. Sum of Root To Leaf Binary Numbers: https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ --- go/sum-of-root-to-leaf-binary-numbers.go | 19 ++++++++++++ go/sum-of-root-to-leaf-binary-numbers_test.go | 30 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 go/sum-of-root-to-leaf-binary-numbers.go create mode 100644 go/sum-of-root-to-leaf-binary-numbers_test.go diff --git a/go/sum-of-root-to-leaf-binary-numbers.go b/go/sum-of-root-to-leaf-binary-numbers.go new file mode 100644 index 0000000..474506f --- /dev/null +++ b/go/sum-of-root-to-leaf-binary-numbers.go @@ -0,0 +1,19 @@ +package leetcode + +func sum(cur *TreeNode, n int, ans *int) { + if cur != nil { + n = (n << 1) + cur.Val + if cur.Left == nil && cur.Right == nil { + *ans += n + } else { + sum(cur.Left, n, ans) + sum(cur.Right, n, ans) + } + } +} + +func sumRootToLeaf(root *TreeNode) int { + ans := 0 + sum(root, 0, &ans) + return ans +} diff --git a/go/sum-of-root-to-leaf-binary-numbers_test.go b/go/sum-of-root-to-leaf-binary-numbers_test.go new file mode 100644 index 0000000..f0a85c6 --- /dev/null +++ b/go/sum-of-root-to-leaf-binary-numbers_test.go @@ -0,0 +1,30 @@ +package leetcode + +import "testing" + +func TestSumRootToLeaf(t *testing.T) { + q1 := &TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 0, + Left: &TreeNode{ + Val: 0, + }, + Right: &TreeNode{ + Val: 1, + }, + }, + Right: &TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 0, + }, + Right: &TreeNode{ + Val: 1, + }, + }, + } + if sumRootToLeaf(q1) != 22 { + t.Fatal() + } +} From 5fbd634bee9a60ecc32215e89e684f60b1fd5e93 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 16:46:26 +0800 Subject: [PATCH 144/220] Add go solution for 766. Toeplitz Matrix 766. Toeplitz Matrix: https://leetcode.com/problems/toeplitz-matrix/ --- go/toeplitz-matrix.go | 13 +++++++++++++ go/toeplitz-matrix_test.go | 21 +++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 go/toeplitz-matrix.go create mode 100644 go/toeplitz-matrix_test.go diff --git a/go/toeplitz-matrix.go b/go/toeplitz-matrix.go new file mode 100644 index 0000000..868cc64 --- /dev/null +++ b/go/toeplitz-matrix.go @@ -0,0 +1,13 @@ +package leetcode + +func isToeplitzMatrix(matrix [][]int) bool { + R, C := len(matrix), len(matrix[0]) + for i := 1; i < R; i++ { + for j := 1; j < C; j++ { + if matrix[i][j] != matrix[i-1][j-1] { + return false + } + } + } + return true +} diff --git a/go/toeplitz-matrix_test.go b/go/toeplitz-matrix_test.go new file mode 100644 index 0000000..e5a393e --- /dev/null +++ b/go/toeplitz-matrix_test.go @@ -0,0 +1,21 @@ +package leetcode + +import "testing" + +func TestIsToeplitzMatrix(t *testing.T) { + q1 := [][]int{ + []int{1, 2, 3, 4}, + []int{5, 1, 2, 3}, + []int{9, 5, 1, 2}, + } + if isToeplitzMatrix(q1) != true { + t.Fatal() + } + q2 := [][]int{ + []int{1, 2}, + []int{2, 2}, + } + if isToeplitzMatrix(q2) != false { + t.Fatal() + } +} From ece16f50e5263b5f053fbce881f18e10f249ef0b Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 16:55:08 +0800 Subject: [PATCH 145/220] Add go solution for 476. Number Complement 476. Number Complement: https://leetcode.com/problems/number-complement/ --- go/number-complement.go | 12 ++++++++++++ go/number-complement_test.go | 9 +++++++++ 2 files changed, 21 insertions(+) create mode 100644 go/number-complement.go create mode 100644 go/number-complement_test.go diff --git a/go/number-complement.go b/go/number-complement.go new file mode 100644 index 0000000..faaac2c --- /dev/null +++ b/go/number-complement.go @@ -0,0 +1,12 @@ +package leetcode + +func findComplement(num int) int { + x := num + x |= x >> 1 + x |= x >> 2 + x |= x >> 4 + x |= x >> 8 + x |= x >> 16 + x >>= 1 + return ^num & x +} diff --git a/go/number-complement_test.go b/go/number-complement_test.go new file mode 100644 index 0000000..7a3336f --- /dev/null +++ b/go/number-complement_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestFindComplement(t *testing.T) { + if findComplement(5) != 2 { + t.Fatal() + } +} From c37e376da3c9d7931bd6fbbe5c6c3960e79fc0e7 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 17:18:45 +0800 Subject: [PATCH 146/220] Add go solution for 1046. Last Stone Weight 1046. Last Stone Weight: https://leetcode.com/problems/last-stone-weight/ --- go/last-stone-weight.go | 50 ++++++++++++++++++++++++++++++++++++ go/last-stone-weight_test.go | 15 +++++++++++ 2 files changed, 65 insertions(+) create mode 100644 go/last-stone-weight.go create mode 100644 go/last-stone-weight_test.go diff --git a/go/last-stone-weight.go b/go/last-stone-weight.go new file mode 100644 index 0000000..edf2613 --- /dev/null +++ b/go/last-stone-weight.go @@ -0,0 +1,50 @@ +package leetcode + +import ( + "container/heap" +) + +type IntHeap []int + +func (h IntHeap) Len() int { + return len(h) +} + +func (h IntHeap) Less(i, j int) bool { + return h[i] > h[j] +} + +func (h IntHeap) Swap(i, j int) { + h[i], h[j] = h[j], h[i] +} + +func (h *IntHeap) Push(x interface{}) { + *h = append(*h, x.(int)) +} + +func (h *IntHeap) Pop() interface{} { + oldh := *h + x := oldh[len(oldh)-1] + newh := oldh[0 : len(oldh)-1] + *h = newh + return x +} + +func lastStoneWeight(stones []int) int { + h := IntHeap(stones) + heap.Init(&h) + for len(h) > 1 { + v1 := heap.Pop(&h).(int) + v2 := heap.Pop(&h).(int) + if v1 > v2 { + heap.Push(&h, v1-v2) + } else if v1 < v2 { + heap.Push(&h, v2-v2) + } + } + if len(h) == 0 { + return 0 + } else { + return h[0] + } +} diff --git a/go/last-stone-weight_test.go b/go/last-stone-weight_test.go new file mode 100644 index 0000000..5b2cfe4 --- /dev/null +++ b/go/last-stone-weight_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestLastStoneWeight(t *testing.T) { + if lastStoneWeight([]int{2, 7, 1, 4, 8, 1}) != 1 { + t.Fatal() + } + if lastStoneWeight([]int{1, 3}) != 2 { + t.Fatal() + } + if lastStoneWeight([]int{2, 2}) != 0 { + t.Fatal() + } +} From 022cfba2ef74f0230173b5a56939fad2a3a6b710 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 17:54:09 +0800 Subject: [PATCH 147/220] Add go solution for 985. Sum of Even Numbers After Queries 985. Sum of Even Numbers After Queries: https://leetcode.com/problems/sum-of-even-numbers-after-queries/ --- go/sum-of-even-numbers-after-queries.go | 23 ++++++++++++++++++++ go/sum-of-even-numbers-after-queries_test.go | 19 ++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 go/sum-of-even-numbers-after-queries.go create mode 100644 go/sum-of-even-numbers-after-queries_test.go diff --git a/go/sum-of-even-numbers-after-queries.go b/go/sum-of-even-numbers-after-queries.go new file mode 100644 index 0000000..3d9165c --- /dev/null +++ b/go/sum-of-even-numbers-after-queries.go @@ -0,0 +1,23 @@ +package leetcode + +func sumEvenAfterQueries(A []int, queries [][]int) []int { + evens := 0 + for _, v := range A { + if v%2 == 0 { + evens += v + } + } + ans := make([]int, len(A)) + for i, q := range queries { + val, idx := q[0], q[1] + if A[idx]%2 == 0 { + evens -= A[idx] + } + A[idx] += val + if A[idx]%2 == 0 { + evens += A[idx] + } + ans[i] = evens + } + return ans +} diff --git a/go/sum-of-even-numbers-after-queries_test.go b/go/sum-of-even-numbers-after-queries_test.go new file mode 100644 index 0000000..528a1de --- /dev/null +++ b/go/sum-of-even-numbers-after-queries_test.go @@ -0,0 +1,19 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestSumEvenAfterQueries(t *testing.T) { + A1, q1, ans1 := []int{1, 2, 3, 4}, + [][]int{ + []int{1, 0}, + []int{-3, 1}, + []int{-4, 0}, + []int{2, 3}, + }, []int{8, 6, 2, 4} + if !reflect.DeepEqual(sumEvenAfterQueries(A1, q1), ans1) { + t.Fatal() + } +} From dc8ce3d89199772330f35d76353feec4152009d0 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 27 Dec 2019 18:00:17 +0800 Subject: [PATCH 148/220] Add go solution for 884. Uncommon Words from Two Sentences 884. Uncommon Words from Two Sentences: https://leetcode.com/problems/uncommon-words-from-two-sentences/ --- go/uncommon-words-from-two-sentences.go | 25 ++++++++++++++++++++ go/uncommon-words-from-two-sentences_test.go | 22 +++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 go/uncommon-words-from-two-sentences.go create mode 100644 go/uncommon-words-from-two-sentences_test.go diff --git a/go/uncommon-words-from-two-sentences.go b/go/uncommon-words-from-two-sentences.go new file mode 100644 index 0000000..8ae8ce0 --- /dev/null +++ b/go/uncommon-words-from-two-sentences.go @@ -0,0 +1,25 @@ +package leetcode + +import "strings" + +func uncommonFromSentences(A string, B string) []string { + countA, countB := make(map[string]int), make(map[string]int) + for _, s := range strings.Split(A, " ") { + countA[s]++ + } + for _, s := range strings.Split(B, " ") { + countB[s]++ + } + ans := []string{} + for s, v := range countA { + if _, ok := countB[s]; v == 1 && !ok { + ans = append(ans, s) + } + } + for s, v := range countB { + if _, ok := countA[s]; v == 1 && !ok { + ans = append(ans, s) + } + } + return ans +} diff --git a/go/uncommon-words-from-two-sentences_test.go b/go/uncommon-words-from-two-sentences_test.go new file mode 100644 index 0000000..0d2d727 --- /dev/null +++ b/go/uncommon-words-from-two-sentences_test.go @@ -0,0 +1,22 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestUncommonFromSentences(t *testing.T) { + A1, B1 := "this apple is sweet", "this apple is sour" + ans1 := []string{"sweet", "sour"} + + if !reflect.DeepEqual(uncommonFromSentences(A1, B1), ans1) { + t.Fatal() + } + + A2, B2 := "apple apple", "banana" + ans2 := []string{"banana"} + + if !reflect.DeepEqual(uncommonFromSentences(A2, B2), ans2) { + t.Fatal() + } +} From 9bdb98e289537c8e53471d0c7a85efd921ba7dca Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 11:50:47 +0800 Subject: [PATCH 149/220] Add go solution for 1189. Maximum Number of Balloons 1189. Maximum Number of Balloons: https://leetcode.com/problems/maximum-number-of-balloons/ --- go/maximum-number-of-balloons.go | 31 +++++++++++++++++++++++++++ go/maximum-number-of-balloons_test.go | 18 ++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 go/maximum-number-of-balloons.go create mode 100644 go/maximum-number-of-balloons_test.go diff --git a/go/maximum-number-of-balloons.go b/go/maximum-number-of-balloons.go new file mode 100644 index 0000000..ddb61be --- /dev/null +++ b/go/maximum-number-of-balloons.go @@ -0,0 +1,31 @@ +package leetcode + +func maxNumberOfBalloons(text string) int { + count := make(map[rune]int) + for _, c := range text { + count[c]++ + } + ans := len(text) / 7 + var x int + x = count['b'] + if x < ans { + ans = x + } + x = count['a'] + if x < ans { + ans = x + } + x = count['l'] / 2 + if x < ans { + ans = x + } + x = count['o'] / 2 + if x < ans { + ans = x + } + x = count['n'] + if x < ans { + ans = x + } + return ans +} diff --git a/go/maximum-number-of-balloons_test.go b/go/maximum-number-of-balloons_test.go new file mode 100644 index 0000000..e5cdba5 --- /dev/null +++ b/go/maximum-number-of-balloons_test.go @@ -0,0 +1,18 @@ +package leetcode + +import "testing" + +func TestMaxNumberOfBalloons(t *testing.T) { + if maxNumberOfBalloons("nlaebolko") != 1 { + t.Fatal() + } + if maxNumberOfBalloons("loonbalxballpoon") != 2 { + t.Fatal() + } + if maxNumberOfBalloons("leetcode") != 0 { + t.Fatal() + } + if maxNumberOfBalloons("balloon") != 1 { + t.Fatal() + } +} From 4147205bf53bd68c0d8df905c651b32c824e37e7 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 12:49:10 +0800 Subject: [PATCH 150/220] Add go solution for 762. Prime Number of Set Bits in Binary Representation 762. Prime Number of Set Bits in Binary Representation: https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/ --- ...er-of-set-bits-in-binary-representation.go | 51 +++++++++++++++++++ ...-set-bits-in-binary-representation_test.go | 18 +++++++ 2 files changed, 69 insertions(+) create mode 100644 go/prime-number-of-set-bits-in-binary-representation.go create mode 100644 go/prime-number-of-set-bits-in-binary-representation_test.go diff --git a/go/prime-number-of-set-bits-in-binary-representation.go b/go/prime-number-of-set-bits-in-binary-representation.go new file mode 100644 index 0000000..29ef9ac --- /dev/null +++ b/go/prime-number-of-set-bits-in-binary-representation.go @@ -0,0 +1,51 @@ +package leetcode + +func c(n, m int) int { + if n < m { + return 0 + } + if m > n-m { + m = n - m + } + ans := 1 + for i := 1; i <= m; i++ { + ans *= n - i + 1 + ans /= i + } + return ans +} + +func countBits(n int) int { + n = (n & 0x55555555) + ((n >> 1) & 0x55555555) + n = (n & 0x33333333) + ((n >> 2) & 0x33333333) + n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f) + n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff) + n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff) + return n +} + +func countPrimeSetBitsBounded(N int) int { + if N <= 2 { + return 0 + } + N++ + ans := 0 + for t := 20; t >= 0; t-- { + if (1< 0 { + n := (((-(1 << uint(t))) & N) >> uint(t)) - 1 + if n >= 0 { + bits := countBits(n) + for _, p := range []int{2, 3, 5, 7, 11, 13, 17, 19} { + if p >= bits { + ans += c(t, p-bits) + } + } + } + } + } + return ans +} + +func countPrimeSetBits(L int, R int) int { + return countPrimeSetBitsBounded(R) - countPrimeSetBitsBounded(L-1) +} diff --git a/go/prime-number-of-set-bits-in-binary-representation_test.go b/go/prime-number-of-set-bits-in-binary-representation_test.go new file mode 100644 index 0000000..108bb63 --- /dev/null +++ b/go/prime-number-of-set-bits-in-binary-representation_test.go @@ -0,0 +1,18 @@ +package leetcode + +import "testing" + +func TestCountPrimeSetBits(t *testing.T) { + if countPrimeSetBits(1, 1) != 0 { + t.Fatal() + } + if countPrimeSetBits(6, 10) != 4 { + t.Fatal() + } + if countPrimeSetBits(10, 15) != 5 { + t.Fatal() + } + if countPrimeSetBits(842, 888) != 23 { + t.Fatal() + } +} From d9802d014be556c6915be79f4f6f81d444d6da19 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 13:05:11 +0800 Subject: [PATCH 151/220] Add go solution for 784. Letter Case Permutation 784. Letter Case Permutation: https://leetcode.com/problems/letter-case-permutation/ --- go/letter-case-permutation.go | 32 ++++++++++++++++++++++++++++++ go/letter-case-permutation_test.go | 18 +++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 go/letter-case-permutation.go create mode 100644 go/letter-case-permutation_test.go diff --git a/go/letter-case-permutation.go b/go/letter-case-permutation.go new file mode 100644 index 0000000..1188db4 --- /dev/null +++ b/go/letter-case-permutation.go @@ -0,0 +1,32 @@ +package leetcode + +import "unicode" + +func iterate(depth int, array []rune, c chan<- string) { + if depth == len(array) { + c <- string(array) + return + } + if unicode.IsLetter(array[depth]) { + array[depth] = unicode.ToLower(array[depth]) + iterate(depth+1, array, c) + array[depth] = unicode.ToUpper(array[depth]) + iterate(depth+1, array, c) + } else { + iterate(depth+1, array, c) + } +} + +func letterCasePermutation(S string) []string { + c := make(chan string) + go func() { + iterate(0, []rune(S), c) + close(c) + }() + + ans := make([]string, 0, 1< Date: Mon, 30 Dec 2019 13:30:50 +0800 Subject: [PATCH 152/220] Add go solution for 1287. Element Appearing More Than 25% In Sorted Array 1287. Element Appearing More Than 25% In Sorted Array: https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/ --- ...lement-appearing-more-than-25-in-sorted-array.go | 13 +++++++++++++ ...t-appearing-more-than-25-in-sorted-array_test.go | 9 +++++++++ 2 files changed, 22 insertions(+) create mode 100644 go/element-appearing-more-than-25-in-sorted-array.go create mode 100644 go/element-appearing-more-than-25-in-sorted-array_test.go diff --git a/go/element-appearing-more-than-25-in-sorted-array.go b/go/element-appearing-more-than-25-in-sorted-array.go new file mode 100644 index 0000000..52468ab --- /dev/null +++ b/go/element-appearing-more-than-25-in-sorted-array.go @@ -0,0 +1,13 @@ +package leetcode + +func findSpecialInteger(arr []int) int { + l := len(arr) + quarter := l / 4 + + for i := 0; i < l; i++ { + if arr[i] == arr[i+quarter] { + return arr[i] + } + } + return -1 +} diff --git a/go/element-appearing-more-than-25-in-sorted-array_test.go b/go/element-appearing-more-than-25-in-sorted-array_test.go new file mode 100644 index 0000000..01baa75 --- /dev/null +++ b/go/element-appearing-more-than-25-in-sorted-array_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestFindSpecialInteger(t *testing.T) { + if findSpecialInteger([]int{1, 2, 2, 6, 6, 6, 6, 7, 10}) != 6 { + t.Fatal() + } +} From a29438c784147ab1ea361744f20bd22b8d28a3d7 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 13:41:04 +0800 Subject: [PATCH 153/220] Add go solution for 824. Goat Latin 824. Goat Latin: https://leetcode.com/problems/goat-latin/ --- go/goat-latin.go | 22 ++++++++++++++++++++++ go/goat-latin_test.go | 9 +++++++++ 2 files changed, 31 insertions(+) create mode 100644 go/goat-latin.go create mode 100644 go/goat-latin_test.go diff --git a/go/goat-latin.go b/go/goat-latin.go new file mode 100644 index 0000000..3a7dcb8 --- /dev/null +++ b/go/goat-latin.go @@ -0,0 +1,22 @@ +package leetcode + +import "strings" + +func toGoatLatin(S string) string { + ans := make([]string, 0, len(S)) + for i, w := range strings.Split(S, " ") { + b := strings.Builder{} + if strings.Index("aeiouAEIOU", string(w[0])) == -1 { + b.WriteString(w[1:]) + b.WriteRune(rune(w[0])) + } else { + b.WriteString(w) + } + b.WriteString("ma") + for j := 0; j <= i; j++ { + b.WriteRune('a') + } + ans = append(ans, b.String()) + } + return strings.Join(ans, " ") +} diff --git a/go/goat-latin_test.go b/go/goat-latin_test.go new file mode 100644 index 0000000..ad4d667 --- /dev/null +++ b/go/goat-latin_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestToGoatLatin(t *testing.T) { + if toGoatLatin("I speak Goat Latin") != "Imaa peaksmaaa oatGmaaaa atinLmaaaaa" { + t.Fatal() + } +} From 4cf33af2b4e58e87f5d3a8ad1464076d362b6a88 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 13:48:48 +0800 Subject: [PATCH 154/220] Add go solution for 868. Binary Gap 868. Binary Gap: https://leetcode.com/problems/binary-gap/ --- go/binary-gap.go | 15 +++++++++++++++ go/binary-gap_test.go | 17 +++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 go/binary-gap.go create mode 100644 go/binary-gap_test.go diff --git a/go/binary-gap.go b/go/binary-gap.go new file mode 100644 index 0000000..a610275 --- /dev/null +++ b/go/binary-gap.go @@ -0,0 +1,15 @@ +package leetcode + +func binaryGap(N int) int { + prev := -1 + ans := 0 + for i := 0; (1 << uint(i)) <= N; i++ { + if (1< 0 { + if prev != -1 && i-prev > ans { + ans = i - prev + } + prev = i + } + } + return ans +} diff --git a/go/binary-gap_test.go b/go/binary-gap_test.go new file mode 100644 index 0000000..3c1e676 --- /dev/null +++ b/go/binary-gap_test.go @@ -0,0 +1,17 @@ +package leetcode + +import "testing" + +func TestBinaryGap(t *testing.T) { + if binaryGap(22) != 2 { + t.Fatal() + } + + if binaryGap(8) != 0 { + t.Fatal() + } + + if binaryGap(6) != 1 { + t.Fatal() + } +} From d24c0bcd688aea416da77495c9f625e7dd374126 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 14:06:47 +0800 Subject: [PATCH 155/220] Add go solution for 1103. Distribute Candies to People 1103. Distribute Candies to People: https://leetcode.com/problems/distribute-candies-to-people/ --- go/distribute-candies-to-people.go | 20 ++++++++++++++++++++ go/distribute-candies-to-people_test.go | 12 ++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 go/distribute-candies-to-people.go create mode 100644 go/distribute-candies-to-people_test.go diff --git a/go/distribute-candies-to-people.go b/go/distribute-candies-to-people.go new file mode 100644 index 0000000..4456865 --- /dev/null +++ b/go/distribute-candies-to-people.go @@ -0,0 +1,20 @@ +package leetcode + +import "math" + +func distributeCandies(candies int, num_people int) []int { + rounds := int((math.Sqrt(8.*float64(candies)+1.5) - 1) / 2) + ans := make([]int, num_people) + for i := 1; i <= num_people; i++ { + cnt := rounds / num_people + ans[i-1] += cnt * (2*i + (cnt-1)*num_people) / 2 + if rounds%num_people >= i { + ans[i-1] += i + cnt*num_people + } + } + used := rounds * (rounds + 1) / 2 + if used < candies { + ans[rounds%num_people] += candies - used + } + return ans +} diff --git a/go/distribute-candies-to-people_test.go b/go/distribute-candies-to-people_test.go new file mode 100644 index 0000000..6aa30b7 --- /dev/null +++ b/go/distribute-candies-to-people_test.go @@ -0,0 +1,12 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestDistributeCandies(t *testing.T) { + if !reflect.DeepEqual(distributeCandies(7, 4), []int{1, 2, 3, 1}) { + t.Fatal() + } +} From ab014a32db9bc8287b65a8eadcdda6b4a2cfc74b Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 14:31:54 +0800 Subject: [PATCH 156/220] Add go solution for 1260. Shift 2D Grid 1260. Shift 2D Grid: https://leetcode.com/problems/shift-2d-grid/ --- go/shift-2d-grid.go | 16 ++++++++++++++++ go/shift-2d-grid_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 go/shift-2d-grid.go create mode 100644 go/shift-2d-grid_test.go diff --git a/go/shift-2d-grid.go b/go/shift-2d-grid.go new file mode 100644 index 0000000..30143ca --- /dev/null +++ b/go/shift-2d-grid.go @@ -0,0 +1,16 @@ +package leetcode + +func shiftGrid(grid [][]int, k int) [][]int { + out := make([][]int, 0, len(grid)) + rows := len(grid) + cols := len(grid[0]) + shift_c := k % cols + shift_r := (k / cols) % rows + for i := 0; i < rows; i++ { + r := make([]int, 0, cols) + r = append(r, grid[(i+rows-shift_r-1)%rows][cols-shift_c:]...) + r = append(r, grid[(i+rows-shift_r)%rows][:cols-shift_c]...) + out = append(out, r) + } + return out +} diff --git a/go/shift-2d-grid_test.go b/go/shift-2d-grid_test.go new file mode 100644 index 0000000..cb001a4 --- /dev/null +++ b/go/shift-2d-grid_test.go @@ -0,0 +1,35 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestShiftGrid(t *testing.T) { + if !reflect.DeepEqual(shiftGrid([][]int{ + []int{1, 2, 3}, + []int{4, 5, 6}, + []int{7, 8, 9}, + }, 1), + [][]int{ + []int{9, 1, 2}, + []int{3, 4, 5}, + []int{6, 7, 8}, + }) { + t.Fatal() + } + if !reflect.DeepEqual(shiftGrid([][]int{ + []int{3, 8, 1, 9}, + []int{19, 7, 2, 5}, + []int{4, 6, 11, 10}, + []int{12, 0, 21, 13}, + }, 4), + [][]int{ + []int{12, 0, 21, 13}, + []int{3, 8, 1, 9}, + []int{19, 7, 2, 5}, + []int{4, 6, 11, 10}, + }) { + t.Fatal() + } +} From 3840e5c22acfc0294497533ecaf39e7cf8c4c297 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 14:39:04 +0800 Subject: [PATCH 157/220] Add go solution for 1009. Complement of Base 10 Integer 1009. Complement of Base 10 Integer: https://leetcode.com/problems/complement-of-base-10-integer/ --- go/complement-of-base-10-integer.go | 14 ++++++++++++++ go/complement-of-base-10-integer_test.go | 15 +++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 go/complement-of-base-10-integer.go create mode 100644 go/complement-of-base-10-integer_test.go diff --git a/go/complement-of-base-10-integer.go b/go/complement-of-base-10-integer.go new file mode 100644 index 0000000..b79e951 --- /dev/null +++ b/go/complement-of-base-10-integer.go @@ -0,0 +1,14 @@ +package leetcode + +func bitwiseComplement(N int) int { + if N == 0 { + return 1 + } + t := N + t |= t >> 1 + t |= t >> 2 + t |= t >> 4 + t |= t >> 8 + t |= t >> 16 + return t ^ N +} diff --git a/go/complement-of-base-10-integer_test.go b/go/complement-of-base-10-integer_test.go new file mode 100644 index 0000000..204aff5 --- /dev/null +++ b/go/complement-of-base-10-integer_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestBitwiseComplement(t *testing.T) { + if bitwiseComplement(5) != 2 { + t.Fatal() + } + if bitwiseComplement(7) != 0 { + t.Fatal() + } + if bitwiseComplement(10) != 5 { + t.Fatal() + } +} From 224826acec7e0acfe4df35d13d53ca8e155250ff Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 15:14:57 +0800 Subject: [PATCH 158/220] Add go solution for 1089. Duplicate Zeros 1089. Duplicate Zeros: https://leetcode.com/problems/duplicate-zeros/ --- go/duplicate-zeros.go | 29 +++++++++++++++++++++++++++++ go/duplicate-zeros_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 go/duplicate-zeros.go create mode 100644 go/duplicate-zeros_test.go diff --git a/go/duplicate-zeros.go b/go/duplicate-zeros.go new file mode 100644 index 0000000..cd928c2 --- /dev/null +++ b/go/duplicate-zeros.go @@ -0,0 +1,29 @@ +package leetcode + +func duplicateZeros(arr []int) { + zeroCnt := 0 + l := len(arr) + last_dup := false + for idx, v := range arr { + if v == 0 { + if idx+zeroCnt+1 < l { + if idx+zeroCnt+2 == l { + last_dup = true + } + zeroCnt++ + } + } + if idx+zeroCnt >= l { + break + } + } + t := l - 1 + for i := 0; i < l-zeroCnt; i++ { + if (i > 0 || last_dup) && arr[l-zeroCnt-1-i] == 0 { + arr[t] = arr[l-zeroCnt-1-i] + t-- + } + arr[t] = arr[l-zeroCnt-1-i] + t-- + } +} diff --git a/go/duplicate-zeros_test.go b/go/duplicate-zeros_test.go new file mode 100644 index 0000000..e528d75 --- /dev/null +++ b/go/duplicate-zeros_test.go @@ -0,0 +1,24 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestDuplicateZeros(t *testing.T) { + arr := []int{1, 0, 2, 3, 0, 4, 5, 0} + duplicateZeros(arr) + if !reflect.DeepEqual(arr, []int{1, 0, 0, 2, 3, 0, 0, 4}) { + t.Fatal() + } + arr2 := []int{1, 2, 3} + duplicateZeros(arr2) + if !reflect.DeepEqual(arr2, []int{1, 2, 3}) { + t.Fatal() + } + arr3 := []int{1, 0} + duplicateZeros(arr3) + if !reflect.DeepEqual(arr3, []int{1, 0}) { + t.Fatal() + } +} From 0cce70cdf091c1563e1a36f5e050f1ce661523ae Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 15:37:44 +0800 Subject: [PATCH 159/220] Add go solution for 1170. Compare Strings by Frequency of the Smallest Character 1170. Compare Strings by Frequency of the Smallest Character: https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/ --- ...-by-frequency-of-the-smallest-character.go | 39 +++++++++++++++++++ ...requency-of-the-smallest-character_test.go | 22 +++++++++++ 2 files changed, 61 insertions(+) create mode 100644 go/compare-strings-by-frequency-of-the-smallest-character.go create mode 100644 go/compare-strings-by-frequency-of-the-smallest-character_test.go diff --git a/go/compare-strings-by-frequency-of-the-smallest-character.go b/go/compare-strings-by-frequency-of-the-smallest-character.go new file mode 100644 index 0000000..978c979 --- /dev/null +++ b/go/compare-strings-by-frequency-of-the-smallest-character.go @@ -0,0 +1,39 @@ +package leetcode + +import "sort" + +func freq(w string) int { + lowest := 'z' + m := make(map[rune]int) + for _, c := range w { + m[c]++ + if c < lowest { + lowest = c + } + } + return m[lowest] +} + +func numSmallerByFrequency(queries []string, words []string) []int { + fwords := make([]int, len(words)) + for idx, w := range words { + fwords[idx] = freq(w) + } + sort.Ints(fwords) + + ans := make([]int, len(queries)) + for idx, w := range queries { + f := freq(w) + L, U := -1, len(words) + for L+1 < U { + m := (L + U) / 2 + if fwords[m] > f { + U = m + } else { + L = m + } + } + ans[idx] = len(words) - U + } + return ans +} diff --git a/go/compare-strings-by-frequency-of-the-smallest-character_test.go b/go/compare-strings-by-frequency-of-the-smallest-character_test.go new file mode 100644 index 0000000..b71cb36 --- /dev/null +++ b/go/compare-strings-by-frequency-of-the-smallest-character_test.go @@ -0,0 +1,22 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestNumSmallerByFrequency(t *testing.T) { + if !reflect.DeepEqual( + numSmallerByFrequency( + []string{"cbd"}, + []string{"zaaaz"}), []int{1}) { + t.Fatal() + } + + if !reflect.DeepEqual( + numSmallerByFrequency( + []string{"bbb", "cc"}, + []string{"a", "aa", "aaa", "aaaa"}), []int{1, 2}) { + t.Fatal() + } +} From c212471cd2d366b05745d1d96993daaf9afa2de2 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 16:07:57 +0800 Subject: [PATCH 160/220] Add go solution for 706. Design HashMap 706. Design HashMap: https://leetcode.com/problems/design-hashmap/ --- go/design-hashmap.go | 39 +++++++++++++++++++++++++++++++++++++++ go/design-hashmap_test.go | 23 +++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 go/design-hashmap.go create mode 100644 go/design-hashmap_test.go diff --git a/go/design-hashmap.go b/go/design-hashmap.go new file mode 100644 index 0000000..0194afd --- /dev/null +++ b/go/design-hashmap.go @@ -0,0 +1,39 @@ +package leetcode + +type MyHashMap struct { + m map[int]int +} + +/** Initialize your data structure here. */ +func Constructor() MyHashMap { + return MyHashMap{ + m: make(map[int]int), + } +} + +/** value will always be non-negative. */ +func (this *MyHashMap) Put(key int, value int) { + this.m[key] = value +} + +/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ +func (this *MyHashMap) Get(key int) int { + val, ok := this.m[key] + if !ok { + return -2 + } + return val +} + +/** Removes the mapping of the specified value key if this map contains a mapping for the key */ +func (this *MyHashMap) Remove(key int) { + delete(this.m, key) +} + +/** + * Your MyHashMap object will be instantiated and called as such: + * obj := Constructor(); + * obj.Put(key,value); + * param_2 := obj.Get(key); + * obj.Remove(key); + */ diff --git a/go/design-hashmap_test.go b/go/design-hashmap_test.go new file mode 100644 index 0000000..f002574 --- /dev/null +++ b/go/design-hashmap_test.go @@ -0,0 +1,23 @@ +package leetcode + +import "testing" + +func TestHashMap(t *testing.T) { + hm := Constructor() + hm.Put(1, 1) + hm.Put(2, 2) + if hm.Get(1) != 1 { + t.Fatal() + } + if hm.Get(3) != -1 { + t.Fatal() + } + hm.Put(2, 1) + if hm.Get(2) != 1 { + t.Fatal() + } + hm.Remove(2) + if hm.Get(2) != -1 { + t.Fatal() + } +} From ca13aa4912b86a28443512ecd8585d2d1b8cdcb1 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 16:11:49 +0800 Subject: [PATCH 161/220] Add go solution for 1137. N-th Tribonacci Number 1137. N-th Tribonacci Number: https://leetcode.com/problems/n-th-tribonacci-number/ --- go/n-th-tribonacci-number.go | 9 +++++++++ go/n-th-tribonacci-number_test.go | 12 ++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 go/n-th-tribonacci-number.go create mode 100644 go/n-th-tribonacci-number_test.go diff --git a/go/n-th-tribonacci-number.go b/go/n-th-tribonacci-number.go new file mode 100644 index 0000000..e118871 --- /dev/null +++ b/go/n-th-tribonacci-number.go @@ -0,0 +1,9 @@ +package leetcode + +func tribonacci(n int) int { + a0, a1, a2 := 0, 1, 1 + for ; n > 0; n-- { + a0, a1, a2 = a1, a2, a0+a1+a2 + } + return a0 +} diff --git a/go/n-th-tribonacci-number_test.go b/go/n-th-tribonacci-number_test.go new file mode 100644 index 0000000..30fb838 --- /dev/null +++ b/go/n-th-tribonacci-number_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestTribonaci(t *testing.T) { + if tribonacci(4) != 4 { + t.Fatal() + } + if tribonacci(25) != 1389537 { + t.Fatal() + } +} From e67920f0005c92d31a96bd36ea273a30b21923fb Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 16:31:07 +0800 Subject: [PATCH 162/220] Add go solution for 892. Surface Area of 3D Shapes 892. Surface Area of 3D Shapes: https://leetcode.com/problems/surface-area-of-3d-shapes/ --- go/surface-area-of-3d-shapes.go | 49 ++++++++++++++++++++++++++++ go/surface-area-of-3d-shapes_test.go | 39 ++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 go/surface-area-of-3d-shapes.go create mode 100644 go/surface-area-of-3d-shapes_test.go diff --git a/go/surface-area-of-3d-shapes.go b/go/surface-area-of-3d-shapes.go new file mode 100644 index 0000000..f4ebb22 --- /dev/null +++ b/go/surface-area-of-3d-shapes.go @@ -0,0 +1,49 @@ +package leetcode + +func surfaceArea(grid [][]int) int { + r := len(grid) + c := len(grid[0]) + + ans := 0 + + for i, row := range grid { + for j, v := range row { + if v > 0 { + ans += 2 + } + ans += 4 * v + if i > 0 { + if v < grid[i-1][j] { + ans -= v + } else { + ans -= grid[i-1][j] + } + } + + if i < r-1 { + if v < grid[i+1][j] { + ans -= v + } else { + ans -= grid[i+1][j] + } + } + + if j > 0 { + if v < grid[i][j-1] { + ans -= v + } else { + ans -= grid[i][j-1] + } + } + + if j < c-1 { + if v < grid[i][j+1] { + ans -= v + } else { + ans -= grid[i][j+1] + } + } + } + } + return ans +} diff --git a/go/surface-area-of-3d-shapes_test.go b/go/surface-area-of-3d-shapes_test.go new file mode 100644 index 0000000..4bab4b9 --- /dev/null +++ b/go/surface-area-of-3d-shapes_test.go @@ -0,0 +1,39 @@ +package leetcode + +import "testing" + +func TestSurfaceArea(t *testing.T) { + if surfaceArea([][]int{[]int{2}}) != 10 { + t.Fatal() + } + + if surfaceArea([][]int{ + []int{1, 2}, + []int{3, 4}, + }) != 34 { + t.Fatal() + } + + if surfaceArea([][]int{ + []int{1, 0}, + []int{0, 2}, + }) != 16 { + t.Fatal() + } + + if surfaceArea([][]int{ + []int{1, 1, 1}, + []int{1, 0, 1}, + []int{1, 1, 1}, + }) != 32 { + t.Fatal() + } + + if surfaceArea([][]int{ + []int{2, 2, 2}, + []int{2, 1, 2}, + []int{2, 2, 2}, + }) != 46 { + t.Fatal() + } +} From 9d8bad8ca21a0233e611410afc8e58d39e3d524d Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 16:38:02 +0800 Subject: [PATCH 163/220] Add go solution for 705. Design HashSet 705. Design HashSet: https://leetcode.com/problems/design-hashset/ --- go/design-hashset.go | 34 ++++++++++++++++++++++++++++++++++ go/design-hashset_test.go | 23 +++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 go/design-hashset.go create mode 100644 go/design-hashset_test.go diff --git a/go/design-hashset.go b/go/design-hashset.go new file mode 100644 index 0000000..cce431e --- /dev/null +++ b/go/design-hashset.go @@ -0,0 +1,34 @@ +package main + +type MyHashSet struct { + m map[int]struct{} +} + +/** Initialize your data structure here. */ +func Constructor() MyHashSet { + return MyHashSet{ + m: make(map[int]struct{}), + } +} + +func (this *MyHashSet) Add(key int) { + this.m[key] = struct{}{} +} + +func (this *MyHashSet) Remove(key int) { + delete(this.m, key) +} + +/** Returns true if this set contains the specified element */ +func (this *MyHashSet) Contains(key int) bool { + _, ok := this.m[key] + return ok +} + +/** + * Your MyHashSet object will be instantiated and called as such: + * obj := Constructor(); + * obj.Add(key); + * obj.Remove(key); + * param_3 := obj.Contains(key); + */ diff --git a/go/design-hashset_test.go b/go/design-hashset_test.go new file mode 100644 index 0000000..420bc0a --- /dev/null +++ b/go/design-hashset_test.go @@ -0,0 +1,23 @@ +package main + +import "testing" + +func TestHashSet(t *testing.T) { + hs := Constructor() + hs.Add(1) + hs.Add(2) + if hs.Contains(1) != true { + t.Fatal() + } + if hs.Contains(3) != false { + t.Fatal() + } + hs.Add(2) + if hs.Contains(2) != true { + t.Fatal() + } + hs.Remove(2) + if hs.Contains(2) != false { + t.Fatal() + } +} From b9e0e4c0889014ee209ed5591ab3cf1abb6972e0 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 16:45:29 +0800 Subject: [PATCH 164/220] Add go solution for 976. Largest Perimeter Triangle 976. Largest Perimeter Triangle: https://leetcode.com/problems/largest-perimeter-triangle/ --- go/largest-perimeter-triangle.go | 14 ++++++++++++++ go/largest-perimeter-triangle_test.go | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 go/largest-perimeter-triangle.go create mode 100644 go/largest-perimeter-triangle_test.go diff --git a/go/largest-perimeter-triangle.go b/go/largest-perimeter-triangle.go new file mode 100644 index 0000000..9f5f407 --- /dev/null +++ b/go/largest-perimeter-triangle.go @@ -0,0 +1,14 @@ +package leetcode + +import "sort" + +func largestPerimeter(A []int) int { + sort.Ints(A) + l := len(A) + for i := l - 1; i >= 2; i-- { + if A[i-1]+A[i-2] > A[i] { + return A[i-1] + A[i-2] + A[i] + } + } + return 0 +} diff --git a/go/largest-perimeter-triangle_test.go b/go/largest-perimeter-triangle_test.go new file mode 100644 index 0000000..a05f431 --- /dev/null +++ b/go/largest-perimeter-triangle_test.go @@ -0,0 +1,18 @@ +package leetcode + +import "testing" + +func TestLargestPerimeter(t *testing.T) { + if largestPerimeter([]int{2, 1, 2}) != 5 { + t.Fatal() + } + if largestPerimeter([]int{1, 2, 1}) != 0 { + t.Fatal() + } + if largestPerimeter([]int{3, 2, 3, 4}) != 10 { + t.Fatal() + } + if largestPerimeter([]int{3, 6, 2, 3}) != 8 { + t.Fatal() + } +} From 0de24917f54ef98562841c588020f594c73ec47f Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 16:52:29 +0800 Subject: [PATCH 165/220] Add go solution for 812. Largest Triangle Area 812. Largest Triangle Area: https://leetcode.com/problems/largest-triangle-area/ --- go/largest-triangle-area.go | 22 ++++++++++++++++++++++ go/largest-triangle-area_test.go | 16 ++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 go/largest-triangle-area.go create mode 100644 go/largest-triangle-area_test.go diff --git a/go/largest-triangle-area.go b/go/largest-triangle-area.go new file mode 100644 index 0000000..b5a0d80 --- /dev/null +++ b/go/largest-triangle-area.go @@ -0,0 +1,22 @@ +package leetcode + +import "math" + +func largestTriangleArea(points [][]int) float64 { + l := len(points) + ans := 0. + for i := 0; i < l; i++ { + for j := 0; j < i; j++ { + for k := 0; k < j; k++ { + p1, p2, p3 := points[i], points[j], points[k] + left := p1[0]*p2[1] + p2[0]*p3[1] + p3[0]*p1[1] + right := p1[1]*p2[0] + p2[1]*p3[0] + p3[1]*p1[0] + area := math.Abs(float64(left-right) / 2) + if area > ans { + ans = area + } + } + } + } + return ans +} diff --git a/go/largest-triangle-area_test.go b/go/largest-triangle-area_test.go new file mode 100644 index 0000000..4169a2a --- /dev/null +++ b/go/largest-triangle-area_test.go @@ -0,0 +1,16 @@ +package leetcode + +import "testing" + +func TestLargestTriangleArea(t *testing.T) { + points := [][]int{ + []int{0, 0}, + []int{0, 1}, + []int{1, 0}, + []int{0, 2}, + []int{2, 0}, + } + if largestTriangleArea(points) != 2. { + t.Fatal() + } +} From 30c10d2196225680e700f94318964512990faf4f Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 17:04:11 +0800 Subject: [PATCH 166/220] Add go solution for 521. Longest Uncommon Subsequence I 521. Longest Uncommon Subsequence I: https://leetcode.com/problems/longest-uncommon-subsequence-i/ --- go/longest-uncommon-subsequence-i.go | 14 ++++++++++++++ go/longest-uncommon-subsequence-i_test.go | 9 +++++++++ 2 files changed, 23 insertions(+) create mode 100644 go/longest-uncommon-subsequence-i.go create mode 100644 go/longest-uncommon-subsequence-i_test.go diff --git a/go/longest-uncommon-subsequence-i.go b/go/longest-uncommon-subsequence-i.go new file mode 100644 index 0000000..165bcf5 --- /dev/null +++ b/go/longest-uncommon-subsequence-i.go @@ -0,0 +1,14 @@ +package leetcode + +func findLUSlength(a string, b string) int { + la, lb := len(a), len(b) + if la > lb { + return la + } else if la < lb { + return lb + } + if a != b { + return la + } + return -1 +} diff --git a/go/longest-uncommon-subsequence-i_test.go b/go/longest-uncommon-subsequence-i_test.go new file mode 100644 index 0000000..0cf1c0b --- /dev/null +++ b/go/longest-uncommon-subsequence-i_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestFindLUSlength(t *testing.T) { + if findLUSlength("aba", "cdc") != 3 { + t.Fatal() + } +} From a7b9ad9ac3edc5cdce565378747a4886c084b970 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 17:19:07 +0800 Subject: [PATCH 167/220] Add go solution for 888. Fair Candy Swap 888. Fair Candy Swap: https://leetcode.com/problems/fair-candy-swap/ --- go/fair-candy-swap.go | 23 +++++++++++++++++++++++ go/fair-candy-swap_test.go | 12 ++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 go/fair-candy-swap.go create mode 100644 go/fair-candy-swap_test.go diff --git a/go/fair-candy-swap.go b/go/fair-candy-swap.go new file mode 100644 index 0000000..9959f59 --- /dev/null +++ b/go/fair-candy-swap.go @@ -0,0 +1,23 @@ +package leetcode + +func fairCandySwap(A []int, B []int) []int { + sA, sB := 0, 0 + for _, v := range A { + sA += v + } + + for _, v := range B { + sB += v + } + + m := make(map[int]struct{}) + for _, v := range A { + m[v] = struct{}{} + } + for _, v := range B { + if _, ok := m[v-(sB-sA)/2]; ok { + return []int{v - (sB-sA)/2, v} + } + } + return nil +} diff --git a/go/fair-candy-swap_test.go b/go/fair-candy-swap_test.go new file mode 100644 index 0000000..6d9a05c --- /dev/null +++ b/go/fair-candy-swap_test.go @@ -0,0 +1,12 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestFairCandySwap(t *testing.T) { + if !reflect.DeepEqual(fairCandySwap([]int{1, 2, 5}, []int{2, 4}), []int{5, 4}) { + t.Fatal() + } +} From d1ae505d98a74d5d4bb8596413a10b1d42925e24 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 30 Dec 2019 17:46:17 +0800 Subject: [PATCH 168/220] Add go solution for 1013. Partition Array Into Three Parts With Equal Sum 1013. Partition Array Into Three Parts With Equal Sum: https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/ --- ...n-array-into-three-parts-with-equal-sum.go | 32 +++++++++++++++++++ ...ay-into-three-parts-with-equal-sum_test.go | 15 +++++++++ 2 files changed, 47 insertions(+) create mode 100644 go/partition-array-into-three-parts-with-equal-sum.go create mode 100644 go/partition-array-into-three-parts-with-equal-sum_test.go diff --git a/go/partition-array-into-three-parts-with-equal-sum.go b/go/partition-array-into-three-parts-with-equal-sum.go new file mode 100644 index 0000000..24a4cd4 --- /dev/null +++ b/go/partition-array-into-three-parts-with-equal-sum.go @@ -0,0 +1,32 @@ +package leetcode + +func canThreePartsEqualSum(A []int) bool { + lA := len(A) + s := 0 + for _, v := range A { + s += v + } + if s%3 != 0 { + return false + } + left := 0 + var i int + for i = 0; i < lA-2; i++ { + left += A[i] + if left == s/3 { + break + } + } + if i == lA-2 { + return false + } + i++ + mid := 0 + for ; i < lA-1; i++ { + mid += A[i] + if mid == s/3 { + break + } + } + return i != lA-1 +} diff --git a/go/partition-array-into-three-parts-with-equal-sum_test.go b/go/partition-array-into-three-parts-with-equal-sum_test.go new file mode 100644 index 0000000..b649b52 --- /dev/null +++ b/go/partition-array-into-three-parts-with-equal-sum_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestCanThreePartsEqualSum(t *testing.T) { + if canThreePartsEqualSum([]int{0, 2, 1, -6, 6, -7, 9, 1, 2, 0, 1}) != true { + t.Fatal() + } + if canThreePartsEqualSum([]int{0, 2, 1, -6, 6, 7, 9, -1, 2, 0, 1}) != false { + t.Fatal() + } + if canThreePartsEqualSum([]int{3, 3, 6, 5, -2, 2, 5, 1, -9, 4}) != true { + t.Fatal() + } +} From 643d1bd7227817de808bb72b4f3346fadb0718e7 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 31 Dec 2019 13:15:34 +0800 Subject: [PATCH 169/220] Add go solution for 917. Reverse Only Letters 917. Reverse Only Letters: https://leetcode.com/problems/reverse-only-letters/ --- go/reverse-only-letters.go | 23 +++++++++++++++++++++++ go/reverse-only-letters_test.go | 15 +++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 go/reverse-only-letters.go create mode 100644 go/reverse-only-letters_test.go diff --git a/go/reverse-only-letters.go b/go/reverse-only-letters.go new file mode 100644 index 0000000..74e8454 --- /dev/null +++ b/go/reverse-only-letters.go @@ -0,0 +1,23 @@ +package leetcode + +import "unicode" + +func reverseOnlyLetters(S string) string { + lS := len(S) + outS := make([]rune, lS) + head, tail := 0, lS-1 + for head <= tail { + if !unicode.IsLetter(rune(S[head])) { + outS[head] = rune(S[head]) + head++ + } else if !unicode.IsLetter(rune(S[tail])) { + outS[tail] = rune(S[tail]) + tail-- + } else { + outS[head], outS[tail] = rune(S[tail]), rune(S[head]) + head++ + tail-- + } + } + return string(outS) +} diff --git a/go/reverse-only-letters_test.go b/go/reverse-only-letters_test.go new file mode 100644 index 0000000..c2bc07e --- /dev/null +++ b/go/reverse-only-letters_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestReverseOnlyLetters(t *testing.T) { + if reverseOnlyLetters("ab-cd") != "dc-ba" { + t.Fatal() + } + if reverseOnlyLetters("a-bC-dEf-ghIj") != "j-Ih-gfE-dCba" { + t.Fatal() + } + if reverseOnlyLetters("Test1ng-Leet=code-Q!") != "Qedo1ct-eeLg=ntse-T!" { + t.Fatal() + } +} From 2c3a9f166f52f14ee5a3a5444f53bc0ccc8b3e85 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 31 Dec 2019 14:46:01 +0800 Subject: [PATCH 170/220] Add go solution for 896. Monotonic Array 896. Monotonic Array: https://leetcode.com/problems/monotonic-array/ --- go/monotonic-array.go | 31 +++++++++++++++++++++++++++++++ go/monotonic-array_test.go | 21 +++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 go/monotonic-array.go create mode 100644 go/monotonic-array_test.go diff --git a/go/monotonic-array.go b/go/monotonic-array.go new file mode 100644 index 0000000..b707990 --- /dev/null +++ b/go/monotonic-array.go @@ -0,0 +1,31 @@ +package leetcode + +func isMonotonic(A []int) bool { + lA := len(A) + if lA <= 1 { + return true + } + check := false + var increasing bool + for idx, n := range A { + if idx > 0 { + prev := A[idx-1] + if !check { + if n > prev { + increasing = true + check = true + } else if n < prev { + increasing = false + check = true + } + } else { + if n != prev { + if increasing != (n > prev) { + return false + } + } + } + } + } + return true +} diff --git a/go/monotonic-array_test.go b/go/monotonic-array_test.go new file mode 100644 index 0000000..2e6157d --- /dev/null +++ b/go/monotonic-array_test.go @@ -0,0 +1,21 @@ +package leetcode + +import "testing" + +func TestIsMonotonic(t *testing.T) { + if isMonotonic([]int{1, 2, 2, 3}) != true { + t.Fatal() + } + if isMonotonic([]int{6, 5, 4, 4}) != true { + t.Fatal() + } + if isMonotonic([]int{1, 3, 2}) != false { + t.Fatal() + } + if isMonotonic([]int{1, 2, 4, 5}) != true { + t.Fatal() + } + if isMonotonic([]int{1, 1, 1}) != true { + t.Fatal() + } +} From fd0d0b05e0b0b8b43d5c77dbcbf2723ba9066872 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 14:04:34 +0800 Subject: [PATCH 171/220] Add go solution for 788. Rotated Digits 788. Rotated Digits: https://leetcode.com/problems/rotated-digits/ --- go/rotated-digits.go | 65 +++++++++++++++++++++++++++++++++++++++ go/rotated-digits_test.go | 9 ++++++ 2 files changed, 74 insertions(+) create mode 100644 go/rotated-digits.go create mode 100644 go/rotated-digits_test.go diff --git a/go/rotated-digits.go b/go/rotated-digits.go new file mode 100644 index 0000000..ac248fa --- /dev/null +++ b/go/rotated-digits.go @@ -0,0 +1,65 @@ +package leetcode + +import "fmt" + +func rotatedDigits(N int) int { + dec := false + // 0 1 2 5 6 8 9 + tN := 0 + for t := 10000; t > 0; t /= 10 { + tN *= 7 + if !dec { + d := (N / t) % 10 + switch d { + case 0: + tN += 0 + case 1: + tN += 1 + case 2: + tN += 2 + case 3, 4: + tN += 2 + dec = true + case 5: + tN += 3 + case 6: + tN += 4 + case 7: + tN += 4 + dec = true + case 8: + tN += 5 + case 9: + tN += 6 + } + } else { + tN += 6 + } + } + fmt.Printf("tN = %d\n", tN) + same := 0 + dec = false + for t := 7 * 7 * 7 * 7; t > 0; t /= 7 { + d := (tN / t) % 7 + same *= 3 + if !dec { + switch d { + case 0: + same += 0 + case 1: + same += 1 + case 2, 3, 4: + same += 1 + dec = true + case 5: + same += 2 + case 6: + same += 2 + dec = true + } + } else { + same += 2 + } + } + return tN - same +} diff --git a/go/rotated-digits_test.go b/go/rotated-digits_test.go new file mode 100644 index 0000000..3f79de3 --- /dev/null +++ b/go/rotated-digits_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestRotatedDigits(t *testing.T) { + if rotatedDigits(10) != 4 { + t.Fatal() + } +} From e6286357f764e8f2ef27282bac65af7fb6728f7a Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 14:16:34 +0800 Subject: [PATCH 172/220] Add go solution for 748. Shortest Completing Word 748. Shortest Completing Word: https://leetcode.com/problems/shortest-completing-word/ --- go/shortest-completing-word.go | 37 +++++++++++++++++++++++++++++ go/shortest-completing-word_test.go | 12 ++++++++++ 2 files changed, 49 insertions(+) create mode 100644 go/shortest-completing-word.go create mode 100644 go/shortest-completing-word_test.go diff --git a/go/shortest-completing-word.go b/go/shortest-completing-word.go new file mode 100644 index 0000000..d0d547e --- /dev/null +++ b/go/shortest-completing-word.go @@ -0,0 +1,37 @@ +package leetcode + +import "unicode" + +func shortestCompletingWord(licensePlate string, words []string) string { + pcounter := make(map[rune]int) + used := 0 + for _, c := range licensePlate { + if unicode.IsLetter(c) { + c = unicode.ToLower(c) + if _, ok := pcounter[c]; !ok { + used++ + } + pcounter[c]++ + } + } + l, ans := -1, "" + for _, w := range words { + rem := used + tmp := make(map[rune]int) + for _, c := range w { + if unicode.IsLetter(c) { + c = unicode.ToLower(c) + tmp[c]++ + if tmp[c] == pcounter[c] { + rem-- + if rem == 0 { + if l == -1 || len(w) < l { + l, ans = len(w), w + } + } + } + } + } + } + return ans +} diff --git a/go/shortest-completing-word_test.go b/go/shortest-completing-word_test.go new file mode 100644 index 0000000..7b7aa30 --- /dev/null +++ b/go/shortest-completing-word_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestShortestCompletingWord(t *testing.T) { + if shortestCompletingWord("1s3 PSt", []string{"step", "steps", "stripe", "stepple"}) != "steps" { + t.Fatal() + } + if shortestCompletingWord("1s3 456", []string{"looks", "pest", "stew", "show"}) != "pest" { + t.Fatal() + } +} From a60fd5ba6d5b1308b88941cdafc97adfd20f9fe5 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 14:21:36 +0800 Subject: [PATCH 173/220] Add go solution for 1184. Distance Between Bus Stops 1184. Distance Between Bus Stops: https://leetcode.com/problems/distance-between-bus-stops/ --- go/distance-between-bus-stops.go | 18 ++++++++++++++++++ go/distance-between-bus-stops_test.go | 12 ++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 go/distance-between-bus-stops.go create mode 100644 go/distance-between-bus-stops_test.go diff --git a/go/distance-between-bus-stops.go b/go/distance-between-bus-stops.go new file mode 100644 index 0000000..5dab610 --- /dev/null +++ b/go/distance-between-bus-stops.go @@ -0,0 +1,18 @@ +package leetcode + +func distanceBetweenBusStops(distance []int, start int, destination int) int { + n := len(distance) + s := 0 + for _, v := range distance { + s += v + } + p := 0 + for t := start; t != destination; t = (t + 1) % n { + p += distance[t] + } + if p > s-p { + return s - p + } else { + return p + } +} diff --git a/go/distance-between-bus-stops_test.go b/go/distance-between-bus-stops_test.go new file mode 100644 index 0000000..295225a --- /dev/null +++ b/go/distance-between-bus-stops_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestDistanceBetweenBusStops(t *testing.T) { + if distanceBetweenBusStops([]int{1, 2, 3, 4}, 0, 1) != 1 { + t.Fatal() + } + if distanceBetweenBusStops([]int{1, 2, 3, 4}, 0, 2) != 3 { + t.Fatal() + } +} From 6d4c3b375f1a68ff5603d47f58794bf3feade8a1 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 14:34:49 +0800 Subject: [PATCH 174/220] Add go solution for 1029. Two City Scheduling 1029. Two City Scheduling: https://leetcode.com/problems/two-city-scheduling/ --- go/two-city-scheduling.go | 44 ++++++++++++++++++++++++++++++++++ go/two-city-scheduling_test.go | 14 +++++++++++ 2 files changed, 58 insertions(+) create mode 100644 go/two-city-scheduling.go create mode 100644 go/two-city-scheduling_test.go diff --git a/go/two-city-scheduling.go b/go/two-city-scheduling.go new file mode 100644 index 0000000..2250fb7 --- /dev/null +++ b/go/two-city-scheduling.go @@ -0,0 +1,44 @@ +package leetcode + +import "sort" + +type people struct { + A int + B int + diff int +} + +type bydiff []people + +func (ps bydiff) Len() int { + return len(ps) +} + +func (ps bydiff) Less(i, j int) bool { + return ps[i].diff < ps[j].diff +} + +func (ps bydiff) Swap(i, j int) { + ps[i], ps[j] = ps[j], ps[i] +} + +func twoCitySchedCost(costs [][]int) int { + n := len(costs) + p := make(bydiff, 0, n) + for _, cost := range costs { + p = append(p, people{ + A: cost[0], + B: cost[1], + diff: cost[0] - cost[1], + }) + } + sort.Sort(p) + ans := 0 + for i := 0; i < n/2; i++ { + ans += p[i].A + } + for i := n / 2; i < n; i++ { + ans += p[i].B + } + return ans +} diff --git a/go/two-city-scheduling_test.go b/go/two-city-scheduling_test.go new file mode 100644 index 0000000..4c359b3 --- /dev/null +++ b/go/two-city-scheduling_test.go @@ -0,0 +1,14 @@ +package leetcode + +import "testing" + +func TestTwoCitySchedCost(t *testing.T) { + if twoCitySchedCost([][]int{ + []int{10, 20}, + []int{30, 200}, + []int{400, 50}, + []int{30, 20}, + }) != 110 { + t.Fatal() + } +} From b9dd8a52844a7a4dea01ec11d6713e0842e424b1 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 15:47:29 +0800 Subject: [PATCH 175/220] Add go solution for 953. Verifying an Alien Dictionary 953. Verifying an Alien Dictionary: https://leetcode.com/problems/verifying-an-alien-dictionary/ --- go/verifying-an-alien-dictionary.go | 31 ++++++++++++++++++++++++ go/verifying-an-alien-dictionary_test.go | 12 +++++++++ 2 files changed, 43 insertions(+) create mode 100644 go/verifying-an-alien-dictionary.go create mode 100644 go/verifying-an-alien-dictionary_test.go diff --git a/go/verifying-an-alien-dictionary.go b/go/verifying-an-alien-dictionary.go new file mode 100644 index 0000000..7d801b4 --- /dev/null +++ b/go/verifying-an-alien-dictionary.go @@ -0,0 +1,31 @@ +package leetcode + +func less(s1, s2 string, rev map[rune]int) bool { + l1, l2 := len(s1), len(s2) + i, j := 0, 0 + for i < l1 && j < l2 { + m1, m2 := rev[rune(s1[i])], rev[rune(s2[j])] + if m1 > m2 { + return false + } else if m1 < m2 { + return true + } + i++ + j++ + } + return i == l1 +} + +func isAlienSorted(words []string, order string) bool { + rev := make(map[rune]int) + for i, c := range order { + rev[c] = i + } + l := len(words) + for i := 1; i < l; i++ { + if !less(words[i-1], words[i], rev) { + return false + } + } + return true +} diff --git a/go/verifying-an-alien-dictionary_test.go b/go/verifying-an-alien-dictionary_test.go new file mode 100644 index 0000000..b8fbbcf --- /dev/null +++ b/go/verifying-an-alien-dictionary_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestIsAlienSorted(t *testing.T) { + if isAlienSorted([]string{"hello", "leetcode"}, "hlabcdefgijkmnopqrstuvwxyz") != true { + t.Fatal() + } + if isAlienSorted([]string{"word", "world", "row"}, "worldabcefghijkmnpqstuvxyz") != false { + t.Fatal() + } +} From 390090105b22c2bfd50845dc5fa94d4c8cb291e4 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 16:01:42 +0800 Subject: [PATCH 176/220] Add go solution for 1275. Find Winner on a Tic Tac Toe Game 1275. Find Winner on a Tic Tac Toe Game: https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/ --- go/find-winner-on-a-tic-tac-toe-game.go | 46 ++++++++++++++++++++ go/find-winner-on-a-tic-tac-toe-game_test.go | 38 ++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 go/find-winner-on-a-tic-tac-toe-game.go create mode 100644 go/find-winner-on-a-tic-tac-toe-game_test.go diff --git a/go/find-winner-on-a-tic-tac-toe-game.go b/go/find-winner-on-a-tic-tac-toe-game.go new file mode 100644 index 0000000..8a59a00 --- /dev/null +++ b/go/find-winner-on-a-tic-tac-toe-game.go @@ -0,0 +1,46 @@ +package leetcode + +func tictactoe(moves [][]int) string { + grid := [][]rune{ + []rune("..."), + []rune("..."), + []rune("..."), + } + for idx, move := range moves { + x, y := move[0], move[1] + if idx%2 == 0 { + grid[x][y] = 'X' + if grid[x][0] == grid[x][1] && grid[x][1] == grid[x][2] { + return "A" + } + if grid[0][y] == grid[1][y] && grid[1][y] == grid[2][y] { + return "A" + } + if grid[0][0] != '.' && grid[0][0] == grid[1][1] && grid[1][1] == grid[2][2] { + return "A" + } + if grid[2][0] != '.' && grid[2][0] == grid[1][1] && grid[1][1] == grid[0][2] { + return "A" + } + } else { + grid[x][y] = 'O' + if grid[x][0] == grid[x][1] && grid[x][1] == grid[x][2] { + return "B" + } + if grid[0][y] == grid[1][y] && grid[1][y] == grid[2][y] { + return "B" + } + if grid[0][0] != '.' && grid[0][0] == grid[1][1] && grid[1][1] == grid[2][2] { + return "B" + } + if grid[2][0] != '.' && grid[2][0] == grid[1][1] && grid[1][1] == grid[0][2] { + return "B" + } + } + } + if len(moves) == 9 { + return "Draw" + } else { + return "Pending" + } +} diff --git a/go/find-winner-on-a-tic-tac-toe-game_test.go b/go/find-winner-on-a-tic-tac-toe-game_test.go new file mode 100644 index 0000000..c9d54b3 --- /dev/null +++ b/go/find-winner-on-a-tic-tac-toe-game_test.go @@ -0,0 +1,38 @@ +package leetcode + +import "testing" + +func TestTictactoe(t *testing.T) { + if tictactoe([][]int{ + []int{0, 0}, + []int{2, 0}, + []int{1, 1}, + []int{2, 1}, + []int{2, 2}, + }) != "A" { + t.Fatal() + } + if tictactoe([][]int{ + []int{0, 0}, + []int{1, 1}, + []int{0, 1}, + []int{0, 2}, + []int{1, 0}, + []int{2, 0}, + }) != "B" { + t.Fatal() + } + if tictactoe([][]int{ + []int{0, 0}, + []int{1, 1}, + []int{2, 0}, + []int{1, 0}, + []int{1, 2}, + []int{2, 1}, + []int{0, 1}, + []int{0, 2}, + []int{2, 2}, + }) != "Draw" { + t.Fatal() + } +} From 0dfef82b5113259e2e0bd8bb3c207f4ee866810f Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 16:20:19 +0800 Subject: [PATCH 177/220] Add go solution for 1071. Greatest Common Divisor of Strings 1071. Greatest Common Divisor of Strings: https://leetcode.com/problems/greatest-common-divisor-of-strings/ --- go/greatest-common-divisor-of-strings.go | 22 +++++++++++++++++++ go/greatest-common-divisor-of-strings_test.go | 15 +++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 go/greatest-common-divisor-of-strings.go create mode 100644 go/greatest-common-divisor-of-strings_test.go diff --git a/go/greatest-common-divisor-of-strings.go b/go/greatest-common-divisor-of-strings.go new file mode 100644 index 0000000..86281f1 --- /dev/null +++ b/go/greatest-common-divisor-of-strings.go @@ -0,0 +1,22 @@ +package leetcode + +func gcdOfStrings(str1 string, str2 string) string { + l1, l2 := len(str1), len(str2) + if l1 < l2 { + if str1[:l1] != str2[:l1] { + return "" + } + return gcdOfStrings(str1, str2[l1:]) + } else if l1 > l2 { + if str1[:l2] != str2[:l2] { + return "" + } + return gcdOfStrings(str1[l2:], str2) + } + + if str1 == str2 { + return str1 + } else { + return "" + } +} diff --git a/go/greatest-common-divisor-of-strings_test.go b/go/greatest-common-divisor-of-strings_test.go new file mode 100644 index 0000000..1a97425 --- /dev/null +++ b/go/greatest-common-divisor-of-strings_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestGcdOfStrings(t *testing.T) { + if gcdOfStrings("ABCABC", "ABC") != "ABC" { + t.Fatal() + } + if gcdOfStrings("ABABAB", "ABAB") != "AB" { + t.Fatal() + } + if gcdOfStrings("LEET", "CODE") != "" { + t.Fatal() + } +} From 6f56b730b596456b32f8218b7d27a4497d60818d Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 16:36:41 +0800 Subject: [PATCH 178/220] Add go solution for 937. Reorder Data in Log Files 937. Reorder Data in Log Files: https://leetcode.com/problems/reorder-data-in-log-files/ --- go/reorder-data-in-log-files.go | 47 ++++++++++++++++++++++++++++ go/reorder-data-in-log-files_test.go | 32 +++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 go/reorder-data-in-log-files.go create mode 100644 go/reorder-data-in-log-files_test.go diff --git a/go/reorder-data-in-log-files.go b/go/reorder-data-in-log-files.go new file mode 100644 index 0000000..e833c32 --- /dev/null +++ b/go/reorder-data-in-log-files.go @@ -0,0 +1,47 @@ +package leetcode + +import ( + "sort" + "strings" + "unicode" +) + +type logs []string + +func (l logs) Len() int { + return len(l) +} + +func (l logs) Less(i, j int) bool { + sp1 := strings.Split(l[i], " ") + sp2 := strings.Split(l[j], " ") + if unicode.IsDigit(rune(sp1[1][0])) && unicode.IsDigit(rune(sp2[1][0])) { + return false + } else if unicode.IsDigit(rune(sp1[1][0])) { + return false + } else if unicode.IsDigit(rune(sp2[1][0])) { + return true + } + l1, l2 := len(sp1), len(sp2) + t1, t2 := 1, 1 + for t1 < l1 && t2 < l2 { + if sp1[t1] < sp2[t2] { + return true + } else if sp1[t1] > sp2[t2] { + return false + } + t1++ + t2++ + } + return t1 == l1 +} + +func (l logs) Swap(i, j int) { + l[i], l[j] = l[j], l[i] +} + +func reorderLogFiles(logs_input []string) []string { + l := logs(logs_input) + sort.Stable(l) + return []string(l) +} diff --git a/go/reorder-data-in-log-files_test.go b/go/reorder-data-in-log-files_test.go new file mode 100644 index 0000000..808abd5 --- /dev/null +++ b/go/reorder-data-in-log-files_test.go @@ -0,0 +1,32 @@ +package leetcode + +import ( + "fmt" + "reflect" + "testing" +) + +func TestReorderLogFiles(t *testing.T) { + for _, s := range reorderLogFiles([]string{"dig1 8 1 5 1", + "let1 art can", + "dig2 3 6", + "let2 own kit dig", + "let3 art zero", + }) { + fmt.Println(s) + } + if !reflect.DeepEqual(reorderLogFiles([]string{"dig1 8 1 5 1", + "let1 art can", + "dig2 3 6", + "let2 own kit dig", + "let3 art zero", + }), + []string{"let1 art can", + "let3 art zero", + "let2 own kit dig", + "dig1 8 1 5 1", + "dig2 3 6", + }) { + t.Fatal() + } +} From c05292fb88bc011723797992e70393fe5abc17f1 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 17:07:41 +0800 Subject: [PATCH 179/220] Add go solution for 733. Flood Fill 733. Flood Fill: https://leetcode.com/problems/flood-fill/ --- go/flood-fill.go | 51 +++++++++++++++++++++++++++++++++++++++++++ go/flood-fill_test.go | 20 +++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 go/flood-fill.go create mode 100644 go/flood-fill_test.go diff --git a/go/flood-fill.go b/go/flood-fill.go new file mode 100644 index 0000000..d38f7b9 --- /dev/null +++ b/go/flood-fill.go @@ -0,0 +1,51 @@ +package leetcode + +type pos struct { + x int + y int +} + +func floodFill(image [][]int, sr int, sc int, newColor int) [][]int { + h, w := len(image), len(image[0]) + size := h * w + queue := make([]pos, size) + head, tail := 0, 0 + oldColor := image[sr][sc] + if oldColor == newColor { + return image + } + queue[head] = pos{x: sr, y: sc} + image[sr][sc] = newColor + head++ + for head != tail { + cur := queue[tail] + tail = (tail + 1) % size + var nx, ny int + + nx, ny = cur.x-1, cur.y + if nx >= 0 && image[nx][ny] == oldColor { + image[nx][ny] = newColor + queue[head] = pos{x: nx, y: ny} + head = (head + 1) % size + } + nx, ny = cur.x+1, cur.y + if nx < h && image[nx][ny] == oldColor { + image[nx][ny] = newColor + queue[head] = pos{x: nx, y: ny} + head = (head + 1) % size + } + nx, ny = cur.x, cur.y-1 + if ny >= 0 && image[nx][ny] == oldColor { + image[nx][ny] = newColor + queue[head] = pos{x: nx, y: ny} + head = (head + 1) % size + } + nx, ny = cur.x, cur.y+1 + if ny < w && image[nx][ny] == oldColor { + image[nx][ny] = newColor + queue[head] = pos{x: nx, y: ny} + head = (head + 1) % size + } + } + return image +} diff --git a/go/flood-fill_test.go b/go/flood-fill_test.go new file mode 100644 index 0000000..c4820c5 --- /dev/null +++ b/go/flood-fill_test.go @@ -0,0 +1,20 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestFloodFill(t *testing.T) { + if !reflect.DeepEqual(floodFill([][]int{ + []int{1, 1, 1}, + []int{1, 1, 0}, + []int{1, 0, 1}, + }, 1, 1, 2), [][]int{ + []int{2, 2, 2}, + []int{2, 2, 0}, + []int{2, 0, 1}, + }) { + t.Fatal() + } +} From 104e6e43053a5bcb2ee84277ffa5a84af5c922dc Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 17:27:01 +0800 Subject: [PATCH 180/220] Add go solution for 993. Cousins in Binary Tree 993. Cousins in Binary Tree: https://leetcode.com/problems/cousins-in-binary-tree/ --- go/cousins-in-binary-tree.go | 51 +++++++++++++++++++++++++++++++ go/cousins-in-binary-tree_test.go | 51 +++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 go/cousins-in-binary-tree.go create mode 100644 go/cousins-in-binary-tree_test.go diff --git a/go/cousins-in-binary-tree.go b/go/cousins-in-binary-tree.go new file mode 100644 index 0000000..cfc41be --- /dev/null +++ b/go/cousins-in-binary-tree.go @@ -0,0 +1,51 @@ +package leetcode + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +type info struct { + depth int + parent int +} + +func findDepth(depth int, cur *TreeNode, x, y int, c chan info) { + if cur.Left != nil { + if cur.Left.Val == x { + c <- info{depth: depth, parent: cur.Val} + } + if cur.Left.Val == y { + c <- info{depth: depth, parent: cur.Val} + } + findDepth(depth+1, cur.Left, x, y, c) + } + if cur.Right != nil { + if cur.Right.Val == x { + c <- info{depth: depth, parent: cur.Val} + } + if cur.Right.Val == y { + c <- info{depth: depth, parent: cur.Val} + } + findDepth(depth+1, cur.Right, x, y, c) + } +} + +func isCousins(root *TreeNode, x int, y int) bool { + if root == nil { + return false + } + if root.Val == x || root.Val == y { + return false + } + c := make(chan info) + go findDepth(0, root, x, y, c) + a := <-c + b := <-c + + return a.depth == b.depth && a.parent != b.parent +} diff --git a/go/cousins-in-binary-tree_test.go b/go/cousins-in-binary-tree_test.go new file mode 100644 index 0000000..aeb0544 --- /dev/null +++ b/go/cousins-in-binary-tree_test.go @@ -0,0 +1,51 @@ +package leetcode + +import "testing" + +func TestFindDepth(t *testing.T) { + if isCousins(&TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 2, + Left: &TreeNode{ + Val: 4, + }, + }, + Right: &TreeNode{ + Val: 3, + }, + }, 4, 3) != false { + t.Fatal() + } + if isCousins(&TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 2, + Right: &TreeNode{ + Val: 4, + }, + }, + Right: &TreeNode{ + Val: 3, + Right: &TreeNode{ + Val: 5, + }, + }, + }, 5, 4) != true { + t.Fatal() + } + if isCousins(&TreeNode{ + Val: 1, + Left: &TreeNode{ + Val: 2, + Right: &TreeNode{ + Val: 4, + }, + }, + Right: &TreeNode{ + Val: 3, + }, + }, 2, 3) != false { + t.Fatal() + } +} From 5cacb57ea81b0589cfe9db24a10e5cbc731d3772 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 17:38:46 +0800 Subject: [PATCH 181/220] Add go solution for 783. Minimum Distance Between BST Nodes 783. Minimum Distance Between BST Nodes: https://leetcode.com/problems/minimum-distance-between-bst-nodes/ --- go/minimum-distance-between-bst-nodes.go | 35 +++++++++++++++++++ go/minimum-distance-between-bst-nodes_test.go | 23 ++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 go/minimum-distance-between-bst-nodes.go create mode 100644 go/minimum-distance-between-bst-nodes_test.go diff --git a/go/minimum-distance-between-bst-nodes.go b/go/minimum-distance-between-bst-nodes.go new file mode 100644 index 0000000..761c77c --- /dev/null +++ b/go/minimum-distance-between-bst-nodes.go @@ -0,0 +1,35 @@ +package leetcode + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func inOrder(cur *TreeNode, c chan *TreeNode) { + if cur != nil { + inOrder(cur.Left, c) + c <- cur + inOrder(cur.Right, c) + } +} + +func minDiffInBST(root *TreeNode) int { + c := make(chan *TreeNode) + go func() { + inOrder(root, c) + close(c) + }() + var prev *TreeNode = nil + minDiff := -1 + for v := range c { + if prev != nil && (minDiff == -1 || v.Val-prev.Val < minDiff) { + minDiff = v.Val - prev.Val + } + prev = v + } + return minDiff +} diff --git a/go/minimum-distance-between-bst-nodes_test.go b/go/minimum-distance-between-bst-nodes_test.go new file mode 100644 index 0000000..7890188 --- /dev/null +++ b/go/minimum-distance-between-bst-nodes_test.go @@ -0,0 +1,23 @@ +package leetcode + +import "testing" + +func TestMinDiffInBST(t *testing.T) { + if minDiffInBST(&TreeNode{ + Val: 4, + Left: &TreeNode{ + Val: 2, + Left: &TreeNode{ + Val: 1, + }, + Right: &TreeNode{ + Val: 3, + }, + }, + Right: &TreeNode{ + Val: 6, + }, + }) != 1 { + t.Fatal() + } +} From 6be4f97e3109c85c5b0c3d3f68ef5ef3fdf49e2d Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 17:47:25 +0800 Subject: [PATCH 182/220] Add go solution for 860. Lemonade Change 860. Lemonade Change: https://leetcode.com/problems/lemonade-change/ --- go/lemonade-change.go | 31 +++++++++++++++++++++++++++++++ go/lemonade-change_test.go | 15 +++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 go/lemonade-change.go create mode 100644 go/lemonade-change_test.go diff --git a/go/lemonade-change.go b/go/lemonade-change.go new file mode 100644 index 0000000..0b76bdc --- /dev/null +++ b/go/lemonade-change.go @@ -0,0 +1,31 @@ +package leetcode + +func lemonadeChange(bills []int) bool { + c5, c10 := 0, 0 + for _, v := range bills { + switch v { + case 5: + c5++ + case 10: + if c5 < 1 { + return false + } + c5-- + c10++ + case 20: + if c10 > 0 { + c10-- + if c5 < 1 { + return false + } + c5-- + } else { + if c5 < 3 { + return false + } + c5 -= 3 + } + } + } + return true +} diff --git a/go/lemonade-change_test.go b/go/lemonade-change_test.go new file mode 100644 index 0000000..ca1ca06 --- /dev/null +++ b/go/lemonade-change_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestLemonadeChange(t *testing.T) { + if lemonadeChange([]int{5, 5, 5, 10, 20}) != true { + t.Fatal() + } + if lemonadeChange([]int{5, 5, 10}) != true { + t.Fatal() + } + if lemonadeChange([]int{10, 10}) != false { + t.Fatal() + } +} From 06e7b5b0a1cc0854226c92f9164c981c913bbec8 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 18:04:13 +0800 Subject: [PATCH 183/220] Add go solution for 1005. Maximize Sum Of Array After K Negations 1005. Maximize Sum Of Array After K Negations: https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/ --- go/maximize-sum-of-array-after-k-negations.go | 47 +++++++++++++++++++ ...ize-sum-of-array-after-k-negations_test.go | 18 +++++++ 2 files changed, 65 insertions(+) create mode 100644 go/maximize-sum-of-array-after-k-negations.go create mode 100644 go/maximize-sum-of-array-after-k-negations_test.go diff --git a/go/maximize-sum-of-array-after-k-negations.go b/go/maximize-sum-of-array-after-k-negations.go new file mode 100644 index 0000000..cfdcb1a --- /dev/null +++ b/go/maximize-sum-of-array-after-k-negations.go @@ -0,0 +1,47 @@ +package leetcode + +import ( + "sort" +) + +type byAbs []int + +func (b byAbs) Len() int { + return len(b) +} + +func (b byAbs) Less(i, j int) bool { + x, y := b[i], b[j] + if x < 0 { + x = -x + } + if y < 0 { + y = -y + } + return x > y +} + +func (b byAbs) Swap(i, j int) { + b[i], b[j] = b[j], b[i] +} + +func largestSumAfterKNegations(A []int, K int) int { + ans := 0 + sort.Sort(byAbs(A)) + for _, v := range A { + if v < 0 && K > 0 { + ans -= v + K-- + } else { + ans += v + } + } + if K%2 == 1 { + if A[len(A)-1] < 0 { + ans += 2 * A[len(A)-1] + } else { + ans -= 2 * A[len(A)-1] + } + } + return ans +} diff --git a/go/maximize-sum-of-array-after-k-negations_test.go b/go/maximize-sum-of-array-after-k-negations_test.go new file mode 100644 index 0000000..3f63f66 --- /dev/null +++ b/go/maximize-sum-of-array-after-k-negations_test.go @@ -0,0 +1,18 @@ +package leetcode + +import "testing" + +func TestLargestSumAfterKNegations(t *testing.T) { + if largestSumAfterKNegations([]int{4, 2, 3}, 1) != 5 { + t.Fatal() + } + if largestSumAfterKNegations([]int{3, -1, 0, 2}, 3) != 6 { + t.Fatal() + } + if largestSumAfterKNegations([]int{2, -3, -1, 5, -4}, 2) != 13 { + t.Fatal() + } + if largestSumAfterKNegations([]int{-8, 3, -5, -3, -5, -2}, 6) != 22 { + t.Fatal() + } +} From 776570d06a6522bcbb0a5d05a6ad1b776e50fabf Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 18:12:29 +0800 Subject: [PATCH 184/220] Add go solution for 1175. Prime Arrangements 1175. Prime Arrangements: https://leetcode.com/problems/prime-arrangements/ --- go/prime-arrangements.go | 27 +++++++++++++++++++++++++++ go/prime-arrangements_test.go | 9 +++++++++ 2 files changed, 36 insertions(+) create mode 100644 go/prime-arrangements.go create mode 100644 go/prime-arrangements_test.go diff --git a/go/prime-arrangements.go b/go/prime-arrangements.go new file mode 100644 index 0000000..8237d36 --- /dev/null +++ b/go/prime-arrangements.go @@ -0,0 +1,27 @@ +package leetcode + +func numPrimeArrangements(n int) int { + const MODULUS = 1000000007 + primes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97} + nprime := 25 + L, U := -1, nprime + for L+1 < U { + m := (L + U) / 2 + if primes[m] > n { + U = m + } else { + L = m + } + } + // (n - U)! * U! + var ans uint64 = 1 + for i := 1; i <= n-U; i++ { + ans *= uint64(i) + ans %= MODULUS + } + for i := 1; i <= U; i++ { + ans *= uint64(i) + ans %= MODULUS + } + return int(ans) +} diff --git a/go/prime-arrangements_test.go b/go/prime-arrangements_test.go new file mode 100644 index 0000000..8196779 --- /dev/null +++ b/go/prime-arrangements_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestNumPrimeArrangements(t *testing.T) { + if numPrimeArrangements(100) != 682289015 { + t.Fatal() + } +} From de6efd09e1b130ba101dd3c1bc7e2d0d2b89449f Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 18:18:04 +0800 Subject: [PATCH 185/220] Add go solution for 704. Binary Search 704. Binary Search: https://leetcode.com/problems/binary-search/ --- go/binary-search.go | 17 +++++++++++++++++ go/binary-search_test.go | 12 ++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 go/binary-search.go create mode 100644 go/binary-search_test.go diff --git a/go/binary-search.go b/go/binary-search.go new file mode 100644 index 0000000..bcd3a97 --- /dev/null +++ b/go/binary-search.go @@ -0,0 +1,17 @@ +package leetcode + +func search(nums []int, target int) int { + L, U := -1, len(nums) + for L+1 < U { + m := (L + U) / 2 + if nums[m] == target { + return m + } + if nums[m] > target { + U = m + } else { + L = m + } + } + return -1 +} diff --git a/go/binary-search_test.go b/go/binary-search_test.go new file mode 100644 index 0000000..bbd7efa --- /dev/null +++ b/go/binary-search_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestSearch(t *testing.T) { + if search([]int{-1, 0, 3, 5, 9, 12}, 9) != 4 { + t.Fatal() + } + if search([]int{-1, 0, 3, 5, 9, 12}, 2) != -1 { + t.Fatal() + } +} From 1166739efae8f22999e9161901cccbe0cdb54776 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 18:25:15 +0800 Subject: [PATCH 186/220] Add go solution for 997. Find the Town Judge 997. Find the Town Judge: https://leetcode.com/problems/find-the-town-judge/ --- go/find-the-town-judge.go | 15 ++++++++++++++ go/find-the-town-judge_test.go | 37 ++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 go/find-the-town-judge.go create mode 100644 go/find-the-town-judge_test.go diff --git a/go/find-the-town-judge.go b/go/find-the-town-judge.go new file mode 100644 index 0000000..29297b7 --- /dev/null +++ b/go/find-the-town-judge.go @@ -0,0 +1,15 @@ +package leetcode + +func findJudge(N int, trust [][]int) int { + indeg, outdeg := make([]int, N), make([]int, N) + for _, t := range trust { + indeg[t[1]-1]++ + outdeg[t[0]-1]++ + } + for i := 0; i < N; i++ { + if indeg[i] == N-1 && outdeg[i] == 0 { + return i + 1 + } + } + return -1 +} diff --git a/go/find-the-town-judge_test.go b/go/find-the-town-judge_test.go new file mode 100644 index 0000000..9ed0a7d --- /dev/null +++ b/go/find-the-town-judge_test.go @@ -0,0 +1,37 @@ +package leetcode + +import "testing" + +func TestFindJudge(t *testing.T) { + if findJudge(2, [][]int{[]int{1, 2}}) != 2 { + t.Fatal() + } + if findJudge(3, [][]int{ + []int{1, 3}, + []int{2, 3}, + }) != 3 { + t.Fatal() + } + if findJudge(3, [][]int{ + []int{1, 3}, + []int{2, 3}, + []int{3, 1}, + }) != -1 { + t.Fatal() + } + if findJudge(3, [][]int{ + []int{1, 2}, + []int{2, 3}, + }) != -1 { + t.Fatal() + } + if findJudge(4, [][]int{ + []int{1, 3}, + []int{1, 4}, + []int{2, 3}, + []int{2, 4}, + []int{4, 3}, + }) != 3 { + t.Fatal() + } +} From 0699a4fb14e7dee7a346ce0b27015777b0b020ea Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 18:30:14 +0800 Subject: [PATCH 187/220] Add go solution for 796. Rotate String 796. Rotate String: https://leetcode.com/problems/rotate-string/ --- go/rotate-string.go | 17 +++++++++++++++++ go/rotate-string_test.go | 12 ++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 go/rotate-string.go create mode 100644 go/rotate-string_test.go diff --git a/go/rotate-string.go b/go/rotate-string.go new file mode 100644 index 0000000..db8e63e --- /dev/null +++ b/go/rotate-string.go @@ -0,0 +1,17 @@ +package leetcode + +func rotateString(A string, B string) bool { + lA, lB := len(A), len(B) + if lA != lB { + return false + } + if lA == 0 { + return true + } + for i := 0; i < lA; i++ { + if A[i:] == B[:lA-i] && A[:i] == B[lA-i:] { + return true + } + } + return false +} diff --git a/go/rotate-string_test.go b/go/rotate-string_test.go new file mode 100644 index 0000000..565479a --- /dev/null +++ b/go/rotate-string_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestRotateString(t *testing.T) { + if rotateString("abcde", "cdeab") != true { + t.Fatal() + } + if rotateString("abcde", "abced") != false { + t.Fatal() + } +} From b04eada83178a5e51fbb7f362d8e12b5df57841d Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Thu, 2 Jan 2020 18:36:23 +0800 Subject: [PATCH 188/220] Add go solution for 1154. Day of the Year 1154. Day of the Year: https://leetcode.com/problems/day-of-the-year/ --- go/day-of-the-year.go | 25 +++++++++++++++++++++++++ go/day-of-the-year_test.go | 18 ++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 go/day-of-the-year.go create mode 100644 go/day-of-the-year_test.go diff --git a/go/day-of-the-year.go b/go/day-of-the-year.go new file mode 100644 index 0000000..a387f99 --- /dev/null +++ b/go/day-of-the-year.go @@ -0,0 +1,25 @@ +package leetcode + +import "fmt" + +func dayOfYear(date string) int { + var y, m, d int + fmt.Sscanf(date, "%d-%d-%d", &y, &m, &d) + leap := false + if y%400 == 0 { + leap = true + } else if y%100 != 0 && y%4 == 0 { + leap = true + } + days := []int{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} + ans := 0 + if m >= 3 && leap { + // leap year + ans++ + } + for i := 1; i < m; i++ { + ans += days[i] + } + ans += d + return ans +} diff --git a/go/day-of-the-year_test.go b/go/day-of-the-year_test.go new file mode 100644 index 0000000..1177197 --- /dev/null +++ b/go/day-of-the-year_test.go @@ -0,0 +1,18 @@ +package leetcode + +import "testing" + +func TestDayOfYear(t *testing.T) { + if dayOfYear("2019-01-09") != 9 { + t.Fatal() + } + if dayOfYear("2019-02-10") != 41 { + t.Fatal() + } + if dayOfYear("2003-03-01") != 60 { + t.Fatal() + } + if dayOfYear("2004-03-01") != 61 { + t.Fatal() + } +} From 23681355d695f5e94e531f381a47c1fdad2f1402 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 14:31:43 +0800 Subject: [PATCH 189/220] Add go solution for 746. Min Cost Climbing Stairs 746. Min Cost Climbing Stairs: https://leetcode.com/problems/min-cost-climbing-stairs/ --- go/min-cost-climbing-stairs.go | 16 ++++++++++++++++ go/min-cost-climbing-stairs_test.go | 12 ++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 go/min-cost-climbing-stairs.go create mode 100644 go/min-cost-climbing-stairs_test.go diff --git a/go/min-cost-climbing-stairs.go b/go/min-cost-climbing-stairs.go new file mode 100644 index 0000000..6c20947 --- /dev/null +++ b/go/min-cost-climbing-stairs.go @@ -0,0 +1,16 @@ +package leetcode + +func minCostClimbingStairs(cost []int) int { + size := len(cost) + prev2, prev1, prev0 := 0, 0, 0 + for i := 2; i <= size; i++ { + n1, n2 := prev2+cost[i-2], prev1+cost[i-1] + if n1 > n2 { + prev0 = n2 + } else { + prev0 = n1 + } + prev2, prev1 = prev1, prev0 + } + return prev0 +} diff --git a/go/min-cost-climbing-stairs_test.go b/go/min-cost-climbing-stairs_test.go new file mode 100644 index 0000000..cb8c410 --- /dev/null +++ b/go/min-cost-climbing-stairs_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestMinCostClimbingStairs(t *testing.T) { + if minCostClimbingStairs([]int{10, 15, 20}) != 15 { + t.Fatal() + } + if minCostClimbingStairs([]int{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}) != 6 { + t.Fatal() + } +} From 3043f833bb292a6a67a791bdaecde3beae0cc9a5 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 14:45:03 +0800 Subject: [PATCH 190/220] Add go solution for 830. Positions of Large Groups 830. Positions of Large Groups: https://leetcode.com/problems/positions-of-large-groups/ --- go/positions-of-large-groups.go | 19 +++++++++++++++++++ go/positions-of-large-groups_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 go/positions-of-large-groups.go create mode 100644 go/positions-of-large-groups_test.go diff --git a/go/positions-of-large-groups.go b/go/positions-of-large-groups.go new file mode 100644 index 0000000..a12f02c --- /dev/null +++ b/go/positions-of-large-groups.go @@ -0,0 +1,19 @@ +package leetcode + +func largeGroupPositions(S string) [][]int { + start := 0 + var prev rune + ans := make([][]int, 0, len(S)/3) + for i, c := range S { + if c != prev { + if i-start >= 3 { + ans = append(ans, []int{start, i - 1}) + } + start, prev = i, c + } + } + if len(S)-start >= 3 { + ans = append(ans, []int{start, len(S) - 1}) + } + return ans +} diff --git a/go/positions-of-large-groups_test.go b/go/positions-of-large-groups_test.go new file mode 100644 index 0000000..295e0a7 --- /dev/null +++ b/go/positions-of-large-groups_test.go @@ -0,0 +1,24 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestLargeGroupPositions(t *testing.T) { + if !reflect.DeepEqual(largeGroupPositions("abbxxxxzzy"), [][]int{ + []int{3, 6}, + }) { + t.Fatal() + } + if !reflect.DeepEqual(largeGroupPositions("abc"), [][]int{}) { + t.Fatal() + } + if !reflect.DeepEqual(largeGroupPositions("abcdddeeeeaabbbcd"), [][]int{ + []int{3, 5}, + []int{6, 9}, + []int{12, 14}, + }) { + t.Fatal() + } +} From 60e2ddfb1174928ab87dd90e62e54a8140f072c9 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 14:50:26 +0800 Subject: [PATCH 191/220] Add go solution for 836. Rectangle Overlap 836. Rectangle Overlap: https://leetcode.com/problems/rectangle-overlap/ --- go/rectangle-overlap.go | 26 ++++++++++++++++++++++++++ go/rectangle-overlap_test.go | 12 ++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 go/rectangle-overlap.go create mode 100644 go/rectangle-overlap_test.go diff --git a/go/rectangle-overlap.go b/go/rectangle-overlap.go new file mode 100644 index 0000000..0327cfa --- /dev/null +++ b/go/rectangle-overlap.go @@ -0,0 +1,26 @@ +package leetcode + +func isRectangleOverlap(rec1 []int, rec2 []int) bool { + var l, r, t, b int + if rec1[0] < rec2[0] { + l = rec2[0] + } else { + l = rec1[0] + } + if rec1[2] < rec2[2] { + r = rec1[2] + } else { + r = rec2[2] + } + if rec1[1] < rec2[1] { + b = rec2[1] + } else { + b = rec1[1] + } + if rec1[3] < rec2[3] { + t = rec1[3] + } else { + t = rec2[3] + } + return t > b && r > l +} diff --git a/go/rectangle-overlap_test.go b/go/rectangle-overlap_test.go new file mode 100644 index 0000000..b037255 --- /dev/null +++ b/go/rectangle-overlap_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestIsRectangleOverlap(t *testing.T) { + if isRectangleOverlap([]int{0, 0, 2, 2}, []int{1, 1, 3, 3}) != true { + t.Fatal() + } + if isRectangleOverlap([]int{0, 0, 1, 1}, []int{1, 0, 2, 1}) != false { + t.Fatal() + } +} From 4684739f64568dbf494a5e11042f3be1bf7798c4 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 15:23:45 +0800 Subject: [PATCH 192/220] Add go solution for 1042. Flower Planting With No Adjacent 1042. Flower Planting With No Adjacent: https://leetcode.com/problems/flower-planting-with-no-adjacent/ --- go/flower-planting-with-no-adjacent.go | 26 +++++++++++++++++ go/flower-planting-with-no-adjacent_test.go | 32 +++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 go/flower-planting-with-no-adjacent.go create mode 100644 go/flower-planting-with-no-adjacent_test.go diff --git a/go/flower-planting-with-no-adjacent.go b/go/flower-planting-with-no-adjacent.go new file mode 100644 index 0000000..e497f96 --- /dev/null +++ b/go/flower-planting-with-no-adjacent.go @@ -0,0 +1,26 @@ +package leetcode + +func gardenNoAdj(N int, paths [][]int) []int { + neighbors := make([][]int, N) + for i := 0; i < N; i++ { + neighbors[i] = make([]int, 0, 3) + } + for _, path := range paths { + neighbors[path[0]-1] = append(neighbors[path[0]-1], path[1]-1) + neighbors[path[1]-1] = append(neighbors[path[1]-1], path[0]-1) + } + ans := make([]int, N) + for i := 0; i < N; i++ { + mask := 0 + for _, nb := range neighbors[i] { + mask |= 1 << uint(ans[nb]) + } + for j := 1; j <= 4; j++ { + if mask&(1< Date: Fri, 3 Jan 2020 15:59:05 +0800 Subject: [PATCH 193/220] Add go solution for 703. Kth Largest Element in a Stream 703. Kth Largest Element in a Stream: https://leetcode.com/problems/kth-largest-element-in-a-stream/ --- go/kth-largest-element-in-a-stream.go | 60 ++++++++++++++++++++++ go/kth-largest-element-in-a-stream_test.go | 22 ++++++++ 2 files changed, 82 insertions(+) create mode 100644 go/kth-largest-element-in-a-stream.go create mode 100644 go/kth-largest-element-in-a-stream_test.go diff --git a/go/kth-largest-element-in-a-stream.go b/go/kth-largest-element-in-a-stream.go new file mode 100644 index 0000000..94aeb2d --- /dev/null +++ b/go/kth-largest-element-in-a-stream.go @@ -0,0 +1,60 @@ +package leetcode + +import "container/heap" + +type minHeap []int + +func (h minHeap) Len() int { + return len(h) +} + +func (h minHeap) Less(i, j int) bool { + return h[i] < h[j] +} + +func (h minHeap) Swap(i, j int) { + h[i], h[j] = h[j], h[i] +} + +func (h *minHeap) Push(x interface{}) { + *h = append(*h, x.(int)) +} + +func (h *minHeap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[:n-1] + return x +} + +type KthLargest struct { + firstK minHeap + k int +} + +func Constructor(k int, nums []int) KthLargest { + firstK := minHeap(nums) + heap.Init(&firstK) + for len(firstK) > k { + heap.Pop(&firstK) + } + return KthLargest{ + firstK: firstK, + k: k, + } +} + +func (this *KthLargest) Add(val int) int { + heap.Push(&this.firstK, val) + for len(this.firstK) > this.k { + heap.Pop(&this.firstK) + } + return this.firstK[0] +} + +/** + * Your KthLargest object will be instantiated and called as such: + * obj := Constructor(k, nums); + * param_1 := obj.Add(val); + */ diff --git a/go/kth-largest-element-in-a-stream_test.go b/go/kth-largest-element-in-a-stream_test.go new file mode 100644 index 0000000..50272a5 --- /dev/null +++ b/go/kth-largest-element-in-a-stream_test.go @@ -0,0 +1,22 @@ +package leetcode + +import "testing" + +func TestKthLargestElementInAStream(t *testing.T) { + kth := Constructor(3, []int{4, 5, 8, 2}) + if kth.Add(3) != 4 { + t.Fatal() + } + if kth.Add(5) != 5 { + t.Fatal() + } + if kth.Add(10) != 5 { + t.Fatal() + } + if kth.Add(9) != 8 { + t.Fatal() + } + if kth.Add(4) != 8 { + t.Fatal() + } +} From 3f696b43339bbc2a5cea231cb03de10db68dff60 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 16:12:17 +0800 Subject: [PATCH 194/220] Add go solution for 1232. Check If It Is a Straight Line 1232. Check If It Is a Straight Line: https://leetcode.com/problems/check-if-it-is-a-straight-line/ --- go/check-if-it-is-a-straight-line.go | 13 +++++++++++ go/check-if-it-is-a-straight-line_test.go | 27 +++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 go/check-if-it-is-a-straight-line.go create mode 100644 go/check-if-it-is-a-straight-line_test.go diff --git a/go/check-if-it-is-a-straight-line.go b/go/check-if-it-is-a-straight-line.go new file mode 100644 index 0000000..ad949b3 --- /dev/null +++ b/go/check-if-it-is-a-straight-line.go @@ -0,0 +1,13 @@ +package leetcode + +func checkStraightLine(coordinates [][]int) bool { + dx, dy := coordinates[1][0]-coordinates[0][0], coordinates[1][1]-coordinates[0][1] + lc := len(coordinates) + for i := 2; i < lc; i++ { + tx, ty := coordinates[i][0]-coordinates[i-1][0], coordinates[i][1]-coordinates[i-1][1] + if ty*dx != dy*tx { + return false + } + } + return true +} diff --git a/go/check-if-it-is-a-straight-line_test.go b/go/check-if-it-is-a-straight-line_test.go new file mode 100644 index 0000000..fb71ba1 --- /dev/null +++ b/go/check-if-it-is-a-straight-line_test.go @@ -0,0 +1,27 @@ +package leetcode + +import "testing" + +func TestCheckStraightLine(t *testing.T) { + if checkStraightLine([][]int{ + []int{1, 2}, + []int{2, 3}, + []int{3, 4}, + []int{4, 5}, + []int{5, 6}, + []int{6, 7}, + }) != true { + t.Fatal() + } + + if checkStraightLine([][]int{ + []int{1, 1}, + []int{2, 2}, + []int{3, 4}, + []int{4, 5}, + []int{5, 6}, + []int{7, 7}, + }) != false { + t.Fatal() + } +} From b2f43ce57c7bda1225f188647ebe34d8d26c7799 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 16:26:07 +0800 Subject: [PATCH 195/220] Add go solution for 1018. Binary Prefix Divisible By 5 1018. Binary Prefix Divisible By 5: https://leetcode.com/problems/binary-prefix-divisible-by-5/ --- go/binary-prefix-divisible-by-5.go | 18 ++++++++++++++++++ go/binary-prefix-divisible-by-5_test.go | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 go/binary-prefix-divisible-by-5.go create mode 100644 go/binary-prefix-divisible-by-5_test.go diff --git a/go/binary-prefix-divisible-by-5.go b/go/binary-prefix-divisible-by-5.go new file mode 100644 index 0000000..a6b9da0 --- /dev/null +++ b/go/binary-prefix-divisible-by-5.go @@ -0,0 +1,18 @@ +package leetcode + +func prefixesDivBy5(A []int) []bool { + ans := make([]bool, len(A)) + m := 0 + t := [][]int{ + []int{0, 1}, + []int{2, 3}, + []int{4, 0}, + []int{1, 2}, + []int{3, 4}, + } + for i, v := range A { + m = t[m][v] + ans[i] = m == 0 + } + return ans +} diff --git a/go/binary-prefix-divisible-by-5_test.go b/go/binary-prefix-divisible-by-5_test.go new file mode 100644 index 0000000..78283da --- /dev/null +++ b/go/binary-prefix-divisible-by-5_test.go @@ -0,0 +1,21 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestPrefixesDivBy5(t *testing.T) { + if !reflect.DeepEqual(prefixesDivBy5([]int{0, 1, 1}), []bool{true, false, false}) { + t.Fatal() + } + if !reflect.DeepEqual(prefixesDivBy5([]int{1, 1, 1}), []bool{false, false, false}) { + t.Fatal() + } + if !reflect.DeepEqual(prefixesDivBy5([]int{0, 1, 1, 1, 1, 1}), []bool{true, false, false, false, true, false}) { + t.Fatal() + } + if !reflect.DeepEqual(prefixesDivBy5([]int{1, 1, 1, 0, 1}), []bool{false, false, false, false, false}) { + t.Fatal() + } +} From d3f4e64afe419359c62e981f3ce8efbd4ba841d6 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 16:48:09 +0800 Subject: [PATCH 196/220] Add go solution for 844. Backspace String Compare 844. Backspace String Compare: https://leetcode.com/problems/backspace-string-compare/ --- go/backspace-string-compare.go | 37 +++++++++++++++++++++++++++++ go/backspace-string-compare_test.go | 24 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 go/backspace-string-compare.go create mode 100644 go/backspace-string-compare_test.go diff --git a/go/backspace-string-compare.go b/go/backspace-string-compare.go new file mode 100644 index 0000000..18e5885 --- /dev/null +++ b/go/backspace-string-compare.go @@ -0,0 +1,37 @@ +package leetcode + +func backspaceCompare(S string, T string) bool { + lS, lT := len(S), len(T) + + iS, iT := lS-1, lT-1 + bS, bT := 0, 0 + for iS >= 0 || iT >= 0 { + for iS >= 0 && (bS > 0 || S[iS] == byte('#')) { + if S[iS] == byte('#') { + bS++ + } else { + bS-- + } + iS-- + } + for iT >= 0 && (bT > 0 || T[iT] == byte('#')) { + if T[iT] == byte('#') { + bT++ + } else { + bT-- + } + iT-- + } + if iS >= 0 && iT >= 0 { + if S[iS] != T[iT] { + return false + } else { + iS-- + iT-- + } + } else if iT >= 0 || iS >= 0 { + return false + } + } + return true +} diff --git a/go/backspace-string-compare_test.go b/go/backspace-string-compare_test.go new file mode 100644 index 0000000..44cfe40 --- /dev/null +++ b/go/backspace-string-compare_test.go @@ -0,0 +1,24 @@ +package leetcode + +import "testing" + +func TestBackspaceCompare(t *testing.T) { + if backspaceCompare("ab#c", "ad#c") != true { + t.Fatal() + } + if backspaceCompare("ab##", "c#d#") != true { + t.Fatal() + } + if backspaceCompare("a##c", "#a#c") != true { + t.Fatal() + } + if backspaceCompare("a#c", "b") != false { + t.Fatal() + } + if backspaceCompare("bbbextm", "bbb#extm") != false { + t.Fatal() + } + if backspaceCompare("nzp#o#g", "b#nzp#o#g") != true { + t.Fatal() + } +} From 710ea29410649564afedc4d5f327359a9a287a02 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 16:52:14 +0800 Subject: [PATCH 197/220] Add go solution for 1010. Pairs of Songs With Total Durations Divisible by 60 1010. Pairs of Songs With Total Durations Divisible by 60: https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ --- ...s-of-songs-with-total-durations-divisible-by-60.go | 11 +++++++++++ ...songs-with-total-durations-divisible-by-60_test.go | 9 +++++++++ 2 files changed, 20 insertions(+) create mode 100644 go/pairs-of-songs-with-total-durations-divisible-by-60.go create mode 100644 go/pairs-of-songs-with-total-durations-divisible-by-60_test.go diff --git a/go/pairs-of-songs-with-total-durations-divisible-by-60.go b/go/pairs-of-songs-with-total-durations-divisible-by-60.go new file mode 100644 index 0000000..dcde51c --- /dev/null +++ b/go/pairs-of-songs-with-total-durations-divisible-by-60.go @@ -0,0 +1,11 @@ +package leetcode + +func numPairsDivisibleBy60(time []int) int { + bucket := make([]int, 60) + ans := 0 + for _, t := range time { + ans += bucket[(60-t%60)%60] + bucket[t%60]++ + } + return ans +} diff --git a/go/pairs-of-songs-with-total-durations-divisible-by-60_test.go b/go/pairs-of-songs-with-total-durations-divisible-by-60_test.go new file mode 100644 index 0000000..1e99dd8 --- /dev/null +++ b/go/pairs-of-songs-with-total-durations-divisible-by-60_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestNumPairsDivisibleBy60(t *testing.T) { + if numPairsDivisibleBy60([]int{30, 20, 150, 100, 40}) != 3 { + t.Fatal() + } +} From e050c66cc333ffd5fff8abc47c3656d2496aeeb0 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 17:05:09 +0800 Subject: [PATCH 198/220] Add go solution for 994. Rotting Oranges 994. Rotting Oranges: https://leetcode.com/problems/rotting-oranges/ --- go/rotting-oranges.go | 54 ++++++++++++++++++++++++++++++++++++++ go/rotting-oranges_test.go | 25 ++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 go/rotting-oranges.go create mode 100644 go/rotting-oranges_test.go diff --git a/go/rotting-oranges.go b/go/rotting-oranges.go new file mode 100644 index 0000000..9264a49 --- /dev/null +++ b/go/rotting-oranges.go @@ -0,0 +1,54 @@ +package leetcode + +func orangesRotting(grid [][]int) int { + h, w := len(grid), len(grid[0]) + qsize := h*w + 1 + q := make([][]int, qsize) + head, tail := 0, 0 + rotten := 0 + for r, row := range grid { + for c, v := range row { + if v == 2 { + q[head] = []int{r, c, 0} + head = (head + 1) % qsize + } + if v > 0 { + rotten++ + } + } + } + + ans := 0 + for head != tail { + state := q[tail] + tail = (tail + 1) % qsize + r, c, t := state[0], state[1], state[2] + ans = t + rotten-- + if r > 0 && grid[r-1][c] == 1 { + grid[r-1][c] = 2 + q[head] = []int{r - 1, c, t + 1} + head = (head + 1) % qsize + } + if r < h-1 && grid[r+1][c] == 1 { + grid[r+1][c] = 2 + q[head] = []int{r + 1, c, t + 1} + head = (head + 1) % qsize + } + if c > 0 && grid[r][c-1] == 1 { + grid[r][c-1] = 2 + q[head] = []int{r, c - 1, t + 1} + head = (head + 1) % qsize + } + if c < w-1 && grid[r][c+1] == 1 { + grid[r][c+1] = 2 + q[head] = []int{r, c + 1, t + 1} + head = (head + 1) % qsize + } + } + if rotten > 0 { + return -1 + } else { + return ans + } +} diff --git a/go/rotting-oranges_test.go b/go/rotting-oranges_test.go new file mode 100644 index 0000000..fc9d568 --- /dev/null +++ b/go/rotting-oranges_test.go @@ -0,0 +1,25 @@ +package leetcode + +import "testing" + +func TestOrangesRotting(t *testing.T) { + if orangesRotting([][]int{ + []int{2, 1, 1}, + []int{1, 1, 0}, + []int{0, 1, 1}, + }) != 4 { + t.Fatal() + } + if orangesRotting([][]int{ + []int{2, 1, 1}, + []int{0, 1, 1}, + []int{1, 0, 1}, + }) != -1 { + t.Fatal() + } + if orangesRotting([][]int{ + []int{0, 2}, + }) != 0 { + t.Fatal() + } +} From 471ae8e8a4342c0a93097d18c5886eb2d9093ead Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 17:11:23 +0800 Subject: [PATCH 199/220] Add go solution for 1128. Number of Equivalent Domino Pairs 1128. Number of Equivalent Domino Pairs: https://leetcode.com/problems/number-of-equivalent-domino-pairs/ --- go/number-of-equivalent-domino-pairs.go | 21 ++++++++++++++++++++ go/number-of-equivalent-domino-pairs_test.go | 14 +++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 go/number-of-equivalent-domino-pairs.go create mode 100644 go/number-of-equivalent-domino-pairs_test.go diff --git a/go/number-of-equivalent-domino-pairs.go b/go/number-of-equivalent-domino-pairs.go new file mode 100644 index 0000000..9225f57 --- /dev/null +++ b/go/number-of-equivalent-domino-pairs.go @@ -0,0 +1,21 @@ +package leetcode + +type Key struct { + x, y int +} + +func numEquivDominoPairs(dominoes [][]int) int { + counter := make(map[Key]int) + for _, d := range dominoes { + if d[0] > d[1] { + counter[Key{d[1], d[0]}]++ + } else { + counter[Key{d[0], d[1]}]++ + } + } + ans := 0 + for _, v := range counter { + ans += v * (v - 1) / 2 + } + return ans +} diff --git a/go/number-of-equivalent-domino-pairs_test.go b/go/number-of-equivalent-domino-pairs_test.go new file mode 100644 index 0000000..b28a0a9 --- /dev/null +++ b/go/number-of-equivalent-domino-pairs_test.go @@ -0,0 +1,14 @@ +package leetcode + +import "testing" + +func TestNumEquivDominoPairs(t *testing.T) { + if numEquivDominoPairs([][]int{ + []int{1, 2}, + []int{2, 1}, + []int{3, 4}, + []int{5, 6}, + }) != 1 { + t.Fatal() + } +} From 5ef2262559089872eae0547e42f6f363cffc3bf2 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 17:18:02 +0800 Subject: [PATCH 200/220] Add go solution for 744. Find Smallest Letter Greater Than Target 744. Find Smallest Letter Greater Than Target: https://leetcode.com/problems/find-smallest-letter-greater-than-target/ --- ...ind-smallest-letter-greater-than-target.go | 18 ++++++++++++++ ...mallest-letter-greater-than-target_test.go | 24 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 go/find-smallest-letter-greater-than-target.go create mode 100644 go/find-smallest-letter-greater-than-target_test.go diff --git a/go/find-smallest-letter-greater-than-target.go b/go/find-smallest-letter-greater-than-target.go new file mode 100644 index 0000000..178302a --- /dev/null +++ b/go/find-smallest-letter-greater-than-target.go @@ -0,0 +1,18 @@ +package leetcode + +func nextGreatestLetter(letters []byte, target byte) byte { + min := byte(255) + min2 := byte(255) + for _, b := range letters { + if b > target && b < min { + min = b + } + if b < min2 { + min2 = b + } + } + if min != byte(255) { + return min + } + return min2 +} diff --git a/go/find-smallest-letter-greater-than-target_test.go b/go/find-smallest-letter-greater-than-target_test.go new file mode 100644 index 0000000..cec2b4f --- /dev/null +++ b/go/find-smallest-letter-greater-than-target_test.go @@ -0,0 +1,24 @@ +package leetcode + +import "testing" + +func TestNextGreatestLetter(t *testing.T) { + if nextGreatestLetter([]byte("cfj"), byte('a')) != byte('c') { + t.Fatal() + } + if nextGreatestLetter([]byte("cfj"), byte('c')) != byte('f') { + t.Fatal() + } + if nextGreatestLetter([]byte("cfj"), byte('d')) != byte('f') { + t.Fatal() + } + if nextGreatestLetter([]byte("cfj"), byte('g')) != byte('j') { + t.Fatal() + } + if nextGreatestLetter([]byte("cfj"), byte('j')) != byte('c') { + t.Fatal() + } + if nextGreatestLetter([]byte("cfj"), byte('k')) != byte('c') { + t.Fatal() + } +} From 5e6621224d99301bfbad30105ad1b0481c6fe1b6 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 17:33:34 +0800 Subject: [PATCH 201/220] Add go solution for 925. Long Pressed Name 925. Long Pressed Name: https://leetcode.com/problems/long-pressed-name/ --- go/long-pressed-name.go | 25 +++++++++++++++++++++++++ go/long-pressed-name_test.go | 18 ++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 go/long-pressed-name.go create mode 100644 go/long-pressed-name_test.go diff --git a/go/long-pressed-name.go b/go/long-pressed-name.go new file mode 100644 index 0000000..543d2a2 --- /dev/null +++ b/go/long-pressed-name.go @@ -0,0 +1,25 @@ +package leetcode + +func isLongPressedName(name string, typed string) bool { + in, it := 0, 0 + ln, lt := len(name), len(typed) + for in < ln || it < lt { + if in < ln && it < lt { + if name[in] == typed[it] { + in++ + it++ + } else if in == 0 { + return false + } else if name[in-1] == typed[it] { + it++ + } else { + return false + } + } else if it == lt { + return false + } else if name[in-1] == typed[it] { + it++ + } + } + return true +} diff --git a/go/long-pressed-name_test.go b/go/long-pressed-name_test.go new file mode 100644 index 0000000..e288425 --- /dev/null +++ b/go/long-pressed-name_test.go @@ -0,0 +1,18 @@ +package leetcode + +import "testing" + +func TestIsLongPressedName(t *testing.T) { + if isLongPressedName("alex", "aaleex") != true { + t.Fatal() + } + if isLongPressedName("saeed", "ssaaedd") != false { + t.Fatal() + } + if isLongPressedName("leelee", "lleeelee") != true { + t.Fatal() + } + if isLongPressedName("laiden", "laiden") != true { + t.Fatal() + } +} From 1b84e402d8ba8d32b37055cf1275b1dcc5a63384 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 18:11:42 +0800 Subject: [PATCH 202/220] Add go solution for 989. Add to Array-Form of Integer 989. Add to Array-Form of Integer: https://leetcode.com/problems/add-to-array-form-of-integer/ --- go/add-to-array-form-of-integer.go | 25 +++++++++++++++++++++++++ go/add-to-array-form-of-integer_test.go | 21 +++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 go/add-to-array-form-of-integer.go create mode 100644 go/add-to-array-form-of-integer_test.go diff --git a/go/add-to-array-form-of-integer.go b/go/add-to-array-form-of-integer.go new file mode 100644 index 0000000..ba8925b --- /dev/null +++ b/go/add-to-array-form-of-integer.go @@ -0,0 +1,25 @@ +package leetcode + +func addToArrayForm(A []int, K int) []int { + lA := len(A) + for t := lA - 1; K > 0 && t >= 0; t-- { + A[t] += K + K = A[t] / 10 + A[t] %= 10 + } + prepend := []int{} + for K > 0 { + prepend = append(prepend, K%10) + K /= 10 + } + if len(prepend) > 0 { + i, j := 0, len(prepend)-1 + for i < j { + prepend[i], prepend[j] = prepend[j], prepend[i] + i++ + j-- + } + A = append(prepend, A...) + } + return A +} diff --git a/go/add-to-array-form-of-integer_test.go b/go/add-to-array-form-of-integer_test.go new file mode 100644 index 0000000..a7c856f --- /dev/null +++ b/go/add-to-array-form-of-integer_test.go @@ -0,0 +1,21 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestAddToArrayForm(t *testing.T) { + if !reflect.DeepEqual(addToArrayForm([]int{1, 2, 0, 0}, 34), []int{1, 2, 3, 4}) { + t.Fatal() + } + if !reflect.DeepEqual(addToArrayForm([]int{2, 7, 4}, 181), []int{4, 5, 5}) { + t.Fatal() + } + if !reflect.DeepEqual(addToArrayForm([]int{2, 1, 5}, 806), []int{1, 0, 2, 1}) { + t.Fatal() + } + if !reflect.DeepEqual(addToArrayForm([]int{9, 9, 9, 9, 9, 9, 9, 9, 9, 9}, 1), []int{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) { + t.Fatal() + } +} From 9b4eeefda1bb9356df283ba1dcb5d1e952ab30b4 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 18:25:12 +0800 Subject: [PATCH 203/220] Add go solution for 819. Most Common Word 819. Most Common Word: https://leetcode.com/problems/most-common-word/ --- go/most-common-word.go | 35 +++++++++++++++++++++++++++++++++++ go/most-common-word_test.go | 9 +++++++++ 2 files changed, 44 insertions(+) create mode 100644 go/most-common-word.go create mode 100644 go/most-common-word_test.go diff --git a/go/most-common-word.go b/go/most-common-word.go new file mode 100644 index 0000000..8bf5463 --- /dev/null +++ b/go/most-common-word.go @@ -0,0 +1,35 @@ +package leetcode + +import ( + "strings" + "unicode" +) + +func mostCommonWord(paragraph string, banned []string) string { + bannedSet := make(map[string]struct{}) + for _, b := range banned { + bannedSet[b] = struct{}{} + } + cnt := make(map[string]int) + start := 0 + for i, c := range paragraph { + if !unicode.IsLetter(c) { + if i-start > 0 { + cnt[strings.ToLower(paragraph[start:i])]++ + } + start = i + 1 + } + } + if len(paragraph)-start > 0 { + cnt[strings.ToLower(paragraph[start:])]++ + } + m := 0 + ans := "" + for k, v := range cnt { + if _, ok := bannedSet[k]; !ok && v > m { + ans = k + m = v + } + } + return ans +} diff --git a/go/most-common-word_test.go b/go/most-common-word_test.go new file mode 100644 index 0000000..cd3ddbf --- /dev/null +++ b/go/most-common-word_test.go @@ -0,0 +1,9 @@ +package leetcode + +import "testing" + +func TestMostCommonWord(t *testing.T) { + if mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", []string{"hit"}) != "ball" { + t.Fatal() + } +} From f23fed951b4df0da7488555723f78a50c7c4937b Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 18:37:04 +0800 Subject: [PATCH 204/220] Add go solution for 724. Find Pivot Index 724. Find Pivot Index: https://leetcode.com/problems/find-pivot-index/ --- go/find-pivot-index.go | 17 +++++++++++++++++ go/find-pivot-index_test.go | 12 ++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 go/find-pivot-index.go create mode 100644 go/find-pivot-index_test.go diff --git a/go/find-pivot-index.go b/go/find-pivot-index.go new file mode 100644 index 0000000..ca905e6 --- /dev/null +++ b/go/find-pivot-index.go @@ -0,0 +1,17 @@ +package leetcode + +func pivotIndex(nums []int) int { + ln := len(nums) + left, right := 0, 0 + for _, v := range nums { + right += v + } + for i := 0; i < ln; i++ { + right -= nums[i] + if left == right { + return i + } + left += nums[i] + } + return -1 +} diff --git a/go/find-pivot-index_test.go b/go/find-pivot-index_test.go new file mode 100644 index 0000000..0059f3f --- /dev/null +++ b/go/find-pivot-index_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestPivotIndex(t *testing.T) { + if pivotIndex([]int{1, 7, 3, 6, 5, 6}) != 3 { + t.Fatal() + } + if pivotIndex([]int{1, 2, 3}) != -1 { + t.Fatal() + } +} From 5fc89111b2151e46c7ab35a404643e51ab5c5188 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 18:48:49 +0800 Subject: [PATCH 205/220] Add go solution for 849. Maximize Distance to Closest Person 849. Maximize Distance to Closest Person: https://leetcode.com/problems/maximize-distance-to-closest-person/ --- go/maximize-distance-to-closest-person.go | 20 +++++++++++++++++++ ...aximize-distance-to-closest-person_test.go | 15 ++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 go/maximize-distance-to-closest-person.go create mode 100644 go/maximize-distance-to-closest-person_test.go diff --git a/go/maximize-distance-to-closest-person.go b/go/maximize-distance-to-closest-person.go new file mode 100644 index 0000000..eec4eaa --- /dev/null +++ b/go/maximize-distance-to-closest-person.go @@ -0,0 +1,20 @@ +package leetcode + +func maxDistToClosest(seats []int) int { + start := 0 + ans := 0 + for i, v := range seats { + if v == 1 { + if start == 0 { + ans = i - start + } else if ans < (i-start+1)/2 { + ans = (i - start + 1) / 2 + } + start = i + 1 + } + } + if len(seats)-start > ans { + ans = len(seats) - start + } + return ans +} diff --git a/go/maximize-distance-to-closest-person_test.go b/go/maximize-distance-to-closest-person_test.go new file mode 100644 index 0000000..6b38d1d --- /dev/null +++ b/go/maximize-distance-to-closest-person_test.go @@ -0,0 +1,15 @@ +package leetcode + +import "testing" + +func TestMaxDistToClosest(t *testing.T) { + if maxDistToClosest([]int{1, 0, 0, 0, 1, 0, 1}) != 2 { + t.Fatal() + } + if maxDistToClosest([]int{1, 0, 0, 0}) != 3 { + t.Fatal() + } + if maxDistToClosest([]int{1, 0, 0, 1}) != 1 { + t.Fatal() + } +} From 86a4481d4b01726027fa7f929ac48a033204977d Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 18:57:17 +0800 Subject: [PATCH 206/220] Add go solution for 747. Largest Number At Least Twice of Others 747. Largest Number At Least Twice of Others: https://leetcode.com/problems/largest-number-at-least-twice-of-others/ --- go/largest-number-at-least-twice-of-others.go | 19 +++++++++++++++++++ ...st-number-at-least-twice-of-others_test.go | 12 ++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 go/largest-number-at-least-twice-of-others.go create mode 100644 go/largest-number-at-least-twice-of-others_test.go diff --git a/go/largest-number-at-least-twice-of-others.go b/go/largest-number-at-least-twice-of-others.go new file mode 100644 index 0000000..878cd18 --- /dev/null +++ b/go/largest-number-at-least-twice-of-others.go @@ -0,0 +1,19 @@ +package leetcode + +func dominantIndex(nums []int) int { + tm, m, mi := 0, 0, 0 + for i, v := range nums { + if m < v { + tm = m * 2 + m = v + mi = i + } else if tm < v*2 { + tm = v * 2 + } + } + if m >= tm { + return mi + } else { + return -1 + } +} diff --git a/go/largest-number-at-least-twice-of-others_test.go b/go/largest-number-at-least-twice-of-others_test.go new file mode 100644 index 0000000..87fcd22 --- /dev/null +++ b/go/largest-number-at-least-twice-of-others_test.go @@ -0,0 +1,12 @@ +package leetcode + +import "testing" + +func TestDominantIndex(t *testing.T) { + if dominantIndex([]int{3, 6, 1, 0}) != 1 { + t.Fatal() + } + if dominantIndex([]int{1, 2, 3, 4}) != -1 { + t.Fatal() + } +} From aa7c20dfa619dc65fc1f830f374f12d730e9b8d7 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 19:05:37 +0800 Subject: [PATCH 207/220] Add go solution for 970. Powerful Integers 970. Powerful Integers: https://leetcode.com/problems/powerful-integers/ --- go/powerful-integers.go | 23 +++++++++++++++++++++++ go/powerful-integers_test.go | 15 +++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 go/powerful-integers.go create mode 100644 go/powerful-integers_test.go diff --git a/go/powerful-integers.go b/go/powerful-integers.go new file mode 100644 index 0000000..d8d02e6 --- /dev/null +++ b/go/powerful-integers.go @@ -0,0 +1,23 @@ +package leetcode + +func powerfulIntegers(x int, y int, bound int) []int { + set := make(map[int]struct{}) + + vx, vy := 1, 1 + for ; vx+1 <= bound; vx *= x { + for vy = 1; vx+vy <= bound; vy *= y { + set[vx+vy] = struct{}{} + if y == 1 { + break + } + } + if x == 1 { + break + } + } + ans := make([]int, 0, len(set)) + for v := range set { + ans = append(ans, v) + } + return ans +} diff --git a/go/powerful-integers_test.go b/go/powerful-integers_test.go new file mode 100644 index 0000000..246e459 --- /dev/null +++ b/go/powerful-integers_test.go @@ -0,0 +1,15 @@ +package leetcode + +import ( + "reflect" + "sort" + "testing" +) + +func TestPowerfulIntegers(t *testing.T) { + v := powerfulIntegers(3, 5, 15) + sort.Ints(v) + if !reflect.DeepEqual(v, []int{2, 4, 6, 8, 10, 14}) { + t.Fatal() + } +} From b83d0e7597274d984e5255f269f85fe999dc2f49 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 3 Jan 2020 19:14:45 +0800 Subject: [PATCH 208/220] Add go solution for 1033. Moving Stones Until Consecutive 1033. Moving Stones Until Consecutive: https://leetcode.com/problems/moving-stones-until-consecutive/ --- go/moving-stones-until-consecutive.go | 20 ++++++++++++++++++++ go/moving-stones-until-consecutive_test.go | 18 ++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 go/moving-stones-until-consecutive.go create mode 100644 go/moving-stones-until-consecutive_test.go diff --git a/go/moving-stones-until-consecutive.go b/go/moving-stones-until-consecutive.go new file mode 100644 index 0000000..48f2878 --- /dev/null +++ b/go/moving-stones-until-consecutive.go @@ -0,0 +1,20 @@ +package leetcode + +func numMovesStones(a int, b int, c int) []int { + if a > b { + a, b = b, a + } + if b > c { + b, c = c, b + } + if a > b { + a, b = b, a + } + m := 2 + if a+1 == b && b+1 == c { + m = 0 + } else if a+2 >= b || b+2 >= c { + m = 1 + } + return []int{m, c - a - 2} +} diff --git a/go/moving-stones-until-consecutive_test.go b/go/moving-stones-until-consecutive_test.go new file mode 100644 index 0000000..ea248ea --- /dev/null +++ b/go/moving-stones-until-consecutive_test.go @@ -0,0 +1,18 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestNumMovesStones(t *testing.T) { + if !reflect.DeepEqual(numMovesStones(1, 2, 5), []int{1, 2}) { + t.Fatal() + } + if !reflect.DeepEqual(numMovesStones(4, 3, 2), []int{0, 0}) { + t.Fatal() + } + if !reflect.DeepEqual(numMovesStones(3, 5, 1), []int{1, 2}) { + t.Fatal() + } +} From 106b8b36bf413b07dfdbaad75cffd4571b213455 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Jan 2020 17:14:54 +0800 Subject: [PATCH 209/220] Add go solution for 1037. Valid Boomerang 1037. Valid Boomerang: https://leetcode.com/problems/valid-boomerang/ --- go/valid-boomerang.go | 7 +++++++ go/valid-boomerang_test.go | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 go/valid-boomerang.go create mode 100644 go/valid-boomerang_test.go diff --git a/go/valid-boomerang.go b/go/valid-boomerang.go new file mode 100644 index 0000000..aae8b2a --- /dev/null +++ b/go/valid-boomerang.go @@ -0,0 +1,7 @@ +package leetcode + +func isBoomerang(points [][]int) bool { + v1 := []int{points[1][0] - points[0][0], points[1][1] - points[0][1]} + v2 := []int{points[2][0] - points[0][0], points[2][1] - points[0][1]} + return v1[0]*v2[1] != v1[1]*v2[0] +} diff --git a/go/valid-boomerang_test.go b/go/valid-boomerang_test.go new file mode 100644 index 0000000..870c888 --- /dev/null +++ b/go/valid-boomerang_test.go @@ -0,0 +1,20 @@ +package leetcode + +import "testing" + +func TestIsBoomerang(t *testing.T) { + if isBoomerang([][]int{ + []int{1, 1}, + []int{2, 3}, + []int{3, 2}, + }) != true { + t.Fatal() + } + if isBoomerang([][]int{ + []int{1, 1}, + []int{2, 2}, + []int{3, 3}, + }) != false { + t.Fatal() + } +} From bc7cbaffcb5e0fff63f4fb82c89cab50c3c5a541 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Jan 2020 17:26:53 +0800 Subject: [PATCH 210/220] Add go solution for 840. Magic Squares In Grid 840. Magic Squares In Grid: https://leetcode.com/problems/magic-squares-in-grid/ --- go/magic-squares-in-grid.go | 44 ++++++++++++++++++++++++++++++++ go/magic-squares-in-grid_test.go | 13 ++++++++++ 2 files changed, 57 insertions(+) create mode 100644 go/magic-squares-in-grid.go create mode 100644 go/magic-squares-in-grid_test.go diff --git a/go/magic-squares-in-grid.go b/go/magic-squares-in-grid.go new file mode 100644 index 0000000..de0763a --- /dev/null +++ b/go/magic-squares-in-grid.go @@ -0,0 +1,44 @@ +package leetcode + +func valid(grid [][]int, x, y int) bool { + visit := make([]bool, 9) + for i := x; i < x+3; i++ { + for j := y; j < y+3; j++ { + if grid[i][j] > 9 || grid[i][j] < 1 { + return false + } + if visit[grid[i][j]-1] { + return false + } + visit[grid[i][j]-1] = true + } + } + for i := 0; i < 3; i++ { + if grid[x+i][y+0]+grid[x+i][y+1]+grid[x+i][y+2] != 15 { + return false + } + if grid[x+0][y+i]+grid[x+1][y+i]+grid[x+2][y+i] != 15 { + return false + } + } + if grid[x+0][y+0]+grid[x+1][y+1]+grid[x+2][y+2] != 15 { + return false + } + if grid[x+0][y+2]+grid[x+1][y+1]+grid[x+2][y+0] != 15 { + return false + } + return true +} + +func numMagicSquaresInside(grid [][]int) int { + h, w := len(grid), len(grid[0]) + ans := 0 + for i := 0; i < h-2; i++ { + for j := 0; j < w-2; j++ { + if valid(grid, i, j) { + ans++ + } + } + } + return ans +} diff --git a/go/magic-squares-in-grid_test.go b/go/magic-squares-in-grid_test.go new file mode 100644 index 0000000..09ac657 --- /dev/null +++ b/go/magic-squares-in-grid_test.go @@ -0,0 +1,13 @@ +package leetcode + +import "testing" + +func TestNumMagicSquaresInside(t *testing.T) { + if numMagicSquaresInside([][]int{ + []int{4, 3, 8, 4}, + []int{9, 5, 1, 9}, + []int{2, 7, 6, 2}, + }) != 1 { + t.Fatal() + } +} From afcf4f930d5c6917af9e73dc555c9d26e47f8019 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Jan 2020 17:40:53 +0800 Subject: [PATCH 211/220] Add go solution for 941. Valid Mountain Array 941. Valid Mountain Array: https://leetcode.com/problems/valid-mountain-array/ --- go/valid-mountain-array.go | 13 +++++++++++++ go/valid-mountain-array_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 go/valid-mountain-array.go create mode 100644 go/valid-mountain-array_test.go diff --git a/go/valid-mountain-array.go b/go/valid-mountain-array.go new file mode 100644 index 0000000..aa29713 --- /dev/null +++ b/go/valid-mountain-array.go @@ -0,0 +1,13 @@ +package leetcode + +func validMountainArray(A []int) bool { + n := len(A) + left, right := 0, n-1 + for i := 0; i < n-1 && A[i+1] > A[i]; i++ { + left = i + 1 + } + for i := n - 1; i > 0 && A[i] < A[i-1]; i-- { + right = i - 1 + } + return left != 0 && right != n-1 && left == right +} diff --git a/go/valid-mountain-array_test.go b/go/valid-mountain-array_test.go new file mode 100644 index 0000000..6f1ed8f --- /dev/null +++ b/go/valid-mountain-array_test.go @@ -0,0 +1,27 @@ +package leetcode + +import "testing" + +func TestValidMountainArray(t *testing.T) { + if validMountainArray([]int{1, 2, 3, 2, 1}) != true { + t.Fatal() + } + if validMountainArray([]int{1, 2, 3, 4, 5}) != false { + t.Fatal() + } + if validMountainArray([]int{}) != false { + t.Fatal() + } + if validMountainArray([]int{1}) != false { + t.Fatal() + } + if validMountainArray([]int{1, 2}) != false { + t.Fatal() + } + if validMountainArray([]int{2, 1}) != false { + t.Fatal() + } + if validMountainArray([]int{1, 2, 1}) != true { + t.Fatal() + } +} From 59069e983c1ba4df6c972d54f8ac97f240c59a5b Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Jan 2020 17:58:57 +0800 Subject: [PATCH 212/220] Add go solution for 949. Largest Time for Given Digits 949. Largest Time for Given Digits: https://leetcode.com/problems/largest-time-for-given-digits/ --- go/largest-time-for-given-digits.go | 47 ++++++++++++++++++++++++ go/largest-time-for-given-digits_test.go | 18 +++++++++ 2 files changed, 65 insertions(+) create mode 100644 go/largest-time-for-given-digits.go create mode 100644 go/largest-time-for-given-digits_test.go diff --git a/go/largest-time-for-given-digits.go b/go/largest-time-for-given-digits.go new file mode 100644 index 0000000..728dd2e --- /dev/null +++ b/go/largest-time-for-given-digits.go @@ -0,0 +1,47 @@ +package leetcode + +import "fmt" + +func largestTimeFromDigits(A []int) string { + cnt := make(map[int]int) + for _, v := range A { + cnt[v]++ + } + for hr := 23; hr >= 0; hr-- { + if cnt[hr/10] > 0 && cnt[hr%10] > 0 { + if hr/10 == hr%10 && cnt[hr/10] == 1 { + continue + } + cnt[hr/10]-- + cnt[hr%10]-- + a, b := -1, -1 + for v := range cnt { + switch cnt[v] { + case 2: + a, b = v, v + case 1: + if a == -1 { + a = v + } else { + b = v + } + } + } + if a < b { + a, b = b, a + } + min := a*10 + b + if min < 60 { + return fmt.Sprintf("%02d:%02d", hr, min) + } else { + min = b*10 + a + if min < 60 { + return fmt.Sprintf("%02d:%02d", hr, min) + } + } + cnt[hr/10]++ + cnt[hr%10]++ + } + } + return "" +} diff --git a/go/largest-time-for-given-digits_test.go b/go/largest-time-for-given-digits_test.go new file mode 100644 index 0000000..f6f8e6f --- /dev/null +++ b/go/largest-time-for-given-digits_test.go @@ -0,0 +1,18 @@ +package leetcode + +import "testing" + +func TestLargestTimeFromDigits(t *testing.T) { + if largestTimeFromDigits([]int{1, 2, 3, 4}) != "23:41" { + t.Fatal() + } + if largestTimeFromDigits([]int{5, 5, 5, 5}) != "" { + t.Fatal() + } + if largestTimeFromDigits([]int{0, 0, 1, 0}) != "10:00" { + t.Fatal() + } + if largestTimeFromDigits([]int{1, 9, 6, 0}) != "19:06" { + t.Fatal() + } +} From 78e5dd58abf5eff3f8c4c709b6046fabe14623d1 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Jan 2020 18:04:11 +0800 Subject: [PATCH 213/220] Add go solution for 914. X of a Kind in a Deck of Cards 914. X of a Kind in a Deck of Cards: https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/ --- go/x-of-a-kind-in-a-deck-of-cards.go | 20 ++++++++++++++++++++ go/x-of-a-kind-in-a-deck-of-cards_test.go | 21 +++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 go/x-of-a-kind-in-a-deck-of-cards.go create mode 100644 go/x-of-a-kind-in-a-deck-of-cards_test.go diff --git a/go/x-of-a-kind-in-a-deck-of-cards.go b/go/x-of-a-kind-in-a-deck-of-cards.go new file mode 100644 index 0000000..3c3ac9d --- /dev/null +++ b/go/x-of-a-kind-in-a-deck-of-cards.go @@ -0,0 +1,20 @@ +package leetcode + +func gcd(a, b int) int { + for a%b != 0 { + a, b = b, a%b + } + return b +} + +func hasGroupsSizeX(deck []int) bool { + cnt := make(map[int]int) + for _, v := range deck { + cnt[v]++ + } + g := 0 + for _, v := range cnt { + g = gcd(g, v) + } + return g > 1 +} diff --git a/go/x-of-a-kind-in-a-deck-of-cards_test.go b/go/x-of-a-kind-in-a-deck-of-cards_test.go new file mode 100644 index 0000000..7d83c98 --- /dev/null +++ b/go/x-of-a-kind-in-a-deck-of-cards_test.go @@ -0,0 +1,21 @@ +package leetcode + +import "testing" + +func TestHasGroupsSizeX(t *testing.T) { + if hasGroupsSizeX([]int{1, 2, 3, 4, 4, 3, 2, 1}) != true { + t.Fatal() + } + if hasGroupsSizeX([]int{1, 1, 1, 2, 2, 2, 3, 3}) != false { + t.Fatal() + } + if hasGroupsSizeX([]int{1}) != false { + t.Fatal() + } + if hasGroupsSizeX([]int{1, 1}) != true { + t.Fatal() + } + if hasGroupsSizeX([]int{1, 1, 2, 2, 2, 2}) != true { + t.Fatal() + } +} From 7193ce9306703a70d4f511c45425bc68bf303a69 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Mon, 6 Jan 2020 18:13:55 +0800 Subject: [PATCH 214/220] Add go solution for 859. Buddy Strings 859. Buddy Strings: https://leetcode.com/problems/buddy-strings/ --- go/buddy-strings.go | 34 ++++++++++++++++++++++++++++++++++ go/buddy-strings_test.go | 21 +++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 go/buddy-strings.go create mode 100644 go/buddy-strings_test.go diff --git a/go/buddy-strings.go b/go/buddy-strings.go new file mode 100644 index 0000000..bf9e877 --- /dev/null +++ b/go/buddy-strings.go @@ -0,0 +1,34 @@ +package leetcode + +func buddyStrings(A string, B string) bool { + if A == B { + dup := make(map[rune]struct{}) + for _, c := range A { + if _, ok := dup[c]; ok { + return true + } + dup[c] = struct{}{} + } + return false + } + chA, chB := byte(0), byte(0) + lA, lB := len(A), len(B) + if lA != lB { + return false + } + changed := false + for i := 0; i < lA; i++ { + if A[i] != B[i] { + if changed { + return false + } else if chA == 0 { + chA, chB = A[i], B[i] + } else if chB == A[i] && chA == B[i] { + changed = true + } else { + return false + } + } + } + return changed +} diff --git a/go/buddy-strings_test.go b/go/buddy-strings_test.go new file mode 100644 index 0000000..1353968 --- /dev/null +++ b/go/buddy-strings_test.go @@ -0,0 +1,21 @@ +package leetcode + +import "testing" + +func TestBuddyStrings(t *testing.T) { + if buddyStrings("ab", "ba") != true { + t.Fatal() + } + if buddyStrings("ab", "ab") != false { + t.Fatal() + } + if buddyStrings("aa", "aa") != true { + t.Fatal() + } + if buddyStrings("aaaaaabc", "aaaaaacb") != true { + t.Fatal() + } + if buddyStrings("", "aa") != false { + t.Fatal() + } +} From 2b9552576ab234f069eea04bb3e62a38b450e1d6 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Jan 2020 15:21:38 +0800 Subject: [PATCH 215/220] Add go solution for 874. Walking Robot Simulation 874. Walking Robot Simulation: https://leetcode.com/problems/walking-robot-simulation/ --- go/walking-robot-simulation.go | 152 ++++++++++++++++++++++++++++ go/walking-robot-simulation_test.go | 28 +++++ 2 files changed, 180 insertions(+) create mode 100644 go/walking-robot-simulation.go create mode 100644 go/walking-robot-simulation_test.go diff --git a/go/walking-robot-simulation.go b/go/walking-robot-simulation.go new file mode 100644 index 0000000..5bd030c --- /dev/null +++ b/go/walking-robot-simulation.go @@ -0,0 +1,152 @@ +package leetcode + +import ( + "sort" +) + +type ByX [][]int +type ByY [][]int + +func (ary ByX) Len() int { + return len(ary) +} + +func (ary ByY) Len() int { + return len(ary) +} + +func (ary ByX) Less(i, j int) bool { + if ary[i][0] == ary[j][0] { + return ary[i][1] < ary[j][1] + } + return ary[i][0] < ary[j][0] +} + +func (ary ByY) Less(i, j int) bool { + if ary[i][1] == ary[j][1] { + return ary[i][0] < ary[j][0] + } + return ary[i][1] < ary[j][1] +} + +func (ary ByX) Swap(i, j int) { + ary[i], ary[j] = ary[j], ary[i] +} + +func (ary ByY) Swap(i, j int) { + ary[i], ary[j] = ary[j], ary[i] +} + +func (ary ByX) findVertical(x, y int) (int, int) { + L, U := -1, ary.Len() + for L+1 < U { + m := (L + U) / 2 + if ary[m][0] < x { + L = m + } else if ary[m][0] > x { + U = m + } else { + if ary[m][1] < y { + L = m + } else { + U = m + } + } + } + return L, U +} + +func (ary ByY) findHorizontal(x, y int) (int, int) { + L, U := -1, ary.Len() + for L+1 < U { + m := (L + U) / 2 + if ary[m][1] < y { + L = m + } else if ary[m][1] > y { + U = m + } else { + if ary[m][0] < x { + L = m + } else { + U = m + } + } + } + return L, U +} + +func robotSim(commands []int, obstacles [][]int) int { + const ( + NORTH = iota + EAST + SOUTH + WEST + ) + N := len(obstacles) + byX := ByX(make([][]int, 0, N)) + byY := ByY(make([][]int, 0, N)) + for _, ob := range obstacles { + if ob[0] != 0 || ob[1] != 0 { + byX = append(byX, ob) + byY = append(byY, ob) + } else { + N-- + } + } + sort.Sort(byX) + sort.Sort(byY) + dir := NORTH + x, y := 0, 0 + ans := 0 + for _, cmd := range commands { + switch cmd { + case -1: + dir = (dir + 1) % 4 + case -2: + dir = (dir + 3) % 4 + default: + switch dir { + case NORTH, SOUTH: + L, U := byX.findVertical(x, y) + switch dir { + case NORTH: + y += cmd + if U < N && byX[U][0] == x { + if y >= byX[U][1] { + y = byX[U][1] - 1 + } + } + case SOUTH: + y -= cmd + if L >= 0 && byX[L][0] == x { + if y <= byX[L][1] { + y = byX[L][1] + 1 + } + } + } + case EAST, WEST: + L, U := byY.findHorizontal(x, y) + switch dir { + case EAST: + x += cmd + if U < N && byY[U][1] == y { + if x >= byY[U][0] { + x = byY[U][0] - 1 + } + } + case WEST: + x -= cmd + if L >= 0 && byY[L][1] == y { + if x <= byY[L][0] { + x = byY[L][0] + 1 + } + } + } + } + if ans < x*x+y*y { + ans = x*x + y*y + } + } + } + return ans +} diff --git a/go/walking-robot-simulation_test.go b/go/walking-robot-simulation_test.go new file mode 100644 index 0000000..5613b32 --- /dev/null +++ b/go/walking-robot-simulation_test.go @@ -0,0 +1,28 @@ +package leetcode + +import "testing" + +func TestRobotSim(t *testing.T) { + if robotSim([]int{4, -1, 3}, [][]int{}) != 25 { + t.Fatal() + } + if robotSim([]int{4, -1, 4, -2, 4}, [][]int{ + []int{2, 4}, + }) != 65 { + t.Fatal() + } + if robotSim([]int{2, 2, 5, -1, -1}, [][]int{ + []int{-3, 5}, + []int{-2, 5}, + []int{3, 2}, + []int{5, 0}, + []int{-2, 0}, + []int{-1, 5}, + []int{5, -3}, + []int{0, 0}, + []int{-4, 4}, + []int{-3, 4}, + }) != 81 { + t.Fatal() + } +} From 3c5b9cea0b39c2d28df4afcda1d36ca69dd76ca8 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Jan 2020 16:33:57 +0800 Subject: [PATCH 216/220] Add go solution for 1299. Replace Elements with Greatest Element on Right Side 1299. Replace Elements with Greatest Element on Right Side: https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/ --- ...elements-with-greatest-element-on-right-side.go | 14 ++++++++++++++ ...nts-with-greatest-element-on-right-side_test.go | 12 ++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 go/replace-elements-with-greatest-element-on-right-side.go create mode 100644 go/replace-elements-with-greatest-element-on-right-side_test.go diff --git a/go/replace-elements-with-greatest-element-on-right-side.go b/go/replace-elements-with-greatest-element-on-right-side.go new file mode 100644 index 0000000..bae888c --- /dev/null +++ b/go/replace-elements-with-greatest-element-on-right-side.go @@ -0,0 +1,14 @@ +package leetcode + +func replaceElements(arr []int) []int { + max := -1 + n := len(arr) + for i := n - 1; i >= 0; i-- { + toset := max + if max < arr[i] { + max = arr[i] + } + arr[i] = toset + } + return arr +} diff --git a/go/replace-elements-with-greatest-element-on-right-side_test.go b/go/replace-elements-with-greatest-element-on-right-side_test.go new file mode 100644 index 0000000..a1f2ba6 --- /dev/null +++ b/go/replace-elements-with-greatest-element-on-right-side_test.go @@ -0,0 +1,12 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestReplaceElements(t *testing.T) { + if !reflect.DeepEqual(replaceElements([]int{17, 18, 5, 4, 6, 1}), []int{18, 6, 6, 6, 1, -1}) { + t.Fatal() + } +} From 2a343d4cb97d3e29844e860ba78af16c41f411e5 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Jan 2020 16:41:15 +0800 Subject: [PATCH 217/220] Add go solution for 1304. Find N Unique Integers Sum up to Zero 1304. Find N Unique Integers Sum up to Zero: https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/ --- go/find-n-unique-integers-sum-up-to-zero.go | 15 +++++++++++++++ ...d-n-unique-integers-sum-up-to-zero_test.go | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 go/find-n-unique-integers-sum-up-to-zero.go create mode 100644 go/find-n-unique-integers-sum-up-to-zero_test.go diff --git a/go/find-n-unique-integers-sum-up-to-zero.go b/go/find-n-unique-integers-sum-up-to-zero.go new file mode 100644 index 0000000..175d4d7 --- /dev/null +++ b/go/find-n-unique-integers-sum-up-to-zero.go @@ -0,0 +1,15 @@ +package leetcode + +func sumZero(n int) []int { + if n == 1 { + return []int{0} + } + ans := make([]int, 0, n) + final := 0 + for i := 1; i < n; i++ { + ans = append(ans, i) + final -= i + } + ans = append(ans, final) + return ans +} diff --git a/go/find-n-unique-integers-sum-up-to-zero_test.go b/go/find-n-unique-integers-sum-up-to-zero_test.go new file mode 100644 index 0000000..c968afa --- /dev/null +++ b/go/find-n-unique-integers-sum-up-to-zero_test.go @@ -0,0 +1,19 @@ +package leetcode + +import "testing" + +func TestSumZero(t *testing.T) { + for _, n := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} { + out := sumZero(n) + if len(out) != n { + t.Fatal() + } + v := 0 + for _, x := range out { + v += x + } + if v != 0 { + t.Fatal() + } + } +} From a360340537a91d4fdb12a09889cc01f18e0edb92 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Tue, 7 Jan 2020 16:53:40 +0800 Subject: [PATCH 218/220] Add go solution for 1309. Decrypt String from Alphabet to Integer Mapping 1309. Decrypt String from Alphabet to Integer Mapping: https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/ --- ...string-from-alphabet-to-integer-mapping.go | 28 +++++++++++++++++++ ...g-from-alphabet-to-integer-mapping_test.go | 18 ++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 go/decrypt-string-from-alphabet-to-integer-mapping.go create mode 100644 go/decrypt-string-from-alphabet-to-integer-mapping_test.go diff --git a/go/decrypt-string-from-alphabet-to-integer-mapping.go b/go/decrypt-string-from-alphabet-to-integer-mapping.go new file mode 100644 index 0000000..4f32e5a --- /dev/null +++ b/go/decrypt-string-from-alphabet-to-integer-mapping.go @@ -0,0 +1,28 @@ +package leetcode + +import "strconv" + +func freqAlphabets(s string) string { + ls := len(s) + out := make([]rune, 0, ls) + p := ls - 1 + for p >= 0 { + if s[p] == '#' { + ch, _ := strconv.Atoi(s[p-2 : p]) + out = append(out, rune(ch-1+'a')) + p -= 3 + } else { + ch := s[p] + out = append(out, rune(ch-'0'-1+'a')) + p-- + } + } + lout := len(out) + i, j := 0, lout-1 + for i < j { + out[i], out[j] = out[j], out[i] + i++ + j-- + } + return string(out) +} diff --git a/go/decrypt-string-from-alphabet-to-integer-mapping_test.go b/go/decrypt-string-from-alphabet-to-integer-mapping_test.go new file mode 100644 index 0000000..55056f7 --- /dev/null +++ b/go/decrypt-string-from-alphabet-to-integer-mapping_test.go @@ -0,0 +1,18 @@ +package leetcode + +import "testing" + +func TestFreqAlphabets(t *testing.T) { + if freqAlphabets("10#11#12") != "jkab" { + t.Fatal() + } + if freqAlphabets("1326#") != "acz" { + t.Fatal() + } + if freqAlphabets("25#") != "y" { + t.Fatal() + } + if freqAlphabets("12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#") != "abcdefghijklmnopqrstuvwxyz" { + t.Fatal() + } +} From 32ebcc171bf92cf41e496d2087919ee280bf4078 Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 17 Jan 2020 15:25:35 +0800 Subject: [PATCH 219/220] Add go solution for 957. Prison Cells After N Days 957. Prison Cells After N Days: https://leetcode.com/problems/prison-cells-after-n-days/ --- go/prison-cells-after-n-days.go | 39 ++++++++++++++++++++++++++++ go/prison-cells-after-n-days_test.go | 17 ++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 go/prison-cells-after-n-days.go create mode 100644 go/prison-cells-after-n-days_test.go diff --git a/go/prison-cells-after-n-days.go b/go/prison-cells-after-n-days.go new file mode 100644 index 0000000..4896db3 --- /dev/null +++ b/go/prison-cells-after-n-days.go @@ -0,0 +1,39 @@ +package leetcode + +func prisonAfterNDays(cells []int, N int) []int { + size := len(cells) + encoded := 0 + for i, v := range cells { + encoded |= v << uint(i) + } + visit := make(map[int]int) + visit[encoded] = 0 + seq := make(map[int]int) + seq[0] = encoded + + for x := 1; x <= N; x++ { + nxt := 0 + for i := 1; i < size-1; i++ { + if ((encoded>>uint(i-1))&1)^((encoded>>uint(i+1))&1) == 0 { + nxt |= 1 << uint(i) + } + } + encoded = nxt + if prev, ok := visit[encoded]; ok { + v := (N-x)%(x-prev) + prev + ans := make([]int, size) + for t := 0; t < size; t++ { + ans[t] = (seq[v] >> uint(t)) & 1 + } + return ans + } else { + visit[encoded] = x + seq[x] = encoded + } + } + ans := make([]int, size) + for t := 0; t < size; t++ { + ans[t] = (encoded >> uint(t)) & 1 + } + return ans +} diff --git a/go/prison-cells-after-n-days_test.go b/go/prison-cells-after-n-days_test.go new file mode 100644 index 0000000..e28143d --- /dev/null +++ b/go/prison-cells-after-n-days_test.go @@ -0,0 +1,17 @@ +package leetcode + +import ( + "reflect" + "testing" +) + +func TestPrisonAfterNDays(t *testing.T) { + if !reflect.DeepEqual(prisonAfterNDays([]int{0, 1, 0, 1, 1, 0, 0, 1}, 7), + []int{0, 0, 1, 1, 0, 0, 0, 0}) { + t.Fatal() + } + if !reflect.DeepEqual(prisonAfterNDays([]int{1, 0, 0, 1, 0, 0, 1, 0}, 1000000000), + []int{0, 0, 1, 1, 1, 1, 1, 0}) { + t.Fatal() + } +} From 844c6f18d06dcb397db76436e5f4b8ddcb1beddc Mon Sep 17 00:00:00 2001 From: Clark Chung Date: Fri, 14 Feb 2020 15:25:05 +0800 Subject: [PATCH 220/220] Add py solution for 1219. Path with Maximum Gold 1219. Path with Maximum Gold: https://leetcode.com/problems/path-with-maximum-gold/ --- py/path-with-maximum-gold.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 py/path-with-maximum-gold.py diff --git a/py/path-with-maximum-gold.py b/py/path-with-maximum-gold.py new file mode 100644 index 0000000..358756f --- /dev/null +++ b/py/path-with-maximum-gold.py @@ -0,0 +1,33 @@ +class Solution(object): + def getMaximumGold(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + self.grid = grid + self.rows = len(grid) + if self.rows: + self.cols = len(grid[0]) + + ans = 0 + for x in range(self.rows): + for y in range(self.cols): + ans = max(ans, self.dfs(x, y)) + + return ans + + def dfs(self, x, y): + if not (0 <= x < self.rows and 0 <= y < self.cols): + return 0 + else: + gold = self.grid[x][y] + if gold == 0: + return 0 + self.grid[x][y] = 0 + ans = 0 + for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: + nxt = self.dfs(x + dx, y + dy) + if nxt > ans: + ans = nxt + self.grid[x][y] = gold + return ans + gold