diff --git a/1-bit-and-2-bit-characters.py b/1-bit-and-2-bit-characters.py new file mode 100644 index 0000000..2a657ad --- /dev/null +++ b/1-bit-and-2-bit-characters.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param bits: a array represented by several bits. + @return: whether the last character must be a one-bit character or not + """ + def isOneBitCharacter(self, bits): + # Write your code here + i = 0 + while i < len(bits): + if i == len(bits) - 1: + return True + if bits[i] == 0: + i += 1 + else: + i += 2 + return False + +# easy: https://www.lintcode.com/problem/1-bit-and-2-bit-characters/ diff --git a/3sum_closest.py b/3sum-closest.py similarity index 100% rename from 3sum_closest.py rename to 3sum-closest.py diff --git a/a_b_problem.py b/a-b-problem.py similarity index 100% rename from a_b_problem.py rename to a-b-problem.py diff --git a/add_and_search_word.py b/add-and-search-word.py similarity index 100% rename from add_and_search_word.py rename to add-and-search-word.py diff --git a/add-and-search.py b/add-and-search.py new file mode 100644 index 0000000..26e2ebe --- /dev/null +++ b/add-and-search.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param inputs: an integer array + @param tests: an integer array + @return: return true if sum of two values in inputs are in tests. + """ + def addAndSearch(self, inputs, tests): + # write your code here. + si = set(tests) + for i in range(len(inputs) - 1): + for j in range(i + 1, len(inputs)): + s = inputs[i] + inputs[j] + if s in si: + return True + return False + +# easy: https://www.lintcode.com/problem/add-and-search/ diff --git a/add_binary.py b/add-binary.py similarity index 100% rename from add_binary.py rename to add-binary.py diff --git a/add_digits.py b/add-digits.py similarity index 100% rename from add_digits.py rename to add-digits.py diff --git a/add-strings.py b/add-strings.py new file mode 100644 index 0000000..71702e4 --- /dev/null +++ b/add-strings.py @@ -0,0 +1,37 @@ +class Solution: + """ + @param num1: a non-negative integers + @param num2: a non-negative integers + @return: return sum of num1 and num2 + """ + def addStrings(self, num1, num2): + # write your code here + ret = [] + l1, l2 = len(num1), len(num2) + num1 = num1[::-1] + num2 = num2[::-1] + step = 0 + for i in range(min(l1, l2)): + v = (ord(num1[i]) - ord('0')) + (ord(num2[i]) - ord('0')) + step + if v >= 10: + ret.append(chr(v - 10 + ord('0'))) + step = 1 + else: + ret.append(chr(v + ord('0'))) + step = 0 + start, num = l1, num2 + if l2 < l1: + start, num = l2, num1 + for i in range(start, len(num)): + v = (ord(num[i]) - ord('0')) + step + if v >= 10: + ret.append(chr(v - 10 + ord('0'))) + step = 1 + else: + ret.append(chr(v + ord('0'))) + step = 0 + if step == 1: + ret.append('1') + return ''.join(ret[::-1]) + +# easy: https://www.lintcode.com/problem/add-strings/ diff --git a/add-two-numbers-ii.py b/add-two-numbers-ii.py new file mode 100644 index 0000000..0e1acee --- /dev/null +++ b/add-two-numbers-ii.py @@ -0,0 +1,63 @@ +""" +Definition of ListNode +class ListNode(object): + def __init__(self, val, next=None): + self.val = val + self.next = next +""" + +class Solution: + """ + @param l1: The first list. + @param l2: The second list. + @return: the sum list of l1 and l2. + """ + def addLists2(self, l1, l2): + # write your code here + head, tail = None, None + step = 0 + l1 = self.reverse(l1) + l2 = self.reverse(l2) + while l1 and l2: + val = l1.val + l2.val + step + step = int(val / 10) + val = val % 10 + if not head: + head = tail = ListNode(val) + else: + tail.next = ListNode(val) + tail = tail.next + l1 = l1.next + l2 = l2.next + if l1 or l2: + l = l1 if l1 else l2 + while l: + val = l.val + step + step = int(val / 10) + val = val % 10 + if not head: + head = tail = ListNode(val) + else: + tail.next = ListNode(val) + tail = tail.next + l = l.next + if step: + tail.next = ListNode(step) + tail = tail.next + return self.reverse(head) + + def reverse(self, node): + head, tail = None, None + while node: + if not head: + head, tail = node, node + node = node.next + tail.next = None + else: + tmp = node.next + node.next = head + head = node + node = tmp + return head + +# medium: https://www.lintcode.com/problem/add-two-numbers-ii/ diff --git a/add_two_numbers.py b/add-two-numbers.py similarity index 100% rename from add_two_numbers.py rename to add-two-numbers.py diff --git a/aircraft-seat.py b/aircraft-seat.py new file mode 100644 index 0000000..d0e2073 --- /dev/null +++ b/aircraft-seat.py @@ -0,0 +1,32 @@ +class Solution: + """ + @param N: the number of rows + @param S: a list of reserved seats + @return: nothing + """ + def solution(self, N, S): + # Write your code here. + # 放4个人只有以下三种方案:BCDE DEFG FGHJ + ret = 0 + occupied = set(S.split(' ')) + for i in range(1, N + 1): + SB = str(i) + 'B' + SC = str(i) + 'C' + SD = str(i) + 'D' + SE = str(i) + 'E' + SF = str(i) + 'F' + SG = str(i) + 'G' + SH = str(i) + 'H' + SI = str(i) + 'I' + SJ = str(i) + 'J' + if (SB not in occupied) and (SC not in occupied) and (SD not in occupied) and (SE not in occupied): + ret += 1 + occupied.add(SE) # 占坑 + if (SD not in occupied) and (SE not in occupied) and (SF not in occupied) and (SG not in occupied): + ret += 1 + occupied.add(SG) + if (SF not in occupied) and (SG not in occupied) and (SH not in occupied) and (SI not in occupied): + ret += 1 + return ret + +# easy: https://www.lintcode.com/problem/aircraft-seat/ diff --git a/alien-dictionaryeasy.py b/alien-dictionaryeasy.py new file mode 100644 index 0000000..4a57d5c --- /dev/null +++ b/alien-dictionaryeasy.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param words: the array of string means the list of words + @param order: a string indicate the order of letters + @return: return true or false + """ + def isAlienSorted(self, words, order): + # + alphabets = 'abcdefghijklmnopqrstuvwxyz' + di = {} + for i in range(len(order)): + di[order[i]] = alphabets[i] + new_words = [] + for word in words: + nw = [] + for c in word: + nw.append(di[c]) + new_words.append(''.join(nw)) + for i in range(len(new_words) - 1): + if new_words[i] > new_words[i + 1]: + return False + return True + +# easy: https://www.lintcode.com/problem/alien-dictionaryeasy/ diff --git a/amicable-pair.py b/amicable-pair.py new file mode 100644 index 0000000..1d66301 --- /dev/null +++ b/amicable-pair.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param: k: An integer + @return: all amicable pairs + """ + def amicablePair(self, k): + # write your code here + ret = [] + for i in range(2, k + 1): + s = self.vsum(i) + if (s <= i) or (s > (k + 1)): + continue + if i == self.vsum(s): + ret.append([i, s]) + return ret + + def vsum(self, v): + ret = 1 + i = 2 + while i * i < v: + if v % i == 0: + ret += (i + int(v / i)) + i += 1 + if i * i == v: + ret += i + return ret + +# easy: https://www.lintcode.com/problem/243 diff --git a/another-zuma.py b/another-zuma.py new file mode 100644 index 0000000..4b6f144 --- /dev/null +++ b/another-zuma.py @@ -0,0 +1,31 @@ +class Solution: + """ + @param s: the pearl sequences. + @param k: every k same pearls together will be removed. + @return: return the pearls after the game. + """ + def zumaGaming(self, s, k): + # write your code here. + sarr = [] + prev = None + cnt = 0 + for c in s: + if c != prev: + if cnt > 0: + sarr.append(prev * cnt) + prev = c + cnt = 1 + else: + cnt += 1 + if cnt == k: + prev = None + cnt = 0 + if prev and (cnt > 0): + sarr.append(prev * cnt) + ns = ''.join(sarr) + if ns != s: + return self.zumaGaming(ns, k) + else: + return ns + +# medium: https://www.lintcode.com/problem/another-zuma/ diff --git a/arrange-interview-city.py b/arrange-interview-city.py new file mode 100644 index 0000000..351eaaf --- /dev/null +++ b/arrange-interview-city.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param cost: The cost of each interviewer + @return: The total cost of all the interviewers. + """ + def TotalCost(self, cost): + # write your code here + # 因为AB人数相等,N一定是偶数。 + ret = 0 + diff = [] + for c in cost: + ret += c[1] + diff.append(c[0] - c[1]) + diff.sort() + for i in range(int(len(diff) / 2)): + ret += diff[i] + return ret + +# easy: https://www.lintcode.com/problem/arrange-interview-city/ diff --git a/arranging-coins.py b/arranging-coins.py new file mode 100644 index 0000000..4d92c12 --- /dev/null +++ b/arranging-coins.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param n: a non-negative integer + @return: the total number of full staircase rows that can be formed + """ + def arrangeCoins(self, n): + # Write your code here + i = 1 + while True: + if n - i > 0: + n -= i + i += 1 + elif n - i == 0: + return i + else: + return i - 1 + +# easy: https://www.lintcode.com/problem/arranging-coins/ diff --git a/array-ame.py b/array-ame.py new file mode 100644 index 0000000..3e97fb3 --- /dev/null +++ b/array-ame.py @@ -0,0 +1,23 @@ +from typing import ( + List, +) + +class Solution: + """ + @param arr: the array + @return: determine the number of moves to make all elements equals + """ + def array_game(self, arr: List[int]) -> int: + # write your code here + ''' + 其它元素加1可以等价为该元素减1,其它元素不动。那么方法如下: + 1. 找到最小的元素 + 2. 计算每个元素和这个最小元素的差 + 3. 差加起来就是总步数 + ''' + r = 0 + m = min(arr) + for i in arr: + r += (i - m) + return r +# medium: https://www.lintcode.com/problem/1907 diff --git a/array-maximum-difference.py b/array-maximum-difference.py new file mode 100644 index 0000000..1b2520a --- /dev/null +++ b/array-maximum-difference.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param a: the array a + @return: return the maximum value + """ + def getAnswer(self, a): + # Write your code here + r = 0 + for i in range(len(a)): + if (a[i] % 2) == 0: + for j in range(i - 1, -1, -1): + if (a[j] % 2) == 1: + r = max(r, a[i] - a[j]) + return r + +# easy: https://www.lintcode.com/problem/1617 diff --git a/array-partition-i.py b/array-partition-i.py new file mode 100644 index 0000000..33dcbfa --- /dev/null +++ b/array-partition-i.py @@ -0,0 +1,14 @@ +class Solution: + """ + @param nums: an array + @return: the sum of min(ai, bi) for all i from 1 to n + """ + def arrayPairSum(self, nums): + # Write your code here + ret = 0 + nums.sort() + for i in range(0, len(nums), 2): + ret += nums[i] + return ret + +# easy: https://www.lintcode.com/problem/array-partition-i/ diff --git a/array-score.py b/array-score.py new file mode 100644 index 0000000..f4f98d7 --- /dev/null +++ b/array-score.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param nums: the array to be scored. + @param k: the requirement of subarray length. + @param u: if the sum is less than u, get 1 score. + @param l: if the sum is greater than l, lose 1 score. + @return: return the sum of scores for every subarray whose length is k. + """ + def arrayScore(self, nums, k, u, l): + # write your code here. + ret = 0 + s = 0 + for i in range(0, k): + s += nums[i] + if s < u: + ret += 1 + if s > l: + ret -= 1 + for i in range(k, len(nums)): + s += nums[i] - nums[i - k] + if s < u: + ret += 1 + if s > l: + ret -= 1 + return ret + +# easy: https://www.lintcode.com/problem/array-score/ diff --git a/arraylist.py b/arraylist.py new file mode 100644 index 0000000..dbd5ce0 --- /dev/null +++ b/arraylist.py @@ -0,0 +1,64 @@ +class ArrayListManager: + ''' + * @param n: You should generate an array list of n elements. + * @return: The array list your just created. + ''' + def create(self, n): + # Write your code here + self.arr = [i for i in range(n)] + return self.arr + + + ''' + * @param list: The list you need to clone + * @return: A deep copyed array list from the given list + ''' + def clone(self, list): + # Write your code here + return [i for i in list] + + + ''' + * @param list: The array list to find the kth element + * @param k: Find the kth element + * @return: The kth element + ''' + def get(self, list, k): + # Write your code here + return list[k] + + + ''' + * @param list: The array list + * @param k: Find the kth element, set it to val + * @param val: Find the kth element, set it to val + ''' + def set(self, list, k, val): + # write your code here + list[k] = val + + + ''' + * @param list: The array list to remove the kth element + * @param k: Remove the kth element + ''' + def remove(self, list, k): + # write tour code here + for i in range(k, len(list) - 1): + list[i] = list[i + 1] + list.pop() + + + ''' + * @param list: The array list. + * @param val: Get the index of the first element that equals to val + * @return: Return the index of that element + ''' + def indexOf(self, list, val): + # Write your code here + for i in range(len(list)): + if list[i] == val: + return i + return -1 + +# easy: https://www.lintcode.com/problem/385/ diff --git a/assign-cookies.py b/assign-cookies.py new file mode 100644 index 0000000..cd1f176 --- /dev/null +++ b/assign-cookies.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param g: children's greed factor + @param s: cookie's size + @return: the maximum number + """ + def findContentChildren(self, g, s): + # Write your code here + # 贪心,优先分配小饼干。 + ret = 0 + g.sort() + s.sort() + i_g, i_s = 0, 0 + while (i_g < len(g)) and (i_s < len(s)): + if s[i_s] < g[i_g]: # 当前饼干不满足需求 + i_s += 1 + else: + i_s += 1 + i_g += 1 + ret += 1 + return ret + +# easy: https://www.lintcode.com/problem/assign-cookies/ diff --git a/assignment_operator_overloading_c_only.cpp b/assignment-operator-overloading-c-only.cpp similarity index 100% rename from assignment_operator_overloading_c_only.cpp rename to assignment-operator-overloading-c-only.cpp diff --git a/associated-query.py b/associated-query.py new file mode 100644 index 0000000..fb7cd02 --- /dev/null +++ b/associated-query.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param datalist1: a list represents the employee table + @param datalist2: a list represents the employee hours table + @return: Returns a list of strings represents the datalist3 + """ + def getList(self, datalist1, datalist2): + # write your code here + ret = [] + di = {} + for data in datalist2: + di[data[0]] = [data[2], data[4], data[6]] + for data in datalist1: + uid = data[0] + uname = data[1] + if uid in di: + line = [uname] + line.extend(di[uid]) + total = 0 + for i in di[uid]: + total += int(i) + line.append(str(total)) + ret.append(line) + return ret; + +# easy: https://www.lintcode.com/problem/associated-query/ diff --git a/attendance-judgment.py b/attendance-judgment.py new file mode 100644 index 0000000..592cd1d --- /dev/null +++ b/attendance-judgment.py @@ -0,0 +1,30 @@ +class Solution: + """ + @param record: Attendance record. + @return: If the student should be punished return true, else return false. + """ + def judge(self, record): + # Write your code here. + cd, cl = 0, 0 + pl = None + for c in record: + if c == 'D': + cd += 1 + if cd == 2: + return True + pl = None + cl = 0 + elif c == 'L': + if pl != 'L': + pl = 'L' + cl += 1 + else: + cl += 1 + if cl == 3: + return True + else: + pl = None + cl = 0 + return False + +# easy: https://www.lintcode.com/problem/attendance-judgment/ diff --git a/average-of-levels-in-binary-tree.py b/average-of-levels-in-binary-tree.py new file mode 100644 index 0000000..465c590 --- /dev/null +++ b/average-of-levels-in-binary-tree.py @@ -0,0 +1,33 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the binary tree of the root + @return: return a list of double + """ + def averageOfLevels(self, root): + # write your code here + ret = [] + levels = [[root], []] + curr = 0 + while levels[curr]: + s = 0 + _next = 1 - curr + for node in levels[curr]: + s += node.val + if node.left: + levels[_next].append(node.left) + if node.right: + levels[_next].append(node.right) + ret.append(s / len(levels[curr])) + levels[curr].clear() + curr = _next + return ret + +# easy: https://www.lintcode.com/problem/average-of-levels-in-binary-tree/description diff --git a/backpack_ii.py b/backpack-ii.py similarity index 100% rename from backpack_ii.py rename to backpack-ii.py diff --git a/backpack_vi.py b/backpack-vi.py similarity index 100% rename from backpack_vi.py rename to backpack-vi.py diff --git a/backspace-string-compare.py b/backspace-string-compare.py new file mode 100644 index 0000000..18e9701 --- /dev/null +++ b/backspace-string-compare.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param S: string S + @param T: string T + @return: Backspace String Compare + """ + def backspaceCompare(self, S, T): + # Write your code here + s = self.cleanBS(S) + t = self.cleanBS(T) + return s == t + + def cleanBS(self, s): + ret = [] + for c in s: + if c != '#': + ret.append(c) + elif ret: + ret.pop() + return ret + +# easy: https://www.lintcode.com/problem/backspace-string-compare/ diff --git a/balanced-array.py b/balanced-array.py new file mode 100644 index 0000000..4eb4fd3 --- /dev/null +++ b/balanced-array.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param sales: a integer array + @return: return a Integer + """ + def BalancedSalesArray(self, sales): + # write your code here + ls, rs = [], [] + for i in sales: + if not ls: + ls.append(i) + else: + ls.append(ls[-1] + i) + for i in range(len(sales) - 1, -1, -1): + if not rs: + rs.append(sales[i]) + else: + rs.append(rs[-1] + sales[i]) + for i in range(len(sales)): + if ls[i] == rs[len(sales) - i - 1]: + return i + return -1 + +# easy: https://www.lintcode.com/problem/1793/ diff --git a/balanced_binary_tree.py b/balanced-binary-tree.py similarity index 100% rename from balanced_binary_tree.py rename to balanced-binary-tree.py diff --git a/base-7.py b/base-7.py new file mode 100644 index 0000000..4d28072 --- /dev/null +++ b/base-7.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param num: the given number + @return: The base 7 string representation + """ + def convertToBase7(self, num): + # Write your code here + minus = False + if num < 0: + num = -num; + minus = True + digits = [] + while num >= 7: + digits.append(num % 7) + num = int(num / 7) + digits.append(num) + k = 1 + ret = 0 + for d in digits: + ret += d * k + k *= 10 + if minus: + return str(-ret) + return str(ret) + +# easy: https://www.lintcode.com/problem/base-7/ diff --git a/baseball-game.py b/baseball-game.py new file mode 100644 index 0000000..a2f5c6e --- /dev/null +++ b/baseball-game.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param ops: the list of operations + @return: the sum of the points you could get in all the rounds + """ + def calPoints(self, ops): + # Write your code here + stack = [] + for i in ops: + if i == '+': + stack.append(stack[-1] + stack[-2]) + elif i == 'C': + stack.pop() + elif i == 'D': + stack.append(stack[-1] * 2) + else: + stack.append(int(i)) + return sum(stack) + +# easy: https://www.lintcode.com/problem/baseball-game/ diff --git a/best_time_to_buy_and_sell_stock_ii.py b/best-time-to-buy-and-sell-stock-ii.py similarity index 100% rename from best_time_to_buy_and_sell_stock_ii.py rename to best-time-to-buy-and-sell-stock-ii.py diff --git a/best_time_to_buy_and_sell_stock_iii.py b/best-time-to-buy-and-sell-stock-iii.py similarity index 100% rename from best_time_to_buy_and_sell_stock_iii.py rename to best-time-to-buy-and-sell-stock-iii.py diff --git a/best_time_to_buy_and_sell_stock.py b/best-time-to-buy-and-sell-stock.py similarity index 100% rename from best_time_to_buy_and_sell_stock.py rename to best-time-to-buy-and-sell-stock.py diff --git a/binary-number-with-alternating-bits.py b/binary-number-with-alternating-bits.py new file mode 100644 index 0000000..9b5b4a6 --- /dev/null +++ b/binary-number-with-alternating-bits.py @@ -0,0 +1,15 @@ +class Solution: + """ + @param n: a postive Integer + @return: if two adjacent bits will always have different values + """ + def hasAlternatingBits(self, n): + # Write your code here + if (n % 2) == 0: + x = int(n / 2) + else: + x = n * 2 + r = x ^ n + return (r & (r + 1)) == 0 + +# easy: https://www.lintcode.com/problem/binary-number-with-alternating-bits/ diff --git a/binary_representation.py b/binary-representation.py similarity index 100% rename from binary_representation.py rename to binary-representation.py diff --git a/binary_tree_inorder_traversal.py b/binary-tree-inorder-traversal.py similarity index 100% rename from binary_tree_inorder_traversal.py rename to binary-tree-inorder-traversal.py diff --git a/binary-tree-leaf-sum.py b/binary-tree-leaf-sum.py new file mode 100644 index 0000000..ffa4d4f --- /dev/null +++ b/binary-tree-leaf-sum.py @@ -0,0 +1,27 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root of the binary tree + @return: An integer + """ + def leafSum(self, root): + # write your code here + if not root: + return 0 + if not (root.left or root.right): + return root.val + r = 0 + if root.left: + r += self.leafSum(root.left) + if root.right: + r += self.leafSum(root.right) + return r + +# easy: https://www.lintcode.com/problem/481 diff --git a/binary_tree_level_order_traversal_ii.py b/binary-tree-level-order-traversal-ii.py similarity index 100% rename from binary_tree_level_order_traversal_ii.py rename to binary-tree-level-order-traversal-ii.py diff --git a/binary_tree_level_order_traversal.py b/binary-tree-level-order-traversal.py similarity index 100% rename from binary_tree_level_order_traversal.py rename to binary-tree-level-order-traversal.py diff --git a/binary-tree-level-sum.py b/binary-tree-level-sum.py new file mode 100644 index 0000000..42c8e1f --- /dev/null +++ b/binary-tree-level-sum.py @@ -0,0 +1,35 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root of the binary tree + @param level: the depth of the target level + @return: An integer + """ + def levelSum(self, root, level): + # write your code here + ret = 0 + if root and (level > 0): + ilevel = 1 + curr_nodes = [root] + next_nodes = [] + while ilevel < level: + for node in curr_nodes: + if node.left: + next_nodes.append(node.left) + if node.right: + next_nodes.append(node.right) + ilevel += 1 + curr_nodes = next_nodes + next_nodes = [] + for node in curr_nodes: + ret += node.val + return ret + +# easy: https://www.lintcode.com/problem/binary-tree-level-sum/ diff --git a/binary-tree-longest-consecutive-sequence.py b/binary-tree-longest-consecutive-sequence.py new file mode 100644 index 0000000..b82eea9 --- /dev/null +++ b/binary-tree-longest-consecutive-sequence.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param root: the root of binary tree + @return: the length of the longest consecutive sequence path + """ + def longestConsecutive(self, root): + # write your code here + return Solution.longest(root, None, 0) + + @staticmethod + def longest(node, parent, curr_len): + if not node: + return 0 + if parent and ((parent.val + 1) == node.val): + curr_len = curr_len + 1 + else: + curr_len = 1 + left_len = Solution.longest(node.left, node, curr_len) + right_len = Solution.longest(node.right, node, curr_len) + return max(curr_len, max(left_len, right_len)) + +# easy: https://www.lintcode.com/problem/binary-tree-longest-consecutive-sequence/ diff --git a/binary_tree_maximum_node.py b/binary-tree-maximum-node.py similarity index 100% rename from binary_tree_maximum_node.py rename to binary-tree-maximum-node.py diff --git a/binary_tree_maximum_path_sum.py b/binary-tree-maximum-path-sum.py similarity index 100% rename from binary_tree_maximum_path_sum.py rename to binary-tree-maximum-path-sum.py diff --git a/binary-tree-path-sum.py b/binary-tree-path-sum.py new file mode 100644 index 0000000..2bf0ee0 --- /dev/null +++ b/binary-tree-path-sum.py @@ -0,0 +1,37 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + + +class Solution: + """ + @param: root: the root of binary tree + @param: target: An integer + @return: all valid paths + """ + def binaryTreePathSum(self, root, target): + # write your code here + ret = [] + self._binaryTreePathSum(ret, [], root, target) + return ret + + def _binaryTreePathSum(self, ret, path, node, target): + if not node: + return + path.append(node.val) + if not (node.left or node.right): + if node.val == target: + ret.append([]) + ret[-1].extend(path) + if node.left: + self._binaryTreePathSum(ret, path, node.left, target - node.val) + path.pop() + if node.right: + self._binaryTreePathSum(ret, path, node.right, target - node.val) + path.pop() + +# easy: https://www.lintcode.com/problem/binary-tree-path-sum/ diff --git a/binary_tree_paths.py b/binary-tree-paths.py similarity index 100% rename from binary_tree_paths.py rename to binary-tree-paths.py diff --git a/binary-tree-postorder-traversal-null.py b/binary-tree-postorder-traversal-null.py new file mode 100644 index 0000000..d0c4745 --- /dev/null +++ b/binary-tree-postorder-traversal-null.py @@ -0,0 +1,30 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: A Tree + @return: Postorder in ArrayList which contains node values. + """ + def postorderTraversal(self, root): + # write your code here + ret = [] + if root: + s1, s2 = [root], [] + while s1: + node = s1.pop() + s2.append(node) + if node.left: + s1.append(node.left) + if node.right: + s1.append(node.right) + while s2: + ret.append(s2.pop().val) + return ret + +# easy: https://www.lintcode.com/problem/binary-tree-postorder-traversal-null/ diff --git a/binary_tree_postorder_traversal.py b/binary-tree-postorder-traversal.py similarity index 100% rename from binary_tree_postorder_traversal.py rename to binary-tree-postorder-traversal.py diff --git a/binary_tree_preorder_traversal.py b/binary-tree-preorder-traversal.py similarity index 100% rename from binary_tree_preorder_traversal.py rename to binary-tree-preorder-traversal.py diff --git a/binary-tree-pruning.py b/binary-tree-pruning.py new file mode 100644 index 0000000..4920f0b --- /dev/null +++ b/binary-tree-pruning.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param root: the root + @return: the same tree where every subtree (of the given tree) not containing a 1 has been removed + """ + def pruneTree(self, root): + # Write your code here + if not root: + return None + if root.left: + root.left = self.pruneTree(root.left) + if root.right: + root.right = self.pruneTree(root.right) + if root.left == None and root.right == None: + if root.val == 0: + return None + return root + +# easy: https://www.lintcode.com/problem/binary-tree-pruning/ diff --git a/binary_tree_serialization.py b/binary-tree-serialization.py similarity index 100% rename from binary_tree_serialization.py rename to binary-tree-serialization.py diff --git a/binary-tree-tilt.py b/binary-tree-tilt.py new file mode 100644 index 0000000..93264c6 --- /dev/null +++ b/binary-tree-tilt.py @@ -0,0 +1,34 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root + @return: the tilt of the whole tree + """ + def findTilt(self, root): + # Write your code here + ret = [0] # 方便传参数 + self.traversal(root, ret) + return ret[0] + + def traversal(self, node, ret): + if node: + left_sum = self.getSum(node.left) + right_sum = self.getSum(node.right) + ret[0] += abs(left_sum - right_sum) + self.traversal(node.left, ret) + self.traversal(node.right, ret) + + def getSum(self, node): + if not node: + return 0 + else: + return node.val + self.getSum(node.left) + self.getSum(node.right) + +# easy: https://www.lintcode.com/problem/binary-tree-tilt/ diff --git a/binary-tree-upside-down.py b/binary-tree-upside-down.py new file mode 100644 index 0000000..94c9bdc --- /dev/null +++ b/binary-tree-upside-down.py @@ -0,0 +1,26 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root of binary tree + @return: new root + """ + def upsideDownBinaryTree(self, root): + # write your code here + # 递归版本,非递归待版本TODO。 + if (root == None) or (root.left == None): + return root + _root = self.upsideDownBinaryTree(root.left) + root.left.left = root.right + root.left.right = root + root.left = None + root.right = None + return _root + +# medium: https://www.lintcode.com/problem/binary-tree-upside-down diff --git a/binary_tree_zigzag_level_order_traversal.py b/binary-tree-zigzag-level-order-traversal.py similarity index 100% rename from binary_tree_zigzag_level_order_traversal.py rename to binary-tree-zigzag-level-order-traversal.py diff --git a/bold-words-in-string.py b/bold-words-in-string.py new file mode 100644 index 0000000..f085bff --- /dev/null +++ b/bold-words-in-string.py @@ -0,0 +1,31 @@ +class Solution: + """ + @param words: the words + @param S: the string + @return: the string with least number of tags + """ + def boldWords(self, words, S): + # Write your code here + ret = [] + bold_mark = [False] * len(S) + for i in range(len(S)): + for word in words: + l = len(word) + if (i + l) <= len(S): + if S[i: i + l] == word: + for j in range(i, i + l): + bold_mark[j] = True + is_bold = False + for i in range(len(S)): + if bold_mark[i] and (not is_bold): + ret.append('') + is_bold = True + elif (not bold_mark[i]) and is_bold: + ret.append('') + is_bold = False + ret.append(S[i]) + if is_bold: + ret.append('') + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/bold-words-in-string/ diff --git a/buddy-strings.py b/buddy-strings.py new file mode 100644 index 0000000..22cc589 --- /dev/null +++ b/buddy-strings.py @@ -0,0 +1,36 @@ +class Solution: + """ + @param A: string A + @param B: string B + @return: bool + """ + def buddyStrings(self, A, B): + # Write your code here + if len(A) != len(B): + return False + di = {} + for i in range(len(A)): + if not A[i] in di: + di[A[i]] = 1 + else: + di[A[i]] += 1 + if A == B: + for k, v in di.items(): + if v >= 2: + return True + return False + for i in range(len(A)): + if not B[i] in di: + di[B[i]] = -1 + else: + di[B[i]] -= 1 + for k, v in di.items(): + if v != 0: + return False + cnt = 0 + for i in range(len(A)): + if A[i] != B[i]: + cnt += 1 + return cnt == 2 + +# easy: https://www.lintcode.com/problem/buddy-strings/ diff --git a/buy-passes.py b/buy-passes.py new file mode 100644 index 0000000..9f837a3 --- /dev/null +++ b/buy-passes.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param arr: the line + @param k: Alex place + @return: the time when Alex requires to buy all passes + """ + def buyPasses(self, arr, k): + # Write your code here. + r = 0 + for i in range(len(arr)): + if i <= k: + r += min(arr[i], arr[k]) + else: + r += min(arr[k] - 1, arr[i]) + return r + +''' +arr = [1, 2, 5] means they want 1, 2, 5 tickets. +k = 1 means Alex is user 1 who needs 2 tickets. +''' + +# medium: https://www.lintcode.com/problem/1851/ diff --git a/calculate-circumference-and-area.py b/calculate-circumference-and-area.py new file mode 100644 index 0000000..6898529 --- /dev/null +++ b/calculate-circumference-and-area.py @@ -0,0 +1,13 @@ +class Solution: + """ + @param r: a Integer represent radius + @return: the circle's circumference nums[0] and area nums[1] + """ + def calculate(self, r): + # write your code here + pi = 3.14 + c = int(pi * 2.0 * r * 100.0) + s = int(pi * r * r * 100.0) + return [c / 100.0, s / 100.0] + +easy: https://www.lintcode.com/problem/calculate-circumference-and-area diff --git a/calculate-number.py b/calculate-number.py new file mode 100644 index 0000000..06881aa --- /dev/null +++ b/calculate-number.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param num: the num + @return: the array subject to the description + """ + def calculateNumber(self, num): + # Write your code here. + ret = [] + count, pos = 0, 0 + while num != 0: + if (num % 2) != 0: + ret.append(pos) + count += 1 + num = int(num / 2) + pos += 1 + ret.append(count) + ret.reverse() + for i in range(1, len(ret)): + ret[i] = pos - ret[i] + return ret + +# easy: https://www.lintcode.com/problem/calculate-number/ diff --git a/can-convert.py b/can-convert.py new file mode 100644 index 0000000..38aa2be --- /dev/null +++ b/can-convert.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param s: string S + @param t: string T + @return: whether S can convert to T + """ + def canConvert(self, s, t): + # Write your code here + if (not s) or (not t): + return False + prev = -1 + ls, lt = 0, 0 + while (ls < len(s)) and (lt < len(t)): + if s[ls] == t[lt]: + ls += 1 + lt += 1 + else: + ls += 1 + return lt == len(t) + +# easy: https://www.lintcode.com/problem/1540/ diff --git a/can-place-flowers.py b/can-place-flowers.py new file mode 100644 index 0000000..801d0fb --- /dev/null +++ b/can-place-flowers.py @@ -0,0 +1,38 @@ +class Solution: + """ + @param flowerbed: an array + @param n: an Integer + @return: if n new flowers can be planted in it without violating the no-adjacent-flowers rule + """ + def canPlaceFlowers(self, flowerbed, n): + # Write your code here + # 连续偶数个0的情况分为以下几种: + # - 空(开始) 0000 满 -> X0X0 + # - 空(起始位置) 0000 空(结束) -> X0X0 + # - 满 0000 满 -> 0X00, 00X0 + # 连续奇数个0的情况分为以下几种: + # - 空(开始) 000 满 -> X00, 0X0 + # - 空(开始) 000 空(结束) -> X0X + # - 满 000 满 -> 0X0 + # - 满 000 空(结束) -> 0X0, 00X + # 在头尾各补一个0,然后判断连续0: + # - 偶数:int((n - 1) / 2) + # - 奇数:(n - 1) / 2 + if not flowerbed: + return False + ext_bed = [] + if flowerbed[0] == 0: + ext_bed.append(0) + ext_bed.extend(flowerbed) + if flowerbed[-1] == 0: + ext_bed.append(0) + total, c_z = 0, 0 + for i in range(len(ext_bed) + 1): # 扩展一位,方便处理最后的0。 + if (i < len(ext_bed)) and (ext_bed[i] == 0): + c_z += 1 + else: + total += int((c_z - 1) / 2) + c_z = 0 + return total >= n + +# easy: https://www.lintcode.com/problem/can-place-flowers/ diff --git a/capitalizes-the-first-letter.py b/capitalizes-the-first-letter.py new file mode 100644 index 0000000..f353109 --- /dev/null +++ b/capitalizes-the-first-letter.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param s: a string + @return: a string after capitalizes the first letter + """ + def capitalizesFirst(self, s): + # Write your code here + ret = list(s) + start = 0 + while start < len(ret): + if ret[start] == ' ': + start += 1 + else: + break + is_first = True + for i in range(start, len(ret)): + if is_first and ret[i] != ' ': + ret[i] = ret[i].upper() + is_first = False + elif ret[i] == ' ': + is_first = True + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/capitalizes-the-first-letter/ diff --git a/character-deletion.py b/character-deletion.py new file mode 100644 index 0000000..54ce3dd --- /dev/null +++ b/character-deletion.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param str: The first string given + @param sub: The given second string + @return: Returns the deleted string + """ + def CharacterDeletion(self, str, sub): + # write your code here + ret = [] + s = set(sub) + for c in str: + if c not in s: + ret.append(c) + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/character-deletion/ diff --git a/character-grid.py b/character-grid.py new file mode 100644 index 0000000..32b0b12 --- /dev/null +++ b/character-grid.py @@ -0,0 +1,33 @@ +class Solution: + """ + @param A: A string + @param B: A string + @return: A string array + """ + def characterGrid(self, A, B): + # write your code here. + ret = [['.'] * len(A) for i in range(len(B))] + row, col = len(A), len(B) + di_a, di_b = {}, {} + self.init_dict(di_a, A) + self.init_dict(di_b, B) + for c in A: + if c in di_b: + col = di_a[c] + row = di_b[c] + break + for i in range(len(B)): + if i == row: + ret[i] = list(A) + for i in range(len(B)): + ret[i][col] = B[i] + for i in range(len(B)): + ret[i] = ''.join(ret[i]) + return ret + + def init_dict(self, di, s): + for i in range(len(s)): + if s[i] not in di: + di[s[i]] = i # 是要记录第一次出现的位置就可以 + +# easy: https://www.lintcode.com/problem/character-grid/ diff --git a/check-full-binary-tree.py b/check-full-binary-tree.py new file mode 100644 index 0000000..bd74626 --- /dev/null +++ b/check-full-binary-tree.py @@ -0,0 +1,29 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the given tree + @return: Whether it is a full tree + """ + def isFullTree(self, root): + # write your code here + if not root: + return None + if (root.left == None) and (root.right == None): # 都为空的话没事 + return True + elif (root.left != None) and (root.right != None): # 需要递归分别检查左右子树 + is_full = self.isFullTree(root.left) + if not is_full: + return False + is_full = self.isFullTree(root.right) + return is_full + else: + return False + +# medium: https://www.lintcode.com/problem/check-full-binary-tree diff --git a/check_sum_of_square_numbers.py b/check-sum-of-square-numbers.py similarity index 100% rename from check_sum_of_square_numbers.py rename to check-sum-of-square-numbers.py diff --git a/chess-game.py b/chess-game.py new file mode 100644 index 0000000..b19d566 --- /dev/null +++ b/chess-game.py @@ -0,0 +1,31 @@ +class Solution: + """ + @param queen: queen‘coordinate + @param knight: knight‘coordinate + @return: if knight is attacked please return true,else return false + """ + def isAttacked(self, queen, knight): + # write your code here + ret = [] + xmark, ymark = zip(*queen) + xmark = set(xmark) + ymark = set(ymark) + diffs_1 = set([]) + diffs_2 = set([]) + for q in queen: + diffs_1.add(q[1] - q[0]) + diffs_2.add(q[0] + q[1]) + for k in knight: + if k[0] in xmark: + ret.append(True) + continue + if k[1] in ymark: + ret.append(True) + continue + if ((k[1] - k[0]) in diffs_1) or ((k[0] + k[1]) in diffs_2): + ret.append(True) + continue + ret.append(False) + return ret + +# easy: https://www.lintcode.com/problem/chess-game/ diff --git a/chess-piece-rotation.py b/chess-piece-rotation.py new file mode 100644 index 0000000..0b3a090 --- /dev/null +++ b/chess-piece-rotation.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param A: Initial chessboard + @param F: Flipped coordinates + @return: return to the flipped board. + """ + def ChessPieceRotation(self, A, F): + # write your code here + rows, cols = len(A), len(A[0]) + records = [[0 for i in range(cols)] for i in range(rows)] + for f in F: + x, y = f[0] - 1, f[1] - 1; + if (y - 1) >= 0: # 上 + records[x][y - 1] += 1 + if (y + 1) < 4: # 下 + records[x][y + 1] += 1 + if (x - 1) >= 0: # 左右 + records[x - 1][y] += 1 + if (x + 1) < 4: #右 + records[x + 1][y] += 1 + for row in range(rows): + for col in range(cols): + if (records[row][col] % 2) != 0: + A[row][col] = 1 - A[row][col] + return A + +# easy: https://www.lintcode.com/problem/chess-piece-rotation/ diff --git a/circle.py b/circle.py new file mode 100644 index 0000000..a1cb36f --- /dev/null +++ b/circle.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param circles: The value of 6 points on n rings + @return: Whether there are two same circles + """ + def samecircle(self, circles): + # write your code here + s = set() + for circle in circles: + circle.sort() + _circle = '-'.join([str(c) for c in circle]) + if _circle in s: + return True + else: + s.add(_circle) + return False + +# easy: https://www.lintcode.com/problem/circle/ diff --git a/classical_binary_search.py b/classical-binary-search.py similarity index 100% rename from classical_binary_search.py rename to classical-binary-search.py diff --git a/climbing-stairs-ii.py b/climbing-stairs-ii.py new file mode 100644 index 0000000..40d171c --- /dev/null +++ b/climbing-stairs-ii.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param n: An integer + @return: An Integer + """ + def climbStairs2(self, n): + # write your code here + self.cache = [-1] * (n + 1) + self.cache[0] = 1 + self._climbStairs2(n) + return self.cache[n] + + def _climbStairs2(self, n): + if n < 0: + return 0 + if self.cache[n] == -1: + if n <= 2: + self.cache[n] = n + else: + self.cache[n] = self._climbStairs2(n - 1) + self._climbStairs2(n - 2) + self._climbStairs2(n - 3) + return self.cache[n] + +# easy: https://www.lintcode.com/problem/climbing-stairs-ii/ diff --git a/climbing_stairs.py b/climbing-stairs.py similarity index 100% rename from climbing_stairs.py rename to climbing-stairs.py diff --git a/clone_binary_tree.py b/clone-binary-tree.py similarity index 100% rename from clone_binary_tree.py rename to clone-binary-tree.py diff --git a/clone_graph.py b/clone-graph.py similarity index 100% rename from clone_graph.py rename to clone-graph.py diff --git a/closest-binary-search-tree-value.py b/closest-binary-search-tree-value.py new file mode 100644 index 0000000..56aaa39 --- /dev/null +++ b/closest-binary-search-tree-value.py @@ -0,0 +1,27 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the given BST + @param target: the given target + @return: the value in the BST that is closest to the target + """ + def closestValue(self, root, target): + # write your code here + if root.val > target: + if root.left: + val = self.closestValue(root.left, target) + return val if abs(root.val - target) > abs(val - target) else root.val + elif root.val < target: + if root.right: + val = self.closestValue(root.right, target) + return val if abs(root.val - target) > abs(val - target) else root.val + return root.val + +# easy: https://www.lintcode.com/problem/closest-binary-search-tree-value/ diff --git a/closest-city.py b/closest-city.py new file mode 100644 index 0000000..0ebce5a --- /dev/null +++ b/closest-city.py @@ -0,0 +1,59 @@ +class Solution: + """ + @param x: an array of integers, the x coordinates of each city[i] + @param y: an array of integers, the y coordinates of each city[i] + @param c: an array of strings that represent the names of each city[i] + @param q: an array of strings that represent the names of query locations + @return: the closest city for each query + """ + def NearestNeighbor(self, x, y, c, q): + # write your code here + ret = [] + di_x = {} + di_y = {} + di_city = {} + for i in range(len(c)): + xi = x[i] + yi = y[i] + city = c[i] + if xi not in di_x: + di_x[xi] = [] + di_x[xi].append(city) + if yi not in di_y: + di_y[yi] = [] + di_y[yi].append(city) + if city not in di_city: + di_city[city] = [xi, yi] + for qcity in q: + r = None + dist = 1000000000 + qx = di_city[qcity][0] + qy = di_city[qcity][1] + if qx in di_x: + for c in di_x[qx]: + if c != qcity: + cy = di_city[c][1] + _dist = abs(cy - qy) + if _dist < dist: + dist = _dist + r = c + elif _dist == dist: + if c < r: + r = c + for c in di_y[qy]: + if c != qcity: + cx = di_city[c][0] + _dist = abs(cx - qx) + if _dist < dist: + dist = _dist + r = c + elif _dist == dist: + if c < r: + r = c + if not r: + ret.append('NONE') + else: + ret.append(r) + return ret + +# easy: https://www.lintcode.com/problem/closest-city/ diff --git a/closest-number-in-sorted-array.py b/closest-number-in-sorted-array.py new file mode 100644 index 0000000..93174c6 --- /dev/null +++ b/closest-number-in-sorted-array.py @@ -0,0 +1,32 @@ +class Solution: + """ + @param A: an integer array sorted in ascending order + @param target: An integer + @return: an integer + """ + def closestNumber(self, A, target): + # write your code here + x, y, z = -1, -1, -1 + i, j = 0, len(A) - 1 + while i <= j: + mid = int((i + j) / 2) + if A[mid] < target: + if (mid < (len(A) - 1)) and (A[mid + 1] >= target): + y = mid + i = mid + 1 + elif A[mid] > target: + if (0 < mid) and (A[mid - 1] <= target): + z = mid + j = mid - 1 + else: + x = mid + break + if x != -1: + return x + if (y == -1) and (A[-1] < target): + return len(A) - 1 + if (z == -1) and (A[0] > target): + return 0 + return y if (target - A[y]) <= (A[z] - target) else z + +# easy: https://www.lintcode.com/problem/459 diff --git a/closest-target-value.py b/closest-target-value.py new file mode 100644 index 0000000..0a22c18 --- /dev/null +++ b/closest-target-value.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param target: the target + @param array: an array + @return: the closest value + """ + def closestTargetValue(self, target, array): + # Write your code here + ret = None + diff = 100000000 # max + i, j = 0, len(array) - 1 + array.sort() + while i < j: + r = array[i] + array[j] + if r == target: + return r + elif r > target: + j -= 1 + else: + if (target - r) < diff: + diff = target - r + ret = r + i += 1 + return ret if ret else -1 + +# easy: https://www.lintcode.com/problem/1478/ diff --git a/coins_in_a_line_ii.py b/coins-in-a-line-ii.py similarity index 100% rename from coins_in_a_line_ii.py rename to coins-in-a-line-ii.py diff --git a/coins_in_a_line.py b/coins-in-a-line.py similarity index 100% rename from coins_in_a_line.py rename to coins-in-a-line.py diff --git a/combination-set.py b/combination-set.py new file mode 100644 index 0000000..2ceae9e --- /dev/null +++ b/combination-set.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param num: a array + @param target: a num + @return: return all combinations + """ + def combinationSet(self, num, target): + # write your code here + ret = [] + self.dfs(ret, num, target, 0) + return ret + + def dfs(self, ret, num, target, cur): + for i in num: + tmp = cur + cur = cur * 10 + i + if cur < target: + ret.append(cur) + if cur > 0: + self.dfs(ret, num, target, cur) + cur = tmp + +# easy: https://www.lintcode.com/problem/combination-set/ diff --git a/combination_sum_ii.py b/combination-sum-ii.py similarity index 100% rename from combination_sum_ii.py rename to combination-sum-ii.py diff --git a/combination_sum.py b/combination-sum.py similarity index 100% rename from combination_sum.py rename to combination-sum.py diff --git a/compare_strings.py b/compare-strings.py similarity index 100% rename from compare_strings.py rename to compare-strings.py diff --git a/compare-version-numbers.py b/compare-version-numbers.py new file mode 100644 index 0000000..73a2b90 --- /dev/null +++ b/compare-version-numbers.py @@ -0,0 +1,25 @@ +class Solution: + """ + @param version1: the first given number + @param version2: the second given number + @return: the result of comparing + """ + def compareVersion(self, version1, version2): + # Write your code here + v1s = version1.split('.') # 先分隔字符串,如果不用python还是建议直接扫字符串比较。 + v2s = version2.split('.') + v1s = [int(v) for v in v1s] + v2s = [int(v) for v in v2s] + for i in range(min(len(v1s), len(v2s))): # 以短的为基准,如果长度一样,那么长得赢了。 + if v1s[i] < v2s[i]: + return -1 + elif v1s[i] > v2s[i]: + return 1 + if len(v1s) == len(v2s): + return 0 + elif len(v1s) > len(v2s): + return 1 + else: + return -1 + +# medium: https://www.lintcode.com/problem/compare-version-numbers diff --git a/concatenated_string_with_uncommon_characters_of_two_strings.py b/concatenated-string-with-uncommon-characters-of-two-strings.py similarity index 100% rename from concatenated_string_with_uncommon_characters_of_two_strings.py rename to concatenated-string-with-uncommon-characters-of-two-strings.py diff --git a/consecutive-numbers-sum.py b/consecutive-numbers-sum.py new file mode 100644 index 0000000..9f619eb --- /dev/null +++ b/consecutive-numbers-sum.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param n: an integer + @return: how many ways can we write it as a sum of consecutive positive integers + """ + def consecutive_numbers_sum(self, n: int) -> int: + # Write your code here + ''' + There is a math tricky: + 1. K = N + 2. K + K + 1 = N -> 2K = N - 1 + 3. K + K + 1 + K + 2 = N -> 3K = N - 1 - 2 + ''' + r = 0 + i = 1 + while n > 0: + if (n % i) == 0: + r += 1 + n -= i + i += 1 + return r + +# medium: https://www.lintcode.com/problem/1439/ diff --git a/construct_binary_tree_from_inorder_and_postorder_traversal.py b/construct-binary-tree-from-inorder-and-postorder-traversal.py similarity index 100% rename from construct_binary_tree_from_inorder_and_postorder_traversal.py rename to construct-binary-tree-from-inorder-and-postorder-traversal.py diff --git a/construct_binary_tree_from_preorder_and_inorder_traversal.py b/construct-binary-tree-from-preorder-and-inorder-traversal.py similarity index 100% rename from construct_binary_tree_from_preorder_and_inorder_traversal.py rename to construct-binary-tree-from-preorder-and-inorder-traversal.py diff --git a/construct-string-from-binary-tree.py b/construct-string-from-binary-tree.py new file mode 100644 index 0000000..d0fc04c --- /dev/null +++ b/construct-string-from-binary-tree.py @@ -0,0 +1,31 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param t: the root of tree + @return: return a string + """ + def tree2str(self, t): + # write your code here + ret = [] + if t: + ret.append(str(t.val)) + if t.left: + ret.append('(') + ret.extend(self.tree2str(t.left)) + ret.append(')') + if t.right: + if not t.left: + ret.extend(['(', ')']) + ret.append('(') + ret.extend(self.tree2str(t.right)) + ret.append(')') + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/construct-string-from-binary-tree/ diff --git a/construct-the-rectangle.py b/construct-the-rectangle.py new file mode 100644 index 0000000..a40a798 --- /dev/null +++ b/construct-the-rectangle.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param area: web page’s area + @return: the length L and the width W of the web page you designed in sequence + """ + def constructRectangle(self, area): + # Write your code here + ret = [] + diff = area + for w in range(1, area + 1): + if area % w == 0: + l = int(area / w) + if w > l: + break + if (l - w) < diff: + diff = l - w + ret = [l, w] + return ret + +# easy: https://www.lintcode.com/problem/construct-the-rectangle/ diff --git a/container-design-ii.py b/container-design-ii.py new file mode 100644 index 0000000..2253f78 --- /dev/null +++ b/container-design-ii.py @@ -0,0 +1,38 @@ +class MyContainerII: + def __init__(self): + # initialize your data structure here + self.data = [] + self.sum = 0 + + """ + @param element: element: Add element into this container. + @return: nothing + """ + def add(self, element): + # write your code here + for i in range(len(self.data)): + if self.data[i] == element: + return + self.data.append(element) + self.sum += element + + """ + @param element: element: Remove element into this container. + @return: nothing + """ + def remove(self, element): + # write your code here + for i in range(len(self.data)): + if self.data[i] == element: + self.data.pop(i) + self.sum -= element + break + + """ + @return: Sum of integers. + """ + def getSum(self): + # write your code here + return self.sum + +# easy: https://www.lintcode.com/problem/container-design-ii/ diff --git a/container-design.py b/container-design.py new file mode 100644 index 0000000..5b12ffc --- /dev/null +++ b/container-design.py @@ -0,0 +1,22 @@ +class MyContainer: + """ + @param element: Add element into this container. + @return: nothing + """ + def add(self, element): + # write your code here. + self.data.append(element) + self.sum += element + + """ + @return: Sum of integers. + """ + def getSum(self): + # write your code here. + return self.sum + + def __init__(self): + self.data = [] + self.sum = 0 + +# easy: https://www.lintcode.com/problem/container-design/ diff --git a/container_with_most_water.py b/container-with-most-water.py similarity index 100% rename from container_with_most_water.py rename to container-with-most-water.py diff --git a/contains-duplicate-ii.py b/contains-duplicate-ii.py new file mode 100644 index 0000000..1162d1f --- /dev/null +++ b/contains-duplicate-ii.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param nums: the given array + @param k: the given number + @return: whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k + """ + def containsNearbyDuplicate(self, nums, k): + # Write your code here + di = {} + for i in range(len(nums)): + if nums[i] in di: + di[nums[i]].append(i) + else: + di[nums[i]] = [i] + for _, v in di.items(): + if len(v) >= 2: + for i in range(1, len(v)): + if (v[i] - v[i - 1]) <= k: + return True + return False + +# easy: https://www.lintcode.com/problem/contains-duplicate-ii/ diff --git a/contains-duplicate.py b/contains-duplicate.py new file mode 100644 index 0000000..cbd9bcb --- /dev/null +++ b/contains-duplicate.py @@ -0,0 +1,15 @@ +class Solution: + """ + @param nums: the given array + @return: if any value appears at least twice in the array + """ + def containsDuplicate(self, nums): + # Write your code here + nums = sorted(nums) + if len(nums) > 1: + for i in range(1, len(nums)): + if nums[i] == nums[i - 1]: + return True + return False + +# easy: https://www.lintcode.com/problem/contains-duplicate/ diff --git a/continuous_subarray_sum.py b/continuous-subarray-sum.py similarity index 100% rename from continuous_subarray_sum.py rename to continuous-subarray-sum.py diff --git a/convert-a-number-to-hexadecimal.py b/convert-a-number-to-hexadecimal.py new file mode 100644 index 0000000..1b9cf9c --- /dev/null +++ b/convert-a-number-to-hexadecimal.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param num: an integer + @return: convert the integer to hexadecimal + """ + def toHex(self, num): + # Write your code here + ret = [] + digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', \ + 'a', 'b', 'c', 'd', 'e', 'f'] + if num < 0: + num += (1 << 32) + while num > 0: + v = num % 16 + ret.append(digits[v]) + num = int(num / 16) + return ''.join(ret[::-1]) + +# easy: https://www.lintcode.com/problem/convert-a-number-to-hexadecimal/ diff --git a/convert-array-list-to-linked-list.py b/convert-array-list-to-linked-list.py new file mode 100644 index 0000000..238c794 --- /dev/null +++ b/convert-array-list-to-linked-list.py @@ -0,0 +1,28 @@ +""" +Definition of ListNode +class ListNode(object): + def __init__(self, val, next=None): + self.val = val + self.next = next +""" + + +class Solution: + """ + @param: nums: an integer array + @return: the first node of linked list + """ + def toLinkedList(self, nums): + # write your code here + head, tail = None, None + for i in nums: + if not head: + head = ListNode(i) + tail = head + else: + node = ListNode(i) + tail.next = node + tail = node + return head + +# easy: https://www.lintcode.com/problem/489 diff --git a/convert_binary_search_tree_to_doubly_linked_list.py b/convert-binary-search-tree-to-doubly-linked-list.py similarity index 100% rename from convert_binary_search_tree_to_doubly_linked_list.py rename to convert-binary-search-tree-to-doubly-linked-list.py diff --git a/convert-binary-tree-to-linked-lists-by-depth.py b/convert-binary-tree-to-linked-lists-by-depth.py new file mode 100644 index 0000000..379e211 --- /dev/null +++ b/convert-binary-tree-to-linked-lists-by-depth.py @@ -0,0 +1,41 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + this.val = val + this.left, this.right = None, None +Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None +""" +class Solution: + # @param {TreeNode} root the root of binary tree + # @return {ListNode[]} a lists of linked list + def binaryTreeToLists(self, root): + # Write your code here + if not root: + return [] + ret = [] + curr_stack = [root] + next_stack = [] + while curr_stack: + head, tail = None, None + for node in curr_stack: + list_node = ListNode(node.val) + if not head: + head = list_node + tail = head + else: + tail.next = list_node + tail = tail.next + if node.left: + next_stack.append(node.left) + if node.right: + next_stack.append(node.right) + ret.append(head) + curr_stack, next_stack = next_stack, [] + return ret + +# easy: https://www.lintcode.com/problem/convert-binary-tree-to-linked-lists-by-depth/ diff --git a/convert_bst_to_greater_tree.py b/convert-bst-to-greater-tree.py similarity index 100% rename from convert_bst_to_greater_tree.py rename to convert-bst-to-greater-tree.py diff --git a/convert_expression_to_reverse_polish_notation.py b/convert-expression-to-reverse-polish-notation.py similarity index 100% rename from convert_expression_to_reverse_polish_notation.py rename to convert-expression-to-reverse-polish-notation.py diff --git a/convert_sorted_array_to_binary_search_tree_with_minimal_height.py b/convert-sorted-array-to-binary-search-tree-with-minimal-height.py similarity index 100% rename from convert_sorted_array_to_binary_search_tree_with_minimal_height.py rename to convert-sorted-array-to-binary-search-tree-with-minimal-height.py diff --git a/convert-sorted-array-to-binary-search-tree.py b/convert-sorted-array-to-binary-search-tree.py new file mode 100644 index 0000000..9423c7b --- /dev/null +++ b/convert-sorted-array-to-binary-search-tree.py @@ -0,0 +1,27 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param nums: the sorted array + @return: the root of the tree + """ + def convertSortedArraytoBinarySearchTree(self, nums): + # Write your code here. + return self._convert(nums, 0, len(nums) - 1) + + def _convert(self, nums, start, end): + if start > end: + return None + mid = int((start + end) / 2) + root = TreeNode(nums[mid]) + root.left = self._convert(nums, start, mid - 1) + root.right = self._convert(nums, mid + 1, end) + return root + +# easy: https://www.lintcode.com/problem/convert-sorted-array-to-binary-search-tree/ diff --git a/convert_sorted_list_to_balanced_bst.py b/convert-sorted-list-to-balanced-bst.py similarity index 100% rename from convert_sorted_list_to_balanced_bst.py rename to convert-sorted-list-to-balanced-bst.py diff --git a/copy_list_with_random_pointer.py b/copy-list-with-random-pointer.py similarity index 100% rename from copy_list_with_random_pointer.py rename to copy-list-with-random-pointer.py diff --git a/cosine_similarity.py b/cosine-similarity.py similarity index 100% rename from cosine_similarity.py rename to cosine-similarity.py diff --git a/count_1_in_binary.py b/count-1-in-binary.py similarity index 100% rename from count_1_in_binary.py rename to count-1-in-binary.py diff --git a/count_and_say.py b/count-and-say.py similarity index 100% rename from count_and_say.py rename to count-and-say.py diff --git a/count-binary-substrings.py b/count-binary-substrings.py new file mode 100644 index 0000000..3592e4a --- /dev/null +++ b/count-binary-substrings.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param s: a string + @return: the number of substrings + """ + def countBinarySubstrings(self, s): + # Write your code here + ret = 0 + if len(s) > 1: + i, pre = 0, -1 # -1代表还没开始 + while i < len(s): + j = i # 记录i原来的值 + while (i < len(s)) and (s[i] == s[j]): + i += 1 + _len = i - j # 连续0/1的长度 + if pre != -1: # 上一段0/1的长度已记录 + ret += min(pre, _len) + pre = _len # 更新长度 + return ret + +# easy: https://www.lintcode.com/problem/count-binary-substrings/ diff --git a/count-characters.py b/count-characters.py new file mode 100644 index 0000000..e5237f1 --- /dev/null +++ b/count-characters.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param: : a string + @return: Return a hash map + """ + + def countCharacters(self, str): + # write your code here + di = {} + for c in str: + if c not in di: + di[c] = 1 + else: + di[c] += 1 + return di + +# easy: https://www.lintcode.com/problem/557 diff --git a/count-duplicates.py b/count-duplicates.py new file mode 100644 index 0000000..503f675 --- /dev/null +++ b/count-duplicates.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param nums: a integer array + @return: return an integer denoting the number of non-unique(duplicate) values + """ + def countduplicates(self, nums): + # write your code here + r = [] + m = {} + for i in range(len(nums)): + if nums[i] not in m: + m[nums[i]] = [-1, 1] + else: + m[nums[i]][1] += 1 + if m[nums[i]][0] == -1: + m[nums[i]][0] = i + for k, v in m.items(): + if v[1] == 1: + m[k] = len(nums) + else: + m[k] = v[0] + s = sorted(m.items(), key = lambda kv: (kv[1], kv[0])) + for kv in s: + if kv[1] < len(nums): + r.append(kv[0]) + return r + +# easy: https://www.lintcode.com/problem/1794/ diff --git a/count_linked_list_nodes.py b/count-linked-list-nodes.py similarity index 100% rename from count_linked_list_nodes.py rename to count-linked-list-nodes.py diff --git a/count-primes.py b/count-primes.py new file mode 100644 index 0000000..5dd15ac --- /dev/null +++ b/count-primes.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param n: a integer + @return: return a integer + """ + def countPrimes(self, n): + # write your code here + nums = [0] * n + for i in range(2, int(math.sqrt(n)) + 1): + if nums[i] == 0: + j = 2 + while (i * j) < n: + nums[i * j] = 1 + j += 1 + return n - sum(nums) - 2 # 0和1扣除 + +# easy: https://www.lintcode.com/problem/count-primes/ diff --git a/counting-bits.py b/counting-bits.py new file mode 100644 index 0000000..d3a22b0 --- /dev/null +++ b/counting-bits.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param num: a non negative integer number + @return: an array represent the number of 1's in their binary + """ + def countBits(self, num): + # write your code here + # 这实际是个数学题。 + # 1. 如果是偶数,和除2后的数的1一样多。 + # 2. 如果是奇数,就是前一个偶数的1的数量再加1。 + if num <= 0: + return [0] + ret = [0] * (num + 1) + for i in range(1, num + 1): + if (i % 2) != 0: + ret[i] = ret[i - 1] + 1 + else: + ret[i] = ret[int(i / 2)] + return ret + +# medium: https://www.lintcode.com/problem/counting-bits diff --git a/counting-universal-subarrays.py b/counting-universal-subarrays.py new file mode 100644 index 0000000..0bae490 --- /dev/null +++ b/counting-universal-subarrays.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param array: An given array. + @return: Return the number of "universal" subarrays. + """ + def subarrays(self, array): + # write your code here. + ''' + 只能出现[x, x, x, y, y, y]的形式 + 思路:记录每个字符连续出多少次。 + - 如果x出现a次,y出现b次。 + - 可以生成min(a, b)个子序列。 + ''' + ret = 0 + prev = array[0] + count = [1] + for i in range(1, len(array)): + c = array[i] + if c == prev: + count[-1] += 1 + else: + prev = c + count.append(1) + for i in range(1, len(count)): + ret += min(count[i - 1], count[i]) + return ret + +# easy: https://www.lintcode.com/problem/counting-universal-subarrays/ diff --git a/decode-string.py b/decode-string.py new file mode 100644 index 0000000..e8ef5fb --- /dev/null +++ b/decode-string.py @@ -0,0 +1,29 @@ +class Solution: + """ + @param s: an expression includes numbers, letters and brackets + @return: a string + """ + def expressionExpand(self, s): + # write your code here + if not s: + return '' + ret = [] + n = 0 + for c in s: + if (c >= '0') and (c <= '9'): + n = n * 10 + int(c) + elif c == '[': + ret.append(n) + n = 0 + elif c == ']': + _s = '' + v = ret.pop() + while type(v) != int: + _s = v + _s + v = ret.pop() + ret.append(_s * v) + else: + ret.append(c) + return ''.join(ret) + +# medium: https://www.lintcode.com/problem/575 diff --git a/decode_ways.py b/decode-ways.py similarity index 100% rename from decode_ways.py rename to decode-ways.py diff --git a/decrease-to-be-palindrome.py b/decrease-to-be-palindrome.py new file mode 100644 index 0000000..df6286f --- /dev/null +++ b/decrease-to-be-palindrome.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param s: the string s + @return: the number of operations at least + """ + def numberOfOperations(self, s): + # Write your code here + ret = 0 + l, r = 0, len(s) - 1 + while l < r: + if s[l] != s[r]: + ret += abs(ord(s[l]) - ord(s[r])) + l += 1 + r -= 1 + return ret + +# easy: https://www.lintcode.com/problem/1784/ diff --git a/decrypt-the-string.py b/decrypt-the-string.py new file mode 100644 index 0000000..9706df2 --- /dev/null +++ b/decrypt-the-string.py @@ -0,0 +1,43 @@ +class Solution: + """ + @param Message: the string xiao Q sent to xiao A. + @return: the string after decompress + """ + def DecompressString(self, Message): + # + ret = [] + stack = [] + i = 0 + s = '' + while i < len(Message): + c = Message[i] + i += 1 + if (c != '[') and (c != ']') and (c != '|'): + s += c + else: + if s: + stack.append(s) + s = '' + stack.append(c) + if s: + stack.append(s) + for s in stack: + if s != ']': + ret.append(s) + elif s == ']': + r0 = ret.pop() + r1 = ret.pop() + while r1 != '|': + r0 = r1 + r0 + r1 = ret.pop() + r2 = 0 + if r1 == '|': + r2 = int(ret.pop()) + ret.pop() # 弹出'[' + if r2 == 0: + ret.append(r0) + else: + ret.append(r0 * r2) + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/decrypt-the-string/ diff --git a/degree-of-an-array.py b/degree-of-an-array.py new file mode 100644 index 0000000..b64cb6c --- /dev/null +++ b/degree-of-an-array.py @@ -0,0 +1,32 @@ +class Solution: + """ + @param nums: a list of integers + @return: return a integer + """ + def findShortestSubArray(self, nums): + # write your code here + di = {} + for i in range(len(nums)): + if nums[i] not in di: + di[nums[i]] = [1, i, i] + else: + di[nums[i]][0] += 1 + di[nums[i]][2] = i + candidates = [] + for k, v in di.items(): + if not candidates: + candidates.append((k, v)) + else: + if v[0] > candidates[-1][1][0]: + candidates = [(k, v)] + elif v[0] == candidates[-1][1][0]: + candidates.append((k, v)) + # 以上把与度有关的元素找出来,同时记录度的值与起止位置。 + ret = len(nums) + for c in candidates: + l = c[1][2] - c[1][1] + 1 + if l < ret: + ret = l + return ret + +# easy: https://www.lintcode.com/problem/degree-of-an-array/ diff --git a/delete_digits.py b/delete-digits.py similarity index 100% rename from delete_digits.py rename to delete-digits.py diff --git a/delete_node_in_the_middle_of_singly_linked_list.py b/delete-node-in-the-middle-of-singly-linked-list.py similarity index 100% rename from delete_node_in_the_middle_of_singly_linked_list.py rename to delete-node-in-the-middle-of-singly-linked-list.py diff --git a/department-statistics.py b/department-statistics.py new file mode 100644 index 0000000..ac15a63 --- /dev/null +++ b/department-statistics.py @@ -0,0 +1,29 @@ +class Solution: + """ + @param employees: information of the employees + @param friendships: the friendships of employees + @return: return the statistics + """ + def departmentStatistics(self, employees, friendships): + # write your code here. + result = {} + bud = {} + for line in employees: + _id, _, bu = line.split(', ') + bud[_id] = bu + if bu not in result: + result[bu] = [set([]), 0] + result[bu][1] += 1 + for f in friendships: + id1, id2 = f.split(', ') + if bud[id1] != bud[id2]: + result[bud[id1]][0].add(id1) + result[bud[id2]][0].add(id2) + ret = [] + for k, v in result.items(): + r = k + ': ' + r += str(len(v[0])) + ' of ' + str(v[1]) + ret.append(r) + return ret + +# easy: https://www.lintcode.com/problem/department-statistics/ diff --git a/detect-capital.py b/detect-capital.py new file mode 100644 index 0000000..c7d898b --- /dev/null +++ b/detect-capital.py @@ -0,0 +1,14 @@ +class Solution: + """ + @param word: a string + @return: return a boolean + """ + def detectCapitalUse(self, word): + # write your code here + if word[0] == word[0].upper(): # 偷懒了... + return (word[1:] == word[1:].lower()) \ + or (word[1:] == word[1:].upper()) + else: + return word[1:] == word[1:].lower() + +# easy: https://www.lintcode.com/problem/detect-capital/ diff --git a/di-string-match.py b/di-string-match.py new file mode 100644 index 0000000..6fff8b6 --- /dev/null +++ b/di-string-match.py @@ -0,0 +1,28 @@ +class Solution: + def diStringMatch(self, S): + # + ''' + 测试几例子可以发现:I序列从0开始递增,D序列从len(S)开始递减。 + IDID + - I 0 + - D 4 + - I 1 + - D 3 + - 2 + ''' + ret = [] + start, end = 0, len(S) + for c in S: + if c == 'I': + ret.append(start) + start += 1 + else: + ret.append(end) + end -= 1 + if S[-1] == 'I': + ret.append(start) + else: + ret.append(end) + return ret + +# easy: https://www.lintcode.com/problem/di-string-match/ diff --git a/diameter-of-binary-tree.py b/diameter-of-binary-tree.py new file mode 100644 index 0000000..fbdd34f --- /dev/null +++ b/diameter-of-binary-tree.py @@ -0,0 +1,36 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: a root of binary tree + @return: return a integer + """ + def diameterOfBinaryTree(self, root): + # write your code here + # 根节点为root的二叉树的直径 + # max(root-left的直径, \ + # root->right的直径, \ + # root->left的最大深度 + root->right的最大深度) + # 重点:此路径不一定会通过树根 + if not root: + return 0 + left_dia = self.diameterOfBinaryTree(root.left) + right_dia = self.diameterOfBinaryTree(root.right) + left_depth = self.depth(root.left) + right_depth = self.depth(root.right) + return max(left_dia, right_dia, left_depth + right_depth) + + def depth(self, root): + if not root: + return 0 + left_depth = self.depth(root.left) + right_depth = self.depth(root.right) + return max(left_depth, right_depth) + 1 + +# easy: https://www.lintcode.com/problem/diameter-of-binary-tree/ diff --git a/dices_sum.py b/dices-sum.py similarity index 100% rename from dices_sum.py rename to dices-sum.py diff --git a/digit_counts.py b/digit-counts.py similarity index 100% rename from digit_counts.py rename to digit-counts.py diff --git a/digital-distortion.py b/digital-distortion.py new file mode 100644 index 0000000..6a32cfe --- /dev/null +++ b/digital-distortion.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param A: the integer discrible in problem + @return: the integer after distortion + """ + def Distortion(self, A): + # + ret = [] + i, j = 0, len(A) - 1 + while i < j: + ret.append(A[j]) + ret.append(A[i]) + j -= 1 + i += 1 + if i == j: + ret.append(A[i]) + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/digital-distortion/ diff --git a/digital-pairing.py b/digital-pairing.py new file mode 100644 index 0000000..8aa8072 --- /dev/null +++ b/digital-pairing.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param nums: the integers to be paired. + @return: return the minimum difference of the maximum value and the minimum value after pairing. + """ + def digitalPairing(self, nums): + # write your code here. + nums.sort() + l = len(nums) + for i in range(int(l / 2)): + nums[i] += nums[- 1] + nums.pop() + nums.sort() + return nums[-1] - nums[0] + +# easy: https://www.lintcode.com/problem/302/ diff --git a/digital-problem.py b/digital-problem.py new file mode 100644 index 0000000..889313b --- /dev/null +++ b/digital-problem.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param n: the number n + @return: the times n convert to 1 + """ + def digitConvert(self, n): + # Write your code here + i = 0 + while n != 1: + if (n % 2) == 0: + n = n / 2 + else: + n = n * 3 + 1 + i += 1 + return i + +# easy: http://lintcode.com/zh-cn/problem/digital-problem/ diff --git a/distinct_subsequences.py b/distinct-subsequences.py similarity index 100% rename from distinct_subsequences.py rename to distinct-subsequences.py diff --git a/distinguish-username.py b/distinguish-username.py new file mode 100644 index 0000000..20f66c6 --- /dev/null +++ b/distinguish-username.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param names: a string array + @return: the string array + """ + def DistinguishUsername(self, names): + # Write your code here + r = [] + m = {} + for n in names: + if n not in m: + m[n] = [1, 0] + else: + m[n][0] += 1 + for n in names: + if m[n][0] == 1: + r.append(n) + else: + if m[n][1] == 0: + r.append(n) + else: + r.append(n + str(m[n][1])) + m[n][1] += 1 + return r + +# easy: https://www.lintcode.com/problem/1789/ diff --git a/distribute-candies.py b/distribute-candies.py new file mode 100644 index 0000000..dd76bbc --- /dev/null +++ b/distribute-candies.py @@ -0,0 +1,10 @@ +class Solution: + """ + @param candies: a list of integers + @return: return a integer + """ + def distributeCandies(self, candies): + # write your code here + return min(len(set(candies)), int(len(candies) / 2)) + +# easy: https://www.lintcode.com/problem/distribute-candies/ diff --git a/divide_two_integers.py b/divide-two-integers.py similarity index 100% rename from divide_two_integers.py rename to divide-two-integers.py diff --git a/dot-product.py b/dot-product.py new file mode 100644 index 0000000..9fa32b1 --- /dev/null +++ b/dot-product.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param A: an array + @param B: an array + @return: dot product of two array + """ + def dotProduct(self, A, B): + # Write your code here + if (len(A) != len(B)) or (len(A) == 0): + return -1 + r = 0 + for i in range(len(A)): + r += A[i] * B[i] + return r + +# easy: https://www.lintcode.com/problem/1480/ diff --git a/double-change.py b/double-change.py new file mode 100644 index 0000000..306c89e --- /dev/null +++ b/double-change.py @@ -0,0 +1,27 @@ +class Solution: + def __init__(self): + self.cache = {} + + """ + @param A: an Integer + @param B: an Integer + @param p: an Integer + @param q: an Integer + @return: Return the minimum time + """ + def DoubleChange(self, A, B, p, q): + # write your code here + # 递归可以解决问,但是会超时。 + if A >= B: + return 0 + if q == 1: + return B - A + else: + cnt = 1 + diff = B - A + while p < diff: + p *= q + cnt += 1 + return cnt + +# easy: https://www.lintcode.com/problem/double-change/ diff --git a/double-factorial.py b/double-factorial.py new file mode 100644 index 0000000..8fc35eb --- /dev/null +++ b/double-factorial.py @@ -0,0 +1,14 @@ +class Solution: + """ + @param n: the given number + @return: the double factorial of the number + """ + def doubleFactorial(self, n): + # Write your code here + r = 1 + while n > 0: + r *= n + n -= 2 + return r + +# easy: https://www.lintcode.com/problem/771/ diff --git a/drop-eggs.py b/drop-eggs.py new file mode 100644 index 0000000..bae493c --- /dev/null +++ b/drop-eggs.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param n: An integer + @return: The sum of a and b + """ + def dropEggs(self, n): + # write your code here + r = 0 + while True: + s = (1 + r) * r / 2 + if s >= n: + break + r += 1 + return r + +# easy: https://www.lintcode.com/problem/254/ diff --git a/edit_distance.py b/edit-distance.py similarity index 100% rename from edit_distance.py rename to edit-distance.py diff --git a/employee-importance.py b/employee-importance.py new file mode 100644 index 0000000..3d2ddde --- /dev/null +++ b/employee-importance.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param imput: + @param id: + @return: the total importance value + """ + def getImportance(self, imput, _id): + # Write your code here. + imput = eval(imput) # 字符串转数组... + di = {} + for i in imput: + print(i) + di[i[0]] = (i[1], i[2]) + return self._search(di, _id) + + def _search(self, di, _id): + ret = di[_id][0] + for i in di[_id][1]: + ret += self._search(di, i) + return ret + +# easy: https://www.lintcode.com/problem/employee-importance/ diff --git a/encode-and-decode-tinyurl.py b/encode-and-decode-tinyurl.py new file mode 100644 index 0000000..f85c595 --- /dev/null +++ b/encode-and-decode-tinyurl.py @@ -0,0 +1,42 @@ +class Solution: + def __init__(self): + self.i = 0 + self.dict = {} + self.chars = [] + digits = '0123456789' + chars = 'abcdefghijklmnopqrstuvwxyz' + for c in digits: + self.chars.append(c) + for c in chars: + self.chars.append(c) + for c in chars.upper(): + self.chars.append(c) + def encode(self, longUrl): + # Encodes a URL to a shortened URL. + hval = self.hash(longUrl) + llen = len(self.chars) + code = [] + while (hval != 0): + code.append(self.chars[hval % llen]) + hval = int(hval / llen) + code = ''.join(code) + self.dict[code] = longUrl + return 'http://tinyurl.com/' + code + + def decode(self, shortUrl): + # Decodes a shortened URL to its original URL. + code = shortUrl.split('/')[-1] + return self.dict[code] + + def hash(self, s): + ret = 0 + for c in s: + i = ord(c) + ret = ret * 33 + i + return ret % 18446744073709551616 # 2 ** 64 + +# Your Codec object will be instantiated and called as such: +# Codec codec = new Codec(); +# codec.decode(codec.encode(url)); + +# medium: https://www.lintcode.com/problem/encode-and-decode-tinyurl/ diff --git a/english-software.py b/english-software.py new file mode 100644 index 0000000..615d414 --- /dev/null +++ b/english-software.py @@ -0,0 +1,34 @@ +class Solution: + """ + @param score: Each student's grades + @param ask: A series of inquiries + @return: Find the percentage of each question asked + """ + def englishSoftware(self, score, ask): + # write your code here + ret = [] + di = {} + for i in range(len(score)): + di[i + 1] = score[i] + score.sort() + for i in ask: + bar = di[i] + i, j = 0, len(score) - 1 + m = 0 + while i <= j: + mid = int((i + j) / 2) + if score[mid] == bar: + k = mid + while k < len(score): + if score[k] != bar: + break + k += 1 + m = k - 1 + break + elif score[mid] < bar: + i = mid + 1 + else: + j = mid - 1 + ret.append(int(m * 100 / len(score))) + return ret +# easy: https://www.lintcode.com/problem/super-lollipop/description diff --git a/evaluate_reverse_polish_notation.py b/evaluate-reverse-polish-notation.py similarity index 100% rename from evaluate_reverse_polish_notation.py rename to evaluate-reverse-polish-notation.py diff --git a/excel-sheet-column-number.py b/excel-sheet-column-number.py new file mode 100644 index 0000000..857428c --- /dev/null +++ b/excel-sheet-column-number.py @@ -0,0 +1,13 @@ +class Solution: + """ + @param s: a string + @return: return a integer + """ + def titleToNumber(self, s): + # write your code here + ret = 0 + for c in s: + ret = ret * 26 + (ord(c) - ord('A') + 1) + return ret + +# easy: https://www.lintcode.com/problem/excel-sheet-column-number/ diff --git a/excel-sheet-column-title.py b/excel-sheet-column-title.py new file mode 100644 index 0000000..83f52f9 --- /dev/null +++ b/excel-sheet-column-title.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param n: a integer + @return: return a string + """ + def convertToTitle(self, n): + # write your code here + ret = [] + while n != 0: + i = n % 26 + if i == 0: + i = 26 + n = int((n - i) / 26) + ret.append(chr(ord('A') + i - 1)) + return ''.join(ret[::-1]) + +# easy: https://www.lintcode.com/problem/excel-sheet-column-title/ diff --git a/expression_evaluation.py b/expression-evaluation.py similarity index 100% rename from expression_evaluation.py rename to expression-evaluation.py diff --git a/external-sorting-practising.py b/external-sorting-practising.py new file mode 100644 index 0000000..0d99174 --- /dev/null +++ b/external-sorting-practising.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param files: some files with integers need to be sorted + @param result: a file for writing numbers + @param n: numbers of files + @return: nothing + """ + def sortOnDisk(self, files, result): + # write your code here + # Lazy mode! + r = [] + for f in files: + while not f.is_empty(): + r.append(f.read()) + r.sort() + for i in r: + result.write(i) + +# easy: https://www.lintcode.com/problem/351 diff --git a/factorial-trailing-zeroes.py b/factorial-trailing-zeroes.py new file mode 100644 index 0000000..eba771a --- /dev/null +++ b/factorial-trailing-zeroes.py @@ -0,0 +1,15 @@ +class Solution: + """ + @param n: a integer + @return: return a integer + """ + def trailingZeroes(self, n): + # write your code here + ret = 0 + while n > 0: + # 技巧,2 * 5 = 10,而且2总是比5多。 + n = int(n / 5) + ret += n + return ret + +# easy: https://www.lintcode.com/problem/factorial-trailing-zeroes/ diff --git a/fair-candy-swap.py b/fair-candy-swap.py new file mode 100644 index 0000000..8cd73b7 --- /dev/null +++ b/fair-candy-swap.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param A: an array + @param B: an array + @return: an integer array + """ + def fairCandySwap(self, A, B): + # Write your code here. + # 题目的关键是只需要交换一个,且答案一定存在。 + sum_a, sum_b = sum(A), sum(B) + target = int((sum_a + sum_b) / 2) # 最终手里的数量 + diff = int((sum_a - sum_b) / 2) + for a in A: + for b in B: + if a - b == diff: + return [a, b] + +# easy: https://www.lintcode.com/problem/fair-candy-swap/ diff --git a/fair-indexes.py b/fair-indexes.py new file mode 100644 index 0000000..5b51d69 --- /dev/null +++ b/fair-indexes.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param A: an array of integers + @param B: an array of integers + @return: return a integer indicating the number of fair indexes. + """ + def CountIndexes(self, A, B): + # Write your code here. + r = 0 + l = len(A) + sa, sb = sum(A), sum(B) + if sa != sb: + return 0 + t = int(sa / 2) + ha, hb = 0, 0 + for i in range(l - 1): + ha += A[i] + hb += B[i] + if (ha == hb) and (ha == t): + r += 1 + return r + +# medium: https://www.lintcode.com/problem/1882/ diff --git a/fast_power.py b/fast-power.py similarity index 100% rename from fast_power.py rename to fast-power.py diff --git a/feature-extraction.py b/feature-extraction.py new file mode 100644 index 0000000..a8e95ae --- /dev/null +++ b/feature-extraction.py @@ -0,0 +1,36 @@ +class Solution: + """ + @param frames: A series of frames + @return: Find the longest feature movement + """ + def FeatureExtraction(self, frames): + # write your code here + r = 0 + di = {} + for i in range(len(frames)): + f = frames[i] + n = f[0] + for j in range(n): + v = str(f[2 * j + 1]) + '-' + str(f[2 * j + 2]) + if v not in di: + di[v] = [i] + else: + if i != di[v][-1]: + di[v].append(i) + for v in di.values(): + l = 0 + prev = -1 + for i in v: + if prev == -1: + l = 1 + else: + if (prev + 1) == i: + l += 1 + else: + l = 1 + prev = i + if l > r: + r = l + return r + +# easy: https://www.lintcode.com/problem/1135/ diff --git a/fetch-supplies-ii.py b/fetch-supplies-ii.py new file mode 100644 index 0000000..259a06d --- /dev/null +++ b/fetch-supplies-ii.py @@ -0,0 +1,37 @@ +import math +import sys + +class Solution: + """ + @param barracks: the position of barracks + @return: the minimum of the maximum of the distance + """ + def fetchSuppliesII(self, barracks): + # write your code here + ret, mret = 0, 0 + l, r = sys.maxsize, -1 + for b in barracks: + if b[0] > r: + r = b[0] + if b[0] < l: + l = b[0] + for i in range(100): + mid = l + (r - l) / 2; + mmid = mid + (r - mid) / 2; + ret = self.maxDist(mid, barracks) + mret = self.maxDist(mmid, barracks) + if(ret > mret): + l = mid; + else: + r = mmid; + return math.sqrt(ret) + + def maxDist(self, x, barracks): + r = 0 + for b in barracks: + d = (x - b[0]) * (x - b[0]) + b[1] * b[1] + if d > r: + r = d + return r + +# medium: https://www.lintcode.com/problem/1899/ diff --git a/fibonacci-easy.py b/fibonacci-easy.py new file mode 100644 index 0000000..2fc669f --- /dev/null +++ b/fibonacci-easy.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param n: an integer + @return: an ineger f(n) + """ + def fibonacci(self, n): + # write your code here + self.cache = [0, 1] + if n < 2: + return self.cache[n] + for i in range(2, n): + tmp = self.cache[1] + self.cache[1] += self.cache[0] + self.cache[0] = tmp + return self.cache[1] + +# easy: https://www.lintcode.com/problem/fibonacci-easy/ diff --git a/final-discounted-price.py b/final-discounted-price.py new file mode 100644 index 0000000..b50df11 --- /dev/null +++ b/final-discounted-price.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param prices: a list of integer + @return: return the actual prices + """ + def FinalDiscountedPrice(self, prices): + # write your code here + r = [p for p in prices] + stack = [] + for i in range(len(prices)): + while stack and (prices[stack[-1]] >= prices[i]): + idx = stack.pop() + r[idx] = prices[idx] - prices[i] + stack.append(i) + return r + +# medium: https://www.lintcode.com/problem/1852/ diff --git a/find-a-classmate-with-the-same-name.sql b/find-a-classmate-with-the-same-name.sql new file mode 100644 index 0000000..bbd913a --- /dev/null +++ b/find-a-classmate-with-the-same-name.sql @@ -0,0 +1,3 @@ +select name from students group by name having count(name) > 1 + +-- easy: https://www.lintcode.com/problem/find-a-classmate-with-the-same-name/ diff --git a/find-all-anagrams-in-a-string.py b/find-all-anagrams-in-a-string.py new file mode 100644 index 0000000..a38db48 --- /dev/null +++ b/find-all-anagrams-in-a-string.py @@ -0,0 +1,42 @@ +def build_di(s, start, end): + di = {} + for i in range(start, end): + update_di(di, s[i], 'add') + return di + +def update_di(di, key, op='remove'): + if op == 'remove': + di[key] -= 1 + if di[key] == 0: + del di[key] + else: + if key in di: + di[key] += 1 + else: + di[key] = 1 + +class Solution: + """ + @param s: a string + @param p: a string + @return: a list of index + """ + def findAnagrams(self, s, p): + # write your code here + ret = [] + len_p = len(p) + if len(s) < len_p: + return ret + di_p = build_di(p, 0, len_p) + di_s = build_di(s, 0, len_p) + if di_s == di_p: + ret.append(0) + for i in range(1, len(s) - len_p + 1): + update_di(di_s, s[i - 1], 'remove') + update_di(di_s, s[i + len_p - 1], 'add') + if s[i] in di_p: + if di_p == di_s: + ret.append(i) + return ret + +# easy: https://www.lintcode.com/problem/find-all-anagrams-in-a-string/ diff --git a/find-all-numbers-disappeared-in-an-array.py b/find-all-numbers-disappeared-in-an-array.py new file mode 100644 index 0000000..aa123d7 --- /dev/null +++ b/find-all-numbers-disappeared-in-an-array.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param nums: a list of integers + @return: return a list of integers + """ + def findDisappearedNumbers(self, nums): + # write your code here + ret = [] + i = 0 + while i < len(nums): + if nums[i] != nums[nums[i] - 1]: # 当前元素的值与索引不匹配 + tmp = nums[nums[i] - 1] # 保留原来位置的值 + nums[nums[i] - 1] = nums[i] + nums[i] = tmp + i -= 1 # 换过来的元素再处理 + i += 1 + for i in range(len(nums)): + if nums[i] != (i + 1): + ret.append(i + 1) + return ret + +# easy: https://www.lintcode.com/problem/find-all-numbers-disappeared-in-an-array/ diff --git a/find-anagram-mappings.py b/find-anagram-mappings.py new file mode 100644 index 0000000..ca58eba --- /dev/null +++ b/find-anagram-mappings.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param A: lists A + @param B: lists B + @return: the index mapping + """ + def anagramMappings(self, A, B): + # Write your code here + ret = [] + di = {} + for i in range(len(B)): + di[B[i]] = i + for i in A: + ret.append(di[i]) + return ret + +# easy: https://www.lintcode.com/problem/find-anagram-mappings/ diff --git a/find_elements_in_matrix.py b/find-elements-in-matrix.py similarity index 100% rename from find_elements_in_matrix.py rename to find-elements-in-matrix.py diff --git a/find-friend-circle-number.py b/find-friend-circle-number.py new file mode 100644 index 0000000..8f389a6 --- /dev/null +++ b/find-friend-circle-number.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param M: a matrix of integer + @return: return an Integer + """ + def findCircleNum(self, M): + # write your code here + r = 0 + n = len(M) + visited = [0] * n + for i in range(n): + if visited[i] == 0: + r += 1 + self.dfs(M, i, visited) + return r + + def dfs(self, M, i, visited): # the ith student + for j in range(len(M)): + if (M[i][j] == 1) and (visited[j] == 0): + visited[j] = 1 + self.dfs(M, j, visited) + +# medium: https://www.lintcode.com/problem/1857 diff --git a/find-google.py b/find-google.py new file mode 100644 index 0000000..aa995c5 --- /dev/null +++ b/find-google.py @@ -0,0 +1,39 @@ +class Solution: + """ + @param S: The c++ file + @return: return if there is "Google" in commet line + """ + def FindGoogle(self, S): + # Write your code here. + lc = False # // 形式的注释 + mlc = False # /* ... */ 形式的注释 + google = '' + for s in S: + prev = None + for c in s: + if (prev == '/') and (c == '/') and (not mlc): + lc = True + elif (prev == '/') and (c == '*') and (not mlc) and (not lc): + mlc = True + elif (prev == '*') and (c == '/') and mlc: + mlc = False + elif lc or mlc: + if c == 'G': + google = 'G' + elif (c == 'o') and (google == 'G'): + google = 'Go' + elif (c == 'o') and (google == 'Go'): + google = 'Goo' + elif (c == 'g') and (google == 'Goo'): + google = 'Goog' + elif (c == 'l') and (google == 'Goog'): + google = 'Googl' + elif (c == 'e') and (google == 'Googl'): + return True + else: + google = '' + prev = c + lc = False + return False + +# easy: https://www.lintcode.com/problem/find-google/ diff --git a/find-letter.py b/find-letter.py new file mode 100644 index 0000000..0b3b83a --- /dev/null +++ b/find-letter.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param str: the str + @return: the letter + """ + def findLetter(self, _str): + # Write your code here. + di = {} + for c in _str: + u_c = c.upper() + if u_c not in di: + di[u_c] = 0 + if c == u_c: + di[u_c] |= 2 + else: + di[u_c] |= 1 + ret = None + for k, v in di.items(): + if v == 3: + if not ret: + ret = k + else: + if k > ret: + ret = k + return ret if ret else '~' + +# easy: https://www.lintcode.com/problem/find-letter/ diff --git a/find-minimum-in-rotated-sorted-array-ii.py b/find-minimum-in-rotated-sorted-array-ii.py new file mode 100644 index 0000000..65781e0 --- /dev/null +++ b/find-minimum-in-rotated-sorted-array-ii.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param nums: a rotated sorted array + @return: the minimum number in the array + """ + def findMin(self, nums): + # write your code here + start, end = 0, len(nums) - 1 + while (start < end) and (nums[start] >= nums[end]): # 结果肯定在start和end中间某个位置 + mid = (start + end) // 2 + if nums[start] < nums[mid]: # mid在前半区间 + start = mid + 1 + elif nums[start] > nums[mid]: # mid在后半区间 + end = mid # 不用减一,有可能就是这个位置。 + else: + start += 1 # 重复元素的特殊情况 + return nums[start] + +# medium: https://www.lintcode.com/problem/find-minimum-in-rotated-sorted-array-ii/ diff --git a/find_minimum_in_rotated_sorted_array.py b/find-minimum-in-rotated-sorted-array.py similarity index 100% rename from find_minimum_in_rotated_sorted_array.py rename to find-minimum-in-rotated-sorted-array.py diff --git a/find_peak_element.py b/find-peak-element.py similarity index 100% rename from find_peak_element.py rename to find-peak-element.py diff --git a/find-pivot-index.py b/find-pivot-index.py new file mode 100644 index 0000000..790f98d --- /dev/null +++ b/find-pivot-index.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param nums: an array + @return: the "pivot" index of this array + """ + def pivotIndex(self, nums): + # Write your code here + nums_sum = sum(nums) + left_sum, right_sum = 0, 0 + for i in range(len(nums)): + if i == 0: + left_sum = 0 + else: + left_sum += nums[i - 1] + right_sum = nums_sum - nums[i] - left_sum + if left_sum == right_sum: + return i + return -1 + +# easy: https://www.lintcode.com/problem/find-pivot-index/ diff --git a/find-smallest-letter-greater-than-target.py b/find-smallest-letter-greater-than-target.py new file mode 100644 index 0000000..af53620 --- /dev/null +++ b/find-smallest-letter-greater-than-target.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param letters: a list of sorted characters + @param target: a target letter + @return: the smallest element in the list that is larger than the given target + """ + def nextGreatestLetter(self, letters, target): + # Write your code here + ret = None + # diff = 100 + s = set(letters) + while True: + if target == 'z': + target = 'a' + else: + target = chr(ord(target) + 1) + if target in s: + return target + +# easy: https://www.lintcode.com/problem/find-smallest-letter-greater-than-target/ diff --git a/find-the-difference.py b/find-the-difference.py new file mode 100644 index 0000000..9e54e8b --- /dev/null +++ b/find-the-difference.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param s: a string + @param t: a string + @return: the letter that was added in t + """ + def findTheDifference(self, s, t): + # Write your code here + di = {} + for c in t: + if c not in di: + di[c] = 1 + else: + di[c] += 1 + for c in s: + di[c] -= 1 + for k, v in di.items(): + if v != 0: + return k + +# easy: https://www.lintcode.com/problem/find-the-difference/ diff --git a/find-the-largest-divisor.py b/find-the-largest-divisor.py new file mode 100644 index 0000000..521710d --- /dev/null +++ b/find-the-largest-divisor.py @@ -0,0 +1,25 @@ +class Solution: + """ + @param A: the array. + @param k: the integer. + @return: the divisor satisfy the requirement. + """ + def FindDivisor(self, A, k): + # + start, end = 1, max(A) + mid = -1 + while start < (end - 1): + mid = int((start + end) / 2) + if self._test(A, mid, k): + start = mid + else: + end = mid + return end if self._test(A, end, k) else start + + def _test(self, A, i, k): + s = 0 + for v in A: + s += math.ceil(v / i) + return s>= k + +# medium: https://www.lintcode.com/problem/find-the-largest-divisor/ diff --git a/find_the_missing_number_ii.py b/find-the-missing-number-ii.py similarity index 100% rename from find_the_missing_number_ii.py rename to find-the-missing-number-ii.py diff --git a/find_the_missing_number.py b/find-the-missing-number.py similarity index 100% rename from find_the_missing_number.py rename to find-the-missing-number.py diff --git a/find-the-number.py b/find-the-number.py new file mode 100644 index 0000000..f03c692 --- /dev/null +++ b/find-the-number.py @@ -0,0 +1,14 @@ +class Solution: + """ + @param nums: a integer array + @param k: a integer + @return: return true or false denoting if the element is present in the array or not + """ + def findnNumber(self, nums, k): + # write your code here + for i in nums: + if k == i: + return True + return False + +# easy: https://www.lintcode.com/problem/find-the-number/ diff --git a/find-the-numbers.py b/find-the-numbers.py new file mode 100644 index 0000000..84fe21c --- /dev/null +++ b/find-the-numbers.py @@ -0,0 +1,25 @@ +class Solution: + """ + @param n: the integer + @return: the numbers that larger and smaller than `n` + """ + def getNumbers(self, n): + # Write your code here + if n < 0: + return [] + if n == 0: + return [1] + n0, n1 = 0, 1 + r = [-1, -1] + while True: + if n0 < n: + r[0] = n0 + if n1 > n: + r[1] = n1 + break + _n = n0 + n1 + n0 = n1 + n1 = _n + return r + +# medium: https://www.lintcode.com/problem/1610/ diff --git a/find-the-rank.py b/find-the-rank.py new file mode 100644 index 0000000..aa6a2e8 --- /dev/null +++ b/find-the-rank.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param scores: two dimensional array + @param K: a integer + @return: return a integer + """ + def FindTheRank(self, scores, K): + # write your code here + m = {} # 偷懒,直接排序然后查表! + total = [sum(scores[i]) for i in range(len(scores))] + for i in range(len(total)): + if total[i] not in m: + m[total[i]] = [i] + else: + m[total[i]].append(i) + total.sort(reverse=True) + return m[total[K - 1]][0] + +# easy: https://www.lintcode.com/problem/1804/ diff --git a/find-the-smallest-divisor-given-a-threshold.py b/find-the-smallest-divisor-given-a-threshold.py new file mode 100644 index 0000000..4eecfac --- /dev/null +++ b/find-the-smallest-divisor-given-a-threshold.py @@ -0,0 +1,31 @@ +import math + +class Solution: + """ + @param nums: an array of integers + @param threshold: an integer + @return: return the smallest divisor + """ + def smallestDivisor(self, nums, threshold): + # write your code here + ret = 0 + min_value = sum(nums) + l, r = 1, max(nums) + while l <= r: + mid = int((l + r) / 2) + if self.check(nums, mid, threshold): + r = mid - 1 + ret = mid + else: + l = mid + 1 + return ret + + def check(self, nums, div, threshold): + s = 0 + for i in nums: + s += math.ceil(i / div) + if s > threshold: + return False + return True + +# medium: https://www.lintcode.com/problem/1816/ diff --git a/find-words.py b/find-words.py new file mode 100644 index 0000000..6062fe0 --- /dev/null +++ b/find-words.py @@ -0,0 +1,38 @@ +class Solution: + """ + @param str: the string + @param dict: the dictionary + @return: return words which are subsequences of the string + """ + def findWords(self, _str, _dict): + # Write your code here. + # same as #23 https://www.lintcode.com/problem/substring-in-dict/ + ret = [] + di = {} + for i in range(len(_str)): + if _str[i] in di: + di[_str[i]].append(i) + else: + di[_str[i]] = [i] + for word in _dict: + min_pos = -1 + match = True + for c in word: + if c not in di: + match = False + break + i = 0 + while i < len(di[c]): + if di[c][i] > min_pos: + min_pos = di[c][i] + break + else: + i += 1 + if i == len(di[c]): # 没有找到一个位置符合递增条件 + match = False + break + if match: + ret.append(word) + return ret + +# medium: https://www.lintcode.com/problem/find-words/ diff --git a/first_bad_version.py b/first-bad-version.py similarity index 100% rename from first_bad_version.py rename to first-bad-version.py diff --git a/first_missing_positive.py b/first-missing-positive.py similarity index 100% rename from first_missing_positive.py rename to first-missing-positive.py diff --git a/first-missing-prime-number.py b/first-missing-prime-number.py new file mode 100644 index 0000000..7ef4f25 --- /dev/null +++ b/first-missing-prime-number.py @@ -0,0 +1,37 @@ +class Solution: + """ + @param nums: an array of integer + @return: the first missing prime number + """ + def firstMissingPrime(self, nums): + # write your code here + ''' + 先排序,然后分3种情况: + 1. 缺少第1个素数2 + 2. 缺少的数在当中 + 3. 缺少的数正好是当前最大素数的下一个 + ''' + if 2 not in nums: + return 2 + nums.sort() + for i in range(3, nums[-1] + 1): + not_prime = False + for k in nums: # 用除法验证是否素数,虽然2重循环,但是有k <= i的限制,效率问题不大。 + if (k <= i) and (i % k == 0): + not_prime = True + break + if not not_prime: + return i + i = nums[-1] + 2 # 没找到,找下一个最大素数,循环知道满足条件。 + while True: + not_prime = False + for k in nums: + if (k <= i) and (i % k == 0): + not_prime = True + break + if not not_prime: + return i + else: + i += 2 + +# medium: https://www.lintcode.com/problem/first-missing-prime-number diff --git a/first_position_of_target.py b/first-position-of-target.py similarity index 100% rename from first_position_of_target.py rename to first-position-of-target.py diff --git a/first_position_unique_character.py b/first-position-unique-character.py similarity index 100% rename from first_position_unique_character.py rename to first-position-unique-character.py diff --git a/first-unique-character-in-a-string.py b/first-unique-character-in-a-string.py new file mode 100644 index 0000000..d70a17e --- /dev/null +++ b/first-unique-character-in-a-string.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param str: str: the given string + @return: char: the first unique character in a given string + """ + def firstUniqChar(self, str): + # Write your code here + # a ~ z = 65 ~ 90 + # A ~ Z = 97 ~ 122 + # 122 - 65 + 1 = 58 + data = [0] * 58 # 计数统计 + for c in str: + data[ord(c) - 65] += 1 + for c in str: # 看首先出现次数为1的就返回 + if data[ord(c) - 65] == 1: + return c + +# easy: https://www.lintcode.com/problem/first-unique-character-in-a-string diff --git a/first-unique-number-in-data-stream.py b/first-unique-number-in-data-stream.py new file mode 100644 index 0000000..838dbf6 --- /dev/null +++ b/first-unique-number-in-data-stream.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param nums: a continuous stream of numbers + @param number: a number + @return: returns the first unique number + """ + def firstUniqueNumber(self, nums, number): + # Write your code here + # 难度在于第一个 + di = {} + pos = 0 + for i in range(0, len(nums)): + if nums[i] == number: + min_pos = len(nums) + items = sorted(di.items(), key = lambda item: item[1]) # 根据位置排序 + if items and (items[0][1] < len(nums)): + return items[0][0] + else: + return number + else: + if nums[i] not in di: # 来,先看这里的注释。 + di[nums[i]] = pos # 记录第一次出现的位置 + pos += 1 + else: + di[nums[i]] = len(nums) # 重复了就把位置挪到最后 + return -1 + +# medium: https://www.lintcode.com/problem/first-unique-number-in-data-stream diff --git a/fizz_buzz.py b/fizz-buzz.py similarity index 100% rename from fizz_buzz.py rename to fizz-buzz.py diff --git a/flatten-2d-vector.py b/flatten-2d-vector.py new file mode 100644 index 0000000..bceef50 --- /dev/null +++ b/flatten-2d-vector.py @@ -0,0 +1,31 @@ +class Vector2D(object): + + # @param vec2d {List[List[int]]} + def __init__(self, vec2d): + # Initialize your data structure here + self.vec2d = vec2d + self.row, self.col = 0, 0 + while (self.row < len(self.vec2d)) \ + and (self.col >= len(self.vec2d[self.row])): + self.row += 1 + self.col = 0 # 处理空数组特殊情况 + + + # @return {int} a next element + def next(self): + # Write your code here + i = self.vec2d[self.row][self.col] + self.col += 1 + while (self.row < len(self.vec2d)) \ + and (self.col >= len(self.vec2d[self.row])): + self.row += 1 + self.col = 0 # 再次处理空数组特殊情况 + return i + + # @return {boolean} true if it has next element + # or false + def hasNext(self): + # Write your code here + return (self.row < len(self.vec2d)) and (self.col < len(self.vec2d[self.row])) + +# medium: https://www.lintcode.com/problem/flatten-2d-vector/ diff --git a/flatten_binary_tree_to_linked_list.py b/flatten-binary-tree-to-linked-list.py similarity index 100% rename from flatten_binary_tree_to_linked_list.py rename to flatten-binary-tree-to-linked-list.py diff --git a/flatten_list.py b/flatten-list.py similarity index 100% rename from flatten_list.py rename to flatten-list.py diff --git a/flatten-nested-list-iterator.py b/flatten-nested-list-iterator.py new file mode 100644 index 0000000..c1df739 --- /dev/null +++ b/flatten-nested-list-iterator.py @@ -0,0 +1,53 @@ +""" +This is the interface that allows for creating nested lists. +You should not implement it, or speculate about its implementation + +class NestedInteger(object): + def isInteger(self): + # @return {boolean} True if this NestedInteger holds a single integer, + # rather than a nested list. + + def getInteger(self): + # @return {int} the single integer that this NestedInteger holds, + # if it holds a single integer + # Return None if this NestedInteger holds a nested list + + def getList(self): + # @return {NestedInteger[]} the nested list that this NestedInteger holds, + # if it holds a nested list + # Return None if this NestedInteger holds a single integer +""" + +class NestedIterator(object): + + def __init__(self, nestedList): + # Initialize your data structure here. + self.stack = [] + self.pushToStack(nestedList) + + # @return {int} the next element in the iteration + def next(self): + # Write your code here + return self.stack.pop().getInteger() + + # @return {boolean} true if the iteration has more element or false + def hasNext(self): + # Write your code here + while self.stack: + tmp = self.stack[-1] + if tmp.isInteger(): + return True + else: + tmp = self.stack.pop() + self.pushToStack(tmp.getList()) + return False + + def pushToStack(self, nestedList): + for i in range(len(nestedList) - 1, -1, -1): + self.stack.append(nestedList[i]) + +# Your NestedIterator object will be instantiated and called as such: +# i, v = NestedIterator(nestedList), [] +# while i.hasNext(): v.append(i.next()) + +# medium: https://www.lintcode.com/problem/flatten-nested-list-iterator/ diff --git a/flip_bits.py b/flip-bits.py similarity index 100% rename from flip_bits.py rename to flip-bits.py diff --git a/flip-game.py b/flip-game.py new file mode 100644 index 0000000..315ad0b --- /dev/null +++ b/flip-game.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param s: the given string + @return: all the possible states of the string after one valid move + """ + def generatePossibleNextMoves(self, s): + # write your code here + ret = [] + for i in range(len(s) - 1): + flipped = [] + if (s[i] == '+') and (s[i + 1] == '+'): + if i > 0: + flipped.append(s[:i]) + flipped.append('--') + if (i + 2) < len(s): + flipped.append(s[i + 2:]) + if flipped: + ret.append(''.join(flipped)) + return ret + +# easy: https://www.lintcode.com/problem/flip-game/ diff --git a/flood-fill.py b/flood-fill.py new file mode 100644 index 0000000..f8ca8b9 --- /dev/null +++ b/flood-fill.py @@ -0,0 +1,38 @@ +class Solution: + """ + @param image: a 2-D array + @param sr: an integer + @param sc: an integer + @param newColor: an integer + @return: the modified image + """ + def floodFill(self, image, sr, sc, newColor): + # Write your code here + self.old_olor = image[sr][sc] + self._floodFill(image, sr, sc, newColor) + return image + + def _canGo(self, image, row, col, _dir): + new_row, new_col = row, col + if _dir == 0: # Up + new_row -= 1 + elif _dir == 1: # Down + new_row += 1 + elif _dir == 2: # Left + new_col -= 1 + else: # Right + new_col += 1 + if (new_row >= 0) and (new_row < len(image)) \ + and (new_col >= 0) and (new_col < len(image[0])): + if image[new_row][new_col] == self.old_olor: + return (new_row, new_col) + return None + + def _floodFill(self, image, row, col, new_color): + image[row][col] = new_color + for _dir in range(4): + r = self._canGo(image, row, col, _dir) + if r: + self._floodFill(image, r[0], r[1], new_color) + +# easy: https://www.lintcode.com/problem/flood-fill/ diff --git a/form-minimum-number.py b/form-minimum-number.py new file mode 100644 index 0000000..e6020ca --- /dev/null +++ b/form-minimum-number.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param str: the pattern + @return: the minimum number + """ + def formMinimumNumber(self, str): + # Write your code here. + n = len(str) + ret = [0] * (n + 1) + i, idx = 0, 0 + while i <= n: + if (i == n) or (str[i] == 'I'): + for j in range(i, idx - 1, -1): + ret[j] = (1 + idx + i - j).__str__() # The first value for I must be 1! + idx = i + 1 + i += 1 + return ''.join(ret) + +# medium: https://www.lintcode.com/problem/1890 diff --git a/friends-of-number-2.java b/friends-of-number-2.java new file mode 100644 index 0000000..a3948a9 --- /dev/null +++ b/friends-of-number-2.java @@ -0,0 +1,17 @@ +// Only java code + +public class Solution { + public static boolean isFriend(int n) { + // write your code here + int r = 0; + while (n > 0) { + if ((n % 2) == 1) { + ++r; + } + n /= 2; + } + return r == 2; + } +} + +// easy: https://www.lintcode.com/problem/2826 diff --git a/friendship-service.py b/friendship-service.py new file mode 100644 index 0000000..84f92c1 --- /dev/null +++ b/friendship-service.py @@ -0,0 +1,48 @@ +class FriendshipService: + + def __init__(self): + # do intialization if necessary + self.followers = {} + self.followings = {} + + """ + @param: user_id: An integer + @return: all followers and sort by user_id + """ + def getFollowers(self, user_id): + # write your code here + return sorted(self.followers[user_id]) if user_id in self.followers else [] + + """ + @param: user_id: An integer + @return: all followings and sort by user_id + """ + def getFollowings(self, user_id): + # write your code here + return sorted(self.followings[user_id]) if user_id in self.followings else [] + + """ + @param: from_user_id: An integer + @param: to_user_id: An integer + @return: nothing + """ + def follow(self, to_user_id, from_user_id): + # write your code here + if to_user_id not in self.followers: + self.followers[to_user_id] = set() + self.followers[to_user_id].add(from_user_id) + if from_user_id not in self.followings: + self.followings[from_user_id] = set() + self.followings[from_user_id].add(to_user_id) + + """ + @param: from_user_id: An integer + @param: to_user_id: An integer + @return: nothing + """ + def unfollow(self, to_user_id, from_user_id): + # write your code here + if to_user_id in self.followers: + self.followers[to_user_id].discard(from_user_id) + if from_user_id in self.followings: + self.followings[from_user_id].discard(to_user_id) diff --git a/gas_station.py b/gas-station.py similarity index 100% rename from gas_station.py rename to gas-station.py diff --git a/generate_parentheses.py b/generate-parentheses.py similarity index 100% rename from generate_parentheses.py rename to generate-parentheses.py diff --git a/geohash-ii.py b/geohash-ii.py new file mode 100644 index 0000000..458cf5e --- /dev/null +++ b/geohash-ii.py @@ -0,0 +1,39 @@ +class GeoHash: + """ + @param: geohash: geohash a base32 string + @return: latitude and longitude a location coordinate pair + """ + def decode(self, geohash): + # write your code here + code = self.b32decode(geohash) + longs, lats = [-180, 180], [-90, 90] + longtitude, latitude = 0, 0 + prec = len(code) + for i in range(0, prec, 2): + if code[i] == '0': + longs[1] = longtitude + else: + longs[0] = longtitude + longtitude = (longs[0] + longs[1]) / 2 + if (i + 1) >= prec: + break + if code[i + 1] == '0': + lats[1] = latitude + else: + lats[0] = latitude + latitude = (lats[0] + lats[1]) / 2 + return (latitude, longtitude) + + def b32decode(self, geohash): + r = '' + bcode = {'0': '00000', '1': '00001', '2': '00010', '3': '00011', + '4': '00100', '5': '00101', '6': '00110', '7': '00111', + '8': '01000', '9': '01001', 'b': '01010', 'c': '01011', + 'd': '01100', 'e': '01101', 'f': '01110', 'g': '01111', + 'h': '10000', 'j': '10001', 'k': '10010', 'm': '10011', + 'n': '10100', 'p': '10101', 'q': '10110', 'r': '10111', + 's': '11000', 't': '11001', 'u': '11010', 'v': '11011', + 'w': '11100', 'x': '11101', 'y': '11110', 'z': '11111'} + for c in geohash: + r += bcode[c] + return r diff --git a/geohash.py b/geohash.py new file mode 100644 index 0000000..9161e23 --- /dev/null +++ b/geohash.py @@ -0,0 +1,41 @@ +import base64 + +class GeoHash: + """ + @param: latitude: one of a location coordinate pair + @param: longitude: one of a location coordinate pair + @param: precision: an integer between 1 to 12 + @return: a base32 string + """ + def encode(self, latitude, longitude, precision): + # write your code here + l = 5 * precision - 1 + longs, lats = [-180, 180], [-90, 90] + code = [] + while l >= 0: + long_mid = (longs[0] + longs[1]) / 2 + lat_mid = (lats[0] + lats[1]) / 2 + if longitude > long_mid: + code.append(1) + longs[0] =long_mid + else: + code.append(0) + longs[1] = long_mid + if latitude > lat_mid: + code.append(1) + lats[0] = lat_mid + else: + code.append(0) + lats[1] = lat_mid + l -= 2 + return self.base32(code, precision) + + def base32(self, code, precision): + r = '' + chars = '0123456789bcdefghjkmnpqrstuvwxyz' + for i in range(0, precision * 5, 5): + idx = 0 + for j in range(5): + idx = idx * 2 + code[i + j] + r += chars[idx] + return r diff --git a/gfs-client.py b/gfs-client.py new file mode 100644 index 0000000..06b37bf --- /dev/null +++ b/gfs-client.py @@ -0,0 +1,63 @@ +''' +Definition of BaseGFSClient +class BaseGFSClient: + def readChunk(self, filename, chunkIndex): + # Read a chunk from GFS + def writeChunk(self, filename, chunkIndex, content): + # Write a chunk to GFS +''' + + +class GFSClient(BaseGFSClient): + """ + @param: chunkSize: An integer + """ + def __init__(self, chunkSize): + # do intialization if necessary + self.chunkSize = chunkSize + super(GFSClient,self).__init__() + + """ + @param: filename: a file name + @return: conetent of the file given from GFS + """ + def read(self, filename): + # write your code here + if filename + '-0' not in self.chunks: + return None + data = '' + i = 0 + while True: + d = self.readChunk(filename, i) + if not d: + break + i += 1 + data += d + return data + + """ + @param: filename: a file name + @param: content: a string + @return: nothing + """ + def write(self, filename, content): + # write your code here + if filename + '-0' in self.chunks: + i = 0 + while True: + f = filename + '-' + str(i) + if f in self.chunks: + del self.chunks[f] + i += 1 + else: + break + bytes = len(content) + chunks = int(bytes / self.chunkSize) + if (chunks * self.chunkSize) < bytes: + chunks += 1 + for i in range(chunks): + begin = i * self.chunkSize + end = begin + self.chunkSize + if end > bytes: + end = bytes + self.writeChunk(filename, i, content[begin:end]) diff --git a/give-change.py b/give-change.py new file mode 100644 index 0000000..660fd60 --- /dev/null +++ b/give-change.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param amount: The amount you should pay. + @return: Return the minimum number of coins for change. + """ + def giveChange(self, amount): + # write you code here. + ret = 0 + coins = [64, 16, 4, 1] + c = 0 + amount = 1024 - amount + while amount > 0: + ret += int(amount / coins[c]) + amount -= int(amount / coins[c]) * coins[c] + c += 1 + return ret + +# easy: https://www.lintcode.com/problem/give-change/ diff --git a/goat-latin.py b/goat-latin.py new file mode 100644 index 0000000..8b3dc2e --- /dev/null +++ b/goat-latin.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param S: + @return: nothing + """ + def toGoatLatin(self, S): + # + words = S.split() # 偷懒做法 + for i in range(len(words)): + word = words[i] + tail = 'ma' + 'a' * (i + 1) + if word[0] in ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']: + words[i] = word + tail + else: + words[i] = word[1:] + word[0] + tail + return ' '.join(words) + +# easy: https://www.lintcode.com/problem/goat-latin/ diff --git a/graph_valid_tree.py b/graph-valid-tree.py similarity index 100% rename from graph_valid_tree.py rename to graph-valid-tree.py diff --git a/gray_code.py b/gray-code.py similarity index 100% rename from gray_code.py rename to gray-code.py diff --git a/greatest-common-divisor.py b/greatest-common-divisor.py new file mode 100644 index 0000000..92ad945 --- /dev/null +++ b/greatest-common-divisor.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param a: the given number + @param b: another number + @return: the greatest common divisor of two numbers + """ + def gcd(self, a, b): + # write your code here + x = max(a, b) + y = min(a, b) + while (x % y) != 0: + tmp = x % y + x = y + y = tmp + return y + +# easy: https://www.lintcode.com/problem/greatest-common-divisor/ diff --git a/group-buy.py b/group-buy.py new file mode 100644 index 0000000..7c54205 --- /dev/null +++ b/group-buy.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param x: the number of people who plan to buy goods A. + @param y: the number of people who plan to buy goods B. + @param z: the number of people who plan to buy goods C. + @return: return the maximum times they can group buy. + """ + def groupBuyTimes(self, x, y, z): + # write your code here + ''' + 其题目并不要求买到x + y + z件商品,然后满足团购条件下购买尽可能多的商品。 + 1. 如果z大于等于x,那么返回x与y之间较小的。 + 2. 如果z大于等于y,同上。 + 3. 如果x和y都大于z,那么z一定能满足。x和y剩下的部分最多可团购(x + y) / 3次,但是要看一下是否满足限制。 + ''' + if z >= x: + return y if x >= y else x + if z >= y: + return y if x >= y else x + x -= z + y -= z + r = int((x + y) / 3) + if r > min(x, y): + r = min(x, y) + return r + z + +# easy: https://www.lintcode.com/problem/group-buy/my-submissions diff --git a/guess_number_game.py b/guess-number-game.py similarity index 100% rename from guess_number_game.py rename to guess-number-game.py diff --git a/hail-conjecture.py b/hail-conjecture.py new file mode 100644 index 0000000..737a9ee --- /dev/null +++ b/hail-conjecture.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param num: an integer + @return: return an integer + """ + def getAnswer(self, num): + # write your code here. + ret = 0 + while num != 1: + if (num % 2) == 0: + num /= 2 + else: + num = num * 3 + 1 + ret += 1 + return ret + +# easy: https://www.lintcode.com/problem/hail-conjecture/ diff --git a/hamming-distance.py b/hamming-distance.py new file mode 100644 index 0000000..951e32a --- /dev/null +++ b/hamming-distance.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param x: an integer + @param y: an integer + @return: return an integer, denote the Hamming Distance between two integers + """ + def hammingDistance(self, x, y): + # write your code here + # 转成2进制字符串后比较,记得长度不同前面补0。 + r = 0 + bx = bin(x)[2:] + by = bin(y)[2:] + diff = abs(len(bx) - len(by)) + if len(bx) > len(by): + by = '0' * diff + by + else: + bx = '0' * diff + bx + for i in range(len(bx)): + if bx[i] != by[i]: + r += 1 + return r + +# easy: https://www.lintcode.com/problem/hamming-distance diff --git a/happy_number.py b/happy-number.py similarity index 100% rename from happy_number.py rename to happy-number.py diff --git a/hash_function.py b/hash-function.py similarity index 100% rename from hash_function.py rename to hash-function.py diff --git a/heaters.py b/heaters.py new file mode 100644 index 0000000..dcb87f2 --- /dev/null +++ b/heaters.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param houses: positions of houses + @param heaters: positions of heaters + @return: the minimum radius standard of heaters + """ + def findRadius(self, houses, heaters): + # Write your code here + # 按照顺序找到每个屋子距离最近的加热器,记录其位置差。 + # 所有的位置差里面最长的那一个就是最小的加热器半径了 + ret = 0 + houses.sort() + heaters.sort() + j = 0 + for i in range(len(houses)): + while j < (len(heaters) - 1): + diff_1 = abs(heaters[j] - houses[i]) + diff_2 = abs(heaters[j + 1] - houses[i]) + if diff_1 >= diff_2: + j += 1 + else: + break + ret = max(ret, abs(heaters[j] - houses[i])) + return ret + +# easy: https://www.lintcode.com/problem/heaters/ diff --git a/hex-conversion.py b/hex-conversion.py new file mode 100644 index 0000000..8d38c5e --- /dev/null +++ b/hex-conversion.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param n: a decimal number + @param k: a Integer represent base-k + @return: a base-k number + """ + def hexConversion(self, n, k): + # write your code here + chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] + digits = [] + while n >= k: + digits.append(chars[n % k]) + n = int(n / k) + digits.append(chars[n]) + return ''.join(digits[::-1]) + +# easy: https://www.lintcode.com/problem/hex-conversion/ diff --git a/highest-growth-stock.py b/highest-growth-stock.py new file mode 100644 index 0000000..d46f8be --- /dev/null +++ b/highest-growth-stock.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param Stock: Stock information + @return: return id + """ + def highestGrowth(self, Stock): + # Write your code here + r = '0' + inc = 0 + for s in Stock: + _inc = float(s[2]) / float(s[1]) + if _inc > inc: + inc = _inc + r = s[0] + elif _inc == inc: + if s[0] < r: + r = s[0] + return r + +# easy: https://www.lintcode.com/problem/1614/ diff --git a/holy-grail-spell.py b/holy-grail-spell.py new file mode 100644 index 0000000..933ec6e --- /dev/null +++ b/holy-grail-spell.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param Spell: The Spell + @return: nothing + """ + def holyGrailspell(self, Spell): + # Write your code here + ret = [] + for i in range(26): + ret.append([0, 0]) + for c in Spell: + c = ord(c) + if (c >= ord('a')) and (c <= ord('z')): + ret[c - ord('a')][0] = 1 + else: + ret[c - ord('A')][1] = 1 + for i in range(25, -1, -1): + if ret[i] == [1, 1]: + return chr(i + ord('A')) + +# easy: https://www.lintcode.com/problem/holy-grail-spell/ diff --git a/house-robber-ii.py b/house-robber-ii.py new file mode 100644 index 0000000..966c312 --- /dev/null +++ b/house-robber-ii.py @@ -0,0 +1,31 @@ +class Solution: + """ + @param nums: An array of non-negative integers. + @return: The maximum amount of money you can rob tonight + """ + def houseRobber2(self, nums): + # write your code here + # 第一间与最后一间不能同时抢 + if (not nums) or (len(nums) == 2): + return 0 + if len(nums) == 1: + return nums[0] + dp_1 = [0] * (len(nums) - 1) # 0到倒数第2间 + dp_2 = [0] * (len(nums) - 1) # 1到最后一间 + for i in range(0, len(nums) - 1): + if i == 0: + dp_1[i] = nums[0] + if i == 1: + dp_1[i] = max(nums[0], nums[1]) + if i > 1: + dp_1[i] = max(dp_1[i - 2] + nums[i], dp_1[i - 1]) + for i in range(1, len(nums)): + if i == 1: + dp_2[i - 1] = nums[1] + if i == 2: + dp_2[i - 1] = max(nums[1], nums[2]) + if i > 2: + dp_2[i - 1] = max(dp_2[i - 3] + nums[i], dp_2[i - 2]) + return max(dp_1[-1], dp_2[-1]) + +# medium: http://lintcode.com/zh-cn/problem/house-robber-ii/ diff --git a/house_robber_iii.py b/house-robber-iii.py similarity index 100% rename from house_robber_iii.py rename to house-robber-iii.py diff --git a/house_robber.py b/house-robber.py similarity index 100% rename from house_robber.py rename to house-robber.py diff --git a/house_robber_ii.py b/house_robber_ii.py deleted file mode 100644 index 9a339dd..0000000 --- a/house_robber_ii.py +++ /dev/null @@ -1,34 +0,0 @@ -# coding: utf-8 - -class Solution: - # @param nums: A list of non-negative integers. - # return: an integer - def houseRobber2(self, nums): - # write your code here - ''' - 与打劫房屋相比: - 1. 如果我抢了第1间,最后一间就不能抢。 - 2. 如果第一间不抢,就可以抢最后一间。 - ''' - if not nums: - return 0 - elif len(nums) == 1: - return nums[0] - elif len(nums) == 2: - return max(nums[0], nums[1]) - else: - ret_1, ret_2 = 0, 0 - # 场景1 - caches = nums[:] - caches[1] = max(caches[0], caches[1]) - for i in xrange(2, len(nums) - 1): - caches[i] = max(caches[i] + caches[i - 2], caches[i - 1]) - ret_1 = caches[-2] - caches = nums[:] - caches[0] = 0 - for i in xrange(2, len(nums)): - caches[i] = max(caches[i] + caches[i - 2], caches[i - 1]) - ret_2 = caches[-1] - return max(ret_1, ret_2) - -# medium: http://lintcode.com/zh-cn/problem/house-robber-ii/ diff --git a/identical_binary_tree.py b/identical-binary-tree.py similarity index 100% rename from identical_binary_tree.py rename to identical-binary-tree.py diff --git a/image-smoother.py b/image-smoother.py new file mode 100644 index 0000000..fa1a716 --- /dev/null +++ b/image-smoother.py @@ -0,0 +1,44 @@ +class Solution: + """ + @param M: a 2D integer matrix + @return: a 2D integer matrix + """ + def imageSmoother(self, M): + # Write your code here + ret = [] + for row in range(len(M)): + ret.append([]) + for col in range(len(M[0])): + ret[-1].append(self.smoother(M, row, col)) + return ret + + def smoother(self, M, row, col): + val = M[row][col] + count = 1 + if ((row - 1) >= 0) and ((col - 1) >= 0): # left-upper + val += M[row - 1][col - 1] + count += 1 + if ((row - 1) >= 0): # upper + val += M[row - 1][col] + count += 1 + if ((row - 1) >= 0) and ((col + 1) < len(M[0])): # right-upper + val += M[row - 1][col + 1] + count += 1 + if ((col - 1) >= 0): # left + val += M[row][col - 1] + count += 1 + if ((col + 1) < len(M[0])): # right + val += M[row][col + 1] + count += 1 + if ((row + 1) < len(M)) and ((col - 1) >= 0): # left-down + val += M[row + 1][col - 1] + count += 1 + if ((row + 1) < len(M)): # down + val += M[row + 1][col] + count += 1 + if ((row + 1) < len(M)) and ((col + 1) < len(M[0])): # right-down + val += M[row + 1][col + 1] + count += 1 + return int(val / count) + +# easy: https://www.lintcode.com/problem/image-smoother/ diff --git a/implement-queue-by-interface.py b/implement-queue-by-interface.py new file mode 100644 index 0000000..28eabe6 --- /dev/null +++ b/implement-queue-by-interface.py @@ -0,0 +1,45 @@ +class InterfaceQueue: + def push(self, element): + pass + + # define an interface for pop method + # write your code here + def pop(self): + pass + + # define an interface for top method + # write your code here + def top(self): + pass + +class MyQueue(InterfaceQueue): + # you can declare your private attributes here + def __init__(self): + # do initialization if necessary + self.i = 0 + self.data = [] + + # implement the push method + # write your code here + def push(self, val): + self.data.append(val) + + # implement the pop method + # write your code here + def pop(self): + ret = self.data[self.i] + self.i += 1 + return ret + + # implement the top method + # write your code here + def top(self): + return self.data[self.i] + +# Your MyQueue object will be instantiated and called as such: +# MyQueue queue = new MyQueue(); +# queue.push(123); +# queue.top(); will return 123; +# queue.pop(); will return 123 and pop the first element in the queue + +# easy: https://www.lintcode.com/problem/546 diff --git a/implement-queue-by-linked-list.py b/implement-queue-by-linked-list.py new file mode 100644 index 0000000..cdd666a --- /dev/null +++ b/implement-queue-by-linked-list.py @@ -0,0 +1,30 @@ +class MyQueue: + def __init__(self): + # 使用系统定义的ListNode + self.head, self.tail = None, None + + """ + @param: item: An integer + @return: nothing + """ + def enqueue(self, item): + # write your code here + if not self.head: + self.head = ListNode(item) + self.tail = self.head + else: + self.tail.next = ListNode(item) + self.tail = self.tail.next + + """ + @return: An integer + """ + def dequeue(self): + # write your code here + ret = None + if self.head: + ret = self.head.val + self.head = self.head.next + return ret + +# easy: https://www.lintcode.com/problem/implement-queue-by-linked-list/ diff --git a/implement_queue_by_two_stacks.py b/implement-queue-by-two-stacks.py similarity index 100% rename from implement_queue_by_two_stacks.py rename to implement-queue-by-two-stacks.py diff --git a/implement-rand10-using-rand7.py b/implement-rand10-using-rand7.py new file mode 100644 index 0000000..b0f63f7 --- /dev/null +++ b/implement-rand10-using-rand7.py @@ -0,0 +1,9 @@ +class Solution(SolBase): + def rand10(self): + # 推导过程可以参考 https://www.jianshu.com/p/1127e746da12 + while True: + i = (self.rand7() - 1) * 7 + (self.rand7() - 1) + if (i >= 1) and (i <= 10): # 因为i在1-10之间均匀分布,超出的值不要! + return i + +# medium: https://www.lintcode.com/problem/1496 diff --git a/implement-stack-by-two-queues.py b/implement-stack-by-two-queues.py new file mode 100644 index 0000000..ad6b609 --- /dev/null +++ b/implement-stack-by-two-queues.py @@ -0,0 +1,59 @@ +class Queue: + def __init__(self): + self.i = 0 + self.arr = [] + + def push(self, v): + self.arr.append(v) + + def pop(self): + r = self.arr[self.i] + self.i += 1 + return r + + def top(self): + return self.arr[self.i] + + def is_empty(self): + return len(self.arr) == self.i + +class Stack: + def __init__(self): + self.qs= [Queue(), Queue()] + self.flag = 0 + + """ + @param: x: An integer + @return: nothing + """ + def push(self, x): + # write your code here + nf = 1 - self.flag + self.qs[nf].push(x) + while not self.qs[self.flag].is_empty(): + self.qs[nf].push(self.qs[self.flag].pop()) + self.flag = nf + + + """ + @return: nothing + """ + def pop(self): + # write your code here + return self.qs[self.flag].pop() + + """ + @return: An integer + """ + def top(self): + # write your code here + return self.qs[self.flag].top() + + """ + @return: True if the stack is empty + """ + def isEmpty(self): + # write your code here + return self.qs[self.flag].is_empty() + +# easy: https://www.lintcode.com/problem/494/ diff --git a/implement-stack.py b/implement-stack.py new file mode 100644 index 0000000..af3985e --- /dev/null +++ b/implement-stack.py @@ -0,0 +1,40 @@ +class Stack: + def __init__(self): + self.stack = [] + self.size = 0 + + """ + @param: x: An integer + @return: nothing + """ + def push(self, x): + # write your code here + if len(self.stack) <= self.size: + self.stack.append(x) + else: + self.stack[self.size] = x + self.size += 1 + + """ + @return: nothing + """ + def pop(self): + # write your code here + self.size -= 1 + return self.stack[self.size]; + + """ + @return: An integer + """ + def top(self): + # write your code here + return self.stack[self.size -1]; + + """ + @return: True if the stack is empty + """ + def isEmpty(self): + # write your code here + return self.size == 0 + +# easy: https://www.lintcode.com/problem/implement-stack/ diff --git a/implement_trie.py b/implement-trie.py similarity index 100% rename from implement_trie.py rename to implement-trie.py diff --git a/increasing-order-search-tree.py b/increasing-order-search-tree.py new file mode 100644 index 0000000..71d5aa0 --- /dev/null +++ b/increasing-order-search-tree.py @@ -0,0 +1,29 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: a binary search tree + @return: Root of a tree + """ + def increasingBST(self, root): + # Write your code here. + if not root: + return None + lr = self.increasingBST(root.left) + rr = self.increasingBST(root.right) + if lr: + node = lr + while node.right != None: + node = node.right + node.right = root + root.left = None + root.right = rr + return lr if lr else root + +# easy: https://www.lintcode.com/problem/increasing-order-search-tree/ diff --git a/inorder-successor-in-bst.py b/inorder-successor-in-bst.py new file mode 100644 index 0000000..2a4375c --- /dev/null +++ b/inorder-successor-in-bst.py @@ -0,0 +1,27 @@ +""" +Definition for a binary tree node. +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None +""" + + +class Solution: + """ + @param: root: The root of the BST. + @param: p: You need find the successor node of p. + @return: Successor of p. + """ + def inorderSuccessor(self, root, p): + # write your code here + # We can utilize the feature of BST! + if not root: + return None + if root.val > p.val: + return self.inorderSuccessor(root.left, p) or root + else: + return self.inorderSuccessor(root.right, p) + +# medium: https://www.lintcode.com/problem/448 diff --git a/input-stream.py b/input-stream.py new file mode 100644 index 0000000..af4b6fc --- /dev/null +++ b/input-stream.py @@ -0,0 +1,25 @@ +class Solution: + """ + @param inputA: Input stream A + @param inputB: Input stream B + @return: The answer + """ + def inputStream(self, inputA, inputB): + # Write your code here + aa = [] + bb = [] + for c in inputA: + if c != '<': + aa.append(c) + else: + if aa: + aa.pop() + for c in inputB: + if c != '<': + bb.append(c) + else: + if bb: + bb.pop() + return 'YES' if aa == bb else 'NO' + +# easy: https://www.lintcode.com/problem/823/ diff --git a/insert-five.py b/insert-five.py new file mode 100644 index 0000000..7ecc23e --- /dev/null +++ b/insert-five.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param a: A number + @return: Returns the maximum number after insertion + """ + def InsertFive(self, a): + # write your code here + ret = [] + s = list(str(abs(a))) + inserted = False + if a < 0: + ret.append('-') + for c in s: + if a >= 0: + if (int(c) < 5) and (not inserted): + ret.append('5') + inserted = True + else: + if (int(c) > 5) and (not inserted): + ret.append('5') + inserted = True + ret.append(c) + if not inserted: + ret.append('5') + return int(''.join(ret)) + +# easy: https://www.lintcode.com/problem/insert-five/ diff --git a/insert_interval.py b/insert-interval.py similarity index 100% rename from insert_interval.py rename to insert-interval.py diff --git a/insert_node_in_a_binary_search_tree.py b/insert-node-in-a-binary-search-tree.py similarity index 100% rename from insert_node_in_a_binary_search_tree.py rename to insert-node-in-a-binary-search-tree.py diff --git a/insert-node-in-sorted-linked-list.py b/insert-node-in-sorted-linked-list.py new file mode 100644 index 0000000..607fe6e --- /dev/null +++ b/insert-node-in-sorted-linked-list.py @@ -0,0 +1,32 @@ +""" +Definition of ListNode +class ListNode(object): + def __init__(self, val, next=None): + self.val = val + self.next = next +""" + +class Solution: + """ + @param head: The head of linked list. + @param val: An integer. + @return: The head of new linked list. + """ + def insertNode(self, head, val): + # write your code here + if not head: + return ListNode(val) + if val <= head.val: + return ListNode(val, head) + curr, _next = head, head.next + while curr and _next: + if (curr.val <= val) and (_next.val >= val): + t = ListNode(val, _next) + curr.next = t + return head + curr = curr.next + _next = _next.next + curr.next = ListNode(val) + return head + +# easy: https://www.lintcode.com/problem/219/ diff --git a/insertion_sort_list.py b/insertion-sort-list.py similarity index 100% rename from insertion_sort_list.py rename to insertion-sort-list.py diff --git a/integer_to_roman.py b/integer-to-roman.py similarity index 100% rename from integer_to_roman.py rename to integer-to-roman.py diff --git a/interleaved-array.py b/interleaved-array.py new file mode 100644 index 0000000..2503320 --- /dev/null +++ b/interleaved-array.py @@ -0,0 +1,15 @@ +class Solution: + """ + @param A: the array A + @param B: the array B + @return: returns an alternate array of arrays A and B. + """ + def interleavedArray(self, A, B): + # Interleaved Array + ret = [] + for i in range(len(A)): + ret.append(A[i]) + ret.append(B[i]) + return ret + +# easy: https://www.lintcode.com/problem/interleaved-array/ diff --git a/interleaving-positive-and-negative-numbers.py b/interleaving-positive-and-negative-numbers.py new file mode 100644 index 0000000..1e5e2d0 --- /dev/null +++ b/interleaving-positive-and-negative-numbers.py @@ -0,0 +1,33 @@ +class Solution: + """ + @param: A: An integer array. + @return: nothing + """ + def rerange(self, A): + # write your code here + # 先分区,负数再前,正数在后。 + start, end = 0, len(A) - 1 + while (start < end): + while (start < end) and (A[start] < 0): + start += 1 + while (end >= 0) and (A[end] > 0): + end -= 1 + if (start < end): + A[start], A[end] = A[end], A[start] + cp, cn = 0, 0 + for i in A: + if i > 0: + cp += 1 + else: + cn += 1 + start, end = 0, len(A) - 1 + if cn > cp: # 前面的负数比后面的正数多 + start += 1 + elif cn < cp: # 后面的正数比前面的负数多 + end -= 1 + while start < end: + A[start], A[end] = A[end], A[start] + start += 2 + end -= 2 + +# medium: http://lintcode.com/zh-cn/problem/interleaving-positive-and-negative-numbers/ diff --git a/interleaving_string.py b/interleaving-string.py similarity index 100% rename from interleaving_string.py rename to interleaving-string.py diff --git a/interleaving_positive_and_negative_numbers.py b/interleaving_positive_and_negative_numbers.py deleted file mode 100644 index 41bdcdc..0000000 --- a/interleaving_positive_and_negative_numbers.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding: utf-8 - -class Solution: - """ - @param A: An integer array. - @return nothing - """ - def rerange(self, A): - # write your code here - ''' - 偶数情况:XXXX,OOOO - - XXXO,OOXO (第4个位置的X与第3个位置的O换) - - XOXO,XOXO (第2个位置的X与第1个位置的O换) - 奇数情况:XXXXXXX,OOOOOOO - - XXXXXOX,OOOOOXO(第6个位置的X与第6个位置的O互换) - - XXXOXOX,OOOXOXO(第4个位置的X与第4个位置的O互换) - - XOXOXOX,OXOXOXO(第2个位置的X与第2个位置的O互换) - X和O,数量比较多的排前面。 - 对于X,XXX,OOO的情况,不考虑前面多余的O,得到X,XOXOXO,然后对多余X后面部分反转得到X,OXOXOX。 - ''' - A.sort() - neg_count, pos_count = 0, 0 - for n in A: - if n < 0: - neg_count += 1 - else: - pos_count += 1 - if pos_count > neg_count: - A.reverse() - # TODO - shift = abs(neg_count - pos_count) - steps = min(neg_count, pos_count) - first_start, first_end = shift, shift + steps - 1 - second_start, second_end = shift + steps, len(A) - 2 # 后半部分的循环总是从倒数第2个元素开始 - if (steps % 2) == 1: # 做起点修正 - first_end -= 1 - while second_end >= second_start: - A[first_end], A[second_end] = A[second_end], A[first_end] - first_end -= 2 - second_end -= 2 - if shift > 0: - start, end = shift, len(A) - 1 - while start < end: - A[start], A[end] = A[end], A[start] - start += 1 - end -= 1 - -# medium: http://lintcode.com/zh-cn/problem/interleaving-positive-and-negative-numbers/ diff --git a/intersection-of-arrays.py b/intersection-of-arrays.py new file mode 100644 index 0000000..9ed8e23 --- /dev/null +++ b/intersection-of-arrays.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param arrs: the arrays + @return: the number of the intersection of the arrays + """ + def intersectionOfArrays(self, arrs): + # write your code here + ret = 0 # There are no duplicated elements in each array + di = {} + for arr in arrs: + for i in arr: + if i in di: + di[i] += 1 + else: + di[i] = 1 + for k, v in di.items(): + if v == len(arrs): + ret += 1 + return ret + +# medium: https://www.lintcode.com/problem/intersection-of-arrays/ diff --git a/intersection_of_two_arrays_ii.py b/intersection-of-two-arrays-ii.py similarity index 100% rename from intersection_of_two_arrays_ii.py rename to intersection-of-two-arrays-ii.py diff --git a/intersection_of_two_arrays.py b/intersection-of-two-arrays.py similarity index 100% rename from intersection_of_two_arrays.py rename to intersection-of-two-arrays.py diff --git a/intersection_of_two_linked_lists.py b/intersection-of-two-linked-lists.py similarity index 100% rename from intersection_of_two_linked_lists.py rename to intersection-of-two-linked-lists.py diff --git a/intersection.py b/intersection.py new file mode 100644 index 0000000..189647f --- /dev/null +++ b/intersection.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param a: first sequence + @param b: second sequence + @return: return ans + """ + def Intersection(self, a, b): + # write your code here + ret = [] + prev_j = 0 + for i in range(len(a)): + _a = a[i] + for j in range(prev_j, len(b)): + _b = b[j] + if _b[0] > _a[1]: + break + if self._intersection(_a, _b): + ret.append([i, j]) + prev_j = j + return ret + + def _intersection(self, a, b): + v0_0, v0_1 = a[0], a[1] + v1_0, v1_1 = b[0], b[1] + return not ((v0_1 < v1_0) or (v0_0 > v1_1) or (v1_0 > v0_1) or (v1_1 < v0_0)) + +# easy: https://www.lintcode.com/problem/intersection/ diff --git a/invert_binary_tree.py b/invert-binary-tree.py similarity index 100% rename from invert_binary_tree.py rename to invert-binary-tree.py diff --git a/inverted-index.py b/inverted-index.py new file mode 100644 index 0000000..dbf47d7 --- /dev/null +++ b/inverted-index.py @@ -0,0 +1,21 @@ +''' +Definition of Document +class Document: + def __init__(self, id, cotent): + self.id = id + self.content = content +''' +class Solution: + # @param {Document[]} docs a list of documents + # @return {dict(string, int[])} an inverted index + def invertedIndex(self, docs): + # Write your code here + r = {} + for d in docs: + for w in d.content.split(' '): + if w: + if w not in r: + r[w] = [d.id] + elif r[w][-1] != (d.id): + r[w].append(d.id) + return r diff --git a/island-perimeter.py b/island-perimeter.py new file mode 100644 index 0000000..fe70e05 --- /dev/null +++ b/island-perimeter.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param grid: a 2D array + @return: the perimeter of the island + """ + def islandPerimeter(self, grid): + # Write your code here + ret = 0 + if len(grid) > 0: + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] != 0: + ret += 4 # 周长最大为4 + # 左边有陆地,减2.两块陆地各减1。 + if (i > 0) and (grid[i - 1][j] == 1): + ret -= 2 + # 上边有陆地,减2.两块陆地各减1。 + if (j > 0) and (grid[i][j - 1] == 1): + ret -= 2 + + return ret + +# easy: https://www.lintcode.com/problem/island-perimeter/ diff --git a/jewels-and-stones.py b/jewels-and-stones.py new file mode 100644 index 0000000..6b6f574 --- /dev/null +++ b/jewels-and-stones.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param J: the types of stones that are jewels + @param S: representing the stones you have + @return: how many of the stones you have are also jewels + """ + def numJewelsInStones(self, J, S): + # Write your code here + ret = 0 + s = set(J) + for c in S: + if c in s: + ret += 1 + return ret + +# easy: https://www.lintcode.com/problem/jewels-and-stones/ diff --git a/johns-backyard-garden.py b/johns-backyard-garden.py new file mode 100644 index 0000000..5808ad4 --- /dev/null +++ b/johns-backyard-garden.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param x: the wall's height + @return: YES or NO + """ + def isBuild(self, x): + # write you code here + # 这题容易被题目吓着,其实就是3和7能不能堆成某个高度。 + # 理论上只要高度满足3 * n + 7 * m就行,但是很难凑。 + # 反向思考,高度除7的余数: + # 1. 余数属于[0, 3, 6]正好都是3的倍数。 + # 2. 如果高度大于7,但是余数等于2,那么可以把7拿出来凑9。 + # 3. 如果高度大于7,但是余数等于5,那么可以把7拿出来凑12。 + # 4. 其它情况就没办法了。 + m = x % 7 + if m in [0, 3, 6]: + return "YES" + elif (x > 7) and ((m == 5) or (m==2)): + return "YES" + else: + return "NO" + +# easy: https://www.lintcode.com/problem/johns-backyard-garden diff --git a/judge-connection.py b/judge-connection.py new file mode 100644 index 0000000..50e8b9a --- /dev/null +++ b/judge-connection.py @@ -0,0 +1,32 @@ +class Solution: + """ + @param arr: the arr + @param k: the k + @return: if all instances of value k in arr are connected + """ + def judgeConnection(self, arr, k): + # Write your code here. + # 如果是连通的DFS肯定可以一波带走 + marked = False + self.rows = len(arr) + self.cols = len(arr[0]) + for r in range(self.rows): + for c in range(self.cols): + if arr[r][c] == k: + if not marked: + self.mark(arr, k, r, c) + marked = True + else: + return False + return True + + def mark(self, arr, k, r, c): + if ((r >= 0) and (r < self.rows)) and ((c >= 0) and (c < self.cols)): + if arr[r][c] == k: + arr[r][c] = -1 + self.mark(arr, k, r - 1, c) + self.mark(arr, k, r + 1, c) + self.mark(arr, k, r, c - 1) + self.mark(arr, k, r, c + 1) + +# medium: https://www.lintcode.com/problem/judge-connection/ diff --git a/judge-route-circle b/judge-route-circle new file mode 100644 index 0000000..deb5c98 --- /dev/null +++ b/judge-route-circle @@ -0,0 +1,20 @@ +class Solution: + """ + @param moves: a sequence of its moves + @return: if this robot makes a circle + """ + def judgeCircle(self, moves): + # Write your code here + x, y = 0, 0 + for m in moves: + if m == 'U': + y += 1 + elif m == 'D': + y -= 1 + elif m == 'L': + x -= 1 + elif m == 'R': + x += 1 + return (x == 0) and (y == 0) + +# easy: https://www.lintcode.com/problem/judge-route-circle/ diff --git a/judgment-repetition.py b/judgment-repetition.py new file mode 100644 index 0000000..287ebdf --- /dev/null +++ b/judgment-repetition.py @@ -0,0 +1,11 @@ +class Solution: + """ + @param arr: An array + @return: A boolean + """ + def isUnique(self, arr): + # write your code here + n = len(arr) + return sum(arr) == int((n - 1) * n / 2) + +# medium: https://www.lintcode.com/problem/571/ diff --git a/jump_game_ii.py b/jump-game-ii.py similarity index 100% rename from jump_game_ii.py rename to jump-game-ii.py diff --git a/jump_game.py b/jump-game.py similarity index 100% rename from jump_game.py rename to jump-game.py diff --git a/k-decimal-addition.py b/k-decimal-addition.py new file mode 100644 index 0000000..daa5a24 --- /dev/null +++ b/k-decimal-addition.py @@ -0,0 +1,32 @@ +class Solution: + """ + @param k: The k + @param a: The A + @param b: The B + @return: The answer + """ + def addition(self, k, a, b): + # Write your code here + r = [] + flag = 0 + a = a[::-1] + b = b[::-1] + i = 0 + while i < min(len(a), len(b)): + v = int(a[i]) + int(b[i]) + flag + r.append(str(int(v % k))) + flag = 1 if v >= k else 0 + i += 1 + arr = a if len(a) > i else b + while i < len(arr): + v = int(arr[i]) + flag + r.append(str(int(v % k))) + flag = 1 if v >= k else 0 + i += 1 + if flag > 0: + r.append('1') + while r and (r[-1] == '0'): + r.pop() + return ''.join(r[::-1]) + +# easy: https://www.lintcode.com/problem/1398/ diff --git a/k-diff-pairs-in-an-array.py b/k-diff-pairs-in-an-array.py new file mode 100644 index 0000000..3837c6d --- /dev/null +++ b/k-diff-pairs-in-an-array.py @@ -0,0 +1,31 @@ +class Solution: + """ + @param nums: an array of integers + @param k: an integer + @return: the number of unique k-diff pairs + """ + def findPairs(self, nums, k): + # Write your code here + ret = 0 + if len(nums) >= 2: + di = {} + for i in nums: + if i not in di: + di[i] = 1 + else: + di[i] += 1 + k = abs(k) + used = set([]) + for i in nums: + if k == 0: + if (i not in used) and (di[i] > 1): + ret += 1 + used.add(i) + else: + if i not in used: + if (i + k) in di: + ret += 1 + used.add(i) + return ret + +# easy: https://www.lintcode.com/problem/k-diff-pairs-in-an-array/ diff --git a/k_sum_ii.py b/k-sum-ii.py similarity index 100% rename from k_sum_ii.py rename to k-sum-ii.py diff --git a/keyboard-row.py b/keyboard-row.py new file mode 100644 index 0000000..e741ac5 --- /dev/null +++ b/keyboard-row.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param words: a list of strings + @return: return a list of strings + """ + def findWords(self, words): + # write your code here + ret = [] + di = {'Q': 1, 'W': 1, 'E': 1, 'R': 1, 'T': 1, 'Y': 1, 'U': 1, 'I': 1, 'O': 1, 'P': 1, + 'A': 2, 'S': 2, 'D': 2, 'F': 2, 'G': 2, 'H': 2, 'J': 2, 'K': 2, 'L': 2, + 'Z': 3, 'X': 3, 'C': 3, 'V': 3, 'B': 3, 'N': 3, 'M': 3} + for word in words: + line = None + match = True + for c in word.upper(): + if not line: + line = di[c] + else: + if line != di[c]: + match = False + break + if match: + ret.append(word) + return ret + +# easy: https://www.lintcode.com/problem/keyboard-row/ diff --git a/keys-and-rooms.py b/keys-and-rooms.py new file mode 100644 index 0000000..3481df9 --- /dev/null +++ b/keys-and-rooms.py @@ -0,0 +1,29 @@ +from typing import ( + List, +) + +class Solution: + """ + @param rooms: a list of keys rooms[i] + @return: can you enter every room + """ + def can_visit_all_rooms(self, rooms: List[List[int]]) -> bool: + # Write your code here + ret = 1 + visited = [0] * len(rooms) + visited[0] = 1 + keys = [rooms[0], []] + curr = 0 + while keys[curr]: + for k in keys[curr]: + if visited[k] == 0: + for _k in rooms[k]: + if visited[_k] == 0: + keys[1 - curr].append(_k) + visited[k] = 1 + ret += 1 + keys[curr].clear() + curr = 1 - curr + return ret == len(rooms) + +# medium: https://www.lintcode.com/problem/1428 diff --git a/kill-process.py b/kill-process.py new file mode 100644 index 0000000..10a5a1b --- /dev/null +++ b/kill-process.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param pid: the process id + @param ppid: the parent process id + @param kill: a PID you want to kill + @return: a list of PIDs of processes that will be killed in the end + """ + def killProcess(self, pid, ppid, kill): + # Write your code here + ret = [] + di = {} + for i in range(len(pid)): + if ppid[i] not in di: + di[ppid[i]] = [pid[i]] + else: + di[ppid[i]].append(pid[i]) + kills = [kill] + while kills: + ret.extend(kills) + tmp = kills + kills = [] + for k in tmp: + if k in di: + kills.extend(di[k]) + return ret + +# easy: https://www.lintcode.com/problem/kill-process/ diff --git a/knight-dialer.py b/knight-dialer.py new file mode 100644 index 0000000..a4f2f48 --- /dev/null +++ b/knight-dialer.py @@ -0,0 +1,33 @@ +class Solution: + """ + @param n: N + @return: return the number of distinct numbers can you dial in this manner mod 1e9+7 + """ + def knight_dialer(self, n: int) -> int: + # + ''' + 可以缓存前序位置 + 1. 到位置0,前一个位置可以是4或6; + 2. 到位置1,前一个位置可以是6或8; + ... + ''' + moves = [[4, 6], + [6, 8], + [7, 9], + [4, 8], + [0, 3, 9], + [], + [0, 1, 7], + [2, 6], + [1, 3], + [2, 4]] + dp = [1] * 10 + for i in range(n - 1): + new_dp = [0] * 10 + for num, count in enumerate(dp): + for m in moves[num]: + new_dp[m] += count + dp = new_dp + return sum(dp) % (10 ** 9 + 7) + +# medium: https://www.lintcode.com/problem/1707 diff --git a/kth_largest_element.py b/kth-largest-element.py similarity index 100% rename from kth_largest_element.py rename to kth-largest-element.py diff --git a/kth-prime-number.py b/kth-prime-number.py new file mode 100644 index 0000000..30a0710 --- /dev/null +++ b/kth-prime-number.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param n: the number + @return: the rank of the number + """ + def kthPrime(self, n): + # write your code here + ret = 0 + judge = [0 for i in range(n + 1)] # [0, n] + for i in range(2, n + 1): + if judge[i] == 0: # 质数 + ret += 1 + j = 2 + while (i * j) < n: + judge[i * j] = 1 + j += 1 + return ret + +# easy: https://www.lintcode.com/problem/kth-prime-number/ diff --git a/kth-smallest-element-in-a-bst.py b/kth-smallest-element-in-a-bst.py new file mode 100644 index 0000000..393ea96 --- /dev/null +++ b/kth-smallest-element-in-a-bst.py @@ -0,0 +1,30 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the given BST + @param k: the given k + @return: the kth smallest element in BST + """ + def kthSmallest(self, root, k): + # write your code here + less = self.count(root.left) # 比root小的元素的数量 + if less == (k - 1): + return root.val + elif less < (k - 1): + return self.kthSmallest(root.right, k - less - 1) + else: + return self.kthSmallest(root.left, k) + + def count(self, root): + if not root: + return 0 + return 1 + self.count(root.left) + self.count(root.right) + +# medium: https://www.lintcode.com/problem/kth-smallest-element-in-a-bst/ diff --git a/kth_smallest_number_in_sorted_matrix.py b/kth-smallest-number-in-sorted-matrix.py similarity index 100% rename from kth_smallest_number_in_sorted_matrix.py rename to kth-smallest-number-in-sorted-matrix.py diff --git a/largest-letter.py b/largest-letter.py new file mode 100644 index 0000000..c1b8cb9 --- /dev/null +++ b/largest-letter.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param s: a string + @return: a string + """ + def largestLetter(self, s): + # write your code here + ret = 'NO' + cs = set([]) + for c in s: + cs.add(c) + for c in s: + if (c.lower() in cs) and (c.upper() in cs): + if ret == 'NO': + ret = c.upper() + else: + if c.upper() > ret: + ret = c.upper() + return ret + +# easy: https://www.lintcode.com/problem/largest-letter/ diff --git a/largest-number-at-least-twice-of-others.py b/largest-number-at-least-twice-of-others.py new file mode 100644 index 0000000..cfbbc05 --- /dev/null +++ b/largest-number-at-least-twice-of-others.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param nums: a integer array + @return: the index of the largest element + """ + def dominantIndex(self, nums): + # Write your code here + if len(nums) == 1: + return 0 + t_1, t_2 = nums[0], nums[1] + p_1, p_2 = 0, 1 + if t_1 < t_2: + t_1, t_2 = t_2, t_1 + p_1, p_2 = p_2, p_1 + for i in range(2, len(nums)): + if nums[i] > t_2: + t_2 = nums[i] + p_2 = i + if t_1 < t_2: + t_1, t_2 = t_2, t_1 + p_1, p_2 = p_2, p_1 + if t_1 >= (t_2 * 2): + return p_1 + else: + return -1 + +# easy: https://www.lintcode.com/problem/largest-number-at-least-twice-of-others/ diff --git a/largest-number-x-which-occurs-x-times.py b/largest-number-x-which-occurs-x-times.py new file mode 100644 index 0000000..0ada543 --- /dev/null +++ b/largest-number-x-which-occurs-x-times.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param arr: an array of integers + @return: return the biggest value X, which occurs in A exactly X times. + """ + def findX(self, arr): + # write your code here + ret = 0 + di = {} + for i in arr: + if i not in di: + di[i] = 0 + di[i] += 1 + for k, v in di.items(): + if k == v: + if k > ret: + ret = k + return ret + +# easy: https://www.lintcode.com/problem/largest-number-x-which-occurs-x-times/ diff --git a/largest_number.py b/largest-number.py similarity index 100% rename from largest_number.py rename to largest-number.py diff --git a/largest-palindrome-product.py b/largest-palindrome-product.py new file mode 100644 index 0000000..362762a --- /dev/null +++ b/largest-palindrome-product.py @@ -0,0 +1,39 @@ +class Solution: + """ + @param n: the number of digit + @return: the largest palindrome mod 1337 + """ + def largestPalindrome(self, n): + # write your code here + ''' + 改良暴力法 + n * n的最大回文数一定是2n位 + 从10 ^ (n - 1)到10 ^ n - 1作为前半部分,凑出整个回文数, + 然后做除法检查。 + 但是n = 8一定超时...所以算好了查表!!! + ''' + return [9,987,123,597,677,1218,877,475][n-1] + + ''' + def largestPalindrome(self, n): + self.low = pow(10, n - 1) + self.up = pow(10, n) + for i in range(self.up - 1, self.low - 1, -1): + x = self.to_palindrome(i) + j = self.up + while j * j >= x: + if (x % j) == 0: + return x % 1337 + j -= 1 + return 9 # n = 1的特殊情况 + + def to_palindrome(self, val): + ret = val * self.up + k = 0 + while val > 0: + k = k * 10 + (val % 10) + val = int(val / 10) + return ret + k + ''' + +# easy: https://www.lintcode.com/problem/largest-palindrome-product/ diff --git a/largest-subarray.py b/largest-subarray.py new file mode 100644 index 0000000..bbfb12b --- /dev/null +++ b/largest-subarray.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param A: the array + @param K: the length + @return: the largest subarray + """ + def largestSubarray(self, A, K): + # Write your code here. + ret = 0 + for i in range(1, len(A) - K + 1): + if cmp_array(A, i, ret, K) > 0: + ret = i + return A[ret:ret + K] + +def cmp_array(A, s_1, s_2, count): + i = 0 + while i < count: + if A[s_1 + i] < A[s_2 + i]: + return -1 + elif A[s_1 + i] > A[s_2 + i]: + return 1 + else: + i += 1 + return 0 + +# easy: https://www.lintcode.com/problem/largest-subarray/ diff --git a/largest-triangle-area.py b/largest-triangle-area.py new file mode 100644 index 0000000..2a2a6a8 --- /dev/null +++ b/largest-triangle-area.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param points: List[List[int]] + @return: return a double + """ + def largestTriangleArea(self, points): + # write your code here + ret = 0 + for i in range(len(points) - 2): + for j in range(i + 1, len(points) - 1): + for k in range(j + 1, len(points)): + area = 0.5 * abs(points[i][0] * points[j][1] \ + + points[j][0] * points[k][1] \ + + points[k][0] * points[i][1] \ + - points[i][1] * points[j][0] \ + - points[j][1] * points[k][0] \ + - points[k][1] * points[i][0]) + if area > ret: + ret = area + return ret + +# easy: https://www.lintcode.com/problem/largest-triangle-area/ diff --git a/last-position-of-target.py b/last-position-of-target.py new file mode 100644 index 0000000..ece40f0 --- /dev/null +++ b/last-position-of-target.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param nums: An integer array sorted in ascending order + @param target: An integer + @return: An integer + """ + def lastPosition(self, nums, target): + # write your code here + i, j = 0, len(nums) - 1 + while i < (j - 1): + m = int((i + j) / 2) + if nums[m] <= target: + i = m + else: + j = m + if j >= i: + if nums[j] == target: + return j + elif nums[i] == target: + return i + return -1 + +# easy: https://www.lintcode.com/problem/458 diff --git a/leaf-similar-trees.py b/leaf-similar-trees.py new file mode 100644 index 0000000..f87e79b --- /dev/null +++ b/leaf-similar-trees.py @@ -0,0 +1,33 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root1: the first tree + @param root2: the second tree + @return: returns whether the leaf sequence is the same + """ + def leafSimilar(self, root1, root2): + # write your code here. + r1, r2 = [], [] + self.dfs(r1, [root1]) + self.dfs(r2, [root2]) + return r1 == r2 + + def dfs(self, leafs, nodes): + while nodes: + node = nodes.pop() + if not (node.left or node.right): + leafs.append(node.val) + else: + if node.left: + nodes.append(node.left) + if node.right: + nodes.append(node.right) + +# easy: https://www.lintcode.com/problem/leaf-similar-trees/ diff --git a/leap-year.py b/leap-year.py new file mode 100644 index 0000000..584f0d1 --- /dev/null +++ b/leap-year.py @@ -0,0 +1,13 @@ +class Solution: + """ + @param n: a number represent year + @return: whether year n is a leap year. + """ + def isLeapYear(self, n): + # write your code here + if n % 400 == 0: + return True + else: + return (n % 4 == 0) and (n % 100 != 0) + +# easy: https://www.lintcode.com/problem/leap-year diff --git a/left_pad.py b/left-pad.py similarity index 100% rename from left_pad.py rename to left-pad.py diff --git a/legal-number-statistics-ii.py b/legal-number-statistics-ii.py new file mode 100644 index 0000000..8304231 --- /dev/null +++ b/legal-number-statistics-ii.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param a: the array a + @param q: the queries q + @return: for each query, return the number of legal integers + """ + def getAns(self, a, q): + # write your code here + ret = [] + for _q in q: + ret.append(0) + for i in a: + if (i >= _q[0]) and (i <= _q[1]): + ret[-1] += 1 + return ret + +# easy: https://www.lintcode.com/problem/legal-number-statistics-ii/ diff --git a/legal-number-statistics.py b/legal-number-statistics.py new file mode 100644 index 0000000..95d679e --- /dev/null +++ b/legal-number-statistics.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param a: the array a + @param L: the integer L + @param R: the integer R + @return: Return the number of legal integers + """ + def getNum(self, a, L, R): + # Write your code here + ret = 0 + for i in a: + if (i >= L) and (i <= R): + ret += 1 + return ret + +# easy: https://www.lintcode.com/problem/legal-number-statistics/ diff --git a/lemonade-change.py b/lemonade-change.py new file mode 100644 index 0000000..795ebe2 --- /dev/null +++ b/lemonade-change.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param bills: the Bill + @return: Return true if and only if you can provide every customer with correct change. + """ + def lemonadeChange(self, bills): + # Write your code here. + # 对于20,优先用10 + 5,不行再用5 * 3。 + count_5, count_10 = 0, 0 + for b in bills: + if b == 5: + count_5 += 1 + elif b == 10: + count_10 += 1 # 收进一张10元 + count_5 -= 1 # 找出一张5元 + else: # 20,另外20不能用于找零 + if count_10: + count_10 -= 1 + count_5 -= 1 + else: + count_5 -= 3 + if count_5 < 0: # 5元不够用 + return False + return True + +# easy: https://www.lintcode.com/problem/lemonade-change/ diff --git a/length_of_last_word.py b/length-of-last-word.py similarity index 100% rename from length_of_last_word.py rename to length-of-last-word.py diff --git a/letter-case-permutation.py b/letter-case-permutation.py new file mode 100644 index 0000000..fac3821 --- /dev/null +++ b/letter-case-permutation.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param S: a string + @return: return a list of strings + """ + def letterCasePermutation(self, S): + # write your code here + if not S: + return [''] + ret = [] + perms = self.letterCasePermutation(S[1:]) + for perm in perms: + if self.is_digit(S[0]): + ret.append(S[0] + perm) + else: + ret.append(S[0].lower() + perm) + ret.append(S[0].upper() + perm) + return ret + + def is_digit(self, c): + return c in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] + +# easy: https://www.lintcode.com/problem/letter-case-permutation/ diff --git a/letter_combinations_of_a_phone_number.py b/letter-combinations-of-a-phone-number.py similarity index 100% rename from letter_combinations_of_a_phone_number.py rename to letter-combinations-of-a-phone-number.py diff --git a/license-key-formatting.py b/license-key-formatting.py new file mode 100644 index 0000000..1eedf95 --- /dev/null +++ b/license-key-formatting.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param S: a string + @param K: a integer + @return: return a string + """ + def licenseKeyFormatting(self, S, K): + # write your code here + ret = [] + count = 0 + for i in range(len(S) - 1, -1, -1): + if S[i] != '-': + count += 1 + ret.append(S[i].upper()) + if (count % K) == 0: + ret.append('-') + if ret[-1] == '-': + ret.pop() + ret.reverse() + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/license-key-formatting/ diff --git a/linked_list_cycle_ii.py b/linked-list-cycle-ii.py similarity index 100% rename from linked_list_cycle_ii.py rename to linked-list-cycle-ii.py diff --git a/linked_list_cycle.py b/linked-list-cycle.py similarity index 100% rename from linked_list_cycle.py rename to linked-list-cycle.py diff --git a/linked-list-simplification.py b/linked-list-simplification.py new file mode 100644 index 0000000..5ccf988 --- /dev/null +++ b/linked-list-simplification.py @@ -0,0 +1,36 @@ +""" +Definition of ListNode +class ListNode(object): + def __init__(self, val, next=None): + self.val = val + self.next = next +""" + +class Solution: + """ + @param head: the linked list to be simplify. + @return: return the linked list after simplifiction. + """ + def simplify(self, head): + # write your code here + if not head: + return head + tail = head + size = 1 + while tail.next: + size += 1 + tail = tail.next + if size <= 2: + size = '' + else: + size = str(size - 2) + new_tail = head + for c in size: + node = ListNode(str(ord(c))) + new_tail.next = node + new_tail = node + if tail != head: + new_tail.next = tail + return head + +# easy: https://www.lintcode.com/problem/linked-list-simplification/ diff --git a/load-balancer.py b/load-balancer.py new file mode 100644 index 0000000..0ceda34 --- /dev/null +++ b/load-balancer.py @@ -0,0 +1,40 @@ +import random + +class LoadBalancer: + def __init__(self): + # do intialization if necessary + self.di = {} + self.servers = [] + self.n = 0 + + """ + @param: server_id: add a new server to the cluster + @return: nothing + """ + def add(self, server_id): + # write your code here + self.di[server_id] = self.n + self.servers.append(server_id) + self.n += 1 + + """ + @param: server_id: server_id remove a bad server from the cluster + @return: nothing + """ + def remove(self, server_id): + # write your code here + i = self.di[server_id] + if i != (self.n - 1): + last_server_id = self.servers[-1] + self.servers[i] = last_server_id + self.di[last_server_id] = i + del self.di[server_id] + self.servers.pop() + self.n -= 1 + + """ + @return: pick a server in the cluster randomly with equal probability + """ + def pick(self): + # write your code here + return self.servers[random.randint(0, len(self.servers) - 1)] diff --git a/longest-ab-substring.py b/longest-ab-substring.py new file mode 100644 index 0000000..15a24b6 --- /dev/null +++ b/longest-ab-substring.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param S: a String consists of a and b + @return: the longest of the longest string that meets the condition + """ + def getAns(self, S): + # Write your code here + r = 0 + diff = 0 + diffs = [] + pos = {} + for i in range(len(S)): + if S[i] == 'A': + diff += 1 + else: + diff -= 1 + diffs.append(diff) + pos[diff] = i + for i in range(len(S)): + if diffs[i] != 0: + if r <= pos[diffs[i]] - i: + r = pos[diffs[i]] - i + if 0 in pos: + if (pos[0] + 1) > r: + r = pos[0] + 1 + return r diff --git a/longest_common_prefix.py b/longest-common-prefix.py similarity index 100% rename from longest_common_prefix.py rename to longest-common-prefix.py diff --git a/longest_common_subsequence.py b/longest-common-subsequence.py similarity index 96% rename from longest_common_subsequence.py rename to longest-common-subsequence.py index b2839c0..6c2b301 100644 --- a/longest_common_subsequence.py +++ b/longest-common-subsequence.py @@ -25,4 +25,4 @@ def _longestCommonSubsequence(self, A, B, start_a, start_b): _len = self._longestCommonSubsequence(A, B, start_a + 1, start_b + 1) self.ret = max(_len + 1, self.ret) self.cache[start_a][start_b] = _len + 1 - return self.cache[start_a][start_b] \ No newline at end of file + return self.cache[start_a][start_b] diff --git a/longest_common_substring.py b/longest-common-substring.py similarity index 100% rename from longest_common_substring.py rename to longest-common-substring.py diff --git a/longest_consecutive_sequence.py b/longest-consecutive-sequence.py similarity index 100% rename from longest_consecutive_sequence.py rename to longest-consecutive-sequence.py diff --git a/longest-harmonious-subsequence.py b/longest-harmonious-subsequence.py new file mode 100644 index 0000000..99778dc --- /dev/null +++ b/longest-harmonious-subsequence.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param nums: a list of integers + @return: return a integer + """ + def findLHS(self, nums): + # write your code here + # 先排序,最大/最小值之差为1,所以第一个元素定了,后面的值也就限制了。 + ret = 0 + nums.sort() + start, new_start = 0, 0 + for i in range(1, len(nums)): + if (nums[i] - nums[start]) > 1: # 判断是否在约束范围 + start = new_start + if nums[i] != nums[i - 1]: + new_start = i # 有机会作为新的开始,因为如果相等就不可能有更长的子序列。 + if (nums[i] - nums[start]) == 1: # [start, i]满足和谐子序列要求 + ret = max(ret, i - start + 1) + return ret + +# easy: https://www.lintcode.com/problem/longest-harmonious-subsequence/ diff --git a/longest_increasing_continuous_subsequence.py b/longest-increasing-continuous-subsequence.py similarity index 100% rename from longest_increasing_continuous_subsequence.py rename to longest-increasing-continuous-subsequence.py diff --git a/longest_increasing_subsequence.py b/longest-increasing-subsequence.py similarity index 100% rename from longest_increasing_subsequence.py rename to longest-increasing-subsequence.py diff --git a/longest-lighting-time.py b/longest-lighting-time.py new file mode 100644 index 0000000..b18f4ec --- /dev/null +++ b/longest-lighting-time.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param operation: A list of operations. + @return: The lamp has the longest liighting time. + """ + def longestLightingTime(self, operation): + # write your code here + ret = 0 + lst = 0 + pt = 0 + for op in operation: + t = op[1] - pt + if t > lst: + lst = t + ret = op[0] + pt = op[1] + return chr(ord('a') + ret) + +# easy: https://www.lintcode.com/problem/longest-lighting-time/ diff --git a/longest-palindrome.py b/longest-palindrome.py new file mode 100644 index 0000000..40f1142 --- /dev/null +++ b/longest-palindrome.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param s: a string which consists of lowercase or uppercase letters + @return: the length of the longest palindromes that can be built + """ + def longestPalindrome(self, s): + # write your code here + ret = 0 + odd = False + di = {} + for c in s: + if c in di: + di[c] += 1 + else: + di[c] = 1 + for k, v in di.items(): + if v % 2 == 0: + ret += v + else: + odd = True + if v > 1: + ret += (v - 1) + if odd: + ret += 1 + return ret + +# easy: https://www.lintcode.com/problem/longest-palindrome/ diff --git a/longest-palindromic-substring.py b/longest-palindromic-substring.py new file mode 100644 index 0000000..a8418f6 --- /dev/null +++ b/longest-palindromic-substring.py @@ -0,0 +1,31 @@ +def find_longest_alindrome(s, start, end): + ret = [0, None, None] + while (start >= 0) and (end < len(s)): + if s[start] == s[end]: + ret[0] = end - start + 1 + ret[1], ret[2] = start, end + start -= 1 + end += 1 + else: + break + return ret + +class Solution: + """ + @param s: input string + @return: the longest palindromic substring + """ + def longestPalindrome(self, s): + # write your code here + # 有O(n)的算法,不过复杂到难以理解,先弃坑了... + ret = [0, 0, 1] + for i in range(len(s)): + r1 = find_longest_alindrome(s, i, i) + r2 = find_longest_alindrome(s, i, i + 1) + if r1[0] > ret[0]: + ret = r1 + if r2[0] > ret[0]: + ret = r2 + return s[ret[1]:ret[2] + 1] + +# medium: https://www.lintcode.com/problem/longest-palindromic-substring/ diff --git a/longest-prefix-of-array.py b/longest-prefix-of-array.py new file mode 100644 index 0000000..6c9525b --- /dev/null +++ b/longest-prefix-of-array.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param X: a integer + @param Y: a integer + @param nums: a list of integer + @return: return the maximum index of largest prefix + """ + def LongestPrefix(self, X, Y, nums): + # write your code here + ret = -1 + cx = 0 + cy = 0 + for i in range(len(nums)): + v = nums[i] + if v == X: + cx += 1 + if v == Y: + cy += 1 + if (cx > 0) and (cx == cy): + ret = i + return ret + +# easy: https://www.lintcode.com/problem/longest-prefix-of-array/ diff --git a/longest-semi-alternating-substring.py b/longest-semi-alternating-substring.py new file mode 100644 index 0000000..1aade34 --- /dev/null +++ b/longest-semi-alternating-substring.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param s: the string + @return: length of longest semi alternating substring + """ + def longestSemiAlternatingSubstring(self, s): + # write your code here + if not s: + return 0 + ret = [] + count = 1 + s += ' ' # 方便处理结束位置 + ss = s[0] # 初始化子串第一个字符 + for i in range(1, len(s)): + if s[i] != s[i - 1]: + if count >= 3: + j = count - 2 # ??? + ret.append(len(ss[:-j])) #因为之前重复次数会大于3,所以重复的字最多保留2个。 + ss = s[i - 1] * 2 # 重新初始ss,也就是最近的两个重复字符开始。 + elif s[i] == ' ': + ret.append(len(ss)) + count = 1 # 重新计数 + else: + count += 1 # 更新连续出现字符长度 + ss += s[i] + return max(ret) + +# easy: https://www.lintcode.com/problem/longest-semi-alternating-substring/ diff --git a/longest-string-chain.py b/longest-string-chain.py new file mode 100644 index 0000000..c53c5fc --- /dev/null +++ b/longest-string-chain.py @@ -0,0 +1,48 @@ +class Solution: + """ + @param words: the list of word. + @return: the length of the longest string chain. + """ + def longestStrChain(self, words): + # + di = {} + for w in words: + i = len(w) + if i not in di: + di[i] = [] + di[i].append(w) + levels = [[], []] + curr = 0 + start_len = 1 + l = 1 # 字符串链长度,最小为1。 + while start_len <= 1000: # 根据条件,一定有结果的。 + if start_len in di: + levels[curr] = di[start_len] + break + start_len += 1 + while levels[curr]: + next_words = [] + if (start_len + l) in di: # 判断能否扩展 + next_words = di[start_len + l] + for w in levels[curr]: + for nw in next_words: + chars = {} + for c in w: + if c not in chars: + chars[c] = 0 + chars[c] += 1 + for c in nw: + if c not in chars: + chars[c] = 0 + chars[c] -= 1 + diff = 0 + for v in chars.values(): + diff += abs(v) + if diff == 1: + levels[curr ^ 1].append(nw) + levels[curr] = [] + curr ^= 1 + l += 1 + return l - 1 + +# medium: https://www.lintcode.com/problem/longest-string-chain/ diff --git a/longest_substring_without_repeating_characters.py b/longest-substring-without_repeating-characters.py similarity index 100% rename from longest_substring_without_repeating_characters.py rename to longest-substring-without_repeating-characters.py diff --git a/longest-uncommon-subsequence-i.py b/longest-uncommon-subsequence-i.py new file mode 100644 index 0000000..059537e --- /dev/null +++ b/longest-uncommon-subsequence-i.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param a: a string + @param b: a string + @return: return a integer + """ + def findLUSlength(self, a, b): + # write your code here + ''' + 如果a包含b,替换为''; + 如果b包含a,替换为''。 + ''' + l1 = a.replace(b,'') + l2 = b.replace(a,'') + return max(len(l1), len(l2)) if max(len(l1), len(l2)) != 0 else -1 + +# easy: https://www.lintcode.com/problem/longest-uncommon-subsequence-i/ diff --git a/longest-univalue-path.py b/longest-univalue-path.py new file mode 100644 index 0000000..8e0cc2f --- /dev/null +++ b/longest-univalue-path.py @@ -0,0 +1,39 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: + @return: the length of the longest path where each node in the path has the same value + """ + def longestUnivaluePath(self, root): + # Write your code here + ''' + 就像网友所说,这题easy难度的确是膨胀了... + 简说下思路: + 1. 5-5-5路径长度是2,5路径长度是0。 + 2. 要处理2种情况:1)路径不经过当前节点;2)路径经过当前节点。 + ''' + self.ret = 0 + self._longestUnivaluePath(root) + return self.ret + + def _longestUnivaluePath(self, node): + if not node: + return 0 + ll = self._longestUnivaluePath(node.left) + lr = self._longestUnivaluePath(node.right) + to_left, to_right = 0, 0 + if node.left and (node.left.val == node.val): + to_left = ll + 1 + if node.right and (node.right.val == node.val): + to_right = lr + 1 + self.ret = max(self.ret, to_left + to_right) # 处理左到右经过当前节点的情况 + return max(to_left, to_right) # 处理需要继续向上的情况 + +# https://www.lintcode.com/problem/longest-univalue-path/ diff --git a/longest-valid-parentheses.py b/longest-valid-parentheses.py new file mode 100644 index 0000000..4751b5c --- /dev/null +++ b/longest-valid-parentheses.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param s: a string + @return: return a integer + """ + def longestValidParentheses(self, s): + # write your code here + ret = 0 + start = 0 + stack = [] + for i in range(len(s)): + if s[i] == '(': + stack.append(i) + else: + if not stack: + start = i + 1 # 重要,因为必须从'('开始。 + else: + stack.pop() + if not stack: + # 必须与上一次结果合并 + ret = max(ret, i - start + 1) + else: + # 因为pop了,不需要再加1。 + ret = max(ret, i - stack[-1]) + return ret + +# easy: https://www.lintcode.com/problem/longest-valid-parentheses/ diff --git a/longest-word-in-dictionary.py b/longest-word-in-dictionary.py new file mode 100644 index 0000000..2c51587 --- /dev/null +++ b/longest-word-in-dictionary.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param words: a list of strings + @return: the longest word in words that can be built one character at a time by other words in words + """ + def longestWord(self, words): + # Write your code here + ret = [-1, None] + s = set(words) + for word in words: + i = len(word) + while i > 0: + if word[:i] not in s: + break + i -= 1 + if i == 0: + if len(word) > ret[0]: + ret = [len(word), word] + elif len(word) == ret[0]: + if word < ret[1]: + ret[1] = word + return ret[1] + +# easy: https://www.lintcode.com/problem/longest-word-in-dictionary/ diff --git a/longest_words.py b/longest-words.py similarity index 100% rename from longest_words.py rename to longest-words.py diff --git a/look-for-points-that-are-bigger-than-the-surrounding-area.py b/look-for-points-that-are-bigger-than-the-surrounding-area.py new file mode 100644 index 0000000..7d80950 --- /dev/null +++ b/look-for-points-that-are-bigger-than-the-surrounding-area.py @@ -0,0 +1,42 @@ +class Solution: + """ + @param grid: a matrix + @return: Find all points that are strictly larger than their neighbors + """ + def highpoints(self, grid): + # write your code here + rows = len(grid) + cols = len(grid[0]) + marks = [[-1] * cols for _ in range(rows)] + for r in range(rows): + for c in range(cols): + if marks[r][c] == -1: + if self.check_and_mark(grid, marks, r, c, r - 1, c): # 上 + continue + if self.check_and_mark(grid, marks, r, c, r + 1, c): # 下 + continue + if self.check_and_mark(grid, marks, r, c, r, c - 1): # 左 + continue + if self.check_and_mark(grid, marks, r, c, r, c + 1): # 右 + continue + if self.check_and_mark(grid, marks, r, c, r - 1, c - 1): # 左上 + continue + if self.check_and_mark(grid, marks, r, c, r + 1, c - 1): # 左下 + continue + if self.check_and_mark(grid, marks, r, c, r - 1, c + 1): # 右上 + continue + if self.check_and_mark(grid, marks, r, c, r + 1, c + 1): # 右下 + continue + marks[r][c] = 1 + return marks + + def check_and_mark(self, grid, marks, r1, c1, r2, c2): + rows = len(grid) + cols = len(grid[0]) + if ((r2 >= 0) and (r2 < rows)) and ((c2 >= 0) and (c2 < cols)): + if grid[r1][c1] <= grid[r2][c2]: + marks[r1][c1] = 0 + return True + return False + +# easy: https://www.lintcode.com/problem/look-for-points-that-are-bigger-than-the-surrounding-area/ diff --git a/lowest-common-ancestor-ii.py b/lowest-common-ancestor-ii.py new file mode 100644 index 0000000..e65b7cb --- /dev/null +++ b/lowest-common-ancestor-ii.py @@ -0,0 +1,29 @@ +""" +Definition of ParentTreeNode: +class ParentTreeNode: + def __init__(self, val): + self.val = val + self.parent, self.left, self.right = None, None, None +""" + + +class Solution: + """ + @param: root: The root of the tree + @param: A: node in the tree + @param: B: node in the tree + @return: The lowest common ancestor of A and B + """ + def lowestCommonAncestorII(self, root, A, B): + # write your code here + s = set([]) + while A: + s.add(A) + A = A.parent + while B: + if B in s: + return B + B = B.parent + return None + +# easy: https://www.lintcode.com/problem/lowest-common-ancestor-ii/ diff --git a/lowest-common-ancestor-of-a-binary-search-tree.py b/lowest-common-ancestor-of-a-binary-search-tree.py new file mode 100644 index 0000000..6356b5a --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree.py @@ -0,0 +1,24 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: root of the tree + @param p: the node p + @param q: the node q + @return: find the LCA of p and q + """ + def lowestCommonAncestor(self, root, p, q): + # write your code here + if root.val > max(p.val, q.val): + return self.lowestCommonAncestor(root.left, p, q) + elif root.val < min(p.val, q.val): + return self.lowestCommonAncestor(root.right, p, q) + return root + +# easy: https://www.lintcode.com/problem/lowest-common-ancestor-of-a-binary-search-tree/ diff --git a/lowest_common_ancestor.py b/lowest-common-ancestor.py similarity index 100% rename from lowest_common_ancestor.py rename to lowest-common-ancestor.py diff --git a/lucky-number-eight.py b/lucky-number-eight.py new file mode 100644 index 0000000..379ae14 --- /dev/null +++ b/lucky-number-eight.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param n: count lucky numbers from 1 ~ n + @return: the numbers of lucky number + """ + def luckyNumber(self, n): + # Write your code here + ret = 0 + for i in range(8, n + 1): + e = False + while i > 0: + if (i % 10) == 8: + e = True + break + else: + i = int(i / 10) + if e: + ret += 1 + return ret + +# easy: https://www.lintcode.com/problem/lucky-number-eight/ diff --git a/majority_number_ii.py b/majority-number-ii.py similarity index 100% rename from majority_number_ii.py rename to majority-number-ii.py diff --git a/majority_number_iii.py b/majority-number-iii.py similarity index 100% rename from majority_number_iii.py rename to majority-number-iii.py diff --git a/majority_number.py b/majority-number.py similarity index 100% rename from majority_number.py rename to majority-number.py diff --git a/makeequilateraltriangle.py b/makeequilateraltriangle.py new file mode 100644 index 0000000..6b52e91 --- /dev/null +++ b/makeequilateraltriangle.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param lengths: the lengths of sticks at the beginning. + @return: return the minimum number of cuts. + """ + def makeEquilateralTriangle(self, lengths): + # write your code here. + ret = 2 + s = set(lengths) + lengths.sort() + for i in range(len(lengths) - 2): + i1 = lengths[i] + i2 = lengths[i + 1] + i3 = lengths[i + 2] + if (i1 == i2) and (i2 == i3): + return 0 + elif (i1 == i2) or (i2 == i3) or ((i1 * 2) in s): + ret = 1 + return ret + +# easy: https://www.lintcode.com/problem/makeequilateraltriangle/ diff --git a/matching-of-parentheses.py b/matching-of-parentheses.py new file mode 100644 index 0000000..ccd7d03 --- /dev/null +++ b/matching-of-parentheses.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param string: A string + @return: whether the string is a valid parentheses + """ + def matchParentheses(self, string): + # write your code here + s = [] + for c in string: + if c == '(': + s.append(c) + else: + if s and (s[-1] == '('): + s.pop() + else: + return False + return not s + +# easy: https://www.lintcode.com/problem/matching-of-parentheses/ diff --git a/matrix-game.py b/matrix-game.py new file mode 100644 index 0000000..f4d8971 --- /dev/null +++ b/matrix-game.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param grids: a integer matrix + @return: return the difference between two people at last. + """ + def MatrixGame(self, grids): + # write your code here + if not grids: + return 0 + ms = [] + for c in range(len(grids[0])): + m = grids[0][c] + for r in range(1, len(grids)): + if grids[r][c] > m: + m = grids[r][c] + ms.append(m) + ms.sort() + r = 0 + af = True + for i in range(len(ms) - 1, -1, -1): + if af: + r += ms[i] + else: + r -= ms[i] + af = not af + return abs(r) + +# easy: https://www.lintcode.com/problem/1421/ diff --git a/matrix_zigzag_traversal.py b/matrix-zigzag-traversal.py similarity index 100% rename from matrix_zigzag_traversal.py rename to matrix-zigzag-traversal.py diff --git a/max-area-of-island.py b/max-area-of-island.py new file mode 100644 index 0000000..0ea8a63 --- /dev/null +++ b/max-area-of-island.py @@ -0,0 +1,31 @@ +def getArea(grid, row, col, area): + if (row >= 0) and (row < len(grid)) and \ + (col >= 0) and (col < len(grid[0])) and \ + (grid[row][col] == 1): + grid[row][col] = 0 + area += 1 + area = getArea(grid, row - 1, col, area) # 上 + area = getArea(grid, row + 1, col, area) # 下 + area = getArea(grid, row, col - 1, area) # 左 + area = getArea(grid, row, col + 1, area) # 右 + return area + +class Solution: + """ + @param grid: a 2D array + @return: the maximum area of an island in the given 2D array + """ + def maxAreaOfIsland(self, grid): + # Write your code here + ret = 0 + if len(grid) == 0: + return ret + for i in range(len(grid)): + for j in range(len(grid[0])): + if grid[i][j] == 1: + area = getArea(grid, i, j, 0) + if area > ret: + ret = area + return ret + +# easy: https://www.lintcode.com/problem/max-area-of-island/ diff --git a/max-consecutive-ones.py b/max-consecutive-ones.py new file mode 100644 index 0000000..1b8efa0 --- /dev/null +++ b/max-consecutive-ones.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param nums: a binary array + @return: the maximum number of consecutive 1s + """ + def findMaxConsecutiveOnes(self, nums): + # Write your code here + ret = 0 + count = 0 + for i in nums: + if i == 0: + if count > 0: + if count > ret: + ret = count + count = 0 + else: + count += 1 + return max(ret, count) + +# easy: https://www.lintcode.com/problem/max-consecutive-ones/ diff --git a/max_points_on_a_line.py b/max-points-on-a-line.py similarity index 100% rename from max_points_on_a_line.py rename to max-points-on-a-line.py diff --git a/maximal_rectangle.py b/maximal-rectangle.py similarity index 100% rename from maximal_rectangle.py rename to maximal-rectangle.py diff --git a/maximal_square.py b/maximal-square.py similarity index 100% rename from maximal_square.py rename to maximal-square.py diff --git a/maximize-distance-to-closest-person.py b/maximize-distance-to-closest-person.py new file mode 100644 index 0000000..d730cbd --- /dev/null +++ b/maximize-distance-to-closest-person.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param seats: an array + @return: the maximum distance + """ + def maxDistToClosest(self, seats): + # Write your code here. + ret = 0 + prev = -1 + mid, head, tail = -1, -1, -1 + for i in range(len(seats)): + if seats[i] != 0: + if prev != -1: + mid = max(mid, i - prev - 1) + else: + head = i + prev = i + if prev != (len(seats) - 1): + tail = len(seats) - prev - 1 # 因为至少1个1 + return max(int((mid + 1) / 2), head, tail) + +# easy: https://www.lintcode.com/problem/maximize-distance-to-closest-person/ diff --git a/maximum-and-minimum.py b/maximum-and-minimum.py new file mode 100644 index 0000000..3e24251 --- /dev/null +++ b/maximum-and-minimum.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param matrix: an input matrix + @return: nums[0]: the maximum,nums[1]: the minimum + """ + def maxAndMin(self, matrix): + # write your code here + if not matrix: + return [] + r = [matrix[0][0], matrix[0][0]] + for row in matrix: + for i in row: + if i > r[0]: # 确保max在前min在后 + r[0] = i + elif i < r[1]: + r[1] = i + return r + +# easy: https://www.lintcode.com/problem/maximum-and-minimum diff --git a/maximum-average-score.py b/maximum-average-score.py new file mode 100644 index 0000000..bd2477d --- /dev/null +++ b/maximum-average-score.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param names: the name + @param grades: the grade + @return: the maximum average score + """ + def maximumAverageScore(self, names, grades): + # Write your code here + ret = 0 + di = {} + for i in range(len(names)): + if names[i] not in di: + di[names[i]] = [grades[i], 1] + else: + di[names[i]][0] += grades[i] + di[names[i]][1] += 1 + for k, v in di.items(): + if (v[0] / v[1]) > ret: + ret = v[0] / v[1] + return float('%.2f' % (ret)) + +# easy: https://www.lintcode.com/problem/maximum-average-score/ diff --git a/maximum_average_subarray.py b/maximum-average-subarray-ii.py similarity index 96% rename from maximum_average_subarray.py rename to maximum-average-subarray-ii.py index b92cc9a..945b1d9 100644 --- a/maximum_average_subarray.py +++ b/maximum-average-subarray-ii.py @@ -43,4 +43,4 @@ def _search(self, nums, k, mid): bar = min(bar, sums[i - k + 1]) return False -# medium: http://lintcode.com/zh-cn/problem/maximum-average-subarray/ +# medium: https://www.lintcode.com/problem/maximum-average-subarray-ii/ diff --git a/maximum-average-subarray.py b/maximum-average-subarray.py new file mode 100644 index 0000000..83b0e23 --- /dev/null +++ b/maximum-average-subarray.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param nums: an array + @param k: an integer + @return: the maximum average value + """ + def findMaxAverage(self, nums, k): + # Write your code here + ret = sum(nums[:k]) + avg = ret + i = 1 + while i < len(nums) - k + 1: + avg = avg - nums[i - 1] + nums[i + k - 1] + if avg > ret: + ret = avg + i += 1 + return ret / k + +# easy: https://www.lintcode.com/problem/maximum-average-subarray/ diff --git a/maximum-binary-tree.py b/maximum-binary-tree.py new file mode 100644 index 0000000..5bb085d --- /dev/null +++ b/maximum-binary-tree.py @@ -0,0 +1,35 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param nums: an array + @return: the maximum tree + """ + def constructMaximumBinaryTree(self, nums): + # Write your code here + return self._constructMaximumBinaryTree(nums, 0, len(nums) - 1) + + def _constructMaximumBinaryTree(self, nums, start, end): + if start > end: + return None + elif start == end: + return TreeNode(nums[start]) + else: + _max = nums[start] + idx = start + for i in range(start + 1, end + 1): + if nums[i] > _max: + _max = nums[i] + idx = i + ret = TreeNode(_max) + ret.left = self._constructMaximumBinaryTree(nums, start, idx - 1) + ret.right = self._constructMaximumBinaryTree(nums, idx + 1, end) + return ret + +# easy: https://www.lintcode.com/problem/maximum-binary-tree/ diff --git a/maximum_depth_of_binary_tree.py b/maximum-depth-of-binary-tree.py similarity index 100% rename from maximum_depth_of_binary_tree.py rename to maximum-depth-of-binary-tree.py diff --git a/maximum-gap.py b/maximum-gap.py new file mode 100644 index 0000000..d44c8bd --- /dev/null +++ b/maximum-gap.py @@ -0,0 +1,44 @@ +class Solution: + """ + @param nums: an array of integers + @return: the maximun difference + """ + def maximumGap(self, nums): + # write your code here + # 不排序的话得参考鸽笼原理。 + # 如果有n个数,那么根据平均距离把数据分段, + # 那么最大值一定是某个区间的最小值减去上个区间的最大值(一定相邻)。 + # 为什么不在一个区间内呢?鸽笼原理的限制。 + # 下面有一些技巧性的处理:因为要分区间,所以即使有2个数也要拆到2个区间。 + # 以下数据举例:[1, 3, 4, 8, 10, 12],进行以下处理: + # - 平均间隔:(12 - 1) / (6 - 1) = 2.2,向下取整为2。 + # - 那么可以用这个公式:int((12 - 1) / 6) + 1 = 2 + # 如果是递增数列[1, 3, 5, 7, 9]那么上面两个公式是等价的: + # - (9 - 1) / (5 - 1) = 2 + # - int((9 - 1) / 5) + 1 = 2 + # 根据期望长度(实际平均长度不小于这个值),我们可以对数据进行分段。 + ret = 0 + if len(nums) >= 2: + _min, _max = min(nums), max(nums) + size = int((_max - _min) / len(nums)) + 1 # 这两个处理比较有技巧性 + buckets = int((_max - _min) / size) + 1 + min_bucket = [_max + 1] * buckets + max_bucket = [_min - 1] * buckets + for i in nums: + idx = int((i - _min) / size) + min_bucket[idx] = min(i, min_bucket[idx]) + max_bucket[idx] = max(i, max_bucket[idx]) + idx = 0 + while idx < buckets: + while max_bucket[idx] == (_min - 1): # 不用担心越界 + idx += 1 + idx_2 = idx + 1 + if idx_2 >= buckets: + break + while min_bucket[idx_2] == (_max + 1): + idx_2 += 1 + ret = max(ret, min_bucket[idx_2] - max_bucket[idx]) + idx = idx_2 + return ret + +# medium: https://www.lintcode.com/problem/maximum-gap/ diff --git a/maximum-moment.py b/maximum-moment.py new file mode 100644 index 0000000..093f726 --- /dev/null +++ b/maximum-moment.py @@ -0,0 +1,25 @@ +class Solution: + """ + @param time: a string of Time + @return: The MaximumMoment + """ + def MaximumMoment(self, time: str) -> str: + # Write your code here. + r = list(time) + if r[4] == '?': + r[4] = '9' + if r[3] == '?': + r[3] = '5' + if r[0] == '?': + if (r[1] == '?') or (r[1] <= '3'): + r[0] = '2' + else: + r[0] = '1' + if r[1] == '?': + if (r[0] == '0') or(r[0] == '1'): + r[1] = '9' + if r[0] == '2': + r[1] = '3' + return ''.join(r) + +# easy: https://www.lintcode.com/problem/1871/ diff --git a/maximum-non-negative-subarray.py b/maximum-non-negative-subarray.py new file mode 100644 index 0000000..6df4ad2 --- /dev/null +++ b/maximum-non-negative-subarray.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param A: an integer array + @return: return maxium contiguous non-negative subarray sum + """ + def maxNonNegativeSubArray(self, A): + # write your code here + ret = -1 + s = 0 + for i in A: + if i >= 0: + s += i + if s > ret: + ret = s + else: + s = 0 + return ret + +# easy: https://www.lintcode.com/problem/maximum-non-negative-subarray/ diff --git a/maximum-product-of-three-numbers.py b/maximum-product-of-three-numbers.py new file mode 100644 index 0000000..614234b --- /dev/null +++ b/maximum-product-of-three-numbers.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param nums: an integer array + @return: the maximum product + """ + def maximumProduct(self, nums): + # Write your code here + ''' + 其实不用考虑正负号的情,先排序,然后比以下两种情况: + 1. 最大的3个数相乘 + 2. 最小的两数承最大的数 + ''' + nums.sort() + return max(nums[0] * nums[1] * nums[-1], nums[-1] * nums[-2] * nums[-3]) + +# easy: https://www.lintcode.com/problem/maximum-product-of-three-numbers/description diff --git a/maximum_product_subarray.py b/maximum-product-subarray.py similarity index 100% rename from maximum_product_subarray.py rename to maximum-product-subarray.py diff --git a/maximum-product.py b/maximum-product.py new file mode 100644 index 0000000..9864e06 --- /dev/null +++ b/maximum-product.py @@ -0,0 +1,13 @@ +class Solution: + """ + @param nums: Unordered array + @return: return the largest product + """ + def MaximumProduct(self, nums): + # write your code here + nums.sort() + if len(nums) < 3: + return 0 + return max( nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1]) + +# medium: https://www.lintcode.com/problem/maximum-product/ diff --git a/maximum_subarray_difference.py b/maximum-subarray-difference.py similarity index 100% rename from maximum_subarray_difference.py rename to maximum-subarray-difference.py diff --git a/maximum_subarray_ii.py b/maximum-subarray-ii.py similarity index 100% rename from maximum_subarray_ii.py rename to maximum-subarray-ii.py diff --git a/maximum_subarray.py b/maximum-subarray.py similarity index 100% rename from maximum_subarray.py rename to maximum-subarray.py diff --git a/maximum-subtree.py b/maximum-subtree.py new file mode 100644 index 0000000..32385e6 --- /dev/null +++ b/maximum-subtree.py @@ -0,0 +1,34 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root of binary tree + @return: the maximum weight node + """ + def findSubtree(self, root): + # write your code here + ret = None + if root: + di = {None: 0} + self.sum(root, di) + s = 0 + for k, v in di.items(): + if v >= s: + s = v + ret = k + return ret + + def sum(self, root, di): + if not root: + return 0 + if root not in di: + di[root] = self.sum(root.left, di) + self.sum(root.right, di) + root.val + return di[root] + +# easy: https://www.lintcode.com/problem/628 diff --git a/maximum-sum-of-two-numbers.py b/maximum-sum-of-two-numbers.py new file mode 100644 index 0000000..c3e54c0 --- /dev/null +++ b/maximum-sum-of-two-numbers.py @@ -0,0 +1,31 @@ +from typing import ( + List, +) + +class Solution: + """ + @param a: An Integer array + @return: returns the maximum sum of two numbers + """ + def maximum_sum(self, a: List[int]) -> int: + # write your code here + r = -1 + di = {} + for i in a: + d = 0 + j = i + while j > 0: + d += j % 10 + j = int(j / 10) + if d not in di: + di[d] = [] + di[d].append(i) + for k, v in di.items(): + if len(v) >= 2: + v.sort() + s = v[-1] + v[-2] + if s > r: + r = s + return r + +# medium: https://www.lintcode.com/problem/1604/ diff --git a/meeting-rooms.py b/meeting-rooms.py new file mode 100644 index 0000000..6471538 --- /dev/null +++ b/meeting-rooms.py @@ -0,0 +1,23 @@ +""" +Definition of Interval. +class Interval(object): + def __init__(self, start, end): + self.start = start + self.end = end +""" + +class Solution: + """ + @param intervals: an array of meeting time intervals + @return: if a person could attend all meetings + """ + def canAttendMeetings(self, intervals): + # Write your code here + if intervals: + intervals.sort(key=lambda i: i.start) + for i in range(len(intervals) - 1): + if intervals[i + 1].start < intervals[i].end: + return False + return True + +# easy: https://www.lintcode.com/problem/meeting-rooms/ diff --git a/merge_intervals.py b/merge-intervals.py similarity index 100% rename from merge_intervals.py rename to merge-intervals.py diff --git a/merge_k_sorted_lists.py b/merge-k-sorted-lists.py similarity index 100% rename from merge_k_sorted_lists.py rename to merge-k-sorted-lists.py diff --git a/merge_number.py b/merge-number.py similarity index 99% rename from merge_number.py rename to merge-number.py index f966978..5ccf434 100644 --- a/merge_number.py +++ b/merge-number.py @@ -52,3 +52,4 @@ def pop(self): def empty(self): return len(self.data) == 0 +# ??? diff --git a/merge_sorted_array.py b/merge-sorted-array.py similarity index 100% rename from merge_sorted_array.py rename to merge-sorted-array.py diff --git a/merge-two-binary-trees.py b/merge-two-binary-trees.py new file mode 100644 index 0000000..68cbda1 --- /dev/null +++ b/merge-two-binary-trees.py @@ -0,0 +1,32 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param t1: the root of the first tree + @param t2: the root of the second tree + @return: the new binary tree after merge + """ + def mergeTrees(self, t1, t2): + # Write your code here + root = None + if t1 and t2: + root = TreeNode(t1.val + t2.val) + root.left = self.mergeTrees(t1.left, t2.left) + root.right = self.mergeTrees(t1.right, t2.right) + elif t1: + root = TreeNode(t1.val) + root.left = self.mergeTrees(t1.left, None) + root.right = self.mergeTrees(t1.right, None) + elif t2: + root = TreeNode(t2.val) + root.left = self.mergeTrees(t2.left, None) + root.right = self.mergeTrees(t2.right, None) + return root + +# easy: https://www.lintcode.com/problem/merge-two-binary-trees/ diff --git a/merge_two_sorted_arrays.py b/merge-two-sorted-arrays.py similarity index 100% rename from merge_two_sorted_arrays.py rename to merge-two-sorted-arrays.py diff --git a/merge-two-sorted-interval-lists.py b/merge-two-sorted-interval-lists.py new file mode 100644 index 0000000..3f94271 --- /dev/null +++ b/merge-two-sorted-interval-lists.py @@ -0,0 +1,30 @@ +""" +Definition of Interval. +class Interval(object): + def __init__(self, start, end): + self.start = start + self.end = end +""" + +class Solution: + """ + @param list1: one of the given list + @param list2: another list + @return: the new sorted list of interval + """ + def mergeTwoInterval(self, list1, list2): + # write your code here + ret = [] + li = list1 + list2 + li.sort(key=lambda x: x.start) # 偷个懒,正常做法是利用已排序特性。 + for r in li: + if not ret: + ret.append(r) + else: + if (r.start >= ret[-1].start) and (r.start <= ret[-1].end): + ret[-1].end = max(r.end, ret[-1].end) + else: + ret.append(r) + return ret + +# easy: https://www.lintcode.com/problem/merge-two-sorted-interval-lists/ diff --git a/merge_two_sorted_lists.py b/merge-two-sorted-lists.py similarity index 100% rename from merge_two_sorted_lists.py rename to merge-two-sorted-lists.py diff --git a/middle-of-the-linked-list.py b/middle-of-the-linked-list.py new file mode 100644 index 0000000..b847beb --- /dev/null +++ b/middle-of-the-linked-list.py @@ -0,0 +1,27 @@ +""" +Definition of ListNode +class ListNode(object): + def __init__(self, val, next=None): + self.val = val + self.next = next +""" + +class Solution: + """ + @param head: the head node + @return: the middle node + """ + def middleNode(self, head): + # write your code here. + # 添一个fake head方便统一处理 + fh = ListNode(0) + fh.next = head + slow, fast = fh, fh + while fast: + fast = fast.next + if fast: + fast = fast.next + slow = slow.next + return slow + +# easy: https://www.lintcode.com/problem/middle-of-the-linked-list/ diff --git a/min-cost-climbing-stairs.py b/min-cost-climbing-stairs.py new file mode 100644 index 0000000..fee6a63 --- /dev/null +++ b/min-cost-climbing-stairs.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param cost: an array + @return: minimum cost to reach the top of the floor + """ + def minCostClimbingStairs(self, cost): + # Write your code here + ''' + 可以从0阶开始,也可以从一阶开始,所以状态数组前2个值为0。 + 对于第n级台阶,可以从n - 1级,也可以从n - 2级台阶抵达,所以方程如下: + dp[n] = min(dp[n - 1] + cost[n - 1], dp[n - 2] + cost[n - 2) + 注意:如果cost长度为3,那么我们的目标是第3级台阶(索引从0开始)。 + ''' + ret = [0] * (len(cost) + 1) + for i in range(2, len(ret)): + ret[i] = min(ret[i - 1] + cost[i - 1], ret[i - 2] + cost[i - 2]) + return ret[-1] + +# easy: https://www.lintcode.com/problem/min-cost-climbing-stairs/ diff --git a/min-deletions-to-obtain-string-in-right-format.py b/min-deletions-to-obtain-string-in-right-format.py new file mode 100644 index 0000000..1da9e84 --- /dev/null +++ b/min-deletions-to-obtain-string-in-right-format.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param s: the string + @return: Min Deletions To Obtain String in Right Format + """ + def minDeletionsToObtainStringInRightFormat(self, s): + # write your code here + ret = len(s) + counting = [] + nums_a = 0 + nums_b = 0 + for c in s: + counting.append([nums_b, 0]) + if c == 'B': + nums_b += 1 + for i in range(len(s) - 1, -1, -1): + c = s[i] + counting[i][1] = nums_a + if c == 'A': + nums_a += 1 + for c in counting: + s = c[0] + c[1] + if s < ret: + ret = s + return ret + +# easy: https://www.lintcode.com/problem/min-deletions-to-obtain-string-in-right-format/ diff --git a/min_stack.py b/min-stack.py similarity index 100% rename from min_stack.py rename to min-stack.py diff --git a/mine-sweeping.py b/mine-sweeping.py new file mode 100644 index 0000000..486ec6a --- /dev/null +++ b/mine-sweeping.py @@ -0,0 +1,35 @@ +from typing import ( + List, +) + +class Solution: + """ + @param Mine_map: an matrix represents the map. + @param Start: the start position. + @return: return an array including all reachable positions. + """ + def Mine_sweeping(self, Mine_map: List[List[int]], Start: List[int]) -> List[List[int]]: + # write your code here + ret = [] + visited = set([]) + cords = [Start] + xlim, ylim = len(Mine_map), len(Mine_map[0]) + dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]] # Up, Down, Left, Right + while cords: + cord = cords.pop() + c = cord[0] * 1000 + cord[1] + if c not in visited: + visited.add(c) + if Mine_map[cord[0]][cord[1]] == 0: + continue + for d in dirs: + x, y = cord[0] + d[0], cord[1] + d[1] + if (x >= 0) and (x < xlim) and (y >= 0) and (y < ylim): + c = x * 1000 + y + if c not in visited: + cords.append([x, y]) + for v in visited: + ret.append([int(v / 1000), v % 1000]) + return ret + +# medium: https://www.lintcode.com/problem/1892 diff --git a/mini-cassandra.py b/mini-cassandra.py new file mode 100644 index 0000000..470a994 --- /dev/null +++ b/mini-cassandra.py @@ -0,0 +1,48 @@ +""" +Definition of Column: +class Column: + def __init__(self, key, value): + self.key = key + self.value = value +""" + + +class MiniCassandra: + def __init__(self): + # do intialization if necessary + self.di = {} + + """ + @param: row_key: a string + @param: column_key: An integer + @param: value: a string + @return: nothing + """ + def insert(self, row_key, column_key, value): + # write your code here + if row_key not in self.di: + self.di[row_key] = [] + i = 0 + while i < len(self.di[row_key]): # No TreeMap, use this ugly way! + if self.di[row_key][i][0] == column_key: + self.di[row_key][i] = (column_key, value) + break + i += 1 + if i == len(self.di[row_key]): + self.di[row_key].append((column_key, value)) + self.di[row_key].sort() + + """ + @param: row_key: a string + @param: column_start: An integer + @param: column_end: An integer + @return: a list of Columns + """ + def query(self, row_key, column_start, column_end): + # write your code here + r = [] + if row_key in self.di: + for v in self.di[row_key]: + if (v[0] >= column_start) and (v[0] <= column_end): + r.append('(' + str(v[0]) + ', "' + v[1] + '")') + return r diff --git a/mini_twitter.py b/mini-twitter.py similarity index 100% rename from mini_twitter.py rename to mini-twitter.py diff --git a/minimum-absolute-difference-in-bst.py b/minimum-absolute-difference-in-bst.py new file mode 100644 index 0000000..d660f74 --- /dev/null +++ b/minimum-absolute-difference-in-bst.py @@ -0,0 +1,33 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root + @return: the minimum absolute difference between values of any two nodes + """ + def getMinimumDifference(self, root): + # Write your code here + self.vals = [] + self.inOrder(root) + ret = self.vals[-1] - self.vals[0] + for i in range(1, len(self.vals)): + if (self.vals[i] - self.vals[i - 1]) < ret: + ret = self.vals[i] - self.vals[i - 1] + return ret + + def inOrder(self, root): + if not root: + return + if root.left: + self.inOrder(root.left) + self.vals.append(root.val) + if root.right: + self.inOrder(root.right) + +# easy: https://www.lintcode.com/problem/minimum-absolute-difference-in-bst/ diff --git a/minimum_adjustment_cost.py b/minimum-adjustment-cost.py similarity index 100% rename from minimum_adjustment_cost.py rename to minimum-adjustment-cost.py diff --git a/minimum-amplitude.py b/minimum-amplitude.py new file mode 100644 index 0000000..0f85246 --- /dev/null +++ b/minimum-amplitude.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param A: a list of integer + @return: Return the smallest amplitude + """ + def MinimumAmplitude(self, A): + # write your code here + ret = 0 + A.sort() + if len(A) > 3: + i = len(A) - 1 + ret = A[i] - A[3] # 去掉前面3个 + ret = min(A[i - 1] - A[2], ret) # 比较去掉前面2个和最后1个的情况 + ret = min(A[i - 2] - A[1], ret) # 比较去掉前面1个和最后2个的情况 + ret = min(A[i - 3] - A[0], ret) # 比较去掉最后3个的情况 + return ret + +# easy: https://www.lintcode.com/problem/minimum-amplitude/ diff --git a/minimum_depth_of_binary_tree.py b/minimum-depth-of-binary-tree.py similarity index 100% rename from minimum_depth_of_binary_tree.py rename to minimum-depth-of-binary-tree.py diff --git a/minimum-difference-between-bst-nodes.py b/minimum-difference-between-bst-nodes.py new file mode 100644 index 0000000..7a79c7c --- /dev/null +++ b/minimum-difference-between-bst-nodes.py @@ -0,0 +1,32 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root + @return: the minimum difference between the values of any two different nodes in the tree + """ + def minDiffInBST(self, root): + # Write your code here + li = [] + self.build_list(root, li) + ret = li[1] - li[0] + for i in range(2, len(li)): + diff = li[i] - li[i - 1] + if diff < ret: + ret = diff + return ret + + + def build_list(self, root, li): + if root: + self.build_list(root.left, li) + li.append(root.val) + self.build_list(root.right, li) + +# easy: https://www.lintcode.com/problem/minimum-difference-between-bst-nodes/ diff --git a/minimum-distance-between-bst-nodes.py b/minimum-distance-between-bst-nodes.py new file mode 100644 index 0000000..4b354d7 --- /dev/null +++ b/minimum-distance-between-bst-nodes.py @@ -0,0 +1,30 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +def search(root, vals): + if not root: + return + search(root.left, vals) + vals[0] = min(vals[0], abs(root.val - vals[1])) + vals[1] = root.val + search(root.right, vals) + +class Solution: + """ + @param root: a Binary Search Tree (BST) with the root node + @return: the minimum difference + """ + def minDiffInBST(self, root): + # Write your code here. + if (not root) or (not (root.left or root.right)): + return 0 + vals = [4294967296, 4294967296] # [返回值,上一个节点的值] + search(root, vals) + return vals[0] + +# easy: https://www.lintcode.com/problem/minimum-distance-between-bst-nodes/ diff --git a/minimum-index-sum-of-two-lists.py b/minimum-index-sum-of-two-lists.py new file mode 100644 index 0000000..135a809 --- /dev/null +++ b/minimum-index-sum-of-two-lists.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param list1: a list of strings + @param list2: a list of strings + @return: the common interest with the least list index sum + """ + def findRestaurant(self, list1, list2): + # Write your code here + ret = [] + min_index_sum = 100000000 + di, di1 = {}, {} + for i in range(len(list1)): + di1[list1[i]] = i + for i in range(len(list2)): + if list2[i] in di1: + index_sum = di1[list2[i]] + i + if index_sum not in di: + di[index_sum] = [list2[i]] + else: + di[index_sum].append(list2[i]) + for k in di.keys(): + if k < min_index_sum: + min_index_sum = k + return di[min_index_sum] + +# easy: https://www.lintcode.com/problem/minimum-index-sum-of-two-lists/ diff --git a/minimum-moves-to-equal-array-elements.py b/minimum-moves-to-equal-array-elements.py new file mode 100644 index 0000000..c3ae04d --- /dev/null +++ b/minimum-moves-to-equal-array-elements.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param nums: an array + @return: the minimum number of moves required to make all array elements equal + """ + def minMoves(self, nums): + # Write your code here + # 为了快速的缩小差距,该选择哪些数字加1呢,不难看出每次需要给除了数组最大值的所有数字加1, + # 这样能快速的到达平衡状态。但是每次都要找到最大值,复杂度不允许啊。 + # + # 其实给n-1个数字加1,效果等同于给那个未被选中的数字减1,比如数组[1,2,3], + # 给除去最大值的其他数字加1,变为[2,3,3],我们全体减1,并不影响数字间相对差异, + # 变为[1,2,2],这个结果其实就是原始数组的最大值3自减1, + # 那么问题也可能转化为,将所有数字都减小到最小值,这样难度就大大降低了, + # 我们只要先找到最小值,然后累加每个数跟最小值之间的差值即可。 + ret = 0 + if len(nums) >= 2: + _min = min(nums) + for i in nums: + ret += i - _min + return ret + +# easy: https://www.lintcode.com/problem/minimum-moves-to-equal-array-elements/ diff --git a/minimum-moves.py b/minimum-moves.py new file mode 100644 index 0000000..88fa3bf --- /dev/null +++ b/minimum-moves.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param S: a string + @return: return the minimum number of moves + """ + def MinimumMoves(self, S): + # write your code here + ret = 0 + if S: + n = 1 + c = S[0] + S += ' ' # 因为最后一个字符也要判断,所以额外加个空格。 + for i in range(1, len(S)): + if c == S[i]: + n += 1 + else: + ret += int(n / 3) # 根据之前连续的数目决定要移动几次 + c = S[i] + n = 1 + return ret + +# easy: https://www.lintcode.com/problem/minimum-moves/ diff --git a/minimum_path_sum.py b/minimum-path-sum.py similarity index 100% rename from minimum_path_sum.py rename to minimum-path-sum.py diff --git a/minimum-rest-days.py b/minimum-rest-days.py new file mode 100644 index 0000000..f9a1194 --- /dev/null +++ b/minimum-rest-days.py @@ -0,0 +1,39 @@ +class Solution: + """ + @param company: Company business + @param gym: Gym business + @return: Find the shortest rest day + """ + def minimumRestDays(self, company, gym): + # write your code here + days = len(company) + ret = days + ''' + 第0行:工作 + 第1行:健身 + 第2行:休息 + dp[0][i]表示第i天工作情况下最小休息几天,同理可推dp[1][i]和dp[2][i]。 + ''' + dp = [[0, 0], [0, 0], [0, 0]] # 滚动数组比较省空间 + dp[0][0] = 0 if company[0] == 1 else 1 # 第0天如果工作最小只休息0天... + dp[1][0] = 0 if gym[0] == 1 else 1 + dp[2][0] = 1 + for i in range(1, days): + t = i & 1 # today + y = (i - 1) & 1 # yesterday + dp[0][t] = dp[1][t] = dp[2][t] = days # 初始化,利用i & 1实现两天交错。 + if company[i] == 1: # 今天可以工作 + dp[0][t] = dp[2][y] # 如果昨天可以休息的话,休息天数不会比昨天可以休息更多!!! + if gym[i - 1] == 1: + dp[0][t] = min(dp[0][t], dp[1][y]) # 如果昨天健身的话,今天可以上班,所以休息天数选择较小的那个。 + if gym[i] == 1: + dp[1][t] = dp[2][y] + if company[i - 1] == 1: + dp[1][t] = min(dp[1][t], dp[0][y]) + for j in range(3): + dp[2][t] = min(dp[2][t], dp[j][y] + 1) # 因为每天都可能休息,所以dp[j][y]要加1! + for i in range(3): + ret = min(ret, dp[i][(days - 1) & 1]) + return ret + +# medium: https://www.lintcode.com/problem/minimum-rest-days diff --git a/minimum_size_subarray_sum.py b/minimum-size-subarray-sum.py similarity index 100% rename from minimum_size_subarray_sum.py rename to minimum-size-subarray-sum.py diff --git a/minimum-step.py b/minimum-step.py new file mode 100644 index 0000000..32ef054 --- /dev/null +++ b/minimum-step.py @@ -0,0 +1,38 @@ +class Solution: + """ + @param colors: the colors of grids + @return: return the minimum step from position 0 to position n - 1 + """ + def minimumStep(self, colors): + # write your code here + ret = 0 + n = len(colors) + visited = set([]) + points = [set([0]), set()] + curr, _next = 0, 1 + cmap = {} + for i in range(n): + c = colors[i] + if c not in cmap: + cmap[c] = set() + cmap[c].add(i) + while points[curr]: + for i in points[curr]: + if i not in visited: + if i == n - 1: + return ret + if ((i - 1) > 0) and ((i - 1) not in visited): + points[_next].add(i - 1) + if ((i + 1) < n) and ((i + 1) not in visited): + points[_next].add(i + 1) + for j in cmap[colors[i]]: + if (j != i) and (j not in visited): + points[_next].add(j) + cmap[colors[i]].clear() # Clear this color! Important!!! + visited.add(i) + points[curr].clear() + curr, _next = _next, curr + ret += 1 + return ret + +# medium: https://www.lintcode.com/problem/1832 diff --git a/minimum_subarray.py b/minimum-subarray.py similarity index 100% rename from minimum_subarray.py rename to minimum-subarray.py diff --git a/minimum-subtree.py b/minimum-subtree.py new file mode 100644 index 0000000..1a03cb6 --- /dev/null +++ b/minimum-subtree.py @@ -0,0 +1,36 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root of binary tree + @return: the root of the minimum subtree + """ + def findSubtree(self, root): + # write your code here + ret = None + if root: + di = {None: 0} + self.sum(root, di) + s = max(di.values()) + for k, v in di.items(): + if k: + if v <= s: + s = v + ret = k + return ret + + def sum(self, root, di): + if not root: + return 0 + if root not in di: + di[root] = self.sum(root.left, di) + self.sum(root.right, di) + root.val + return di[root] + + +# easy: https://www.lintcode.com/problem/596/ diff --git a/minimum_window_substring.py b/minimum-window-substring.py similarity index 100% rename from minimum_window_substring.py rename to minimum-window-substring.py diff --git a/missing_string.py b/missing-string.py similarity index 100% rename from missing_string.py rename to missing-string.py diff --git a/mock_hanoi_tower_by_stacks.py b/mock-hanoi-tower-by-stacks.py similarity index 100% rename from mock_hanoi_tower_by_stacks.py rename to mock-hanoi-tower-by-stacks.py diff --git a/modern-ludo-i.py b/modern-ludo-i.py new file mode 100644 index 0000000..e3004ee --- /dev/null +++ b/modern-ludo-i.py @@ -0,0 +1,29 @@ +class Solution: + """ + @param length: the length of board + @param connections: the connections of the positions + @return: the minimum steps to reach the end + """ + def modernLudo(self, length, connections): + # Write your code here + # 7步的情况:1的话走1步到2,走6步到7,丢1次足够了... + if length <= 7: + return 1 + sc = [0] # 短路表,因为从1开始,所以都额外加个元素。 + dp = [0] + for i in range(1, length + 1): + sc.append(i) # 自己和自己一定短路 + dp.append(length + 1) + dp[1] = 0 # 一开始就在位置1 + for i in range(len(connections)): + sc[connections[i][0]] = connections[i][1] # 短路表内容 + for i in range(2, length + 1): + if (i - 6) <= 1: + dp[i] = 1 # 丢1次肯定能到 + else: + for j in range(i - 1, i - 7, -1): # 往前看6步 + dp[i] = min(dp[j] + 1, dp[i]) # j丢1次肯定能到i + dp[sc[i]] = min(dp[i], dp[sc[i]]) # 更新第i个点对应的短路位置 + return dp[-1] + +# easy: https://www.lintcode.com/problem/modern-ludo-i/ diff --git a/monotone_increasing_digits.py b/monotone-increasing-digits.py similarity index 98% rename from monotone_increasing_digits.py rename to monotone-increasing-digits.py index ef1775d..dd7b10d 100644 --- a/monotone_increasing_digits.py +++ b/monotone-increasing-digits.py @@ -18,3 +18,5 @@ def monotoneDigits(self, num): for i in range(j, digits_len): digits[i] = 9 return reduce(lambda x, y: x * 10 + y, digits) + +# ??? diff --git a/monotonic-array.py b/monotonic-array.py new file mode 100644 index 0000000..8efa2df --- /dev/null +++ b/monotonic-array.py @@ -0,0 +1,29 @@ +class Solution: + """ + @param A: a array + @return: is it monotonous + """ + def isMonotonic(self, A): + # Write your code here. + if len(A) < 2: + return True + _dir = True # 记录方向 + i = 1 + while i < len(A): + if A[i - 1] < A[i]: + _dir = -1 + break + elif A[i - 1] > A[i]: + _dir = 1 + break + i += 1 + for j in range(i, len(A) - 1): + if _dir == -1: + if A[j] > A[j + 1]: + return False + else: + if A[j] < A[j + 1]: + return False + return True + +# easy: https://www.lintcode.com/problem/monotonic-array/ diff --git a/most-common-word.py b/most-common-word.py new file mode 100644 index 0000000..3199d4c --- /dev/null +++ b/most-common-word.py @@ -0,0 +1,39 @@ +class Solution: + """ + @param paragraph: + @param banned: + @return: nothing + """ + def mostCommonWord(self, paragraph, banned): + di = {} + banned_s = set([]) + for b in banned: + banned_s.add(b.lower()) + word = [] + for c in paragraph: + if c in [' ', ',', '.', '!', '?', ';', "'"]: + if word: + w = ''.join(word).lower() + if w not in banned_s: + if w in di: + di[w] += 1 + else: + di[w] = 1 + word = [] + else: + word.append(c) + if word: + w = ''.join(word).lower() + if w not in banned_s: + if w in di: + di[w] += 1 + else: + di[w] = 1 + ret, c = None, 0 + for k, v in di.items(): + if v > c: + c = v + ret = k + return ret + +# easy: https://www.lintcode.com/problem/most-common-word/ diff --git a/move_zeroes.py b/move-zeroes.py similarity index 100% rename from move_zeroes.py rename to move-zeroes.py diff --git a/movie-recommendation.py b/movie-recommendation.py new file mode 100644 index 0000000..adcc5b3 --- /dev/null +++ b/movie-recommendation.py @@ -0,0 +1,46 @@ +import functools + +class Solution: + def minMalwareSpread(self, graph): + movies_viewed_by = {} # 电影被哪些人看过 + for i in range(len(graph)): + for m in graph[i]: + if m not in movies_viewed_by: + movies_viewed_by[m] = set([]) + movies_viewed_by[m].add(i) + ret = [] + candidates = {} + for u in range(len(graph)): + candidates[u] = {} + for m in graph[u]: + for _u in movies_viewed_by[m]: + if _u != u: + for _m in graph[_u]: + if _m not in graph[u]: + if _m not in candidates[u]: + candidates[u][_m] = 0 + candidates[u][_m] += 1 + def cmp(x, y): # 排序规则坑爹 + if x[1] < y[1]: + return 1 + elif x[1] == y[1]: + if x[0] < y[0]: + return -1 + elif x[0] == y[0]: + return 0 + else: + return 1 + else: + return -1 + arr = sorted(candidates[u].items(), key=functools.cmp_to_key(cmp)) + ret.append([]) + for i in range(len(arr)): + if (i < 5): + ret[-1].append(arr[i][0]) + else: + break + if u == 9: + print(ret[-1]) + return ret + +# easy: https://www.lintcode.com/problem/movie-recommendation/description diff --git a/moving-average-from-data-stream.py b/moving-average-from-data-stream.py new file mode 100644 index 0000000..5cd7ddd --- /dev/null +++ b/moving-average-from-data-stream.py @@ -0,0 +1,27 @@ +class MovingAverage: + """ + @param: size: An integer + """ + def __init__(self, size): + # do intialization if necessary + self.size = size + self.queue = [] + self.start = 0 + self.total = 0 + + """ + @param: val: An integer + @return: + """ + def next(self, val): + self.total += val + if len(self.queue) == self.size: # 限制数组大小,实现更优雅。 + self.total -= self.queue[self.start] + self.queue[self.start] = val + self.start += 1 + self.start %- self.size + else: + self.queue.append(val) + return self.total / len(self.queue) + +# medium: https://lintcode.com/zh-cn/problem/moving-average-from-data-stream/ diff --git a/moving-circle.py b/moving-circle.py new file mode 100644 index 0000000..2d4d4b3 --- /dev/null +++ b/moving-circle.py @@ -0,0 +1,46 @@ +class Solution: + """ + @param position: the position of circle A,B and point P. + @return: if two circle intersect return 1, otherwise -1. + """ + def IfIntersect(self, position): + # + # 判断两个圆相交:abs(r1 - r2) <= dist <= r1 + r2 + xa = position[0] + ya = position[1] + ra = position[2] + xb = position[3] + yb = position[4] + rb = position[5] + xp = position[6] + yp = position[7] + dist_ab = math.sqrt((xa - xb) ** 2 + (ya - yb) ** 2) + dist_bp = math.sqrt((xp - xb) ** 2 + (yp - yb) ** 2) + min_rab = abs(ra - rb) + max_rab = ra + rb + if (min_rab <= dist_ab) and (dist_ab <= max_rab): # 初始相交 + return 1 + elif (min_rab <= dist_bp) and (dist_bp <= max_rab): # P点相交 + return 1 + a = yp - ya # 这里公式都忘了... + b = xa - xp + if (a == 0) and (b == 0): + return -1 + c = xp * ya - xa * yp + dist = (a * xb + b * yb + c) / math.sqrt(a * a + b * b) + xi = (b * b * xb - a * b * yb - a * c) / (a * a + b * b) + yi = (a * a * yb - a * b * xb - b * c) / (a * a + b * b) + if (min_rab <= dist) and (dist <= max_rab): + if self.is_inline([xa, ya], [xp, yp], [xi, yi], ra): # 交点是不是在直线上 + return 1 + return -1 + + def is_inline(self, pa, pp, pb, ra): + max_x = pa[0] if pa[0] > pp[0] else pp[0] + min_x = pp[0] if pa[0] > pp[0] else pa[0] + max_y = pa[1] if pa[1] > pp[1] else pp[1] + min_y = pp[1] if pa[1] > pp[1] else pa[1] + flag = ((pb[0] - pa[0]) * (pp[1] - pa[1])) == ((pp[0] - pa[0]) * (pb[1] - pa[1])) + return flag and ((min_x <= pb[0]) and (pb[0 ]<= max_x)) and ((min_y <= pb[1]) and (pb[1] <= max_y)) + +# medium: https://www.lintcode.com/problem/moving-circle/ diff --git a/moving-target.py b/moving-target.py new file mode 100644 index 0000000..749568e --- /dev/null +++ b/moving-target.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param nums: a list of integer + @param target: an integer + @return: nothing + """ + def MoveTarget(self, nums, target): + # write your code here + steps = 0 + for i in range(len(nums) - 1, -1, -1): + if nums[i] == target: + steps += 1 + else: + nums[i + steps] = nums[i] + for i in range(steps): + nums[i] = target + return nums + +# easy: https://www.lintcode.com/problem/moving-target/ diff --git a/multi-keyword-sort.py b/multi-keyword-sort.py new file mode 100644 index 0000000..b18f711 --- /dev/null +++ b/multi-keyword-sort.py @@ -0,0 +1,22 @@ +from functools import cmp_to_key + +class Solution: + """ + @param array: the input array + @return: the sorted array + """ + def multiSort(self, array): + # Write your code here + import functools + return sorted(array, key=functools.cmp_to_key(self.my_cmp)) + + @staticmethod + def my_cmp(x, y): + if x[1] < y[1]: + return 1 + else: + if x[1] == y[1]: + return -1 if x[0] < y[0] else 1 + return -1 + +# easy: https://www.lintcode.com/problem/multi-keyword-sort/ diff --git a/multi-string-search.py b/multi-string-search.py new file mode 100644 index 0000000..6c17127 --- /dev/null +++ b/multi-string-search.py @@ -0,0 +1,41 @@ +class Solution: + """ + @param sourceString: a string + @param targetStrings: a string array + @return: Returns a bool array indicating whether each string in targetStrings is a substring of the sourceString + """ + def whetherStringsAreSubstrings(self, sourceString, targetStrings): + # write your code here + ret = [] + di = {} + for i in range(len(sourceString)): + c = sourceString[i] + if c not in di: + di[c] = [] + di[c].append(i) + for s in targetStrings: + if s: + c = s[0] + if c not in di: + ret.append(False) + else: + match = False + for start in di[c]: + r = True + for i in range(len(s)): + if (start + i) < len(sourceString): + if s[i] != sourceString[i + start]: + r = False + break + else: + r = False + break + if r: + match = True + break + ret.append(match) + else: + ret.append(True) + return ret + +# easy: https://www.lintcode.com/problem/multi-string-search/ diff --git a/multiply-strings.py b/multiply-strings.py new file mode 100644 index 0000000..08b9c47 --- /dev/null +++ b/multiply-strings.py @@ -0,0 +1,61 @@ +class Solution: + """ + @param num1: a non-negative integers + @param num2: a non-negative integers + @return: return product of num1 and num2 + """ + def multiply(self, num1, num2): + # write your code here + vs = [] + i = 0 + num1 = num1[::-1] + num2 = num2[::-1] + for c in num2: + vs.append(self._multiply(num1, int(c), i)) + i += 1 + ret = vs[0] + for i in range(1, len(vs)): + ret = self._add(ret, vs[i]) + for i in range(len(ret) - 1, -1, -1): + if ret[i] == '0': + ret.pop() + else: + break + ret = ret[::-1] + if not ret: + return '0' + else: + return ''.join(ret) + + def _multiply(self, num1, k, zs): + ret = ['0'] * zs + val = [] + step = 0 + for i in num1: + i = int(i) + v = i * k + step + val.append(str(v % 10)) + step = int(v / 10) + if step: + val.append(int(step)) + return ret + val + + def _add(self, num1, num2): # num1 <= num2, already reversed + ret = [] + step = 0 + for i in range(len(num1)): + v1 = int(num1[i]) + v2 = int(num2[i]) + v = v1 + v2 + step + ret.append(str(v % 10)) + step = int(v / 10) + for i in range(len(num1), len(num2)): + v1 = int(num2[i]) + v = v1 + step + ret.append(str(v % 10)) + step = int(v / 10) + if step: + ret.append('1') + return ret + +# medium: https://www.lintcode.com/problem/multiply-strings/ diff --git a/multiply-two-numbers.py b/multiply-two-numbers.py new file mode 100644 index 0000000..733ccf5 --- /dev/null +++ b/multiply-two-numbers.py @@ -0,0 +1,47 @@ +""" +Definition of ListNode +class ListNode(object): + def __init__(self, val, next=None): + self.val = val + self.next = next +""" + +class Solution: + """ + @param l1: the first list + @param l2: the second list + @return: the product list of l1 and l2 + """ + def multiplyLists(self, l1, l2): + # write your code here + ret = 0 + l1 = self.reverse(l1) + l2 = self.reverse(l2) + print(l1.val, l2.val) + i = 1 + while l1: + j = 1 + tmp = l2 + while tmp: + ret += i * j * l1.val * tmp.val + tmp = tmp.next + j *= 10 + i *= 10 + l1 = l1.next + return ret + + def reverse(self, node): + head, tail = None, None + while node: + if not head: + head, tail = node, node + node = node.next + tail.next = None + else: + tmp = node.next + node.next = head + head = node + node = tmp + return head + +# easy: https://www.lintcode.com/problem/multiply-two-numbers/ diff --git a/music-pairs.py b/music-pairs.py new file mode 100644 index 0000000..bc938f9 --- /dev/null +++ b/music-pairs.py @@ -0,0 +1,30 @@ +class Solution: + """ + @param musics: the musics + @return: calc the number of pair of music + """ + def musicPairs(self, musics): + # write your code here + ret = 0 + di = {} + musics.sort() + for m in musics: + if m not in di: + di[m] = 0 + di[m] += 1 + for i in range(len(musics)): + m = musics[i] + di[m] -= 1 + r = self.round(m) + while r <= musics[-1]: + if (r in di) and (di[r] > 0): + ret += di[r] + r += 60 + else: + break + return ret + + def round(self, n): + return 60 * (int(n / 60) + 1) - n + +# easy: https://www.lintcode.com/problem/music-pairs/ diff --git a/n-ary-tree-level-order-traversal.py b/n-ary-tree-level-order-traversal.py new file mode 100644 index 0000000..15888d6 --- /dev/null +++ b/n-ary-tree-level-order-traversal.py @@ -0,0 +1,16 @@ +class Solution: + def levelOrder(self, root): # 坑,root[0]才是真root! + ret = [] + if root: + levels = [[root[0]], []] + cur_level, next_level = 0, 1 + while levels[cur_level]: + ret.append([]) + for node in levels[cur_level]: + ret[-1].append(node.label) + levels[next_level].extend(node.neighbors) + levels[cur_level] = [] + cur_level, next_level = next_level, cur_level + return ret + +# easy: https://www.lintcode.com/problem/n-ary-tree-level-order-traversal/ diff --git a/n-ary-tree-postorder-traversal.py b/n-ary-tree-postorder-traversal.py new file mode 100644 index 0000000..40799d4 --- /dev/null +++ b/n-ary-tree-postorder-traversal.py @@ -0,0 +1,25 @@ +""" +class UndirectedGraphNode: + def __init__(self, x): + self.label = x + self.neighbors = [] +""" + +class Solution: + """ + @param root: the root of the tree + @return: post order of the tree + """ + def postorder(self, root): + # write your code here + ret = [] + self._postorder(root, ret) + return ret + + def _postorder(self, root, ret): + if root: + for n in root.neighbors: + self._postorder(n, ret) + ret.append(root.label) + +# easy: https://www.lintcode.com/problem/n-ary-tree-postorder-traversal/ diff --git a/n-ary-tree-preorder-traversal.py b/n-ary-tree-preorder-traversal.py new file mode 100644 index 0000000..5f7abe2 --- /dev/null +++ b/n-ary-tree-preorder-traversal.py @@ -0,0 +1,25 @@ +""" +class UndirectedGraphNode: + def __init__(self, x): + self.label = x + self.neighbors = [] +""" + +class Solution: + """ + @param root: the tree + @return: pre order of the tree + """ + def preorder(self, root): + # write your code here + ret = [] + self._preorder(root, ret) + return ret + + def _preorder(self, root, ret): + if root: + ret.append(root.label) + for node in root.neighbors: + self._preorder(node, ret) + +# easy: https://www.lintcode.com/problem/n-ary-tree-preorder-traversal/ diff --git a/n_queens_ii.py b/n-queens-ii.py similarity index 100% rename from n_queens_ii.py rename to n-queens-ii.py diff --git a/n_queens.py b/n-queens.py similarity index 100% rename from n_queens.py rename to n-queens.py diff --git a/name-deduplication.py b/name-deduplication.py new file mode 100644 index 0000000..b992f5d --- /dev/null +++ b/name-deduplication.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param names: a string array + @return: a string array + """ + def nameDeduplication(self, names): + # write your code here + ret = [] + s = set() + for n in names: + nl = n.lower() + if nl not in s: + s.add(nl) + ret.append(nl) + return ret + +# easy: https://www.lintcode.com/problem/487 diff --git a/narcissistic-number.py b/narcissistic-number.py new file mode 100644 index 0000000..18b33f8 --- /dev/null +++ b/narcissistic-number.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param n: The number of digits + @return: All narcissistic numbers with n digits + """ + def getNarcissisticNumbers(self, n): + # write your code here + ret = [] + if n == 1: + ret.append(0) + for i in range(pow(10, n - 1), pow(10, n)): + _i = i + s = 0 + while i > 0: + s += pow(i % 10, n) + i = int(i / 10) + if s == _i: + ret.append(s) + return ret + +# easy: https://www.lintcode.com/problem/147/description diff --git a/nested-list-weight-sum.py b/nested-list-weight-sum.py new file mode 100644 index 0000000..a203f3b --- /dev/null +++ b/nested-list-weight-sum.py @@ -0,0 +1,39 @@ +""" +This is the interface that allows for creating nested lists. +You should not implement it, or speculate about its implementation + +class NestedInteger(object): + def isInteger(self): + # @return {boolean} True if this NestedInteger holds a single integer, + # rather than a nested list. + + def getInteger(self): + # @return {int} the single integer that this NestedInteger holds, + # if it holds a single integer + # Return None if this NestedInteger holds a nested list + + def getList(self): + # @return {NestedInteger[]} the nested list that this NestedInteger holds, + # if it holds a nested list + # Return None if this NestedInteger holds a single integer +""" + + +class Solution(object): + # @param {NestedInteger[]} nestedList a list of NestedInteger Object + # @return {int} an integer + @staticmethod + def _depthSum(nestedList, count, level=1): # 递归,level记录深度 + for i in nestedList: + if i.isInteger(): + count[0] += i.getInteger() * level + else: + Solution._depthSum(i.getList(), count, level+1) + + def depthSum(self, nestedList): + # Write your code here + count = [0] + Solution._depthSum(nestedList, count) + return count[0] + +# easy: https://www.lintcode.com/problem/nested-list-weight-sum diff --git a/new-21-game.py b/new-21-game.py new file mode 100644 index 0000000..8db5d73 --- /dev/null +++ b/new-21-game.py @@ -0,0 +1,31 @@ +class Solution: + """ + @param n: int + @param k: int + @param w: int + @return: the probability + """ + def new21_game(self, n: int, k: int, w: int) -> float: + # Write your code here. + ''' + 使用DP,dpi表示当前值为i的概率。每次可选牌的范围是1到w,所以如果当前值为i, + 那么上一次的取值范围为i - w到i - 1。 + 我们要求的结果是大于k的数,所以最终i的范围落在k到k + w - 1。如果n >= k + w, + 那么就跟就说100%.如果n < k + w,那么累加概率值即可。 + ''' + if (k == 0) or (n >= (k + w)): + return 1 + r = 0 + s = 0 + dp = [0] * (n + 1) # [0, n] + for i in range(1, n + 1): + dp[i] = (s / w + 1 / w) if (i <= w) else (s / w) + if i < k: + s += dp[i] + if i > w: + s -= dp[i - w] + if i >= k: + r += dp[i] + return r + +# medium: https://www.lintcode.com/problem/1432 diff --git a/next-greater-element-i.py b/next-greater-element-i.py new file mode 100644 index 0000000..c8574fd --- /dev/null +++ b/next-greater-element-i.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param nums1: an array + @param nums2: an array + @return: find all the next greater numbers for nums1's elements in the corresponding places of nums2 + """ + def nextGreaterElement(self, nums1, nums2): + # Write your code here + # 如何理解题目: + # - 对于nums1的数字i,先找到它在nums2的位置。 + # - 然后从这个位置开始,找到第一个比它大的数。 + # 所以我们可以先构造一张表,对于nums2的每个元素i,记录后面出现的第一个比它大的数。 + # 重点关注for-while代码: + # - 如果堆栈为空,当前元素入栈。 + # - 继续for循环,如果当前堆栈不为空,且大于堆栈最后一个元素!!! + # 记住,堆栈内的元素顺序是与for循环同样顺序进入的。 + # 那么这个元素后第一个出现的比它大的元素找到,弹出并构造字典关系。 + # 继续循环,之前满足的也一起构造了。 + di = {} + stack = [] + for i in nums2: + while stack and (stack[-1] < i): + di[stack.pop()] = i + stack.append(i) + return [di.get(i, -1) for i in nums1] + +# easy: https://www.lintcode.com/problem/next-greater-element-i/ diff --git a/next_permutation_ii.py b/next-permutation-ii.py similarity index 100% rename from next_permutation_ii.py rename to next-permutation-ii.py diff --git a/next_permutation.py b/next-permutation.py similarity index 100% rename from next_permutation.py rename to next-permutation.py diff --git a/nim-game.py b/nim-game.py new file mode 100644 index 0000000..e0a301a --- /dev/null +++ b/nim-game.py @@ -0,0 +1,10 @@ +class Solution: + """ + @param n: an integer + @return: whether you can win the game given the number of stones in the heap + """ + def canWinNim(self, n): + # Write your code here + return (n % 4) != 0 + +# easy: https://www.lintcode.com/problem/nim-game/ diff --git a/non-decreasing-array.py b/non-decreasing-array.py new file mode 100644 index 0000000..83d72ee --- /dev/null +++ b/non-decreasing-array.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param nums: an array + @return: if it could become non-decreasing by modifying at most 1 element + """ + def checkPossibility(self, nums): + # Write your code here + k = -1 + for i in range(len(nums) - 1): + if nums[i + 1] < nums[i]: + k = i + 1 # 可疑,需要处理! + break + if k > 0: + if k == 1: + prev = nums[k] # 要考虑出现的第一个元素就比后面大的情况 + else: + prev = nums[k - 1] # 比较基准 + for i in range(k + 1, len(nums)): + if nums[i] < prev: + return False + prev = nums[i] + return True + +# https://www.lintcode.com/problem/non-decreasing-array/ diff --git a/nth-digit.py b/nth-digit.py new file mode 100644 index 0000000..072c905 --- /dev/null +++ b/nth-digit.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param n: a positive integer + @return: the nth digit of the infinite integer sequence + """ + def findNthDigit(self, n): + # write your code here + # 首先明确以下知识:9个一位数,90个两位数,900个三位数,依次类推。 + count = 1 # 数字从1开始 + digits = 1 # 位数 + while n > (9 * digits * count): + n -= 9 * digits * count + count *= 10 + digits += 1 + count += ((n - 1) / digits) # 计算出现在那个数 + pos = (n - 1) % digits # 这个数里的具体位置 + return int(str(count)[pos]) + +# easy: https://www.lintcode.com/problem/nth-digit/ diff --git a/nth_to_last_node_in_list.py b/nth-to-last-node-in-list.py similarity index 100% rename from nth_to_last_node_in_list.py rename to nth-to-last-node-in-list.py diff --git a/number-change.py b/number-change.py new file mode 100644 index 0000000..0a1b1dc --- /dev/null +++ b/number-change.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param k: integer k + @return: minimum number of operations that change 0 to k + """ + def numberChange(self, k): + # write your code here + if k == 0: + return 0 + else: + if (k % 2) == 0: + return 1 + self.numberChange(int(k/2)) + else: + return 1 + self.numberChange(k - 1) + +# medium: https://www.lintcode.com/problem/1825/ diff --git a/number-complement.py b/number-complement.py new file mode 100644 index 0000000..f858742 --- /dev/null +++ b/number-complement.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param num: an integer + @return: the complement number + """ + def findComplement(self, num): + # Write your code here + i = 1 + while i <= num: + i *= 2 + if i == num: + return i - 1 + else: + return i -1 - num + +# easy: https://www.lintcode.com/problem/number-complement/ diff --git a/number-of-1-bits.py b/number-of-1-bits.py new file mode 100644 index 0000000..6d2e2c6 --- /dev/null +++ b/number-of-1-bits.py @@ -0,0 +1,15 @@ +class Solution: + """ + @param n: an unsigned integer + @return: the number of ’1' bits + """ + def hammingWeight(self, n): + # write your code here + ret = 0 + while n >= 2: + if n % 2 != 0: + ret += 1 + n = int(n / 2) + return ret + n + +# easy: https://www.lintcode.com/problem/number-of-1-bits/ diff --git a/number-of-a.py b/number-of-a.py new file mode 100644 index 0000000..74570da --- /dev/null +++ b/number-of-a.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param s: the given string + @return: the number of A + """ + def countA(self, s): + # Write your code here + return self._countA(s, 0, len(s) - 1) + + def _countA(self, s, start, end): + if start <= end: + mid = (start + end) // 2 + c = s[mid] + if c == 'B': + return self._countA(s, mid + 1, end) + else: + ret = self._countA(s, start, mid - 1) + if c == 'A': + ret += 1 + self._countA(s, mid + 1, end) + return ret + else: + return 0 + +# easy: https://www.lintcode.com/problem/number-of-a/ diff --git a/number_of_airplanes_in_the_sky.py b/number-of-airplanes-in-the-sky.py similarity index 100% rename from number_of_airplanes_in_the_sky.py rename to number-of-airplanes-in-the-sky.py diff --git a/number-of-boomerangs.py b/number-of-boomerangs.py new file mode 100644 index 0000000..1a37c3b --- /dev/null +++ b/number-of-boomerangs.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param points: a 2D array + @return: the number of boomerangs + """ + def numberOfBoomerangs(self, points): + # Write your code here + ret = 0 + for i in range(len(points)): + di = {} # 根据距离记录点位对数 + total = 0 + for j in range(len(points)): # 元组的顺序是重要的!!! + if i != j: # 每一对点都是不同的!!! + dist = pow(points[j][0] - points[i][0], 2) + \ + pow(points[j][1] - points[i][1], 2) + if dist in di: + # 在已有di[dist]对点位的情况下, + # 每新增一个点位但表增加了di[dist]种[i, j, k]组合。 + # [i, j, k]又可以变成[i, k, j],所以后面要乘2. + total += di[dist] + di[dist] += 1 + else: + di[dist] = 1 # 有一对点位 + print(i, total) + ret += total * 2 + return ret + +# easy: https://www.lintcode.com/problem/number-of-boomerangs/ diff --git a/number_of_islands.py b/number-of-islands.py similarity index 100% rename from number_of_islands.py rename to number-of-islands.py diff --git a/number-of-lines-to-write-string.py b/number-of-lines-to-write-string.py new file mode 100644 index 0000000..01c4d37 --- /dev/null +++ b/number-of-lines-to-write-string.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param widths: an array + @param S: a string + @return: how many lines have at least one character from S, and what is the width used by the last such line + """ + def numberOfLines(self, widths, S): + # Write your code here + lines = 0 + steps = 0 + w = 0 + for c in S: + c = ord(c) - ord('a') + if w + widths[c] > 100: + lines += 1 + w = widths[c] + else: + w += widths[c] + steps = w + return [lines + 1, steps] + +# easy: https://www.lintcode.com/problem/number-of-lines-to-write-string/ diff --git a/number-of-segments-in-a-string.py b/number-of-segments-in-a-string.py new file mode 100644 index 0000000..8c00a81 --- /dev/null +++ b/number-of-segments-in-a-string.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param s: a string + @return: the number of segments in a string + """ + def countSegments(self, s): + # write yout code here + ret = 0 + is_word = False + for c in s: + if c != ' ': + if not is_word: + ret += 1 + is_word = True + else: + is_word = False + return ret + +# easy: https://www.lintcode.com/problem/number-of-segments-in-a-string/ diff --git a/number-of-substrings-with-all-zeroes.py b/number-of-substrings-with-all-zeroes.py new file mode 100644 index 0000000..10a3297 --- /dev/null +++ b/number-of-substrings-with-all-zeroes.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param str: the string + @return: the number of substrings + """ + def stringCount(self, str): + # Write your code here. + r = 0 + zeros = 0 + prev = 'x' + for c in str: + if (prev == '0') and (c != '0'): + zeros = 0 + elif c == '0': + if prev != '0': + zeros = 1 + else: + zeros += 1 + r += zeros + prev = c + return r + +# medium: https://www.lintcode.com/problem/1870 diff --git a/number-of-ways-to-stay-in-the-same-place-after-some-steps-i.py b/number-of-ways-to-stay-in-the-same-place-after-some-steps-i.py new file mode 100644 index 0000000..414b27c --- /dev/null +++ b/number-of-ways-to-stay-in-the-same-place-after-some-steps-i.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param steps: steps you can move + @param arrLen: the length of the array + @return: Number of Ways to Stay in the Same Place After Some Steps + """ + def numWays(self, steps, arrLen): + # write your code here + # DP: 第i步到位置j的方案可以根据之前状态推出 + # dp[i][j] = dp[i-1][j] + ~ 不动 + # dp[i-1][j+1] + ~ 向左 + # dp[i-1][j-1] ~ 向右 + dist = min(steps, arrLen) # 最远可以到位置cols + dp = [[0 for i in range(dist)] for i in range(steps + 1)] # 第0步到第steps步 + dp[0][0] = 1 + for step in range(1, steps + 1): + for d in range(dist): + if d == 0: + dp[step][d] += dp[step - 1][d] + if (d + 1) < dist: + dp[step][d] += dp[step - 1][d + 1] # 可以向左一步回到0点 + elif d == (dist - 1): + dp[step][d] += dp[step - 1][d] + dp[step - 1][d - 1] # 可以向向一步到终点 + else: + dp[step][d] += dp[step - 1][d] + dp[step - 1][d + 1] + dp[step - 1][d - 1] + return dp[steps][0] % (pow(10, 9) + 7) + +# easy: https://www.lintcode.com/problem/number-of-ways-to-stay-in-the-same-place-after-some-steps-i/ diff --git a/o1_check_power_of_2.py b/o1-check-power-of-2.py similarity index 100% rename from o1_check_power_of_2.py rename to o1-check-power-of-2.py diff --git a/odd-even-linked-list.py b/odd-even-linked-list.py new file mode 100644 index 0000000..43034be --- /dev/null +++ b/odd-even-linked-list.py @@ -0,0 +1,44 @@ +""" +Definition of ListNode +class ListNode(object): + def __init__(self, val, next=None): + self.val = val + self.next = next +""" + +class Solution: + """ + @param head: a singly linked list + @return: Modified linked list + """ + def oddEvenList(self, head): + # write your code here + odd_head, odd_tail = None, None # 奇偶分开再合并 + even_head, even_tail = None, None + is_odd = True + while head != None: + node = head + head = node.next + node.next = None + if is_odd: + if odd_head is None: + odd_head = node + odd_tail = node + else: + odd_tail.next = node + odd_tail = node + else: + if even_head is None: + even_head = node + even_tail = node + else: + even_tail.next = node + even_tail = node + is_odd = not is_odd + if odd_head: + odd_tail.next = even_head + return odd_head + else: + return even_head + +# medium: https://www.lintcode.com/problem/odd-even-linked-list diff --git a/order-check.py b/order-check.py new file mode 100644 index 0000000..6dff0ff --- /dev/null +++ b/order-check.py @@ -0,0 +1,15 @@ +class Solution: + """ + @param heights: Students height + @return: How many people are not where they should be + """ + def orderCheck(self, heights): + # write your code here + ret = 0 + sorte_heights = sorted(heights) + for i in range(len(heights)): + if heights[i] != sorte_heights[i]: + ret += 1 + return ret + +# easy: https://www.lintcode.com/problem/order-check/ diff --git a/paint_fence.py b/paint-fence.py similarity index 100% rename from paint_fence.py rename to paint-fence.py diff --git a/paint-fill.py b/paint-fill.py new file mode 100644 index 0000000..fac89ac --- /dev/null +++ b/paint-fill.py @@ -0,0 +1,29 @@ +class Solution: + """ + @param screen: a two-dimensional array of colors + @param x: the abscissa of the specified point + @param y: the ordinate of the specified point + @param newColor: the specified color + @return: Can it be filled + """ + def paintFill(self, screen, x, y, newColor): + # write your code here. + if screen[x][y] == newColor: + return False + old_color = screen[x][y] + screen[x][y] = newColor + if x > 0: # Left + if screen[x - 1][y] == old_color: + self.paintFill(screen, x - 1, y, newColor) + elif x < (len(screen[0]) - 1): # Right + if screen[x + 1][y] == old_color: + self.paintFill(screen, x + 1, y, newColor) + elif y > 0: # Up + if screen[x][y - 1] == old_color: + self.paintFill(screen, x, y - 1, newColor) + elif y < (len(screen) - 1): + if screen[x][y + 1] == old_color: + self.paintFill(screen, x, y + 1, newColor) + return True + +# easy: https://www.lintcode.com/problem/paint-fill/ diff --git a/paint_house.py b/paint-house.py similarity index 100% rename from paint_house.py rename to paint-house.py diff --git a/palindrome_linked_list.py b/palindrome-linked-list.py similarity index 100% rename from palindrome_linked_list.py rename to palindrome-linked-list.py diff --git a/palindrome-number-ii.py b/palindrome-number-ii.py new file mode 100644 index 0000000..ae8d025 --- /dev/null +++ b/palindrome-number-ii.py @@ -0,0 +1,14 @@ +class Solution: + """ + @param n: non-negative integer n. + @return: return whether a binary representation of a non-negative integer n is a palindrome. + """ + def isPalindrome(self, n): + # Write your code here + num = bin(n)[2:] + for i in range(len(num)): + if num[i] != num[-i - 1]: + return False + return True + +# easy: https://www.lintcode.com/problem/807 diff --git a/palindrome-number.py b/palindrome-number.py new file mode 100644 index 0000000..a56dc5f --- /dev/null +++ b/palindrome-number.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param num: a positive number + @return: true if it's a palindrome or false + """ + def isPalindrome(self, num): + # write your code here + s = str(num) # 转字符串以免溢出 + i, j = 0, len(s) - 1 + while i < j: + if s[i] == s[j]: + i += 1 + j -= 1 + else: + return False + return True + +# easy: https://www.lintcode.com/problem/palindrome-number diff --git a/palindrome_partitioning.py b/palindrome-partitioning.py similarity index 100% rename from palindrome_partitioning.py rename to palindrome-partitioning.py diff --git a/palindrome_partitioning_ii.py b/palindrome-partitioning_ii.py similarity index 100% rename from palindrome_partitioning_ii.py rename to palindrome-partitioning_ii.py diff --git a/palindrome-permutation.py b/palindrome-permutation.py new file mode 100644 index 0000000..47334a7 --- /dev/null +++ b/palindrome-permutation.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param s: the given string + @return: if a permutation of the string could form a palindrome + """ + def canPermutePalindrome(self, s): + # write your code here + counting = {} + for c in s: + if c not in counting: + counting[c] = 1 + else: + counting[c] += 1 + not_2 = 0 + for k, v in counting.items(): + if (v % 2) != 0: + not_2 += 1 + if (len(s) % 2) == 0: + return not_2 == 0 + else: + return not_2 == 1 + +# easy: https://www.lintcode.com/problem/palindrome-permutation/ diff --git a/palindromic-substrings.py b/palindromic-substrings.py new file mode 100644 index 0000000..1c5bcda --- /dev/null +++ b/palindromic-substrings.py @@ -0,0 +1,47 @@ +def count_alindromic(s, begin, end, count): + while (begin >= 0) and (end < len(s)): + if s[begin] == s[end]: + count[0] += 1 + begin -= 1 + end += 1 + else: + break + +class Solution: + """ + @param str: s string + @return: return an integer, denote the number of the palindromic substrings + """ + def countPalindromicSubstrings(self, _str): + # write your code here + # 回文可以是奇数,也可以是偶数。 + # 如果xy...yx是回文,那么y...y一定也是回文。 + ret = [0] + for i in range(len(_str)): + count_alindromic(_str, i, i, ret) + count_alindromic(_str, i, i + 1, ret) + return ret[0] + +########## + +class Solution: + """ + @param str: s string + @return: return an integer, denote the number of the palindromic substrings + """ + def countPalindromicSubstrings(self, _str): + # write your code here + # dp[i][j]表示str[i:j + 1]是否为回文串。 + # 如果dp[i][j]是回文串,那么dp[i + 1][j - 1]一定也是。 + ret = 0 + dp = [[False] * len(_str) for i in range(len(_str))] + for i in range(len(_str) - 1, -1, -1): + for j in range(i, len(_str)): + if _str[i] == _str[j]: + # 相邻或中间段为回文,不用担心数组越界,想一下为什么? + if ((j - i) <= 2) or dp[i + 1][j - 1]: + dp[i][j] = True + ret += 1 + return ret + +# easy: https://www.lintcode.com/problem/palindromic-substrings/ diff --git a/parking-dilemma.py b/parking-dilemma.py new file mode 100644 index 0000000..e32b181 --- /dev/null +++ b/parking-dilemma.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param cars: integer array of length denoting the parking slots where cars are parked + @param k: integer denoting the number of cars that have to be covered by the roof + @return: return the minium length of the roof that would cover k cars + """ + def ParkingDilemma(self, cars, k): + # write your code here + cars.sort() + ret = cars[k - 1] - cars[0] + 1 + for i in range(k, len(cars)): + length = cars[i] - cars[i - k + 1] + 1 + if length < ret: + ret = length + return ret + +# easy: https://www.lintcode.com/problem/parking-dilemma/ diff --git a/partition_array_by_odd_and_even.py b/partition-array-by-odd-and-even.py similarity index 100% rename from partition_array_by_odd_and_even.py rename to partition-array-by-odd-and-even.py diff --git a/partition-array-iii.py b/partition-array-iii.py new file mode 100644 index 0000000..93f534e --- /dev/null +++ b/partition-array-iii.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param array: the input array + @param k: the sequence length + @return: if it is possible, return true, otherwise false + """ + def partitionArratIII(self, array, k): + # write your code here + if (len(array) % k) != 0: + return False + n = len(array) / k + di = {} + for i in array: + if i not in di: + di[i] = 0 + di[i] += 1 + for k, v in di.items(): + if v > n: + return False + return True + +# easy: https://www.lintcode.com/problem/partition-array-iii/ diff --git a/partition_array.py b/partition-array.py similarity index 100% rename from partition_array.py rename to partition-array.py diff --git a/partition-equal-subset-sum.py b/partition-equal-subset-sum.py new file mode 100644 index 0000000..7f4911f --- /dev/null +++ b/partition-equal-subset-sum.py @@ -0,0 +1,30 @@ +class Solution: + """ + @param nums: a non-empty array only positive integers + @return: true if can partition or false + """ + def canPartition(self, nums): + # write your code here + ''' + 1. 和为奇数一定不行 + 2. 和为偶数,使用DP,状态矩阵为dp[i][j],代表前i个元素能否构造和j。状态转移方程如下(索引从0开始算): + - 状态1:dp[i - 1][j - nums[i - 1]] -> dp[i][j] + - 状态2:dp[i - 1][j] -> dp[i][j] + ''' + nums_sum = sum(nums) + if (nums_sum % 2) != 0: + return False + nums_sum = int(nums_sum / 2) + nums_len = len(nums) + dp = [[False] * (nums_sum + 1) for i in range(nums_len + 1)] + for i in range(nums_len + 1): + dp[i][0] = True # 0个元素就构造和为0 + for i in range(1, nums_len + 1): + for j in range(1, nums_sum + 1): + if j >= nums[i - 1]: + dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i - 1]] + else: + dp[i][j] = dp[i - 1][j] + return dp[nums_len][nums_sum] + +# medium: https://www.lintcode.com/problem/partition-equal-subset-sum/ diff --git a/partition_list.py b/partition-list.py similarity index 100% rename from partition_list.py rename to partition-list.py diff --git a/partitioning-array.py b/partitioning-array.py new file mode 100644 index 0000000..438bde6 --- /dev/null +++ b/partitioning-array.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param A: Integer array + @param k: a integer + @return: return is possible to partition the array satisfying the above conditions + """ + def PartitioningArray(self, A, k): + # write your code here + if len(A) % k != 0: + return False + di = {} + for i in A: + if i not in di: + di[i] = 1 + else: + di[i] += 1 + if di[i] > k: + return False + return True + +# easy: https://www.lintcode.com/problem/partitioning-array/ diff --git a/pascals-triangle-ii.py b/pascals-triangle-ii.py new file mode 100644 index 0000000..34a3f8e --- /dev/null +++ b/pascals-triangle-ii.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param rowIndex: a non-negative index + @return: the kth index row of the Pascal's triangle + """ + def getRow(self, rowIndex): + # write your code here + rows = [[1, 1], []] + idx = 0 + for i in range(1, rowIndex): + idx_next = 1 - idx + rows[idx_next] = [1] * (i + 2) + for j in range(1, i + 1): + rows[idx_next][j] = rows[idx][j - 1] + rows[idx][j] + idx, idx_next = idx_next, idx + return rows[idx] + +# easy: https://www.lintcode.com/problem/pascals-triangle-ii/ diff --git a/pascals-triangle.py b/pascals-triangle.py new file mode 100644 index 0000000..a8c2692 --- /dev/null +++ b/pascals-triangle.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param numRows: num of rows + @return: generate Pascal's triangle + """ + def generate(self, numRows): + # write your code here + ret = [] + for i in range(numRows): + row = [1] * (i + 1) + for j in range(1, i): + row[j] = ret[-1][j - 1] + ret[-1][j] + ret.append(row) + return ret + +# easy: https://www.lintcode.com/problem/pascals-triangle/ diff --git a/path-sum.py b/path-sum.py new file mode 100644 index 0000000..585fe70 --- /dev/null +++ b/path-sum.py @@ -0,0 +1,29 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the tree + @param sum: the sum + @return: if the tree has a root-to-leaf path + """ + def pathSum(self, root, sum): + # Write your code here. + if not root: + return False + if (not root.left) and (not root.right): + return root.val == sum + b_left, b_right = False, False + if root.left: + b_left = self.pathSum(root.left, sum - root.val) + if root.right: + b_right = self.pathSum(root.right, sum - root.val) + return b_left or b_right + + +# easy: https://www.lintcode.com/problem/path-sum/ diff --git a/peak-index-in-a-mountain-array.py b/peak-index-in-a-mountain-array.py new file mode 100644 index 0000000..8c30ecd --- /dev/null +++ b/peak-index-in-a-mountain-array.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param A: an array + @return: any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] + """ + def peakIndexInMountainArray(self, A): + # Write your code here + # 二分法,找到一个满足比左右元素都大的元素即可。 + left, right = 0, len(A) - 1 + while left < right: + mid = left + int((right - left) / 2) + if A[mid] < A[mid + 1]: + left = mid + 1 + else: + right = mid + return right + + +# easy: https://www.lintcode.com/problem/peak-index-in-a-mountain-array/ diff --git a/perfect-number.py b/perfect-number.py new file mode 100644 index 0000000..e156c34 --- /dev/null +++ b/perfect-number.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param num: an integer + @return: returns true when it is a perfect number and false when it is not + """ + def checkPerfectNumber(self, num): + # write your code here + if num == 1: + return False + ret = 1 + i = 2 + while i * i <= num: + if num % i == 0: + ret += (i + int(num / i)) + i += 1 + return ret == num + +# easy: https://www.lintcode.com/problem/perfect-number/ diff --git a/perfect_squares.py b/perfect-squares.py similarity index 100% rename from perfect_squares.py rename to perfect-squares.py diff --git a/perfect-string.py b/perfect-string.py new file mode 100644 index 0000000..3ea6e91 --- /dev/null +++ b/perfect-string.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param s: string need to be transformed + @param k: minimum char can be transformed in one operation + @return: minimum times to transform all char into '1' + """ + def perfectString(self, s, k): + # Write your code here + ret = 0 + cz = k # 技巧! + for c in s: + if c == '0': + if cz == k: + ret += 1 # 遇到0就替换,后面连着的0尽可能多的一起替换。 + cz -= 1 + else: + cz = k # 重置 + if cz == 0: # 最多替换k个0 + cz = k + return ret + +# easy: https://www.lintcode.com/problem/perfect-string/ diff --git a/permutation-index.py b/permutation-index.py new file mode 100644 index 0000000..00887a2 --- /dev/null +++ b/permutation-index.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param A: An array of integers + @return: A long integer + """ + def permutationIndex(self, A): + # write your code here + ret = 1 + facts = [1] + for i in range(1, len(A)): + facts.append(facts[-1] * i) + for i in range(len(A)): + rc = 0 # 逆序数 + for j in range(i + 1, len(A)): + if A[i] > A[j]: + rc += 1 + ret += rc * facts[len(A) - i - 1] + return ret + +# medium: http://lintcode.com/zh-cn/problem/permutation-index/ diff --git a/permutation_sequence.py b/permutation-sequence.py similarity index 100% rename from permutation_sequence.py rename to permutation-sequence.py diff --git a/permutation_index.py b/permutation_index.py deleted file mode 100644 index 47eed2b..0000000 --- a/permutation_index.py +++ /dev/null @@ -1,18 +0,0 @@ -# coding: utf-8 - -class Solution: - # @param {int[]} A an integer array - # @return {long} a long integer - def permutationIndex(self, A): - # Write your code here - ret = 1 - for i in xrange(0, len(A)): - fact, rc = 1, 0 # 初始化阶乘与逆序数 - for j in xrange(i + 1, len(A)): - if A[i] > A[j]: - rc += 1 - fact *= (j - i) - ret += rc * fact - return ret - -# easy: http://lintcode.com/zh-cn/problem/permutation-index/ diff --git a/permutations_ii.py b/permutations-ii.py similarity index 100% rename from permutations_ii.py rename to permutations-ii.py diff --git a/pick-apples.py b/pick-apples.py new file mode 100644 index 0000000..fda8e74 --- /dev/null +++ b/pick-apples.py @@ -0,0 +1,34 @@ +from typing import ( + List, +) + +class Solution: + """ + @param a: a list of integer + @param k: a integer + @param l: a integer + @return: return the maximum number of apples that they can collect. + """ + def pick_apples(self, a: List[int], k: int, l: int) -> int: + # write your code here + r = -1 + n = len(a) + if (k + l) > n: + return r + alice, bob = [0] * n, [0] * n + # 构造alice选k颗树的可能结果,可以写两重循环,但是当k非常大时,这样效率高。 + for i in range(k): + alice[k - 1] += a[i] + for i in range(k, n): + alice[i] = alice[i - 1] + a[i] - a[i - k] + for i in range(l): + bob[l - 1] += a[i] + for i in range(l, n): + bob[i] = bob[i - 1] + a[i] - a[i - l] + for i in range(k - 1, n): + for j in range(l - 1, n): + if ((i - j) >= k) or ((j -i) >= l): + r = max(r, alice[i] + bob[j]) + return r + +# medium: https://www.lintcode.com/problem/1850 diff --git a/pick-carrots.py b/pick-carrots.py new file mode 100644 index 0000000..e953b8f --- /dev/null +++ b/pick-carrots.py @@ -0,0 +1,37 @@ +class Solution: + """ + @param carrot: an integer matrix + @return: Return the number of steps that can be moved. + """ + def PickCarrots(self, carrot): + # write your code here + rows = len(carrot) + cols = len(carrot[0]) + cr = int((rows -1) / 2) + cc = int((cols -1) / 2) + marked = [[False] * cols for i in range(rows)] + ret = carrot[cr][cc] + marked[cr][cc] = True + r, c = cr, cc + while True: + dirs = [[r - 1, c], [r + 1, c], [r, c - 1], [r, c + 1]] # 上下左右 + nums = [-1, -1, -1, -1] + pos = 0 + for i in range(len(dirs)): + _r = dirs[i][0] + _c = dirs[i][1] + if ((_r >= 0) and (_r < rows)) and ((_c >= 0) and (_c < cols)) and (not marked[_r][_c]): + nums[i] = carrot[_r][_c] + if nums[i] >= nums[pos]: + pos = i + if nums[pos] == -1: + break + r = dirs[pos][0] + c = dirs[pos][1] + if marked[r][c]: + break + ret += carrot[r][c] + marked[r][c] = True + return ret + +# easy: https://www.lintcode.com/problem/pick-carrots/ diff --git a/pioneering-palindrome.py b/pioneering-palindrome.py new file mode 100644 index 0000000..a6a3bda --- /dev/null +++ b/pioneering-palindrome.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param s: A string containing only uppercase and lowercase letters + @return: Judge whether it can become a palindrome + """ + def isPalindrome(self, s): + # write your code here + di = {} + odd_chars = 0 + for c in s: + if c not in di: + di[c] = 0 + di[c] += 1 + for k, v in di.items(): + if (v % 2) == 1: + odd_chars += 1 + return odd_chars <= 1 + +# easy: https://www.lintcode.com/problem/pioneering-palindrome/ diff --git a/plus-one-linked-list.py b/plus-one-linked-list.py new file mode 100644 index 0000000..f6438c3 --- /dev/null +++ b/plus-one-linked-list.py @@ -0,0 +1,39 @@ +""" +Definition of ListNode +class ListNode(object): + def __init__(self, val, next=None): + self.val = val + self.next = next +""" + +class Solution: + """ + @param head: the first Node + @return: the answer after plus one + """ + def plusOne(self, head): + # Write your code here + new_head = self.reverse(head) + flag = 1 + node = new_head + prev = None + while node: + node.val += flag + flag = int(node.val / 10) + node.val %= 10 + prev = node + node = node.next + if flag > 0: + prev.next = ListNode(flag) + return self.reverse(new_head) + + def reverse(self, head): + new_head = None + while head: + node = head + head = head.next + node.next = new_head + new_head = node + return new_head + +# medium: https://www.lintcode.com/problem/plus-one-linked-list/ diff --git a/plus_one.py b/plus-one.py similarity index 100% rename from plus_one.py rename to plus-one.py diff --git a/poor-pigs.py b/poor-pigs.py new file mode 100644 index 0000000..fb2a4d5 --- /dev/null +++ b/poor-pigs.py @@ -0,0 +1,30 @@ +class Solution: + """ + @param buckets: an integer + @param minutesToDie: an integer + @param minutesToTest: an integer + @return: how many pigs you need to figure out the "poison" bucket within p minutes + """ + def poorPigs(self, buckets, minutesToDie, minutesToTest): + # Write your code here + # 一次喝一桶,停m分钟再喝下一桶。 + # 先处理限制1小时的情况 + # - 一只猪1小时5桶水,没法更快了。 + # - 25桶水怎么办?排除5行5列,然后: + # * * * * * Y1 + # * * * * * Y2 + # * * * * * Y3 + # * * * * * Y4 + # * * * * * Y5 + # X1 X2 X3 X4 X5 + # 猪1确定X坐标,猪2确定Y坐标,2只搞定。 + # 那么我们现在不用关心几桶水,反过来看3只猪的情况,坐标从2维扩展到3维,能处理125桶水。 + # 下面处理通用情况,m分钟死,限制p分钟,1只猪能确定int(m / p) + 1桶水。 + # 那么考虑空间维度,一个pow函数搞定。 + n = int(minutesToTest / minutesToDie) + 1 + ret = 0 + while pow(n, ret) < buckets: + ret += 1 + return ret + +# easy: https://www.lintcode.com/problem/poor-pigs/ diff --git a/positions-of-large-groups.py b/positions-of-large-groups.py new file mode 100644 index 0000000..3f65269 --- /dev/null +++ b/positions-of-large-groups.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param S: a string + @return: the starting and ending positions of every large group + """ + def largeGroupPositions(self, S): + # Write your code here + ret = [] + prev = S[0] + count = [[0, 0]] + for i in range(1, len(S)): + c = S[i] + if c == prev: + count[-1][1] = i + else: + prev = c + count.append([i, i]) + for c in count: + if (c[1] - c[0]) >= 2: + ret.append(c) + return ret + +# easy: https://www.lintcode.com/problem/positions-of-large-groups/ diff --git a/power-of-four.py b/power-of-four.py new file mode 100644 index 0000000..9de7fab --- /dev/null +++ b/power-of-four.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param num: an integer + @return: whether the integer is a power of 4 + """ + def isPowerOfFour(self, num): + # Write your code here + s = set([1, + 4, + 16, + 64, + 256, + 1024, + 4096, + 16384, + 65536, + 262144, + 1048576, + 4194304, + 16777216, + 67108864, + 268435456, + 1073741824]) + return num in s + +# easy: https://www.lintcode.com/problem/power-of-four/ diff --git a/power-of-three.py b/power-of-three.py new file mode 100644 index 0000000..d6196ab --- /dev/null +++ b/power-of-three.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param n: an integer + @return: if n is a power of three + """ + def isPowerOfThree(self, n): + # Write your code here + # 用log的方法我不认为合理,只是隐藏了循环。 + ret = False + i = 1 + while i <= n: + if i == n: + ret = True + break + else: + i *= 3 + return ret + +# easy: https://www.lintcode.com/problem/power-of-three/ diff --git a/power-of-two.py b/power-of-two.py new file mode 100644 index 0000000..e4ea57f --- /dev/null +++ b/power-of-two.py @@ -0,0 +1,12 @@ +class Solution: + """ + @param n: an integer + @return: if n is a power of two + """ + def isPowerOfTwo(self, n): + # Write your code here + if n == 0: + return False + return (n & (n - 1)) == 0 + +# easy: https://www.lintcode.com/problem/power-of-two/ diff --git a/powx_n.py b/powx-n.py similarity index 100% rename from powx_n.py rename to powx-n.py diff --git a/prettyprint.py b/prettyprint.py new file mode 100644 index 0000000..f6a1786 --- /dev/null +++ b/prettyprint.py @@ -0,0 +1,35 @@ +class Solution: + """ + @param text: the text to print + @param width: the width of the window + @return: return the result of pretty print. + """ + def prettyPrint(self, text, width): + # write your code here + ret = ['*' * (width + 2)] + for line in text: + n = width + _line = [] + for word in line: + if n >= (len(word) + 1): + _line.append(word) + n -= (len(word) + 1) + else: + if n == len(word): + _line.append(word) + fmt_line = ' '.join(_line) + ret.append('*' + fmt_line + ' ' * (width - len(fmt_line)) + '*') + _line = [] + n = width + else: + fmt_line = ' '.join(_line) + ret.append('*' + fmt_line + ' ' * (width - len(fmt_line)) + '*') + _line = [word] + n = width - (len(word) + 1) + if _line: + fmt_line = ' '.join(_line) + ret.append('*' + fmt_line + ' ' * (width - len(fmt_line)) + '*') + ret.append('*' * (width + 2)) + return ret + +# easy: https://www.lintcode.com/problem/prettyprint/ diff --git a/previous_permutation.py b/previous-permutation.py similarity index 100% rename from previous_permutation.py rename to previous-permutation.py diff --git a/prime-factor-statistics.py b/prime-factor-statistics.py new file mode 100644 index 0000000..05642a1 --- /dev/null +++ b/prime-factor-statistics.py @@ -0,0 +1,15 @@ +class Solution: + """ + @param N: a number + @return: the number of prime numbers. + """ + def Count_PrimeNum(self, N): + # + dp = [1] * (N + 1) # 技巧在这里,对于dp[2]及之后元素,本来就至少有一个质因数。 + for num in range(3, N + 1): + for i in range(2, int(math.sqrt(num)) + 1): + if num % i == 0: + d = int(num / i) + dp[num] = dp[i] + dp[d] + break + return sum(dp[2:]) diff --git a/prime-factorization.py b/prime-factorization.py new file mode 100644 index 0000000..43039e6 --- /dev/null +++ b/prime-factorization.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param num: An integer + @return: an integer array + """ + def primeFactorization(self, num): + # write your code here + ret = [] + i = 2 + while i * i <= num: + if (num % i) == 0: + ret.append(i) + num = int(num / i) + i = 2 + else: + i += 1 + if num > 0: + ret.append(num) + return ret + +# easy: https://www.lintcode.com/problem/235 diff --git a/prime-number-of-set-bits-in-binary-representation.py b/prime-number-of-set-bits-in-binary-representation.py new file mode 100644 index 0000000..4565c1e --- /dev/null +++ b/prime-number-of-set-bits-in-binary-representation.py @@ -0,0 +1,36 @@ +class Solution: + """ + @param L: an integer + @param R: an integer + @return: the count of numbers in the range [L, R] having a prime number of set bits in their binary representation + """ + def countPrimeSetBits(self, L, R): + # Write your code here + ret = 0 + for i in range(L, R + 1): + c = self.count_1(i) + if self.is_prime(c): + ret += 1 + return ret + + def count_1(self, n): + ret = 0 + while (n > 0): + if (n % 2) == 1: + ret += 1 + n = int(n / 2) + return ret + + def is_prime(self, n): + if n == 1: + return False + elif n == 2: + return True + else: + for i in range(2, n): + if (i * i) <= n: + if (n % i) == 0: + return False + return True + +# easy: https://www.lintcode.com/problem/prime-number-of-set-bits-in-binary-representation/ diff --git a/print_numbers_by_recursion.py b/print-numbers-by-recursion.py similarity index 100% rename from print_numbers_by_recursion.py rename to print-numbers-by-recursion.py diff --git a/processing-form.py b/processing-form.py new file mode 100644 index 0000000..65b7acf --- /dev/null +++ b/processing-form.py @@ -0,0 +1,31 @@ +from typing import ( + List, +) + +class Solution: + """ + @param a: the csv file a + @return: return the processed file + """ + def processing_file(self, a: List[str]) -> List[str]: + # Write your code here + ret = [] + rows = len(a) + ls = [] + for i in range(rows): + words = a[i].split(',') + for i in range(len(words)): + if i >= len(ls): + ls.append(len(words[i])) + if len(words[i]) > ls[i]: + ls[i] = len(words[i]) + for i in range(rows): + s = [] + words = a[i].split(',') + for i in range(len(words)): + w = words[i] + s.append(' ' * (ls[i] - len(w)) + w) + ret.append(','.join(s)) + return ret + +# medium: https://www.lintcode.com/problem/1618/ diff --git a/product-list.py b/product-list.py new file mode 100644 index 0000000..ea25845 --- /dev/null +++ b/product-list.py @@ -0,0 +1,32 @@ +class Solution: + """ + @param offset: the number of items that the customer has viewed + @param n: the number of items that can be displayed on a page + @param len1: the length of L1 + @param len2: the length of L2 + @return: returns the intervals of goods displayed in L1 and L2 + """ + def ProductList(self, offset, n, len1, len2): + # write your code here + ret = [0, 0, 0, 0] + total = offset + n + if offset < len1: + ret[0] = offset + if total <= len1: + ret[1] = total + else: + ret[1] = len1 + else: + ret[0] = len1 + ret[1] = len1 + if total >= len1: + if offset >= len1: + ret[2] = offset - len1 + print(total, len1) + total -= len1 + if total > len2: + total = len2 + ret[3] = total + return ret + +# easy: https://www.lintcode.com/problem/product-list/ diff --git a/product_of_array_exclude_itself.py b/product-of-array-exclude-itself.py similarity index 100% rename from product_of_array_exclude_itself.py rename to product-of-array-exclude-itself.py diff --git a/range-addition-ii.py b/range-addition-ii.py new file mode 100644 index 0000000..eb43337 --- /dev/null +++ b/range-addition-ii.py @@ -0,0 +1,15 @@ +class Solution: + """ + @param m: an integer + @param n: an integer + @param ops: List[List[int]] + @return: return an integer + """ + def maxCount(self, m, n, ops): + # write your code here + if not ops: + return m * n + ops = zip(*ops) + return min(ops[0]) * min(ops[1]) + +# easy: https://www.lintcode.com/problem/range-addition-ii/ diff --git a/range-sum-query-immutable.py b/range-sum-query-immutable.py new file mode 100644 index 0000000..dc19684 --- /dev/null +++ b/range-sum-query-immutable.py @@ -0,0 +1,19 @@ +class NumArray(object): + + def __init__(self, nums): + """ + :type nums: List[int] + """ + self.cache = [0] + for i in nums: + self.cache.append(i + self.cache[-1]) + + def sumRange(self, i, j): + """ + :type i: int + :type j: int + :rtype: int + """ + return self.cache[j + 1] - self.cache[i] + +# easy: https://www.lintcode.com/problem/range-sum-query-immutable/ diff --git a/ransom-note.py b/ransom-note.py new file mode 100644 index 0000000..9f9a534 --- /dev/null +++ b/ransom-note.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param ransomNote: a string + @param magazine: a string + @return: whether the ransom note can be constructed from the magazines + """ + def canConstruct(self, ransomNote, magazine): + # Write your code here + di = {} + for c in magazine: + if c not in di: + di[c] = 1 + else: + di[c] += 1 + for c in ransomNote: + if c not in di: + return False + else: + di[c] -= 1 + if di[c] < 0: + return False + return True + +# easy: https://www.lintcode.com/problem/ransom-note/ diff --git a/reach-a-number.py b/reach-a-number.py new file mode 100644 index 0000000..42f2e7b --- /dev/null +++ b/reach-a-number.py @@ -0,0 +1,34 @@ +class Solution: + """ + @param target: the destination + @return: the minimum number of steps + """ + def reachNumber(self, target): + # Write your code here + ''' + 思路解析:暴力法可以解,但是一定超时! + 1. target正负是等价的。 + 2. 一直走,到大于等于target为止。如果相等,直接返回步数。 + 3. 不相等,处理以下几种情况:(n一定比step小) + 1. 差n为偶数,找到之前的n步一负一正即可解决。步数不变。 + 2. 差n为奇数,想办法把它变成偶数就和上面的情况一样了。 + 1. 步数step为偶数,多走一步就是偶数了(n + (step + 1) = 偶数)。 + 2. 步数step为奇数,必须多走两步(n + (step + 1) + (step + 2) = 偶数) + ''' + target = int(math.fabs(target)) + pos, step = 0, 1 + while (pos < target): + pos += step; + step += 1 + step -= 1 # 总共走了几步 + if pos == target: + return step + pos -= target + if (pos % 2) == 0: + return step + if (step % 2) == 0: + return step + 1 + else: + return step + 2 + +# easy: https://www.lintcode.com/problem/reach-a-number/ diff --git a/reaching-point-ii.py b/reaching-point-ii.py new file mode 100644 index 0000000..7c3d5a8 --- /dev/null +++ b/reaching-point-ii.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param start: a point [x, y] + @param target: a point [x, y] + @return: return True and False + """ + def ReachingPointsII(self, start, target): + # write your code here + ''' + Look somebody's clue, it's really interesting! + if target-y > target-x, it means it comes from (x, y) to (x, x + y), vice versa. + So you should immediately know what to do, but do minus is too slow! + Think about [1, 1] to [1, 1,000,000,000]... + Let's make a example: [4, 15], run this way: + - [4, 11] + - [4, 7] + - [4, 3] 11 % 4 = 3, so let's go!!! + ''' + while (start[0] < target[0]) and (start[1] < target[1]): + if target[1] > target[0]: + target[1] %= target[0] + else: + target[0] %= target[1] + f1 = (start[0] == target[0]) and (((target[1] - start[1]) % start[0]) == 0) + f2 = (start[1] == target[1]) and (((target[0] - start[0]) % start[1]) == 0) + return f1 or f2 + +# medium: https://www.lintcode.com/problem/1846 diff --git a/reaching-point.py b/reaching-point.py new file mode 100644 index 0000000..218503e --- /dev/null +++ b/reaching-point.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param start: a point [x, y] + @param target: a point [x, y] + @return: return True or False + """ + def ReachingPoints(self, start, target): + # write your code here + while start != target: + if (target[0] < start[0]) or (target[1] < start[1]): + return False + if target[0] < target[1]: + target[1] -= target[0] + else: + target[0] -= target[1] + return True diff --git a/rearrange-a-string-with-integers.py b/rearrange-a-string-with-integers.py new file mode 100644 index 0000000..061d75e --- /dev/null +++ b/rearrange-a-string-with-integers.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param str: a string containing uppercase alphabets and integer digits + @return: the alphabets in the order followed by the sum of digits + """ + def rearrange(self, str): + # Write your code here + count = 0 + ret = [] + for c in str: + if (c < '0') or (c > '9'): + ret.append(c) + else: + count += int(c) + ret.sort() + if count != 0: + ret.append(count.__str__()) + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/rearrange-a-string-with-integers diff --git a/recommended-results-are-scattered.py b/recommended-results-are-scattered.py new file mode 100644 index 0000000..d354af3 --- /dev/null +++ b/recommended-results-are-scattered.py @@ -0,0 +1,40 @@ +class Solution: + """ + @param elements: A list of recommended elements. + @param n: [picture P] can appear at most 1 in every n + @return: Return the scattered result. + """ + def scatter(self, elements, n): + # write your code here + ret = [] + start = 0 + while start < len(elements): + if elements[start].startswith('P'): + ret.extend(elements[:start + 1]) + break + start += 1 + plist, vlist = [], [] + for i in range(start + 1, len(elements)): + e = elements[i] + if e.startswith('P'): + plist.append(e) + else: + vlist.append(e) + v_start, p_start = 0, 0 + while True: + if v_start == len(vlist): + break + elif (len(vlist) - v_start) < (n - 1): + ret.extend(vlist[v_start:]) + else: + ret.extend(vlist[v_start : v_start + n - 1]) + if p_start >= len(plist): + break + v_start += (n - 1) + if v_start > len(vlist): + break + ret.append(plist[p_start]) + p_start += 1 + return ret + +# easy: https://www.lintcode.com/problem/recommended-results-are-scattered/ diff --git a/recover-binary-search-tree.py b/recover-binary-search-tree.py new file mode 100644 index 0000000..c9f87ab --- /dev/null +++ b/recover-binary-search-tree.py @@ -0,0 +1,41 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the given tree + @return: the tree after swapping + """ + def bstSwappedNode(self, root): + # write your code here + nodes = [] + self.inorder(root, nodes) + start, end = 0, len(nodes) - 1 + while start < len(nodes) - 1: + if nodes[start].val < nodes[start + 1].val: + start += 1 + else: + break + while end >= 1: + if nodes[end].val > nodes[end - 1].val: + end -= 1 + else: + break + if start < end: + nodes[start].val, nodes[end].val = nodes[end].val, nodes[start].val + return root + + def inorder(self, root, nodes): + if root: + if root.left: + self.inorder(root.left, nodes) + nodes.append(root) + if root.right: + self.inorder(root.right, nodes) + +# medium: https://www.lintcode.com/problem/recover-binary-search-tree/ diff --git a/recover_rotated_sorted_array.py b/recover-rotated-sorted-array.py similarity index 100% rename from recover_rotated_sorted_array.py rename to recover-rotated-sorted-array.py diff --git a/rectangle_area.py b/rectangle-area.py similarity index 100% rename from rectangle_area.py rename to rectangle-area.py diff --git a/rectangle-overlap.py b/rectangle-overlap.py new file mode 100644 index 0000000..45954d2 --- /dev/null +++ b/rectangle-overlap.py @@ -0,0 +1,25 @@ +""" +Definition for a point. +class Point: + def __init__(self, a=0, b=0): + self.x = a + self.y = b +""" + +class Solution: + """ + @param l1: top-left coordinate of first rectangle + @param r1: bottom-right coordinate of first rectangle + @param l2: top-left coordinate of second rectangle + @param r2: bottom-right coordinate of second rectangle + @return: true if they are overlap or false + """ + def doOverlap(self, l1, r1, l2, r2): + # write your code here + # 不重叠的规则比较好写,xy轴同时不交叉即可。 + if (((l2.x > r1.x) or (r2.x < l1.x)) \ + or ((r2.y > l1.y) or (l2.y < r1.y))): + return False + return True + +# https://www.lintcode.com/problem/rectangle-overlap/ diff --git a/regular_expression_matching.py b/regular-expression-matching.py similarity index 100% rename from regular_expression_matching.py rename to regular-expression-matching.py diff --git a/relative-ranks.py b/relative-ranks.py new file mode 100644 index 0000000..df40106 --- /dev/null +++ b/relative-ranks.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param nums: List[int] + @return: return List[str] + """ + def findRelativeRanks(self, nums): + # write your code here + ret = [] + sorted_nums = sorted(nums)[::-1] + di = {} + for i in range(len(sorted_nums)): + di[sorted_nums[i]] = i + 1 + if i < 3: + di[sorted_nums[i]] = ['Gold Medal', 'Silver Medal', 'Bronze Medal'][i] + for i in nums: + ret.append(str(di[i])) + return ret + +# easy: https://www.lintcode.com/problem/relative-ranks/ diff --git a/remove-arbitrary-space.py b/remove-arbitrary-space.py new file mode 100644 index 0000000..c8edcc7 --- /dev/null +++ b/remove-arbitrary-space.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param s: the original string + @return: the string without arbitrary spaces + """ + def removeExtra(self, s): + # write your code here + ret = [] + for c in s: + if not ret: + if c != ' ': + ret.append(c) + else: + if c != ' ': + ret.append(c) + else: + if c != ret[-1]: + ret.append(c) + return ''.join(ret).rstrip() + +# easy: https://www.lintcode.com/problem/remove-arbitrary-space/ diff --git a/remove-dights.py b/remove-dights.py new file mode 100644 index 0000000..575dcfe --- /dev/null +++ b/remove-dights.py @@ -0,0 +1,30 @@ +class Solution: + """ + @param num: a number + @param k: the k digits + @return: the smallest number + """ + def removeKdigits(self, num, k): + # write your code here. + if k <= 0: + return num + if k >= len(num): + return '0' + new_len = len(num) - k + stack = [] + for i in range(len(num)): + while stack and (k > 0) and (stack[-1] > num[i]): + # 当前元素比栈顶元素小,且还有数字可以删除。 + stack.pop() + k = k - 1 + stack.append(num[i]) + start = 0 + while stack[start] == '0': + start += 1 + if start >= new_len: + break + if start >= new_len: + return '0' + return ''.join(stack[start:new_len]) + +# easy: https://www.lintcode.com/problem/remove-dights/ diff --git a/remove-duplicate-letters.py b/remove-duplicate-letters.py new file mode 100644 index 0000000..20d8983 --- /dev/null +++ b/remove-duplicate-letters.py @@ -0,0 +1,35 @@ +class Solution: + """ + @param s: a string + @return: return a string + """ + def removeDuplicateLetters(self, s): + # write your code here + ''' + 因为要求字典序最小,当一个字符出现的时候,必须进行如下判断: + 1. 如果ret没有内容直接加入 + 2. 判断ret最后一个字符 + - 如果还有出现机会:如果比当前字符大,删掉,继续比ret的最后一个字符,因为字典序要求最小。 + - 将当前字符插入 + ''' + ret = [] + counting = {} + visited = {} + for c in s: + if c not in counting: + counting[c] = 1 + else: + counting[c] += 1 + visited[c] = False # 先初始化为False + for c in s: + counting[c] -= 1 + if visited[c]: + continue + while (len(ret) > 0) and (counting[ret[-1]] > 0) and (ret[-1] > c): + visited[ret[-1]] = False + ret.pop() + ret.append(c) + visited[c] = True + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/remove-duplicate-letters/ diff --git a/remove-duplicate-numbers-in-array.py b/remove-duplicate-numbers-in-array.py new file mode 100644 index 0000000..b6b544e --- /dev/null +++ b/remove-duplicate-numbers-in-array.py @@ -0,0 +1,25 @@ +class Solution: + """ + @param nums: an array of integers + @return: the number of unique integers + """ + def deduplication(self, nums): + # write your code here + ''' + nums.sort() + steps = 0 + for i in range(1, len(nums)): + if nums[i] == nums[i - 1]: + steps += 1 + else: + nums[i - steps] = nums[i] + return len(nums) - steps + ''' + s = set(nums) + i = 0 + for v in s: + nums[i] = v + i += 1 + return len(s) + +# easy: https://www.lintcode.com/problem/521 diff --git a/remove_duplicates_from_sorted_array_ii.py b/remove-duplicates-from-sorted-array-ii.py similarity index 100% rename from remove_duplicates_from_sorted_array_ii.py rename to remove-duplicates-from-sorted-array-ii.py diff --git a/remove_duplicates_from_sorted_array.py b/remove-duplicates-from-sorted-array.py similarity index 100% rename from remove_duplicates_from_sorted_array.py rename to remove-duplicates-from-sorted-array.py diff --git a/remove-duplicates-from-unsorted-list.py b/remove-duplicates-from-unsorted-list.py new file mode 100644 index 0000000..3307b31 --- /dev/null +++ b/remove-duplicates-from-unsorted-list.py @@ -0,0 +1,32 @@ +""" +Definition of ListNode +class ListNode(object): + def __init__(self, val, next=None): + self.val = val + self.next = next +""" + +class Solution: + """ + @param head: The first node of linked list. + @return: Head node. + """ + def removeDuplicates(self, head): + # write your code here + if head: + s = set([head.val]) + node = head.next + tail = head + tail.next = None + while node: + if node.val not in s: + s.add(node.val) + tail.next = node + tail = node + node = node.next + tail.next = None + else: + node = node.next + return head + +# easy: https://www.lintcode.com/problem/217/discuss diff --git a/remove_element.py b/remove-element.py similarity index 100% rename from remove_element.py rename to remove-element.py diff --git a/remove_linked_list_elements.py b/remove-linked-list-elements.py similarity index 89% rename from remove_linked_list_elements.py rename to remove-linked-list-elements.py index 67c265e..4e80060 100644 --- a/remove_linked_list_elements.py +++ b/remove-linked-list-elements.py @@ -18,4 +18,4 @@ def removeElements(self, head, val): node = node.next return head -# entry: http://www.lintcode.com/zh-cn/problem/remove-linked-list-elements/ +# naive: http://www.lintcode.com/zh-cn/problem/remove-linked-list-elements/ diff --git a/remove_node_in_binary_search_tree.py b/remove-node-in-binary-search-tree.py similarity index 100% rename from remove_node_in_binary_search_tree.py rename to remove-node-in-binary-search-tree.py diff --git a/remove_nth_node_from_end_of_list.py b/remove-nth-node-from-end-of-list.py similarity index 100% rename from remove_nth_node_from_end_of_list.py rename to remove-nth-node-from-end-of-list.py diff --git a/remove-the-invalid-parentheses.py b/remove-the-invalid-parentheses.py new file mode 100644 index 0000000..1f9037d --- /dev/null +++ b/remove-the-invalid-parentheses.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param s: A string with lowercase letters and parentheses + @return: A string which has been removed invalid parentheses + """ + def removeParentheses(self, s: str) -> str: + # write your code here. + r = [] + lps, rps = 0, 0 + for c in s: + if c != ')': + r.append(c) + if c == '(': + lps += 1 + else: + if rps < lps: + r.append(c) + rps += 1 + diff = lps - rps + for i in range(len(r) - 1, -1, -1): + if (r[i] == '(') and (diff > 0): + r[i] = '' + diff -= 1 + if diff == 0: + break + return ''.join(r) + +# easy: https://www.lintcode.com/problem/2506/ diff --git a/reorder_array_to_construct_the_minimum_number.py b/reorder-array-to-construct-the-minimum-number.py similarity index 100% rename from reorder_array_to_construct_the_minimum_number.py rename to reorder-array-to-construct-the-minimum-number.py diff --git a/reorder_list.py b/reorder-list.py similarity index 100% rename from reorder_list.py rename to reorder-list.py diff --git a/reordered-power-of-2.py b/reordered-power-of-2.py new file mode 100644 index 0000000..feb72c0 --- /dev/null +++ b/reordered-power-of-2.py @@ -0,0 +1,40 @@ +class Solution: + """ + @param n: int + @return: return true or false + """ + def reordered_power_of2(self, n: int) -> bool: + # write your code here + digits = self.get_digits(n) + p2s = [] + self.build_p2s(p2s, digits) + for p in p2s: + if self.compare(p, n): + return True + return False + + def get_digits(self, n): + r = 0 + while n > 0: + r += 1 + n = n // 10 + return r + + def build_p2s(self, p2s, digits): + i = 1 + while True: + d = self.get_digits(i) + if d < digits: + i *= 2 + elif d == digits: + p2s.append(i) + i *= 2 + else: + break + + def compare(self, v1, v2): + v1 = ''.join(sorted(str(v1))) + v2 = ''.join(sorted(str(v2))) + return v1 == v2 + +# medium: https://www.lintcode.com/problem/1499 diff --git a/repeated-string-match.py b/repeated-string-match.py new file mode 100644 index 0000000..417e1a8 --- /dev/null +++ b/repeated-string-match.py @@ -0,0 +1,43 @@ +class Solution: + """ + @param A: a string + @param B: a string + @return: return an integer + """ + def repeatedStringMatch(self, A, B): + # write your code here + # 因为存在不匹配的可能性,要确定一个次数上限。 + # 如果A的长度是5,B的长度是15/16,那么最多循环4次一定就能匹配,否则无解。 + # 具体解释(能匹配的情况): + # A的格式:ABCDE + # B的格式:EABCD-EABCD-EABCD-E + # A循环4次:ABCD-[EABCD-EABCD-EABCD-E] + # 但是如果B的长度是17,那么最多循环5次一定就能匹配,否则无解。 + # B的格式:EABCD-EABCD-EABCD-EA + # A循环4次:ABCD-[EABCD-EABCD-EABCD-EA]-BCDE + # 可以试着证明一下,然后用下面的公式计算limit。 + if A: + limit = int(len(B) / len(A)) + if (len(B) % len(A)) <= 1: + limit += 1 + else: + limit += 2 + _str = list(A) + ret = 1 + while limit >= 0: + if len(_str) >= len(B): + for i in range(len(_str) - len(B) + 1): + j = 0 + while j < len(B): + if _str[i + j] != B[j]: + break + else: + j += 1 + if j == len(B): + return ret + _str += list(A) + ret += 1 + limit -= 1 + return -1 + +# easy: https://www.lintcode.com/problem/repeated-string-match/ diff --git a/repeated-substring-pattern.py b/repeated-substring-pattern.py new file mode 100644 index 0000000..2ceeb5b --- /dev/null +++ b/repeated-substring-pattern.py @@ -0,0 +1,15 @@ +class Solution: + """ + @param s: a string + @return: return a boolean + """ + def repeatedSubstringPattern(self, s): + # write your code here + for i in range(1, int(len(s) / 2) + 1): + if (len(s) % i) == 0: + ns = s[:i] * int(len(s) / i) + if ns == s: + return True + return False + +# easy: https://www.lintcode.com/problem/repeated-substring-pattern/ diff --git a/reshape-the-matrix.py b/reshape-the-matrix.py new file mode 100644 index 0000000..7b50eea --- /dev/null +++ b/reshape-the-matrix.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param nums: List[List[int]] + @param r: an integer + @param c: an integer + @return: return List[List[int]] + """ + def matrixReshape(self, nums, r, c): + # write your code here + old_row, old_col = len(nums), len(nums[0]) + if (r * c) != (old_row * old_col): + return nums + ret = [[0] * c for i in range(r)] + for i in range(old_row): + for j in range(old_col): + idx = i * old_col + j + ret[int(idx / c)][idx % c] = nums[i][j] + return ret + +# easy: https://www.lintcode.com/problem/reshape-the-matrix/ diff --git a/restore_ip_addresses.py b/restore-ip-addresses.py similarity index 100% rename from restore_ip_addresses.py rename to restore-ip-addresses.py diff --git a/reverse_3_digit_integer.py b/reverse-3-digit-integer.py similarity index 82% rename from reverse_3_digit_integer.py rename to reverse-3-digit-integer.py index 5050864..58582bf 100644 --- a/reverse_3_digit_integer.py +++ b/reverse-3-digit-integer.py @@ -11,4 +11,4 @@ def reverseInteger(self, number): number /= 10 return ret -# entry: http://www.lintcode.com/zh-cn/problem/reverse-3-digit-integer/ +# naive: http://www.lintcode.com/zh-cn/problem/reverse-3-digit-integer/ diff --git a/reverse-array.py b/reverse-array.py new file mode 100644 index 0000000..b418594 --- /dev/null +++ b/reverse-array.py @@ -0,0 +1,14 @@ +class Solution: + """ + @param nums: a integer array + @return: nothing + """ + def reverseArray(self, nums): + # write your code here + i, j = 0, len(nums) - 1 + while i < j: + nums[i], nums[j] = nums[j], nums[i] + i += 1 + j -= 1 + +# easy: https://www.lintcode.com/problem/reverse-array/ diff --git a/reverse-ascii-encoded-strings.py b/reverse-ascii-encoded-strings.py new file mode 100644 index 0000000..e6de5e5 --- /dev/null +++ b/reverse-ascii-encoded-strings.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param encodeString: an encode string + @return: a reversed decoded string + """ + def reverseAsciiEncodedString(self, encodeString): + # Write your code here + r = [] + for i in range(len(encodeString) - 1, 0, -2): + v0 = int(encodeString[i]) + v1 = int(encodeString[i - 1]) + c = chr(v1 * 10 + v0) + r.append(c) + return ''.join(r) + +# easy: https://www.lintcode.com/problem/1781/ diff --git a/reverse-bits.py b/reverse-bits.py new file mode 100644 index 0000000..cc88b7b --- /dev/null +++ b/reverse-bits.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param n: an integer + @return: return an integer + """ + def reverseBits(self, n): + # write your code here + ret = 0 + step = 31 + while n: + i = n % 2 + ret += i << step + step -= 1 + n = int((n - i) / 2) + return ret + +# easy: https://www.lintcode.com/problem/reverse-bits/ diff --git a/reverse_integer.py b/reverse-integer.py similarity index 100% rename from reverse_integer.py rename to reverse-integer.py diff --git a/reverse_linked_list_ii.py b/reverse-linked-list-ii.py similarity index 100% rename from reverse_linked_list_ii.py rename to reverse-linked-list-ii.py diff --git a/reverse_linked_list.py b/reverse-linked-list.py similarity index 100% rename from reverse_linked_list.py rename to reverse-linked-list.py diff --git a/reverse_nodes_in_k_group.py b/reverse-nodes-in-k-group.py similarity index 100% rename from reverse_nodes_in_k_group.py rename to reverse-nodes-in-k-group.py diff --git a/reverse-order-storage.py b/reverse-order-storage.py new file mode 100644 index 0000000..2358eeb --- /dev/null +++ b/reverse-order-storage.py @@ -0,0 +1,15 @@ +class Solution: + """ + @param head: the given linked list + @return: the array that store the values in reverse order + """ + def reverseStore(self, head): + # write your code here + ret = [] + while head: + ret.append(head.val) + head = head.next + ret.reverse() + return ret + +# easy: https://www.lintcode.com/problem/reverse-order-storage diff --git a/reverse_pairs.py b/reverse-pairs.py similarity index 100% rename from reverse_pairs.py rename to reverse-pairs.py diff --git a/reverse-string-ii.py b/reverse-string-ii.py new file mode 100644 index 0000000..fa296a7 --- /dev/null +++ b/reverse-string-ii.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param s: the string + @param k: the integer k + @return: the answer + """ + def reverseStringII(self, s, k): + # Write your code here. + ret = [] + i = 0 + while i < len(s): + ik, ikk = i + k, i + k * 2 + if ik > len(s): + ik = len(s) + for j in range(ik - i): + ret.append(s[ik - 1 - j]) + j = ik + if ikk > len(s): + ikk = len(s) + while j < ikk: + ret.append(s[j]) + j += 1 + i = ikk + return ''.join(ret) + + +# easy: https://www.lintcode.com/problem/1182/ diff --git a/reverse-string.py b/reverse-string.py new file mode 100644 index 0000000..3ef9da3 --- /dev/null +++ b/reverse-string.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param s: a string + @return: return a string + """ + def reverseString(self, s): + # write your code here + s = list(s) + start, end = 0, len(s) - 1 + while start < end: + s[start], s[end] = s[end], s[start] + start += 1 + end -= 1 + return ''.join(s) + +# easy: https://www.lintcode.com/problem/reverse-string/ diff --git a/reverse-vowels-of-a-string.py b/reverse-vowels-of-a-string.py new file mode 100644 index 0000000..7b2268a --- /dev/null +++ b/reverse-vowels-of-a-string.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param s: a string + @return: reverse only the vowels of a string + """ + def reverseVowels(self, s): + # write your code here + ret = list(s) + vs = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']) + i, j = 0, len(s) - 1 + while i < j: + while i < len(s): + if ret[i] in vs: + break + else: + i += 1 + while j >= 0: + if ret[j] in vs: + break + else: + j -= 1 + if i < j: + ret[i], ret[j] = ret[j], ret[i] + i += 1 + j -= 1 + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/reverse-vowels-of-a-string/ diff --git a/reverse-words-in-a-string-iii.py b/reverse-words-in-a-string-iii.py new file mode 100644 index 0000000..6211f75 --- /dev/null +++ b/reverse-words-in-a-string-iii.py @@ -0,0 +1,31 @@ +class Solution: + """ + @param s: a string + @return: reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order + """ + def reverseWords(self, s): + # Write your code here + s = list(s) + is_word = False + start, end = -1, -1 + for i in range(len(s)): + if s[i] != ' ': + if not is_word: + is_word = True + start, end = i, i + else: + end += 1 + else: + is_word = False + self.reverseWord(s, start, end) + if is_word: + self.reverseWord(s, start, end) + return ''.join(s) + + def reverseWord(self, s, start, end): + while start < end: + s[start], s[end] = s[end], s[start] + start += 1 + end -= 1 + +# easy: https://www.lintcode.com/problem/reverse-words-in-a-string-iii/ diff --git a/reverse_words_in_a_string.py b/reverse-words-in-a-string.py similarity index 100% rename from reverse_words_in_a_string.py rename to reverse-words-in-a-string.py diff --git a/rle-iterator.py b/rle-iterator.py new file mode 100644 index 0000000..d97f4e4 --- /dev/null +++ b/rle-iterator.py @@ -0,0 +1,33 @@ +class Solution: + """ + @param A: the run-length encoded sequence + """ + def __init__(self, A): + # do some initialization if necessary + self.A = A + self.i = 0 + self.char = None + self.count = 0 + + """ + @param n: the number of elements to exhaust + @return: exhausts the next n elements and returns the last element exhausted + """ + def next(self, n): + # write your code here + if self.count <= 0: + if self.i < len(self.A) - 1: + self.count = self.A[self.i] + self.char = self.A[self.i + 1] + self.i += 2 + else: + return -1 + if n > self.count: + n -= self.count + self.count = 0 + return self.next(n) + else: + self.count -= n + return self.char + +# medium: https://www.lintcode.com/problem/1741/ diff --git a/roman_to_integer.py b/roman-to-integer.py similarity index 100% rename from roman_to_integer.py rename to roman-to-integer.py diff --git a/root-of-equation.py b/root-of-equation.py new file mode 100644 index 0000000..c1aa8f4 --- /dev/null +++ b/root-of-equation.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param a: parameter of the equation + @param b: parameter of the equation + @param c: parameter of the equation + @return: a double array, contains at most two root + """ + def rootOfEquation(self, a, b, c): + # write your code here + r = b * b - 4 * a * c + if r < 0: + return [] + elif r == 0: + return [-b / (a * 2)] + else: + r = math.sqrt(r) + if a > 0: + return [(-b - r) / (a * 2), (-b + r) / (a * 2)] + else: + return [(-b + r) / (a * 2), (-b - r) / (a * 2)] + +# easy: https://www.lintcode.com/problem/239/ diff --git a/rotate-array.py b/rotate-array.py new file mode 100644 index 0000000..dc26aaa --- /dev/null +++ b/rotate-array.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param nums: an array + @param k: an integer + @return: rotate the array to the right by k steps + """ + def rotate(self, nums, k): + # Write your code here + k = k % len(nums) + self.reverse(nums, 0, len(nums) - k - 1) + self.reverse(nums, len(nums) - k, len(nums) - 1) + self.reverse(nums, 0, len(nums) - 1) + return nums + + def reverse(self, nums, start, end): + while start < end: + nums[start], nums[end] = nums[end], nums[start] + start += 1 + end -= 1 + +# easy: https://www.lintcode.com/problem/rotate-array/ diff --git a/rotate_image.py b/rotate-image.py similarity index 100% rename from rotate_image.py rename to rotate-image.py diff --git a/rotate_list.py b/rotate-list.py similarity index 100% rename from rotate_list.py rename to rotate-list.py diff --git a/rotate-string-ii.py b/rotate-string-ii.py new file mode 100644 index 0000000..a8856b9 --- /dev/null +++ b/rotate-string-ii.py @@ -0,0 +1,36 @@ +class Solution: + """ + @param str: A String + @param left: a left offset + @param right: a right offset + @return: return a rotate string + """ + def RotateString2(self, str, left, right): + # write your code here + li = list(str) + ls, rs = -1, -1 + right %= len(li) + left %= len(li) + if right > left: + rs = right - left + elif left > right: + ls = left - right + shift = -1 + if ls > 0: + shift = ls + elif rs > 0: + shift = len(li) - rs + if shift > 0: + self.reverse(li, 0, shift) + self.reverse(li, shift, len(li)) + self.reverse(li, 0, len(li)) + return ''.join(li) + + def reverse(self, li, start, end): + end = end - 1 + while start < end: + li[start], li[end] = li[end], li[start] + start += 1 + end -= 1 + +# easy: https://www.lintcode.com/problem/rotate-string-ii/ diff --git a/rotate_string.py b/rotate-string.py similarity index 100% rename from rotate_string.py rename to rotate-string.py diff --git a/rotate_words.py b/rotate-words.py similarity index 100% rename from rotate_words.py rename to rotate-words.py diff --git a/rotated-digits.py b/rotated-digits.py new file mode 100644 index 0000000..31ec301 --- /dev/null +++ b/rotated-digits.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param N: a positive number + @return: how many numbers X from 1 to N are good + """ + def rotatedDigits(self, N): + # write your code here + ret = 0 + for n in range(1, N+1): + ret += self.check(n) + return ret + + def check(self, n): + ret = 0 + while n > 0: + i = n % 10 + n = int(n / 10) + if i in [3, 4, 7]: + return 0 + elif i in [2, 5, 6, 9]: + ret = 1 + return ret + +# easy: https://www.lintcode.com/problem/rotated-digits/ diff --git a/rotated-nums.py b/rotated-nums.py new file mode 100644 index 0000000..449b698 --- /dev/null +++ b/rotated-nums.py @@ -0,0 +1,18 @@ +class Solution: + def __init__(self): + self.cache = {1: 5, 2: 6, 3: 30} + + """ + @param n: length of good nums + @return: The num of good nums of length n + """ + def RotatedNums(self, n): + # write your code here + init = [0, 5, 6, 30] + if n <= 3: + return init[n] + start = 2 if (n % 2) == 0 else 3 + steps = int((n - start) / 2) # 一定要取整数,不然浮点数计算精度会有问题。 + return int(init[start] * pow(7, steps)) + +# easy: https://www.lintcode.com/problem/rotated-nums/ diff --git a/route_between_two_nodes_in_graph.py b/route-between-two-nodes-in-graph.py similarity index 100% rename from route_between_two_nodes_in_graph.py rename to route-between-two-nodes-in-graph.py diff --git a/same-diagonal-elements.py b/same-diagonal-elements.py new file mode 100644 index 0000000..d788e3e --- /dev/null +++ b/same-diagonal-elements.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param matrix: a matrix + @return: return true if same. + """ + def judgeSame(self, matrix): + # write your code here. + # 1st row, then 1st column. + n = len(matrix) + for i in range(n): + r, c = 1, i + 1 + while (r < n) and (c < n): + if matrix[r][c] != matrix[0][i]: + return False + r += 1 + c += 1 + for i in range(1, n): + r, c = i + 1, 1 + while (r < n) and (c < n): + if matrix[r][c] != matrix[i][0]: + return False + r += 1 + c += 1 + return True + +# easy: https://www.lintcode.com/problem/same-diagonal-elements/ diff --git a/same-numbe.py b/same-numbe.py new file mode 100644 index 0000000..68745b1 --- /dev/null +++ b/same-numbe.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param nums: the arrays + @param k: the distance of the same number + @return: the ans of this question + """ + def sameNumber(self, nums, k): + # Write your code here + di = {} + for i in range(len(nums)): + if nums[i] not in di: + di[nums[i]] = i + else: + if (i - di[nums[i]]) < k: + return 'YES' + return 'NO' + +# easy: https://www.lintcode.com/problem/1368/ diff --git a/search_a_2d_matrix_ii.py b/search-a-2d-matrix-ii.py similarity index 100% rename from search_a_2d_matrix_ii.py rename to search-a-2d-matrix-ii.py diff --git a/search_a_2d_matrix.py b/search-a-2d-matrix.py similarity index 100% rename from search_a_2d_matrix.py rename to search-a-2d-matrix.py diff --git a/search_for_a_range.py b/search-for-a-range.py similarity index 100% rename from search_for_a_range.py rename to search-for-a-range.py diff --git a/search-in-a-binary-search-tree.py b/search-in-a-binary-search-tree.py new file mode 100644 index 0000000..b050d11 --- /dev/null +++ b/search-in-a-binary-search-tree.py @@ -0,0 +1,26 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the tree + @param val: the val which should be find + @return: the node + """ + def searchBST(self, root, val): + # Write your code here. + if not root: + return None + if root.val == val: + return root + elif val < root.val: + return self.searchBST(root.left, val) + else: + return self.searchBST(root.right, val) + +# easy: https://www.lintcode.com/problem/search-in-a-binary-search-tree/ diff --git a/search-in-rotated-sorted-array-ii.py b/search-in-rotated-sorted-array-ii.py new file mode 100644 index 0000000..0e21d9e --- /dev/null +++ b/search-in-rotated-sorted-array-ii.py @@ -0,0 +1,31 @@ +class Solution: + """ + @param A: an integer ratated sorted array and duplicates are allowed + @param target: An integer + @return: a boolean + """ + def search(self, A, target): + # write your code here + start, end = 0, len(A) - 1 + while start <= end: + mid = int((start + end) / 2) + if A[mid] == target: + return True + m1, m2 = mid, mid + while (m1 > start) and (A[m1] <= A[start]): + m1 -= 1 + if A[m1] == target: + return True + while (m2 < end) and (A[m2] >= A[end]): + m2 += 1 + if A[m2] == target: + return True + if (A[m1] >= target) and (A[start] <= target): + end = m1 - 1 + elif (A[m2] <= target) and (A[end] >= target): + start = m2 + 1 + else: + break + return False + +# medium: https://www.lintcode.com/problem/search-in-rotated-sorted-array-ii/ diff --git a/search_in_rotated_sorted_array.py b/search-in-rotated-sorted-array.py similarity index 100% rename from search_in_rotated_sorted_array.py rename to search-in-rotated-sorted-array.py diff --git a/search_insert_position.py b/search-insert-position.py similarity index 100% rename from search_insert_position.py rename to search-insert-position.py diff --git a/second-max-of-array.py b/second-max-of-array.py new file mode 100644 index 0000000..9bc3122 --- /dev/null +++ b/second-max-of-array.py @@ -0,0 +1,23 @@ +class Solution: + """ + @param nums: An integer array + @return: The second max number in the array. + """ + @staticmethod + def update(data, value): + m = min(data) + if data[0] == m: + pos = 0 + else: + pos = 1 + if value > data[pos]: + data[pos] = value # 更新比较小的那个数 + + def secondMax(self, nums): + # write your code here + data = nums[0:2] + for i in range(2, len(nums)): + Solution.update(data, nums[i]) + return min(data) + +# easy: https://www.lintcode.com/problem/second-max-of-array diff --git a/second-minimum-node-in-a-binary-tree.py b/second-minimum-node-in-a-binary-tree.py new file mode 100644 index 0000000..cd78a60 --- /dev/null +++ b/second-minimum-node-in-a-binary-tree.py @@ -0,0 +1,34 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root + @return: the second minimum value in the set made of all the nodes' value in the whole tree + """ + def findSecondMinimumValue(self, root): + # Write your code here + # 深入领会题目:这个结点的值不大于它的两个子结点 + if (not root) or (not (root.left or root.right)): + return -1 + left_val, right_val = -1, -1 + if root.left: + left_val = root.left.val + if left_val == root.val: + left_val = self.findSecondMinimumValue(root.left) + if root.right: + right_val = root.right.val + if right_val == root.val: + right_val = self.findSecondMinimumValue(root.right) + if (left_val != -1) and (right_val != -1): + return min(left_val, right_val) + if left_val != -1: + return left_val + return right_val + +# easy: https://www.lintcode.com/problem/second-minimum-node-in-a-binary-tree/ diff --git a/segment_tree_build_ii.py b/segment-tree-build-ii.py similarity index 100% rename from segment_tree_build_ii.py rename to segment-tree-build-ii.py diff --git a/segment_tree_build.py b/segment-tree-build.py similarity index 100% rename from segment_tree_build.py rename to segment-tree-build.py diff --git a/segment_tree_modify.py b/segment-tree-modify.py similarity index 100% rename from segment_tree_modify.py rename to segment-tree-modify.py diff --git a/segment_tree_query_ii.py b/segment-tree-query-ii.py similarity index 100% rename from segment_tree_query_ii.py rename to segment-tree-query-ii.py diff --git a/segment_tree_query.py b/segment-tree-query.py similarity index 100% rename from segment_tree_query.py rename to segment-tree-query.py diff --git a/self-dividing-numbers.py b/self-dividing-numbers.py new file mode 100644 index 0000000..724f8cb --- /dev/null +++ b/self-dividing-numbers.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param lower: Integer : lower bound + @param upper: Integer : upper bound + @return: a list of every possible Digit Divide Numbers + """ + def digitDivideNums(self, lower, upper): + # write your code here + ret = [] + i = lower + while i <= upper: + tmp = i + while i > 0: + v = i % 10 + if v == 0: + break + else: + if (tmp % v) == 0: + i = int(i / 10) + else: + break + if i == 0: + ret.append(tmp) + i = tmp + 1 + return ret + +# medium: https://www.lintcode.com/problem/self-dividing-numbers/ diff --git a/sentence-similarity.py b/sentence-similarity.py new file mode 100644 index 0000000..d58b4a7 --- /dev/null +++ b/sentence-similarity.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param words1: a list of string + @param words2: a list of string + @param pairs: a list of string pairs + @return: return a boolean, denote whether two sentences are similar or not + """ + def isSentenceSimilarity(self, words1, words2, pairs): + # write your code here + if len(words1) == len(words2): + new_pairs = set([]) + for pair in pairs: + new_pairs.add(pair[0] + pair[1]) + new_pairs.add(pair[1] + pair[0]) + print(new_pairs) + for i in range(len(words1)): + same = (words1[i] == words2[i]) + same = same or ((words1[i] + words2[i]) in new_pairs) + if not same: + return False + return True + return False + +# easy: https://www.lintcode.com/problem/sentence-similarity/ diff --git a/set_matrix_zeroes.py b/set-matrix-zeroes.py similarity index 100% rename from set_matrix_zeroes.py rename to set-matrix-zeroes.py diff --git a/set-mismatch.py b/set-mismatch.py new file mode 100644 index 0000000..0256dcb --- /dev/null +++ b/set-mismatch.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param nums: an array + @return: the number occurs twice and the number that is missing + """ + def findErrorNums(self, nums): + # Write your code here + ret = [] + di = {} + for i in nums: + if i not in di: + di[i] = 1 + else: + di[i] += 1 + ret.append(i) + for i in range(1, len(nums) + 1): + if i not in di: + ret.append(i) + break + return ret + +# easy: https://www.lintcode.com/problem/set-mismatch/ diff --git a/set-operation.py b/set-operation.py new file mode 100644 index 0000000..a68aacf --- /dev/null +++ b/set-operation.py @@ -0,0 +1,12 @@ +class Solution: + """ + @param A: The set A + @param B: The set B + @return: Return the size of three sets + """ + def getAnswer(self, A, B): + # Write your code here + a, b = set(A), set(B) + return [len(a | b), len(a & b), len(a - b)] + +# easy: https://www.lintcode.com/problem/1471/ diff --git a/shape_factory.py b/shape-factory.py similarity index 97% rename from shape_factory.py rename to shape-factory.py index 2861af2..175d7d3 100644 --- a/shape_factory.py +++ b/shape-factory.py @@ -38,4 +38,4 @@ def getShape(self, shapeType): elif shapeType == 'Rectangle': return Rectangle() else: - return None \ No newline at end of file + return None diff --git a/shortest-unordered-array.py b/shortest-unordered-array.py new file mode 100644 index 0000000..2fb85f5 --- /dev/null +++ b/shortest-unordered-array.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param arr: an array of integers + @return: the length of the shortest possible subsequence of integers that are unordered + """ + def shortestUnorderedArray(self, arr): + # write your code here + order = arr[1] > arr[0] # 升序:True + if order: + for i in range(1, len(arr) - 1): + if arr[i + 1] < arr[i]: + return 3 + else: + for i in range(1, len(arr) - 1): + if arr[i + 1] > arr[i]: + return 3 + return 0 + +# easy: https://www.lintcode.com/problem/shortest-unordered-array/ diff --git a/shortest-unsorted-continuous-subarray.py b/shortest-unsorted-continuous-subarray.py new file mode 100644 index 0000000..bb03974 --- /dev/null +++ b/shortest-unsorted-continuous-subarray.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param nums: an array + @return: the shortest subarray's length + """ + def findUnsortedSubarray(self, nums): + # Write your code here + # 有个有趣的做法,排序都可以省了。。。 + # 1. 找到最右边的比之前max小的元素 + # 2. 找到最左边的比之后min大的元素 + _max, _min = nums[0], nums[-1] + l, r = -1, -2 + for i in range(1, len(nums)): + _max = max(_max, nums[i]) + _min = min(_min, nums[len(nums) - i - 1]) + if _max != nums[i]: + r = i + if _min != nums[len(nums) - i - 1]: + l = len(nums) - i - 1 + return r - l + 1 + +# easy: https://www.lintcode.com/problem/shortest-unsorted-continuous-subarray/ diff --git a/shortest-word-distance.py b/shortest-word-distance.py new file mode 100644 index 0000000..7b0de1e --- /dev/null +++ b/shortest-word-distance.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param words: a list of words + @param word1: a string + @param word2: a string + @return: the shortest distance between word1 and word2 in the list + """ + def shortestDistance(self, words, word1, word2): + # Write your code here + ret = len(words) + i_1, i_2 = -1, -1 + for i in range(len(words)): + if words[i] == word1: + i_1 = i + elif words[i] == word2: + i_2 = i + else: + continue + if (i_1 >= 0) and (i_2 >= 0): + print(i_1, i_2) + ret = min(ret, abs(i_1 - i_2)) + return ret + +# easy: https://www.lintcode.com/problem/shortest-word-distance/ diff --git a/similar-rgb-color.py b/similar-rgb-color.py new file mode 100644 index 0000000..b3d9641 --- /dev/null +++ b/similar-rgb-color.py @@ -0,0 +1,31 @@ +class Solution: + """ + @param color: the given color + @return: a 7 character color that is most similar to the given color + """ + def similarRGB(self, color): + # Write your code here + # RGB三个颜色分开找,可以用二分法优化,这里偷懒暴力了。 + ret = '#' + for i in (1, 3, 5): + c = self.find_nearest_color(color[i:i+2]) + if c == '0': + ret += '0' + ret += c + return ret + + def find_nearest_color(self, color): + ret = '' + diff = 256 + color = int(color, 16) + colors = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff] + for _color in colors: + if abs(_color - color) < diff: + diff = abs(_color - color) + ret = _color + return self.to_hex(ret) + + def to_hex(self, i): + return hex(i)[2:] + +# easy: https://www.lintcode.com/problem/similar-rgb-color/description diff --git a/simple-queries.py b/simple-queries.py new file mode 100644 index 0000000..5b33380 --- /dev/null +++ b/simple-queries.py @@ -0,0 +1,36 @@ +class Solution: + """ + @param nums: + @param sub: + @return: return a Integer array + """ + def SimpleQueries (self, nums, sub): + # write your code here + if not sub: + return [] + ret, _ret = [0] * len(sub), [0] + di = {} + for i in range(len(sub)): + if sub[i] not in di: + di[sub[i]] = [i] + di[sub[i]].append(i) + nums.sort() + sub.sort() + i, j = 0, 0 + while i < len(nums): + if nums[i] <= sub[j]: + _ret[-1] += 1 + i += 1 + else: + j += 1 + if j >= len(sub): + break + _ret.append(_ret[-1]) + for k in range(j, len(sub)): + _ret.append(_ret[-1]) + for k in range(len(sub)): + ret[di[sub[k]][-1]] = _ret[k] + di[sub[k]].pop() + return ret + +# medium: https://www.lintcode.com/problem/1791/ diff --git a/simplify_path.py b/simplify-path.py similarity index 100% rename from simplify_path.py rename to simplify-path.py diff --git a/single_number_ii.py b/single-number-ii.py similarity index 100% rename from single_number_ii.py rename to single-number-ii.py diff --git a/single_number_iii.py b/single-number-iii.py similarity index 100% rename from single_number_iii.py rename to single-number-iii.py diff --git a/single_number.py b/single-number.py similarity index 100% rename from single_number.py rename to single-number.py diff --git a/slide-soduku.py b/slide-soduku.py new file mode 100644 index 0000000..8647307 --- /dev/null +++ b/slide-soduku.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param number: an only contains from 1 to 9 array + @return: return whether or not each sliding window position contains all the numbers for 1 to 9 + """ + def SlidingWindows(self, number): + # write your code here + ret = [] + n = len(number[0]) + for start in range(0, n - 2): + s = set([]) + for r in range(3): + for c in range(3): + s.add(number[r][c + start]) + ret.append(len(s) == 9) + return ret + +# easy: https://www.lintcode.com/problem/slide-soduku/ diff --git a/sliding-window-unique-elements-sum.py b/sliding-window-unique-elements-sum.py new file mode 100644 index 0000000..bd4281f --- /dev/null +++ b/sliding-window-unique-elements-sum.py @@ -0,0 +1,42 @@ +class Solution: + """ + @param nums: the given array + @param k: the window size + @return: the sum of the count of unique elements in each window + """ + def slidingWindowUniqueElementsSum(self, nums, k): + # write your code here + ret = 0 + uniques = 0 + di = {} + window_size = k + if k > len(nums): + window_size = len(nums) + # 初始化窗口 + for i in range(0, window_size): + if nums[i] not in di: + di[nums[i]] = 1 + uniques += 1 + else: + if di[nums[i]] == 1: + uniques -= 1 + di[nums[i]] += 1 + ret += uniques + for i in range(k, len(nums)): + prev_num = nums[i - k] + di[prev_num] -= 1 + if di[prev_num] == 1: # 上一个数字从不unique因为滑动再次unique + uniques += 1 + elif di[prev_num] == 0: # 上一个数字因为unique滑动出去没有了 + uniques -= 1 + if (nums[i] not in di) or (di[nums[i]] == 0): # 新滑动进来的数字符合unique条件 + di[nums[i]] = 1 + uniques += 1 + else: + if di[nums[i]] == 1: # 新滑动进来的数字从unique变成不符合条件 + uniques -= 1 + di[nums[i]] += 1 + ret += uniques + return ret + +# https://www.lintcode.com/problem/sliding-window-unique-elements-sum diff --git a/smart-sale.py b/smart-sale.py new file mode 100644 index 0000000..4209de5 --- /dev/null +++ b/smart-sale.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param ids: ID number of items + @param m: The largest number of items that can be remove + @return: the result of the min item + """ + def minItem(self, ids, m): + # write your code here + r = 0 + di = {} + for i in ids: + if i not in di: + di[i] = 1 + r += 1 + else: + di[i] += 1 + s = sorted(di.values()) + for i in s: + if i > m: + return r + else: + m -= i + r -= 1 + return r + +# medium: https://www.lintcode.com/problem/1914 diff --git a/sort_colors_ii.py b/sort-colors-ii.py similarity index 100% rename from sort_colors_ii.py rename to sort-colors-ii.py diff --git a/sort_colors.py b/sort-colors.py similarity index 100% rename from sort_colors.py rename to sort-colors.py diff --git a/sort_integers_ii.py b/sort-integers-ii.py similarity index 100% rename from sort_integers_ii.py rename to sort-integers-ii.py diff --git a/sort_integers.py b/sort-integers.py similarity index 84% rename from sort_integers.py rename to sort-integers.py index 7f523dd..6531ce3 100644 --- a/sort_integers.py +++ b/sort-integers.py @@ -10,4 +10,4 @@ def sortIntegers(self, A): if A[i] > A[j]: A[i], A[j] = A[j], A[i] -# entry: http://www.lintcode.com/problem/sort-integers +# naive: http://www.lintcode.com/problem/sort-integers diff --git a/sort_letters_by_case.py b/sort-letters-by-case.py similarity index 100% rename from sort_letters_by_case.py rename to sort-letters-by-case.py diff --git a/sort_list.py b/sort-list.py similarity index 100% rename from sort_list.py rename to sort-list.py diff --git a/space_replacement.py b/space-replacement.py similarity index 100% rename from space_replacement.py rename to space-replacement.py diff --git a/sparse-matrix-multiplication.py b/sparse-matrix-multiplication.py new file mode 100644 index 0000000..30de40a --- /dev/null +++ b/sparse-matrix-multiplication.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param A: a sparse matrix + @param B: a sparse matrix + @return: the result of A * B + """ + def multiply(self, A, B): + # write your code here + ret = [] + rows_a, cols_a = len(A), len(A[0]) + rows_b, cols_b = len(B), len(B[0]) + for i in range(rows_a): + di = {} + row = [0] * cols_b + for j in range(cols_a): + if A[i][j] != 0: + di[j] = A[i][j] + for j in range(cols_b): + for k, v in di.items(): + row[j] += v * B[k][j] + ret.append(row) + return ret + +# medium: https://www.lintcode.com/problem/sparse-matrix-multiplication/ diff --git a/special-palindrome-string.py b/special-palindrome-string.py new file mode 100644 index 0000000..edbe7d1 --- /dev/null +++ b/special-palindrome-string.py @@ -0,0 +1,29 @@ +class Solution: + """ + @param ambigram: A list of paired ambigram letter. + @param word: A string need to be judged. + @return: If it is special palindrome string, return true. + """ + def ispalindrome(self, ambigram, word): + # write your code here. + di = {} + for a in ambigram: + if a[0] not in di: + di[a[0]] = set([a[0]]) + di[a[0]].add(a[1]) + if a[1] not in di: + di[a[1]] = set([a[1]]) + di[a[1]].add(a[0]) + for c in word: + if c not in di: + di[c] = set([c]) + i, j = 0, len(word) - 1 + while i < j: + if word[i] != word[j]: + if not di[word[i]].intersection(di[word[j]]): + return False + i += 1 + j -= 1 + return True + +# easy: https://www.lintcode.com/problem/special-palindrome-string/ diff --git a/spiral-array.py b/spiral-array.py new file mode 100644 index 0000000..9d79293 --- /dev/null +++ b/spiral-array.py @@ -0,0 +1,39 @@ +class Solution: + """ + @param n: a Integer + @return: a spiral array + """ + def spiralArray(self, n): + # write your code here + ret = [[0] * n for i in range(n)] + row_up, row_down = 0, n + col_left, col_right = 0, n + i, size = 1, n * n + while i <= size: + for c in range(col_left, col_right): # right + if i > size: + break + ret[row_up][c] = i + i += 1 + for r in range(row_up + 1, row_down): # down + if i > size: + break + ret[r][col_right - 1] = i + i += 1 + for c in range(col_right - 2, col_left - 1, -1): # left + if i > size: + break + ret[row_down - 1][c] = i + i += 1 + for r in range(row_down - 2, row_up, -1): # up + if i > size: + break + ret[r][col_left] = i + i += 1 + row_up += 1 + row_down -= 1 + col_left += 1 + col_right -= 1 + return ret + +# easy: https://www.lintcode.com/problem/spiral-array/ diff --git a/spiral_matrix_ii.py b/spiral-matrix-ii.py similarity index 100% rename from spiral_matrix_ii.py rename to spiral-matrix-ii.py diff --git a/spiral_matrix.py b/spiral-matrix.py similarity index 100% rename from spiral_matrix.py rename to spiral-matrix.py diff --git a/split-array.py b/split-array.py new file mode 100644 index 0000000..164cb4c --- /dev/null +++ b/split-array.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param arr: an inter array + @return: return the min sum + """ + def splitArray(self, arr): + # write your code here + nums = [] + for i in range(1, len(arr) - 1): + if len(nums) < 3: + nums.append([arr[i], i]) + nums = sorted(nums, key=lambda x: x[0]) + else: + for j in range(2, -1, -1): + if nums[j][0] > arr[i]: + nums[j] = [arr[i], i] + nums = sorted(nums, key=lambda x: x[0]) + break + nums = sorted(nums, key=lambda x: x[1]) + v1, v2, v3 = 100000000000, 100000000000, 100000000000 + if (nums[1][1] - nums[0][1]) > 1: + v1 = nums[0][0] + nums[1][0] + v2 = nums[0][0] + nums[2][0] + if (nums[2][1] - nums[1][1]) > 1: + v3 = nums[1][0] + nums[2][0] + return min(v1, v2, v3) + +# easy: https://www.lintcode.com/problem/split-array/ diff --git a/split_string.py b/split-string.py similarity index 100% rename from split_string.py rename to split-string.py diff --git a/spreadsheet-notation-conversion.py b/spreadsheet-notation-conversion.py new file mode 100644 index 0000000..292aad2 --- /dev/null +++ b/spreadsheet-notation-conversion.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param index: the index to be converted + @return: return the string after convert. + """ + def convert(self, index): + # write your code here + ret = '' + line = int((index - 1) / 702) + 1 + no = index - (line - 1) * 702 + ret += str(line) + if no == 702: + ret += 'Z' + elif no > 26: + ret += chr(ord('A') + int(no / 26) - 1) + ret += chr(ord('A') + (no - 1) % 26) + return ret + +# easy: https://www.lintcode.com/problem/spreadsheet-notation-conversion/ diff --git a/sqrtx-ii.py b/sqrtx-ii.py new file mode 100644 index 0000000..5009cd6 --- /dev/null +++ b/sqrtx-ii.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param x: a double + @return: the square root of x + """ + def sqrt(self, x): + # write your code here + i, j = 0, x + if x < 1: + j = 1 + while True: + m = (i + j) / 2 + m2 = m * m + if abs(m2 - x) < 0.00000000000001: + return m + elif m2 > x: + j = m + else: + i = m + return -1 + +# medium: https://www.lintcode.com/problem/586 diff --git a/squares-of-a-sorted-array.py b/squares-of-a-sorted-array.py new file mode 100644 index 0000000..57a5d3a --- /dev/null +++ b/squares-of-a-sorted-array.py @@ -0,0 +1,14 @@ +class Solution: + """ + @param A: The array A. + @return: The array of the squares. + """ + def SquareArray(self, A): + # + ret = [] + for i in A: + ret.append(i * i) + ret.sort() + return ret + +# easy: https://www.lintcode.com/problem/squares-of-a-sorted-array/ diff --git a/stretch-word.py b/stretch-word.py new file mode 100644 index 0000000..4674867 --- /dev/null +++ b/stretch-word.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param S: the string + @return: The numbers of strings + """ + def stretchWord(self, S): + # write your code here + ret = 0 + pc = None + cnt = 0 + for c in S: + if c != pc: + pc = c + cnt = 0 + if not ret: + ret = 1 + else: + if cnt >= 1: + continue + cnt += 1 + ret *= 2 + return ret + +# easy: https://www.lintcode.com/problem/stretch-word/ diff --git a/string-compression.py b/string-compression.py new file mode 100644 index 0000000..ee19869 --- /dev/null +++ b/string-compression.py @@ -0,0 +1,25 @@ +class Solution: + """ + @param str: a string + @return: a compressed string + """ + def compress(self, str): + # write your code here + if not str: + return str + ret = [str[0]] + prev_c = str[0] + count = 1 + for i in range(1, len(str)): + if str[i] == prev_c: + count += 1 + else: + ret.append('%d' % count) + prev_c = str[i] + ret.append(prev_c) + count = 1 + ret.append('%d' % count) + ret = ''.join(ret) + return str if len(ret) >= len(str) else ret + +# easy: http://lintcode.com/zh-cn/problem/string-compression/ diff --git a/string-game.py b/string-game.py new file mode 100644 index 0000000..cbec221 --- /dev/null +++ b/string-game.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param s: a string for this game + @return: return whether Alice can win this game + """ + def stringGame(self, s): + # Write your code here + # Nim模型是拿最后一块石子的赢,但这属于反Nim模型。 + # 先手必胜的条件: + # - 所有堆的石子数均=1,且有偶数堆。 + # - 至少有一个堆的石子的数量大于1,且石子堆的异或和不等与0。 + # 证明网上有。 + cnt = 0 + xor = 0 + di = {} + for c in s: + if c not in di: + di[c] = 0 + di[c] += 1 + for k, v in di.items(): + if v == 1: + cnt += 1 + xor ^= v + if cnt == len(s): + return (cnt % 2) == 0 + return xor > 0 + +# easy: https://www.lintcode.com/problem/string-game/ diff --git a/string_permutation.py b/string-permutation.py similarity index 100% rename from string_permutation.py rename to string-permutation.py diff --git a/string-sorting.py b/string-sorting.py new file mode 100644 index 0000000..03e944f --- /dev/null +++ b/string-sorting.py @@ -0,0 +1,12 @@ +class Solution: + """ + @param s: string + @return: sort string in lexicographical order + """ + def sorting(self, s): + # write your code here + ns = s.split(',') + ns.sort() + return ','.join(ns) + +# easy: https://www.lintcode.com/problem/string-sorting/ diff --git a/string_to_integer_ii.py b/string-to-integer-ii.py similarity index 100% rename from string_to_integer_ii.py rename to string-to-integer-ii.py diff --git a/strings_homomorphism.py b/strings-homomorphism.py similarity index 100% rename from strings_homomorphism.py rename to strings-homomorphism.py diff --git a/strobogrammatic-number.py b/strobogrammatic-number.py new file mode 100644 index 0000000..3862ba8 --- /dev/null +++ b/strobogrammatic-number.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param num: a string + @return: true if a number is strobogrammatic or false + """ + @staticmethod + def check_same(left, right): # 反转180度依然保持一致的数字对 + return [left, right] in [['6', '9'], ['9', '6'], ['0', '0'], ['1', '1'], ['8', '8']] + + def isStrobogrammatic(self, num): + # write your code here + i, j = 0, len(num) - 1 + while i < j: + if Solution.check_same(num[i], num[j]): + i += 1 + j -= 1 + else: + return False + if i == j: # 反转180度依然保持一致的单个数字 + return num[i] in ['0', '1', '8'] + else: + return True + +# easy: https://www.lintcode.com/problem/strobogrammatic-number diff --git a/student-attendance-record-i.py b/student-attendance-record-i.py new file mode 100644 index 0000000..5ac245a --- /dev/null +++ b/student-attendance-record-i.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param s: a string + @return: whether the student could be rewarded according to his attendance record + """ + def checkRecord(self, s): + # Write your code here + prev = None + count_l, count_a = 0, 0 + for c in s: + if c == 'L': + if prev != 'L': + count_l = 1 + else: + count_l += 1 + if count_l == 3: + return False + else: + count_l = 0 + if c == 'A': + count_a += 1 + if count_a > 1: + return False + prev = c + return True + +# easy: https://www.lintcode.com/problem/student-attendance-record-i/ diff --git a/sub-palindrome.py b/sub-palindrome.py new file mode 100644 index 0000000..2d0cdf9 --- /dev/null +++ b/sub-palindrome.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param s: the string + @return: the number of substring + """ + def countSubstrings(self, s): + # Write your code here. + ret = set([]) + for i in range(len(s)): + l = i + for j in range(2): # 处理奇数偶数长度 + r = l + j # 0是奇数,1是偶数。 + while (l >= 0) and (r < len(s)) and (s[l] == s[r]): + ret.add(s[l : r + 1]) + l -= 1 + r += 1 + l = i + return len(ret) + +# easy: https://www.lintcode.com/problem/1856/ diff --git a/subarray_sum_closest.py b/subarray-sum-closest.py similarity index 52% rename from subarray_sum_closest.py rename to subarray-sum-closest.py index 7d90b85..5cb56ad 100644 --- a/subarray_sum_closest.py +++ b/subarray-sum-closest.py @@ -1,30 +1,25 @@ -# coding: utf-8 - class Solution: """ - @param nums: A list of integers - @return: A list of integers includes the index of the first number - and the index of the last number + @param: nums: A list of integers + @return: A list of integers includes the index of the first number and the index of the last number """ def subarraySumClosest(self, nums): # write your code here - # 序列a[i + 1]到a[j]的和等于a[0]到a[j]的和减去a[0]到a[i]的和。 if not nums: return [] sums = [] tmp = 0 - for i in xrange(len(nums)): + for i in range(len(nums)): tmp += nums[i] sums.append([tmp, i]) sums.sort() - ret = [0, 0] - diff = 2147483647 - for i in xrange(1, len(sums)): + diff = abs(sums[0][0]) + ret = [0, sums[0][1]] + for i in range(1, len(sums)): if abs(sums[i][0] - sums[i - 1][0]) < diff: diff = abs(sums[i][0] - sums[i - 1][0]) - ret = [] - ret.append(min(sums[i][1], sums[i - 1][1]) + 1) - ret.append(max(sums[i][1], sums[i - 1][1])) + ret[0] = min(sums[i][1], sums[i - 1][1]) + 1 + ret[1] = max(sums[i][1], sums[i - 1][1]) return ret # medium: http://lintcode.com/problem/subarray-sum-closest diff --git a/subarray-sum-equals-k.py b/subarray-sum-equals-k.py new file mode 100644 index 0000000..9988c54 --- /dev/null +++ b/subarray-sum-equals-k.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param nums: a list of integer + @param k: an integer + @return: return an integer, denote the number of continuous subarrays whose sum equals to k + """ + def subarraySumEqualsK(self, nums, k): + # write your code here + # 遍历数组nums,计算从第0个元素到当前元素的和,用哈希表保存出现过的累积和sum的次数。 + # 如果sum - k在哈希表中出现过,则代表从当前下标i往前有连续的子数组的和为k!!! + ret = 0 + di = {0:1} + _sum = 0 + for i in nums: + _sum += i + if (_sum - k) in di: + ret += di[_sum - k] + if _sum in di: + di[_sum] += 1 + else: + di[_sum] = 1 + return ret + +# easy: https://www.lintcode.com/problem/subarray-sum-equals-k/ diff --git a/subarray-sum-equals-to-k-ii.py b/subarray-sum-equals-to-k-ii.py new file mode 100644 index 0000000..75792d0 --- /dev/null +++ b/subarray-sum-equals-to-k-ii.py @@ -0,0 +1,30 @@ +from typing import ( + List, +) + +class Solution: + """ + @param nums: a list of integer + @param k: an integer + @return: return an integer, denote the minimum length of continuous subarrays whose sum equals to k + """ + def subarray_sum_equals_k_i_i(self, nums: List[int], k: int) -> int: + # write your code here + r = len(nums) + 1 + s = 0 + di = {0: [-1]} + for i in range(len(nums)): + s += nums[i] + if s not in di: + di[s] = [] + di[s].append(i) + for s, ids in di.items(): + t = s - k + if t in di: + for i in ids: + for j in di[t]: + if i > j: + r = min(r, i - j) + return r if r <= len(nums) else -1 + +# medium: https://www.lintcode.com/problem/1844/ diff --git a/subarray_sum.py b/subarray-sum.py similarity index 100% rename from subarray_sum.py rename to subarray-sum.py diff --git a/subdomain-visit-count.py b/subdomain-visit-count.py new file mode 100644 index 0000000..a21882f --- /dev/null +++ b/subdomain-visit-count.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param cpdomains: a list cpdomains of count-paired domains + @return: a list of count-paired domains + """ + def subdomainVisits(self, cpdomains): + # Write your code here + di = {} + for d in cpdomains: + count, domain = d.split(' ') + count = int(count) + parts = domain.split('.') + for i in range(1, len(parts) + 1): # 拆分组合 + sd = '.'.join(parts[len(parts) -i:]) + if sd not in di: + di[sd] = count + else: + di[sd] += count + ret = [] + for k, v in di.items(): + ret.append(str(v) + ' ' + k) + return ret + +# easy: https://www.lintcode.com/problem/subdomain-visit-count diff --git a/submatrix_sum.py b/submatrix-sum.py similarity index 100% rename from submatrix_sum.py rename to submatrix-sum.py diff --git a/substring-in-dict.py b/substring-in-dict.py new file mode 100644 index 0000000..44bfb25 --- /dev/null +++ b/substring-in-dict.py @@ -0,0 +1,39 @@ +class Solution: + """ + @param s: a string + @param wordDict: A set of words. + @return: All correct words + """ + def wordSubsequence(self, s, wordDict): + # write your code here + # 记录每个字母在哪些位置出现过, + # 如果位置能构造递增序列则满足。 + ret = [] + di = {} + for i in range(len(s)): + if s[i] in di: + di[s[i]].append(i) + else: + di[s[i]] = [i] + for word in wordDict: + min_pos = -1 + match = True + for c in word: + if c not in di: + match = False + break + i = 0 + while i < len(di[c]): + if di[c][i] > min_pos: + min_pos = di[c][i] + break + else: + i += 1 + if i == len(di[c]): # 没有找到一个位置符合递增条件 + match = False + break + if match: + ret.append(word) + return ret + +# medium: https://www.lintcode.com/problem/substring-in-dict/ diff --git a/substring-rotation.py b/substring-rotation.py new file mode 100644 index 0000000..53f012e --- /dev/null +++ b/substring-rotation.py @@ -0,0 +1,13 @@ +class Solution: + """ + @param s1: the first string + @param s2: the second string + @return: true if s2 is a rotation of s1 or false + """ + def isRotation(self, s1, s2): + # write your code here + if (len(s1) != len(s2)) or (not (s1 and s2)): + return False + return Substring.isSubstring(s1 + s1, s2) + +# easy: https://www.lintcode.com/problem/216/ diff --git a/subtree-of-another-tree.py b/subtree-of-another-tree.py new file mode 100644 index 0000000..3d92964 --- /dev/null +++ b/subtree-of-another-tree.py @@ -0,0 +1,36 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param s: the s' root + @param t: the t' root + @return: whether tree t has exactly the same structure and node values with a subtree of s + """ + def isSubtree(self, s, t): + # Write your code here + if not s: + return False + if self.isSameTree(s, t) \ + or self.isSubtree(s.left, t) \ + or self.isSubtree(s.right, t): + return True + return False + + def isSameTree(self, s, t): + if s and t: + if s.val != t.val: + return False + elif not (s or t): + return True + else: + return False + return self.isSameTree(s.left, t.left) \ + and self.isSameTree(s.right, t.right) + +# easy: https://www.lintcode.com/problem/subtree-of-another-tree/ diff --git a/subtree-with-maximum-average.py b/subtree-with-maximum-average.py new file mode 100644 index 0000000..76bab2a --- /dev/null +++ b/subtree-with-maximum-average.py @@ -0,0 +1,43 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root of binary tree + @return: the root of the maximum average of subtree + """ + def findSubtree2(self, root): + # write your code here + if not root: + return None + di = {None: [0, 0]} + self.calc_average(di, root) + ret, a = None, 0 + for k, v in di.items(): + if not ret: + ret, a = k, v[0] + else: + if v[0] > a: + a = v[0] + ret = k + return ret + + def calc_average(self, di, node): + if not node: + return + if node.left not in di: + self.calc_average(di, node.left) + la, lc = di[node.left] + if node.right not in di: + self.calc_average(di, node.right) + ra, rc = di[node.right] + cc = lc + rc + 1 + ca = (la * lc + ra * rc + node.val) / cc + di[node] = [ca, cc] + +# easy: https://www.lintcode.com/problem/597/ diff --git a/sum-of-all-subarrays.py b/sum-of-all-subarrays.py new file mode 100644 index 0000000..b2a2f62 --- /dev/null +++ b/sum-of-all-subarrays.py @@ -0,0 +1,20 @@ +def do_sum(nums, idx, ret, _sum): # _sum记录子数组的和 + if idx >= len(nums): + return + _sum += nums[idx] + ret[0] += _sum + do_sum(nums, idx + 1, ret, _sum) + +class Solution: + """ + @param nums: a Integer list + @return: return the sum of subarrays + """ + def SubArraySum(self, nums): + # write your code here + ret = [0] + for i in range(len(nums)): + do_sum(nums, i, ret, 0) + return ret[0] + +# easy: https://www.lintcode.com/problem/sum-of-all-subarrays/ diff --git a/sum-of-all-subsets.py b/sum-of-all-subsets.py new file mode 100644 index 0000000..d314dac --- /dev/null +++ b/sum-of-all-subsets.py @@ -0,0 +1,12 @@ +class Solution: + """ + @param n: the given number + @return: Sum of elements in subsets + """ + def subSum(self, n): + # write your code here + if n == 1: + return 1 + return (1 << (n - 2)) * (1 + n) * n + +# easy: https://www.lintcode.com/problem/sum-of-all-subsets/ diff --git a/sum-of-left-leaves.py b/sum-of-left-leaves.py new file mode 100644 index 0000000..c84e9f9 --- /dev/null +++ b/sum-of-left-leaves.py @@ -0,0 +1,29 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: t + @return: the sum of all left leaves + """ + def sumOfLeftLeaves(self, root): + # Write your code here + ret = [0] # 简化参数处理 + if root: + self._sumOfLeftLeaves(ret, root, 0) + return ret[0] + + def _sumOfLeftLeaves(self, ret, node, _dir): + if not (node.left or node.right) and (_dir == -1): + ret[0] += node.val + if node.left: + self._sumOfLeftLeaves(ret, node.left, -1) + if node.right: + self._sumOfLeftLeaves(ret, node.right, 1) + +# easy: https://www.lintcode.com/problem/sum-of-left-leaves/ diff --git a/sum-of-small-numbers.java b/sum-of-small-numbers.java new file mode 100644 index 0000000..9250197 --- /dev/null +++ b/sum-of-small-numbers.java @@ -0,0 +1,27 @@ +// Only java code + +import java.util.*; + +public class Main { + public static void main(String[] args){ + // write your code here + int ret = 0; + int max = Integer.MIN_VALUE; + int c = 0; + Scanner scanner = new Scanner(System.in); + int n = scanner.nextInt(); + for (int i = 0; i < n; ++i) { + int v = scanner.nextInt(); + ret += v; + if (v > max) { + max = v; + c = 1; + } else if (v == max) { + ++c; + } + } + System.out.println(ret - max * c); + } +} + +// easy: https://www.lintcode.com/problem/2820 diff --git a/sum-of-two-strings.py b/sum-of-two-strings.py new file mode 100644 index 0000000..bdf207e --- /dev/null +++ b/sum-of-two-strings.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param A: a string + @param B: a string + @return: return the sum of two strings + """ + def SumofTwoStrings(self, A, B): + # write your code here + ret = [] + min_len = min(len(A), len(B)) + A = list(A) # 偷个懒,不然循环要从后往前写。 + B = list(B) + A.reverse() + B.reverse() + for i in range(min_len): + ret.append(str(int(A[i]) + int(B[i]))) + if len(A) > min_len: + ret.extend(A[min_len:]) + elif len(B) > min_len: + ret.extend(B[min_len:]) + ret.reverse() + return ''.join(ret) + +# easy: https://www.lintcode.com/problem/sum-of-two-strings/ diff --git a/super-lollipop.py b/super-lollipop.py new file mode 100644 index 0000000..87d6d6a --- /dev/null +++ b/super-lollipop.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param v1: the speed of GGbond + @param v2: the speed of SuperQ + @param s: the speed that lollipop can add + @param w: the cost of lollipop + @return: the minimal price + """ + def getAns(self, v1, v2, s, w): + # Write your code here + ret = max(w) + if v1 > v2: + return 0 + for i in range(len(s)): + if (v1 + s[i]) > v2: + ret = min(w[i], ret) + return ret + +# easy: https://www.lintcode.com/problem/super-lollipop/ diff --git a/super_ugly_number.py b/super-ugly-number.py similarity index 100% rename from super_ugly_number.py rename to super-ugly-number.py diff --git a/surrounded_regions.py b/surrounded-regions.py similarity index 100% rename from surrounded_regions.py rename to surrounded-regions.py diff --git a/swap_nodes_in_pairs.py b/swap-nodes-in-pairs.py similarity index 100% rename from swap_nodes_in_pairs.py rename to swap-nodes-in-pairs.py diff --git a/swap_two_nodes_in_linked_list.py b/swap-two-nodes-in-linked-list.py similarity index 100% rename from swap_two_nodes_in_linked_list.py rename to swap-two-nodes-in-linked-list.py diff --git a/symmetric-binary-tree.py b/symmetric-binary-tree.py new file mode 100644 index 0000000..091868d --- /dev/null +++ b/symmetric-binary-tree.py @@ -0,0 +1,30 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: the root of binary tree. + @return: true if it is a mirror of itself, or false. + """ + def isSymmetric(self, root): + # write your code here + if root: + return self.checkSymmetric(root.left, root.right) + return True + + def checkSymmetric(self, left, right): + if left and right: + if left.val == right.val: + return self.checkSymmetric(left.left, right.right) and self.checkSymmetric(left.right, right.left) + else: + return False + elif (not left) and (not right): + return True + return False + +# easy: https://www.lintcode.com/problem/468/ diff --git a/symmetric-tree.py b/symmetric-tree.py new file mode 100644 index 0000000..d7774c7 --- /dev/null +++ b/symmetric-tree.py @@ -0,0 +1,28 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param root: root of the given tree + @return: whether it is a mirror of itself + """ + def isSymmetric(self, root): + # Write your code here + if not root: + return True + return self.compare(root.left, root.right) + + def compare(self, left, right): + if (not left) and (not right): + return True + elif left and right: + return self.compare(left.left, right.right) and self.compare(left.right, right.left) + else: + return False + +# easy: https://www.lintcode.com/problem/symmetric-tree/ diff --git a/task-scheduler.py b/task-scheduler.py new file mode 100644 index 0000000..f49b18d --- /dev/null +++ b/task-scheduler.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param tasks: the given char array representing tasks CPU need to do + @param n: the non-negative cooling interval + @return: the least number of intervals the CPU will take to finish all the given tasks + """ + def leastInterval(self, tasks, n): + # write your code here + # 1. 先按任务出现的次数排序 + # 2. 统计有多少个任务是小于最大出现次数的 + # 3. 计算因为n导致需要核外耗时的结果 + c = [0 for i in range(26)] + for t in tasks: + c[ord(t) - ord('A')] += 1 + c.sort() + i = 25 + while (i >= 0) and (c[i] == c[-1]): + i -= 1 + return max(len(tasks), (c[-1] - 1) * (n + 1) + 25 - i) + +# medium: https://www.lintcode.com/problem/945 diff --git a/team-notification.py b/team-notification.py new file mode 100644 index 0000000..7738702 --- /dev/null +++ b/team-notification.py @@ -0,0 +1,37 @@ +class Solution: + """ + @param n: the number of members in team. + @param groups: the groups. + @return: return how many members will get notifications. + """ + def teamNotification(self, n, groups): + # write your code here. + u = UnionSearch(n) + for g in groups: + if g: + x = g[0] + for i in range(1, len(g)): + u.union(x, g[i]) + return u.get_count(0) + +class UnionSearch: + def __init__(self, n): + self.parent = [i for i in range(n)] + self.count = [1] * n + + def find(self, x): + if x != self.parent[x]: + self.parent[x] = self.find(self.parent[x]) + return self.parent[x] + + def union(self, x, y): + px = self.find(x) + py = self.find(y) + if px != py: + self.parent[py] = x + self.count[px] += self.count[py] + + def get_count(self, x): + return self.count[self.find(x)] + +# medium: https://www.lintcode.com/problem/337 diff --git a/text-compression.py b/text-compression.py new file mode 100644 index 0000000..23b0435 --- /dev/null +++ b/text-compression.py @@ -0,0 +1,38 @@ +class Solution: + """ + @param lines: the text to compress. + @return: return the text after compression. + """ + def textCompression(self, lines): + # write your code here. + ret = [] + di = {} + i = 1 + for line in lines: + _ret = [] + word = '' + for c in line: + if ((c >= 'a') and (c <= 'z')) or ((c >= 'A') and (c <= 'Z')): + word += c + else: + if word: + if word in di: + _ret.append(str(di[word])) + else: + _ret.append(word) + di[word] = i + i += 1 + word = '' + _ret.append(c) + if word: # 只有一个单词 + if word in di: + _ret.append(str(di[word])) + else: + _ret.append(word) + di[word] = i + i += 1 + word = '' + ret.append(''.join(_ret)) + return ret + +# easy: https://www.lintcode.com/problem/text-compression/ diff --git a/the-candidate-with-the-most-votes.py b/the-candidate-with-the-most-votes.py new file mode 100644 index 0000000..ddc70cc --- /dev/null +++ b/the-candidate-with-the-most-votes.py @@ -0,0 +1,24 @@ +class Solution: + """ + @param votes: The array of names of candidates in the election. + @return: The name of the candidate who has the most votes. + """ + def candidateWithTheMostVotes(self, votes): + # Write your code here + ret = '' + mv = 0 + di = {} + for v in votes: + if v not in di: + di[v] = 1 + else: + di[v] += 1 + for k, v in di.items(): # 不对字典排序,遍历! + if v > mv: + mv = v + ret = k + elif (v == mv) and (k < ret): + ret = k + return ret + +# easy: https://www.lintcode.com/problem/1780/ diff --git a/the-height-of-the-second-tallest-player.sql b/the-height-of-the-second-tallest-player.sql new file mode 100644 index 0000000..c91e166 --- /dev/null +++ b/the-height-of-the-second-tallest-player.sql @@ -0,0 +1,13 @@ +-- Write your SQL Query here -- +-- example: SELECT * FROM XX_TABLE WHERE XXX -- + +select +( + if( + (select count(*) from (select distinct height from players) p) >= 2, + (select distinct height from players order by height desc limit 1 offset 1), + NULL + ) +) second_height + +-- https://www.lintcode.com/problem/the-height-of-the-second-tallest-player/ diff --git a/the-longest-common-prefix-ii.py b/the-longest-common-prefix-ii.py new file mode 100644 index 0000000..1de092d --- /dev/null +++ b/the-longest-common-prefix-ii.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param dic: the n strings + @param target: the target string + @return: The ans + """ + def the_longest_common_prefix(self, dic, target): + # write your code here + ret = 0 + for word in dic: + tmp = 0 + for i in range(min(len(word), len(target))): + if word[i] == target[i]: + tmp += 1 + else: + break + if tmp > ret: + ret = tmp + return ret + +# easy: https://www.lintcode.com/problem/the-longest-common-prefix-ii/ diff --git a/the-maze-iv.py b/the-maze-iv.py new file mode 100644 index 0000000..e673d23 --- /dev/null +++ b/the-maze-iv.py @@ -0,0 +1,39 @@ +class Solution: + """ + @param maps: + @return: + """ + def the_maze_i_v(self, maps): + # + ret = 0 + md = 0 + dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]] + paths = [set(), set()] + curr = 0 + rows, cols = len(maps), len(maps[0]) + for i in range(rows): + for j in range(cols): + if maps[i][j] == 'S': + paths[curr].add((i, j)) + while paths[curr]: + if ret == 32: + k = 0 + for i in range(rows): + for j in range(cols): + if maps[i][j] == '.': + k += 1 + for p in paths[curr]: + if maps[p[0]][p[1]] == 'T': + return ret + for d in dirs: + r = p[0] + d[0] + c = p[1] + d[1] + if (r >= 0) and (r < rows) and (c >= 0) and (c < cols) and ((maps[r][c] == '.') or (maps[r][c] == 'T')): + paths[1 - curr].add((r, c)) + maps[p[0]][p[1]] = '#' + paths[curr].clear() + curr = 1 - curr + ret += 1 + return -1 + +# medium: https://www.lintcode.com/problem/1685/ diff --git a/the-months-days.py b/the-months-days.py new file mode 100644 index 0000000..0ec4155 --- /dev/null +++ b/the-months-days.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param year: a number year + @param month: a number month + @return: Given the year and the month, return the number of days of the month. + """ + def getTheMonthDays(self, year, month): + # write your code here + if month == 2: + return 29 if self.is_leap_year(year) else 28 + else: + return 31 if month in [1, 3, 5, 7, 8, 10, 12] else 30 + + def is_leap_year(self, year): + return (((year % 4) == 0) and ((year % 100) != 0)) or ((year % 400) == 0) + +# easy: https://www.lintcode.com/problem/the-months-days/ diff --git a/the-result-of-investment.py b/the-result-of-investment.py new file mode 100644 index 0000000..75a993b --- /dev/null +++ b/the-result-of-investment.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param funds: The investment each time + @param a: The initial funds of A + @param b: The initial funds of B + @param c: The initial funds of C + @return: The final funds + """ + def getAns(self, funds, a, b, c): + # Write your code here + r = [a, b, c] + for f in funds: + v = r[0] + p = 0 + for i in [1, 2]: + if r[i] < v: + v = r[i] + p = i + r[p] += f + return r + +# easy: https://www.lintcode.com/problem/1615/ diff --git a/the_smallest_difference.py b/the-smallest-difference.py similarity index 100% rename from the_smallest_difference.py rename to the-smallest-difference.py diff --git a/the-sum-of-array.py b/the-sum-of-array.py new file mode 100644 index 0000000..ce503a0 --- /dev/null +++ b/the-sum-of-array.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param arr: An array + @return: An array + """ + def getSum(self, arr): + # Write your code here. + ret = [] + arr_copy = arr.copy() + arr.sort() + di = {} + for i in arr: + di[i] = 0 + for i in range(1, len(arr)): + di[arr[i]] = arr[i - 1] + di[arr[i - 1]] + for i in arr_copy: + ret.append(di[i]) + return ret + +# easy: https://www.lintcode.com/problem/the-sum-of-array/ diff --git a/third-maximum-number.py b/third-maximum-number.py new file mode 100644 index 0000000..c6bcaae --- /dev/null +++ b/third-maximum-number.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param nums: the array + @return: the third maximum number in this array + """ + def thirdMax(self, nums): + # Write your code here. + ret = set([]) + for n in nums: + if n not in ret: + if len(ret) < 3: + ret.add(n) + else: + m = min(ret) + if (m < n): + ret.remove(m) + ret.add(n) + return max(ret) if len(ret) < 3 else min(ret) + +# easy: https://www.lintcode.com/problem/third-maximum-number/description diff --git a/threhold-alerts.py b/threhold-alerts.py new file mode 100644 index 0000000..4c0f9c4 --- /dev/null +++ b/threhold-alerts.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param n: + @param k: + @param l: is len + @param num: //same as problem + @return: //return long + """ + def solve(self, n, k, l, num): + # + r = 0 + p = 0 + w = num[0 : l] + s = sum(w) + if (s / l) > k: + r += 1 + for i in range(l, len(num)): + s -= w[p] + w[p] = num[i] + s += w[p] + p += 1 + p %= l + if (s / l) > k: + r += 1 + return r + +# easy: https://www.lintcode.com/problem/1815/ diff --git a/throw-garbage.py b/throw-garbage.py new file mode 100644 index 0000000..8df056b --- /dev/null +++ b/throw-garbage.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param BagList: the weight of all garbage bags. + @return: an integer represent the minimum number of times. + """ + def Count_ThrowTimes(self, BagList): + # + # Because at least the bag is 1.01, so you can take at most 2 bags at 1 time! + r = 0 + BagList.sort() + i, j = 0, len(BagList) - 1 + while i < j: + s = BagList[i] + BagList[j] + if s > 3: + j -= 1 + else: + i += 1 + j -= 1 + r += 1 + if i == j: + r += 1 + return r diff --git a/time-angle.py b/time-angle.py new file mode 100644 index 0000000..f30d608 --- /dev/null +++ b/time-angle.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param h: hours + @param m: minutes + @return: angle between hour hand and minute hand at X:Y in a clock + """ + def timeAngle(self, h, m): + # write your code here + h = h * 5 + m / 12 + ret = abs(h - m) * 6 + if ret > 180: + return 360 - ret + else: + return ret + +# easy: https://www.lintcode.com/problem/time-angle/ diff --git a/time-magic.py b/time-magic.py new file mode 100644 index 0000000..2346140 --- /dev/null +++ b/time-magic.py @@ -0,0 +1,44 @@ +class Solution: + """ + @param newTime: new time + @return: maximum time + """ + def timeMagic(self, newTime): + # + h, m = newTime.split(':') + h = list(h) + m = list(m) + h_index, m_index = -1, -1 + if (h[0] == '?') and (h[1] == '?'): + h = ['2', '3'] + else: + if h[0] == '?': + h_index = 0 + elif h[1] == '?': + h_index = 1 + if (m[0] == '?') and (m[1] == '?'): + m = ['5', '9'] + else: + if m[0] == '?': + m_index = 0 + elif m[1] == '?': + m_index = 1 + if h_index != -1: + for i in range(9, 0, -1): + h[h_index] = str(i) + if self.validate(int(h[0]) * 10 + int(h[1]), 'h'): + break + if m_index != -1: + for i in range(9, 0, -1): + m[m_index] = str(i) + if self.validate(int(m[0]) * 10 + int(m[1]), 'm'): + break + return ':'.join([''.join(h), ''.join(m)]) + + def validate(self, val, part): + if part == 'h': + return (val >= 0) and (val <= 23) + else: + return (val >= 0) and (val <= 59) + +# easy: https://www.lintcode.com/problem/time-magic/ diff --git a/time-to-Flower-tree.py b/time-to-Flower-tree.py new file mode 100644 index 0000000..e4f978f --- /dev/null +++ b/time-to-Flower-tree.py @@ -0,0 +1,28 @@ +from typing import ( + List, +) + +class Solution: + """ + @param father: the father of every node + @param time: the time from father[i] to node i + @return: time to flower tree + """ + def time_to_flower_tree(self, father: List[int], time: List[int]) -> int: + # write your code here + n = len(father) + ret = [-1] * n + ret[0] = 0 + for i in range(1, n): + self.get_time(i, father, time, ret) + return max(ret) + + def get_time(self, n, father, time, ret): + f = father[n] + if ret[f] == -1: + ret[n] = time[n] + self.get_time(f, father, time, ret) + else: + ret[n] = time[n] + ret[f] + return ret[n] + +# medium: https://www.lintcode.com/problem/1862 diff --git a/tiny-url.py b/tiny-url.py new file mode 100644 index 0000000..86359ce --- /dev/null +++ b/tiny-url.py @@ -0,0 +1,32 @@ +class TinyUrl: + def __init__(self): + self.l2s = {} # long 2 short + self.s2l = {} # short 2 long + self.used = 0 + + """ + @param: url: a long url + @return: a short url starts with http://tiny.url/ + """ + def longToShort(self, url): + # write your code here + if url in self.l2s: + return self.l2s[url] + chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + surl = 'http://tiny.url/' + _used = self.used + for i in range(6): + surl += chars[_used % 52] + _used = int(_used / 52) + self.used += 1 + self.s2l[surl] = url + return surl + + + """ + @param: url: a short url starts with http://tiny.url/ + @return: a long url + """ + def shortToLong(self, url): + # write your code here + return self.s2l[url] diff --git a/to-lower-case.py b/to-lower-case.py new file mode 100644 index 0000000..2b6c4b9 --- /dev/null +++ b/to-lower-case.py @@ -0,0 +1,10 @@ +class Solution: + """ + @param str: the input string + @return: The lower case string + """ + def toLowerCase(self, str): + # Write your code here + return str.lower() # 懒得具体写了... + +# easy: https://www.lintcode.com/problem/to-lower-case/ diff --git a/toeplitz-matrix.py b/toeplitz-matrix.py new file mode 100644 index 0000000..fe6fc86 --- /dev/null +++ b/toeplitz-matrix.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param matrix: the given matrix + @return: True if and only if the matrix is Toeplitz + """ + def isToeplitzMatrix(self, matrix): + # Write your code here + if not matrix: + return True + rows = len(matrix) + cols = len(matrix[0]) + for row in range(rows): + col = 0 + while row < (rows - 1) and col < (cols - 1): + if matrix[row][col] != matrix[row + 1][col + 1]: + return False + row += 1 + col += 1 + return True + +# easy: https://www.lintcode.com/problem/toeplitz-matrix/ diff --git a/top-k-largest-numbers.py b/top-k-largest-numbers.py new file mode 100644 index 0000000..9c1a9a7 --- /dev/null +++ b/top-k-largest-numbers.py @@ -0,0 +1,33 @@ +class Solution: + """ + @param nums: an integer array + @param k: An integer + @return: the top k largest numbers in array + """ + def topk(self, nums, k): + # write your code here + ret = [] + for i in range(len(nums), -1, -1): + self.adjustDown(nums, len(nums), i) + for i in range(1, k + 1): + ret.append(nums[0]) + nums[0] = nums[-i] + self.adjustDown(nums, len(nums) - i, 0) + return ret + + def adjustDown(self, nums, size, i): + while i < size: + left = i * 2 + 1 + right = i * 2 + 2 + max_pos = i + if (left < size) and (nums[left] > nums[max_pos]): + max_pos = left + if (right < size) and (nums[right] > nums[max_pos]): + max_pos = right + if max_pos != i: + nums[i], nums[max_pos] = nums[max_pos], nums[i] + i = max_pos + else: + break + +# medium: https://www.lintcode.com/problem/top-k-largest-numbers/ diff --git a/topological_sorting.py b/topological-sorting.py similarity index 100% rename from topological_sorting.py rename to topological-sorting.py diff --git a/total-occurrence-of-target.py b/total-occurrence-of-target.py new file mode 100644 index 0000000..8056382 --- /dev/null +++ b/total-occurrence-of-target.py @@ -0,0 +1,58 @@ +class Solution: + """ + @param A: A an integer array sorted in ascending order + @param target: An integer + @return: An integer + """ + def totalOccurrence(self, A, target): + # write your code here + i = self.bSearch(A, target) + if i == -1: + return 0 + start = self.fMin(A, 0, i, target) + end = self.fMax(A, i, len(A) - 1, target) + if start == -1: + start = 0 + if end == -1: + end = len(A) - 1 + return end - start + 1 + + def bSearch(self, A, target): + i, j = 0, len(A) - 1 + while i <= j: + mid = int((i + j) / 2) + if A[mid] > target: + j = mid - 1 + elif A[mid] < target: + i = mid + 1 + else: + return mid + return -1 + + def fMin(self, A, start, end, target): + i, j = start , end + while i <= j: + mid = int((i + j) / 2) + if A[mid] < target: + if (mid < end) and (A[mid + 1] == target): + return mid + 1 + else: + i = mid + 1 + else: + j = mid - 1 + return -1 + + def fMax(self, A, start, end, target): + i, j = start , end + while i <= j: + mid = int((i + j) / 2) + if A[mid] > target: + if (start < mid) and (A[mid - 1] <= target): + return mid - 1 + else: + j = mid - 1 + else: + i = mid + 1 + return -1 + +# easy: https://www.lintcode.com/problem/462/ diff --git a/tower-of-hanoi.py b/tower-of-hanoi.py new file mode 100644 index 0000000..af8c31c --- /dev/null +++ b/tower-of-hanoi.py @@ -0,0 +1,22 @@ +class Solution: + """ + @param n: the number of disks + @return: the order of moves + """ + def towerOfHanoi(self, n): + # write your code here + ret = [] + if n > 0: + Solution.move(n, 'A', 'C', 'B', ret) + return ret + + @staticmethod + def move(n, source, target, by, ret): + if n == 1: + ret.append('from %s to %s' % (source, target)) + else: + Solution.move(n - 1, source, by, target, ret) + ret.append('from %s to %s' % (source, target)) + Solution.move(n - 1, by, target, source, ret) + +# medium: http://lintcode.com/zh-cn/problem/tower-of-hanoi/ diff --git a/toy_factory.py b/toy-factory.py similarity index 100% rename from toy_factory.py rename to toy-factory.py diff --git a/trackswitching.py b/trackswitching.py new file mode 100644 index 0000000..22ef2b5 --- /dev/null +++ b/trackswitching.py @@ -0,0 +1,34 @@ +class Solution: + """ + @param obstacles: the tracks which obstacles are settled on. + @return: return the minimum times to switch the track. + """ + def trackSwitching(self, obstacles): + # write your code here. + n = len(obstacles) + ret = n + dp = [[0, 0], [0, 0], [0, 0]] + dp[obstacles[0] - 1][0] = 1000000 + if obstacles[0] == 1: + dp[1][0], dp[2][0] = 0, 1 + elif obstacles[0] == 2: + dp[0][0], dp[2][0] = 1, 1 + elif obstacles[0] == 3: + dp[0][0], dp[1][0] = 1, 0 + for i in range(1, n): + pmin = min(dp[0][0], min(dp[1][0], dp[2][0])) + r = obstacles[i] - 1 + for j in range(3): + if j == r: + dp[j][1] = 1000000 + else: + if dp[j][0] != 1000000: + dp[j][1] = min(dp[j][0], pmin + 1) + else: + dp[j][1] = pmin + 1 + dp[0][0] = dp[0][1] + dp[1][0] = dp[1][1] + dp[2][0] = dp[2][1] + return min(dp[0][0], min(dp[1][0], dp[2][0])) + +# medium: https://www.lintcode.com/problem/348 diff --git a/trailing_zeros.py b/trailing-zeros.py similarity index 100% rename from trailing_zeros.py rename to trailing-zeros.py diff --git a/trapping_rain_water.py b/trapping-rain-water.py similarity index 100% rename from trapping_rain_water.py rename to trapping-rain-water.py diff --git a/travel-plan.py b/travel-plan.py new file mode 100644 index 0000000..66a90ff --- /dev/null +++ b/travel-plan.py @@ -0,0 +1,33 @@ +class Solution: + """ + @param arr: the distance between any two cities + @return: the minimum distance Alice needs to walk to complete the travel plan + """ + def travelPlan(self, arr): + # Write your code here. + self.r = 1000000 + used = set([0]) + paths = [0] + self.dfs(arr, paths, used) + return self.r + + def dfs(self, arr, paths, used): + n = len(arr) + if len(paths) == n: + d = 0 + for i in range(n - 1): + d += arr[paths[i]][paths[i + 1]] + d += arr[paths[-1]][0] + if d < self.r: + self.r = d + return self.r + else: + for i in range(1, n): + if i not in used: + paths.append(i) + used.add(i) + self.dfs(arr, paths, used) + paths.pop() + used.remove(i) + +# medium: https://www.lintcode.com/problem/1891/ diff --git a/treeplanning.py b/treeplanning.py new file mode 100644 index 0000000..3bc7168 --- /dev/null +++ b/treeplanning.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param trees: the positions of trees. + @param d: the minimum beautiful interval. + @return: the minimum number of trees to remove to make trees beautiful. + """ + def treePlanning(self, trees, d): + # write your code here. + left = [trees[0]] + prev = left[0] + for i in range(1, len(trees)): + if (trees[i] - prev) >= d: + left.append(trees[i]) + prev = trees[i] + return len(trees) - len(left) + +# easy: https://www.lintcode.com/problem/treeplanning/ diff --git a/triangle_count.py b/triangle-count.py similarity index 100% rename from triangle_count.py rename to triangle-count.py diff --git a/tweaked-identical-binary-tree.py b/tweaked-identical-binary-tree.py new file mode 100644 index 0000000..d6fdae7 --- /dev/null +++ b/tweaked-identical-binary-tree.py @@ -0,0 +1,26 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param a: the root of binary tree a. + @param b: the root of binary tree b. + @return: true if they are tweaked identical, or false. + """ + def isTweakedIdentical(self, a, b): + # write your code here + if a and b: + if a.val == b.val: + f1 = self.isTweakedIdentical(a.left, b.left) and self.isTweakedIdentical(a.right, b.right) + f2 = self.isTweakedIdentical(a.left, b.right) and self.isTweakedIdentical(a.right, b.left) + return f1 or f2 + elif not (a or b): + return True + return False + +# easy: https://www.lintcode.com/problem/470 diff --git a/twitch-words.py b/twitch-words.py new file mode 100644 index 0000000..fabc383 --- /dev/null +++ b/twitch-words.py @@ -0,0 +1,27 @@ +class Solution: + """ + @param str: the origin string + @return: the start and end of every twitch words + """ + def twitchWords(self, str): + # Write your code here + r = [] + i = 0 + prev = None + c = 0 + p = 0 + while i < len(str): + if str[i] != prev: + if c >= 3: + r.append([p, p + c - 1]) + prev = str[i] + c = 1 + p = i + else: + c += 1 + i += 1 + if c >= 3: + r.append([p, p + c - 1]) + return r + +# easy: https://www.lintcode.com/problem/1401/ diff --git a/two_strings_are_anagrams.py b/two-strings-are-anagrams.py similarity index 100% rename from two_strings_are_anagrams.py rename to two-strings-are-anagrams.py diff --git a/two-sum-iii-data-structure-design.py b/two-sum-iii-data-structure-design.py new file mode 100644 index 0000000..fe33a1c --- /dev/null +++ b/two-sum-iii-data-structure-design.py @@ -0,0 +1,32 @@ +class TwoSum: + def __init__(self): + self.di = {} + + """ + @param number: An integer + @return: nothing + """ + def add(self, number): + # write your code here + if number in self.di: + self.di[number] += 1 + else: + self.di[number] = 1 + + """ + @param value: An integer + @return: Find if there exists any pair of numbers which sum is equal to the value. + """ + def find(self, value): + # write your code here + for k, v in self.di.items(): + t = value - k + if t == k: + if (t in self.di) and (self.di[t] >= 2): + return True + else: + if t in self.di: + return True + return False + +# easy: https://www.lintcode.com/problem/two-sum-iii-data-structure-design/ diff --git a/two-sum-iv-input-is-a-bst.py b/two-sum-iv-input-is-a-bst.py new file mode 100644 index 0000000..2b635ee --- /dev/null +++ b/two-sum-iv-input-is-a-bst.py @@ -0,0 +1,45 @@ +""" +Definition of TreeNode: +class TreeNode: + def __init__(self, val): + self.val = val + self.left, self.right = None, None +""" + +class Solution: + """ + @param: : the root of tree + @param: : the target sum + @return: two numbers from tree which sum is n + """ + + def twoSum(self, root, n): + # write your code here + if root: + ret = [-1, n] + self._twoSum(root, root, n, ret) + if (ret[0] + ret[1]) == n: + return ret + return None + + def _twoSum(self, root, node, n, ret): + if not node: + return + if self.exists(root, n - node.val): + ret[0] = node.val + ret[1] = n - node.val + else: + self._twoSum(root, node.left, n, ret) + self._twoSum(root, node.right, n, ret) + + def exists(self, root, val): + if not root: + return False + if root.val == val: + return True + elif root.val > val: + return self.exists(root.left, val) + else: + return self.exists(root.right, val) + +# easy: https://www.lintcode.com/problem/two-sum-iv-input-is-a-bst/ diff --git a/two_sum.py b/two-sum.py similarity index 100% rename from two_sum.py rename to two-sum.py diff --git a/typing-practising.py b/typing-practising.py new file mode 100644 index 0000000..b14d6fe --- /dev/null +++ b/typing-practising.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param s: A string + @return: A string + """ + def getTextcontent(self, s): + # write your code here. + chars = [] + for c in s: + if c != '<': + chars.append(c) + else: + if chars: + chars.pop() + return ''.join(chars) + +# easy: https://www.lintcode.com/problem/typing-practising/ diff --git a/ugly_number_ii.py b/ugly-number-ii.py similarity index 100% rename from ugly_number_ii.py rename to ugly-number-ii.py diff --git a/ugly_number.py b/ugly-number.py similarity index 100% rename from ugly_number.py rename to ugly-number.py diff --git a/uncommon-words-from-two-sentences.py b/uncommon-words-from-two-sentences.py new file mode 100644 index 0000000..e0f63fa --- /dev/null +++ b/uncommon-words-from-two-sentences.py @@ -0,0 +1,31 @@ +class Solution: + """ + @param A: Sentence A + @param B: Sentence B + @return: Uncommon Words from Two Sentences + """ + def uncommonFromSentences(self, A, B): + # Write your code here. + ret = [] + di_a, di_b = {}, {} + words_a = A.split(' ') + words_b = B.split(' ') + self.buildDict(words_a, di_a) + self.buildDict(words_b, di_b) + self.checkWords(di_a, di_b, ret) + self.checkWords(di_b, di_a, ret) + return ret + + def buildDict(self, words, di): + for word in words: + if word in di: + di[word] += 1 + else: + di[word] = 1 + + def checkWords(self, di_src, di_target, ret): + for k in di_src: + if (di_src[k] == 1) and (k not in di_target): + ret.append(k) + +# easy: https://www.lintcode.com/problem/uncommon-words-from-two-sentences/ diff --git a/unique-array.py b/unique-array.py new file mode 100644 index 0000000..4f27597 --- /dev/null +++ b/unique-array.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param arr: a integer array + @return: return the unique array + """ + def getUniqueArray(self, arr): + # write your code here + s = set([]) + dups = 0 + for i in range(len(arr)): + v = arr[i] + if v not in s: + s.add(v) + arr[i - dups] = v + else: + dups += 1 + return arr[:-dups] + +# easy: https://www.lintcode.com/problem/unique-array/ diff --git a/unique_binary_search_trees_ii.py b/unique-binary-search-trees-ii.py similarity index 100% rename from unique_binary_search_trees_ii.py rename to unique-binary-search-trees-ii.py diff --git a/unique_binary_search_trees.py b/unique-binary-search-trees.py similarity index 94% rename from unique_binary_search_trees.py rename to unique-binary-search-trees.py index d543582..2f4ad6a 100644 --- a/unique_binary_search_trees.py +++ b/unique-binary-search-trees.py @@ -11,4 +11,4 @@ def numTrees(self, n): for i in xrange(2, n + 1): for j in xrange(1, i + 1): methods[i] += methods[j - 1] * methods[i - j] - return methods[-1] \ No newline at end of file + return methods[-1] diff --git a/unique_characters.py b/unique-characters.py similarity index 100% rename from unique_characters.py rename to unique-characters.py diff --git a/unique-email-addresses.py b/unique-email-addresses.py new file mode 100644 index 0000000..b68076f --- /dev/null +++ b/unique-email-addresses.py @@ -0,0 +1,16 @@ +class Solution: + """ + @param emails: + @return: The number of the different email addresses + """ + def numUniqueEmails(self, emails): + # write your code here + r = set([]) + for e in emails: + ls, rs = e.split('@') + ls = ls.split('+')[0] + ls = ls.replace('.', '') + r.add(ls + '@' + rs) + return len(r) + +# easy: https://www.lintcode.com/problem/1713/ diff --git a/unique-morse-code-words.py b/unique-morse-code-words.py new file mode 100644 index 0000000..1c7cd91 --- /dev/null +++ b/unique-morse-code-words.py @@ -0,0 +1,19 @@ +class Solution: + """ + @param words: the given list of words + @return: the number of different transformations among all words we have + """ + def uniqueMorseRepresentations(self, words): + # Write your code here + table = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] + s = set([]) + for word in words: + codes = [] + for c in word: + codes += table[ord(c) - ord('a')] + morsed = ''.join(codes) + if morsed not in s: + s.add(morsed) + return len(s) + +# easy: https://www.lintcode.com/problem/unique-morse-code-words/ diff --git a/unique_paths_ii.py b/unique-paths-ii.py similarity index 100% rename from unique_paths_ii.py rename to unique-paths-ii.py diff --git a/unique_paths.py b/unique-paths.py similarity index 100% rename from unique_paths.py rename to unique-paths.py diff --git a/unique-twitter-user-id-set.py b/unique-twitter-user-id-set.py new file mode 100644 index 0000000..0976b60 --- /dev/null +++ b/unique-twitter-user-id-set.py @@ -0,0 +1,30 @@ +class Solution: + """ + @param arr: a integer array + @return: return ids sum is minimum. + """ + def UniqueIDSum(self, arr): + # write your code here + ret = 0 + di = {} + a = arr.copy() + a.sort() + prev = a[0] - 1 + for i in a: + if i != prev: + if prev in di: + if i <= di[prev][-1]: + di[i] = [di[prev][-1] + 1] + else: + di[i] = [i] + else: + di[i] = [i] + prev = i + else: + v = di[i][-1] + 1 + di[i].append(v) + for v in di.values(): + ret += sum(v) + return ret + +# easy: https://www.lintcode.com/problem/1521/ diff --git a/update_bits.py b/update-bits.py similarity index 100% rename from update_bits.py rename to update-bits.py diff --git a/url-edcode.py b/url-edcode.py new file mode 100644 index 0000000..110b3e6 --- /dev/null +++ b/url-edcode.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param base_url: the string of base_url + @param query_params: sequence of two-element tuples by query_params + @return: return a url query string + """ + def urlencode(self, base_url: str, query_params: list[list[str]]) -> str: + # write your code. + if not query_params: + return base_url + qps = [] + for qp in query_params: + qps.append(qp[0] + '=' + qp[1]) + qps.sort() + return base_url + '?' + '&'.join(qps) + +# easy: https://www.lintcode.com/problem/253/ diff --git a/valid_number.py b/valid-number.py similarity index 100% rename from valid_number.py rename to valid-number.py diff --git a/valid_palindrome.py b/valid-palindrome.py similarity index 100% rename from valid_palindrome.py rename to valid-palindrome.py diff --git a/valid_parentheses.py b/valid-parentheses.py similarity index 100% rename from valid_parentheses.py rename to valid-parentheses.py diff --git a/valid-perfect-square.py b/valid-perfect-square.py new file mode 100644 index 0000000..57a1045 --- /dev/null +++ b/valid-perfect-square.py @@ -0,0 +1,20 @@ +class Solution: + """ + @param num: a positive integer + @return: if num is a perfect square else False + """ + def isPerfectSquare(self, num): + # write your code here + i, j = 0, num + while i <= j: + k = int((i + j) / 2) # 二分收敛 + k2 = k * k + if k2 == num: + return True + elif k2 > num: + j = k - 1 + else: + i = k + 1 + return False + +# easy: https://www.lintcode.com/problem/valid-perfect-square diff --git a/valid_sudoku.py b/valid-sudoku.py similarity index 100% rename from valid_sudoku.py rename to valid-sudoku.py diff --git a/valid-triangle.py b/valid-triangle.py new file mode 100644 index 0000000..9752b16 --- /dev/null +++ b/valid-triangle.py @@ -0,0 +1,14 @@ +class Solution: + """ + @param a: a integer represent the length of one edge + @param b: a integer represent the length of one edge + @param c: a integer represent the length of one edge + @return: whether three edges can form a triangle + """ + def isValidTriangle(self, a, b, c): + # write your code here + lines = sorted([a, b, c]) + return ((lines[0] + lines[1]) > lines[2]) \ + and ((lines[2] - lines[1]) < lines[0]) + +# easy: https://www.lintcode.com/problem/valid-triangle/ diff --git a/valid-word-abbreviation.py b/valid-word-abbreviation.py new file mode 100644 index 0000000..9f990ff --- /dev/null +++ b/valid-word-abbreviation.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param word: a non-empty string + @param abbr: an abbreviation + @return: true if string matches with the given abbr or false + """ + def validWordAbbreviation(self, word, abbr): + # write your code here + word_len = len(word) + if len(abbr) > len(word): + return False + pos = 0 + step = 0 + for c in abbr: + # print(c) + if c not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: + pos += step + if c != word[pos]: + return False + pos += 1 + step = 0 + else: + step = step * 10 + int(c) + if (pos + step) > len(word): + return False + return True + +# easy: https://www.lintcode.com/problem/valid-word-abbreviation/ diff --git a/valid-word-square.py b/valid-word-square.py new file mode 100644 index 0000000..5f011fe --- /dev/null +++ b/valid-word-square.py @@ -0,0 +1,17 @@ +class Solution: + """ + @param words: a list of string + @return: a boolean + """ + def validWordSquare(self, words): + # Write your code here + for i in range(len(words)): + for j in range(len(words[i])): + try: + if words[i][j] != words[j][i]: + return False + except: + return False + return True + +# easy: https://www.lintcode.com/problem/valid-word-square/ diff --git a/validate_binary_search_tree.py b/validate-binary-search-tree.py similarity index 100% rename from validate_binary_search_tree.py rename to validate-binary-search-tree.py diff --git a/valley-sequence.py b/valley-sequence.py new file mode 100644 index 0000000..1ce43d8 --- /dev/null +++ b/valley-sequence.py @@ -0,0 +1,35 @@ +class Solution: + """ + @param num: sequence + @return: The longest valley sequence + """ + def valley(self, num): + # write your code here + ret = 0 + di = {} # key is the value in the number, value is the coresponding position. + n = len(num) + dpl, dpr = [0] * n, [0] * n # l descending, r ascending... important!!! + for i in range(n): + if num[i] not in di: + di[num[i]] = [] + di[num[i]].append(i) + dpl[i] = 1 + for j in range(i - 1, -1, -1): + if num[j] > num[i]: + dpl[i] = max(dpl[i], dpl[j] + 1) + for i in range(n - 1, -1, -1): + dpr[i] = 1 + for j in range(i + 1, n): + if num[j] > num[i]: + dpr[i] = max(dpr[i], dpr[j] + 1) + for i in num: + l = di[i] + if len(l) < 2: + continue + for j in range(len(l)): + for k in range(j + 1, len(l)): + ret = max(ret, min(dpl[l[j]], dpr[l[k]]) * 2) + di[i] = [] + return ret + +# medium: https://www.lintcode.com/problem/342/ diff --git a/vlid-anagram.py b/vlid-anagram.py new file mode 100644 index 0000000..20393fc --- /dev/null +++ b/vlid-anagram.py @@ -0,0 +1,26 @@ +class Solution: + """ + @param s: string s + @param t: string t + @return: Given two strings s and t, write a function to determine if t is an anagram of s. + """ + def isAnagram(self, s, t): + # write your code here + if len(s) != len(t): + return False + di = {} + for i in range(len(s)): + if s[i] in di: + di[s[i]] += 1 + else: + di[s[i]] = 1 + if t[i] in di: + di[t[i]] -= 1 + else: + di[t[i]] = -1 + for k, v in di.items(): + if v != 0: + return False + return True + +# easy: https://www.lintcode.com/problem/vlid-anagram/ diff --git a/walking-robot-simulation.py b/walking-robot-simulation.py new file mode 100644 index 0000000..4b0a60e --- /dev/null +++ b/walking-robot-simulation.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param commands: type: List[int] + @param obstacles: type: List[List[int]] + @return: Return the square of the maximum Euclidean distance + """ + def robotSim(self, commands, obstacles): + # write your code here + pos = [0, 0] + dirs = ((0, 1), (-1, 0), (0, -1), (1, 0)) # 初始方向向上,逆时针方向转。 + dir_idx = 0 # 初始方向向上 + for c in commands: + if c == -1: # 右转90度,数组向左循环移动。 + dir_idx = abs(dir_idx - 1 + 4) % 4 + elif c == -2: # 左转90度,数组向右循环移动。 + dir_idx = (dir_idx + 1) % 4 + _dir = dirs[dir_idx] + if (c >= 1) and (c <= 9): + while c > 0: + c -= 1 + next_pos = [pos[0] + _dir[0], pos[1] + _dir[1]] # 下一步位置 + if next_pos in obstacles: + break + else: + pos = next_pos # 更新位置 + return pos[0] * pos[0] + pos[1] * pos[1] + +# easy: https://www.lintcode.com/problem/walking-robot-simulation/ diff --git a/watering-flowers.py b/watering-flowers.py new file mode 100644 index 0000000..149b9ef --- /dev/null +++ b/watering-flowers.py @@ -0,0 +1,34 @@ +from typing import ( + List, +) + +class Solution: + """ + @param plants: + @param capacity1: + @param capacity2: + @return: + """ + def water_plants(self, plants: List[int], capacity1: int, capacity2: int) -> int: + # + ret = 0 + n = len(plants) + c1, c2 = 0, 0 + n1, n2 = 0, n - 1 + while n1 < n2: + if c1 < plants[n1]: + c1 = capacity1 + ret += 1 + if c2 < plants[n2]: + c2 = capacity2 + ret += 1 + c1 -= plants[n1] + c2 -= plants[n2] + n1 += 1 + n2 -= 1 + if (n1 == n2) and (plants[n1] > (c1 + c2)): + return ret + 1 + else: + return ret + +# medium: https://www.lintcode.com/problem/1518 diff --git a/wiggle_sort.py b/wiggle-sort.py similarity index 100% rename from wiggle_sort.py rename to wiggle-sort.py diff --git a/window-sum.py b/window-sum.py new file mode 100644 index 0000000..3f43346 --- /dev/null +++ b/window-sum.py @@ -0,0 +1,18 @@ +class Solution: + """ + @param nums: a list of integers. + @param k: length of window. + @return: the sum of the element inside the window at each moving. + """ + def winSum(self, nums, k): + # write your code here + ret = [] + if nums: + ret.append(0) + for i in range(k): + ret[0] += nums[i] + for i in range(1, len(nums) - k + 1): + ret.append(ret[i - 1] - nums[i - 1] + nums[i + k - 1]) + return ret; + +# easy: https://www.lintcode.com/problem/window-sum/ diff --git a/wood_cut.py b/wood-cut.py similarity index 100% rename from wood_cut.py rename to wood-cut.py diff --git a/word_break.py b/word-break.py similarity index 100% rename from word_break.py rename to word-break.py diff --git a/word_count_map_reduce.py b/word-count-map-reduce.py similarity index 100% rename from word_count_map_reduce.py rename to word-count-map-reduce.py diff --git a/word_ladder.py b/word-ladder.py similarity index 100% rename from word_ladder.py rename to word-ladder.py diff --git a/word-pattern.py b/word-pattern.py new file mode 100644 index 0000000..b4bf4ed --- /dev/null +++ b/word-pattern.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param pattern: a string, denote pattern string + @param teststr: a string, denote matching string + @return: an boolean, denote whether the pattern string and the matching string match or not + """ + def wordPattern(self, pattern, teststr): + # write your code here + di = {} + pattern_mapping = [] + _id = 0 + for c in pattern: + if c not in di: + di[c] = _id + _id += 1 + pattern_mapping.append(di[c]) + _id = 0 + di.clear() + str_mapping = [] + words = teststr.split(' ') + for word in words: + if word not in di: + di[word] = _id + _id += 1 + str_mapping.append(di[word]) + return str_mapping == pattern_mapping + +# easy: https://www.lintcode.com/problem/word-pattern/ diff --git a/word_search.py b/word-search.py similarity index 100% rename from word_search.py rename to word-search.py diff --git a/word-spacing.py b/word-spacing.py new file mode 100644 index 0000000..e093052 --- /dev/null +++ b/word-spacing.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param words: the words given. + @param wordA: the first word you need to find. + @param wordB: the second word you need to find. + @return: return the spacing of the closest wordA and wordB. + """ + def wordSpacing(self, words, wordA, wordB): + # write your code here. + ret = len(words) + ais = [] + bis = [] + for i in range(len(words)): + word = words[i] + if word == wordA: + ais.append(i) + elif word == wordB: + bis.append(i) + if (not ais) or (not bis): + return -1 + for i in ais: + for j in bis: + dist = abs(j - i) + if dist < ret: + ret = dist + return ret + +# easy: https://www.lintcode.com/problem/word-spacing/ diff --git a/x-of-a-kind-in-a-deck-of-cards.py b/x-of-a-kind-in-a-deck-of-cards.py new file mode 100644 index 0000000..ca35f05 --- /dev/null +++ b/x-of-a-kind-in-a-deck-of-cards.py @@ -0,0 +1,28 @@ +class Solution: + """ + @param deck: a integer array + @return: return a value of bool + """ + def hasGroupsSizeX(self, deck): + # write your code here + # 分组统计后只要找到找到大于1的最大公约数即可 + if len(deck) < 2: + return False + di = {} + for d in deck: + if d not in di: + di[d] = 1 + else: + di[d] += 1 + m = min(di.values()) + for i in range(2, m + 1): + match = True + for v in di.values(): + if v % i != 0: + match = False + break + if match: + return match + return False + +# easy: https://www.lintcode.com/problem/x-of-a-kind-in-a-deck-of-cards/ diff --git a/yang-hui-triangle.py b/yang-hui-triangle.py new file mode 100644 index 0000000..01b8961 --- /dev/null +++ b/yang-hui-triangle.py @@ -0,0 +1,21 @@ +class Solution: + """ + @param n: a Integer + @return: the first n-line Yang Hui's triangle + """ + def calcYangHuisTriangle(self, n): + # write your code here + if n == 0: + return [] + else: + ret = [[1]] + for i in range(1, n): + prev_level = ret[-1] + new_level = [1] + for i in range(len(prev_level) - 1): + new_level.append(prev_level[i] + prev_level[i + 1]) + new_level.append(1) + ret.append(new_level) + return ret + +# easy: http://lintcode.com/zh-cn/problem/yang-hui-triangle/ diff --git a/zigzag-iterator.py b/zigzag-iterator.py new file mode 100644 index 0000000..4701fa7 --- /dev/null +++ b/zigzag-iterator.py @@ -0,0 +1,49 @@ +class ZigzagIterator: + """ + @param: v1: A 1d vector + @param: v2: A 1d vector + """ + def __init__(self, v1, v2): + # do intialization if necessary + self.v1 = v1 + self.v2 = v2 + self.i1 = 0 + self.i2 = 0 + self.curr = 1 + if not v1: + self.curr = 2 + + """ + @return: An integer + """ + def _next(self): + # write your code here + if self.curr == 1: + if self.i1 < len(self.v1): + i = self.i1 + self.i1 += 1 + if self.i2 < len(self.v2): + self.curr = 2 + return self.v1[i] + else: + if self.i2 < len(self.v2): + i = self.i2 + self.i2 += 1 + if self.i1 < len(self.v1): + self.curr = 1 + return self.v2[i] + + """ + @return: True if has next + """ + def hasNext(self): + # write your code here + return (self.i1 < len(self.v1)) or (self.i2 < len(self.v2)) + + +# Your ZigzagIterator object will be instantiated and called as such: +# solution, result = ZigzagIterator(v1, v2), [] +# while solution.hasNext(): result.append(solution.next()) +# Output result + +# medium: https://www.lintcode.com/problem/540/