查看: 1004| 回复: 9
跳转到指定楼层
上一主题 下一主题
收起左侧

新开刷卡贴

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
From 2018-12-22

上一篇:比自己牛逼的人都比自己努力,不自觉的孩子打卡求监督
下一篇:LeetCode subscription 付款系统有问题?
🔗
 楼主| tall_cool_13 2018-12-22 20:50:57 | 只看该作者
全局:

  1. # log(n)
  2. class Solution(object):

  3.         @staticmethod
  4.         def multiply(x, y):
  5.                 x1, x2, x3, x4 = x
  6.                 y1, y2, y3, y4 = y
  7.                 return (x1 * y1 + x2 * y3, x1 * y2 + x2 * y4, x3 * y1 + x4 * y3, x3 * y2 + x4 * y4)

  8.         @staticmethod
  9.         def matrix_pow(matrix, n):
  10.                 if n == 1:
  11.                         return matrix

  12.                 if n % 2 == 1:
  13.                         return Solution.multiply(matrix,
  14.                                                                          Solution.multiply(Solution.matrix_pow(matrix, (n-1)/2),
  15.                                                                                                             Solution.matrix_pow(matrix, (n-1)/2)))
  16.                 else:
  17.                         return Solution.multiply(Solution.matrix_pow(matrix, n/2),
  18.                                                      Solution.matrix_pow(matrix, n/2))


  19.         def get(self, n):
  20.                 if n == 1 or n == 2: return 1
  21.                 # pow((0, 1, 1, 1), n - 1) * (1, 1)
  22.                 x1, x2, x3, x4 = Solution.matrix_pow((0, 1, 1, 1), n - 1)
  23.                 return x1 + x2


  24. if __name__ == "__main__":
  25.         obj = Solution()
  26.         for i in range(1, 100):
  27.                 print("i: %s, fabo: %s" % (i, obj.get(i)))
复制代码



补充内容 (2018-12-22 20:51):
time complexity: log(N)
回复

使用道具 举报

🔗
 楼主| tall_cool_13 2018-12-22 21:58:35 | 只看该作者
全局:
Leetcode 518, 代码写了好一会儿


  1. class Solution(object):
  2.     def change(self, amount, coins):
  3.         """
  4.         :type amount: int
  5.         :type coins: List[int]
  6.         :rtype: int
  7.         """
  8.         if len(coins) == 0:
  9.                 return 1 if amount == 0 else 0

  10.         coins = sorted(coins)
  11.         dp = []
  12.         # dp[amount][idx]
  13.         # amount starting from 1
  14.         # idx starting from 0
  15.         # initialization
  16.         # idx = len(coins) - 1 or amount = 0
  17.         for j in range(amount + 1):
  18.                 dp.append([1 if j == 0 else 0] * len(coins))  # one possible way when amount = 0
  19.                 if j % coins[-1] == 0:  # integer division
  20.                         dp[j][-1] = 1

  21.         for i in range(1, amount + 1):
  22.                 for j in range(len(coins) - 1)[::-1]:
  23.                         dp[i][j] = dp[i][j + 1] + (dp[i - coins[j]][j] if i - coins[j] >= 0 else 0)

  24.         return dp[amount][0]


  25. if __name__ == "__main__":
  26.         obj = Solution()
  27.         # print(obj.change(25, [1, 2, 5]))
  28.         print(obj.change(10, [5]))
  29.         
复制代码

补充内容 (2018-12-22 21:59):
使用dp
回复

使用道具 举报

🔗
 楼主| tall_cool_13 2018-12-22 22:23:43 | 只看该作者
全局:
Leetcode 264



  1. class Solution(object):
  2.     def nthUglyNumber(self, n):
  3.         """
  4.         :type n: int
  5.         :rtype: int
  6.         """
  7.         tag2, tag3, tag5 = 0, 0, 0
  8.         ans = []
  9.         ans.append(1)
  10.         for _ in range(n - 1):
  11.                 ans.append(min(2 * ans[tag2], 3 * ans[tag3], 5 * ans[tag5]))

  12.                 while 2 * ans[tag2] <= ans[-1]: tag2 += 1
  13.                 while 3 * ans[tag3] <= ans[-1]: tag3 += 1
  14.                 while 5 * ans[tag5] <= ans[-1]: tag5 += 1
  15.         return ans
复制代码

补充内容 (2018-12-22 22:24):
Time complexity: O(N)
回复

使用道具 举报

🔗
 楼主| tall_cool_13 2018-12-22 23:15:33 | 只看该作者
全局:
Leetcode 886

  1. import collections

  2. class Solution(object):
  3.     def __init__(self):
  4.         self.ans = True

  5.     def dfs(self, p, graph, colors):
  6.         for next in graph[p]:
  7.             if colors[next] == 0:
  8.                 colors[next] = -1 * colors[p]
  9.                 self.dfs(next, graph, colors)
  10.             else:
  11.                 if colors[next] == colors[p]:
  12.                     self.ans = False
  13.                     break

  14.     def possibleBipartition(self, N, dislikes):
  15.         colors = [0] * (N + 1)  # 0 => initial, 1 => read, -1 => blue
  16.         graph = collections.defaultdict(list)
  17.         for pairs in dislikes:
  18.             graph[pairs[0]].append(pairs[1])
  19.             graph[pairs[1]].append(pairs[0])

  20.         for p in range(1, N + 1):
  21.             if colors[p] == 0 and p in graph:
  22.                 colors[p] = 1
  23.                 self.dfs(p, graph, colors)
  24.                 if not self.ans:
  25.                     return False
  26.         return True


  27. if __name__ == "__main__":
  28.         obj = Solution()
  29.         print(obj.possibleBipartition(3, [[1,2],[1,3],[2,3]]))
复制代码
回复

使用道具 举报

🔗
 楼主| tall_cool_13 2018-12-22 23:40:48 | 只看该作者
全局:
Leetcode 449, 利用BST的性质,直接将前序遍历的结果保存
  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. #     def __init__(self, x):
  4. #         self.val = x
  5. #         self.left = None
  6. #         self.right = None

  7. class Codec:

  8.     def serialize(self, root):
  9.         """Encodes a tree to a single string.
  10.         
  11.         :type root: TreeNode
  12.         :rtype: str
  13.         """
  14.         # using prior reversal
  15.         import json
  16.         ans = []
  17.         def rev(ans, root):
  18.             if not root:
  19.                 return
  20.             ans.append(root.val)
  21.             rev(ans, root.left)
  22.             rev(ans, root.right)
  23.         
  24.         rev(ans, root)
  25.         return json.dumps(ans)
  26.         

  27.     def deserialize(self, data):
  28.         """Decodes your encoded data to tree.
  29.         
  30.         :type data: str
  31.         :rtype: TreeNode
  32.         """
  33.         import json
  34.         data = json.loads(data)
  35.         return self.deser(data)
  36.    
  37.     def deser(self, data):   
  38.         if not data:
  39.             return None
  40.         
  41.         root = TreeNode(data[0])
  42.         i = 1
  43.         while i < len(data) and data[i] < data[0]:
  44.             i += 1
  45.         root.left = self.deser(data[1:i])
  46.         root.right = self.deser(data[i:])
  47.         return root
  48.         

  49. # Your Codec object will be instantiated and called as such:
  50. # codec = Codec()
  51. # codec.deserialize(codec.serialize(root))
复制代码
回复

使用道具 举报

🔗
 楼主| tall_cool_13 2018-12-23 09:25:36 | 只看该作者
全局:
top k smallest numbers in the array, 使用最大堆, python 自带最小堆,我们使用最小堆来实现一个最大堆然后来实现该功能
  1. # https://docs.python.org/2/library/heapq.html
  2. import sys
  3. import heapq
  4. import sys

  5. class TopKHeap(object):
  6.     # implementation the max-heap
  7.     def __init__(self, k):
  8.         self.k = k
  9.         self.data = []

  10.     def push(self, elem):
  11.         elem = sys.maxsize - elem
  12.         if len(self.data) < self.k:
  13.             heapq.heappush(self.data, elem)
  14.         else:
  15.             topk_small = self.data[0]
  16.             if elem > topk_small:
  17.                 heapq.heapreplace(self.data, elem)  

  18.     def topk(self):
  19.         return [int(sys.maxsize - elem) for elem in self.data]


  20. def main():
  21.     # have to using the max-heap, default using min-heap
  22.     list_num = [1, 2, 10, 4, 5, 6, 7, 8, 9, -1]
  23.     th = TopKHeap(5)

  24.     for i in list_num:
  25.         th.push(i)

  26.     print th.topk()

  27. if __name__ == "__main__":
  28.     main()
复制代码
回复

使用道具 举报

🔗
 楼主| tall_cool_13 2018-12-23 10:06:17 | 只看该作者
全局:
翻转一个stack,仅仅使用递归,有点小意思

  1. # merely using recursion
  2. class Solution(object):
  3.         def reverse_stack(self, stack):
  4.                 if len(stack) == 0:
  5.                         return []

  6.                 top = stack.pop()
  7.                 self.reverse_stack(stack)
  8.                 self.send_bottom(stack, top)
  9.                 return stack

  10.         def send_bottom(self, stack, top):
  11.                 if len(stack) == 0:
  12.                         stack.append(top)
  13.                 else:
  14.                         t_top = stack.pop()
  15.                         self.send_bottom(stack, top)
  16.                         stack.append(t_top)


  17. if __name__ == "__main__":
  18.         obj = Solution()
  19.         print(obj.reverse_stack([1, 2, 3, 4, 5, 6]))
复制代码
回复

使用道具 举报

🔗
 楼主| tall_cool_13 2018-12-23 20:17:17 | 只看该作者
全局:
Leetcode 962, Maximum Width Ramp


  1. import sys
  2. class Solution:
  3.     def maxWidthRamp(self, A):
  4.         """
  5.         :type A: List[int]
  6.         :rtype: int
  7.         """
  8.         uniq = {}
  9.         for idx, elem in enumerate(A):
  10.             uniq[elem] = [idx, uniq[elem][1] if elem in uniq else idx]

  11.         # (number, right-most index, left-most index)
  12.         uniq = [(k, v[0], v[1]) for k, v in uniq.items()]

  13.         uniq = sorted(uniq, key=lambda x: x[0])

  14.         ans, m = 0, sys.maxsize
  15.         for elem in uniq:
  16.             m = min(m, elem[2])
  17.             ans = max(ans, elem[1] - m)

  18.         return ans
复制代码
回复

使用道具 举报

🔗
 楼主| tall_cool_13 2018-12-23 22:05:59 | 只看该作者
全局:
Leetcode 963,

  1. import collections
  2. import sys
  3. class Solution:

  4.     def minAreaFreeRect(self, A):
  5.         """
  6.         :type points: List[List[int]]
  7.         :rtype: float
  8.         """
  9.         def get_len(p1, p2):
  10.             return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)

  11.         h_vectors = collections.defaultdict(list)
  12.         N = len(A)
  13.         for i in range(N):
  14.             for j in range(i + 1, N):
  15.                 vector = (A[j][0] - A[i][0], A[j][1] - A[i][1])
  16.                 pos = -1 if vector[1] < 0 or (vector[1] == 0 and vector[0] < 0) else 1
  17.                 # the order is important
  18.                 h_vectors[(vector[0] * pos, vector[1] * pos)].append((i, j) if pos == 1 else (j, i))

  19.         ans = sys.maxsize
  20.         for vector, lines in h_vectors.items():
  21.             if len(lines) >= 2:
  22.                 for i in range(len(lines)):
  23.                     for j in range(i + 1, len(lines)):
  24.                         p1, p2 = A[lines[i][0]], A[lines[i][1]]
  25.                         p3, p4 = A[lines[j][0]], A[lines[j][1]]
  26.                         if (p1[0] - p3[0]) * (p1[0] - p2[0]) + (p1[1] - p3[1]) * (p1[1] - p2[1]) == 0:  # perpendicular
  27.                             ans = min(get_len(p1, p2) * get_len(p1, p3), ans)

  28.         return 0 if ans == sys.maxsize else ans
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表