Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

week2 #419

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open

week2 #419

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added Week_02/.DS_Store
Binary file not shown.
17 changes: 17 additions & 0 deletions Week_02/id_55/LeetCode_236_55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root in (None, p, q):
return root
left=self.lowestCommonAncestor(root.left, p, q)
right=self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
else:
return left or right
12 changes: 12 additions & 0 deletions Week_02/id_55/LeetCode_242_55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# 上周有个相同题目用数组但是没法处理unicode,换成字典就可以了
def isAnagramUnicode(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False

alpha = {}
beta = {}
for c in s:
alpha[c] = alpha.get(c, 0) + 1
for c in t:
beta[c] = beta.get(c, 0) + 1
return alpha == beta
20 changes: 20 additions & 0 deletions Week_02/id_55/LeetCode_441_55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 这是上周的题一直就想到这个解,感觉拿不出手
class Solution:
def arrangeCoins(self, n: int) -> int:
level = 1
while level <= n:
n -= level
level += 1
return level-1

def arrangeCoins2(self, n: int) -> int:
level = 1
m = int(n/2)+1 #细想了想最多有int(n/2)+1行了吧
while level <= m:
n -= level
if n < 0:
break
level += 1
return level-1

# 看了别人的二分法思路思路O(logn)
27 changes: 27 additions & 0 deletions Week_02/id_55/LeetCode_671_55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None


class Solution:

def findSecondMinimumValue(self, root: TreeNode) -> int:
val_set = set([])

def findRun(root):
if not root:
return
val_set.add(root.val)
if (root.left):
findRun(root.left)
if (root.right):
findRun(root.right)

findRun(root)
a = list(val_set)
a.sort()
if len(a) < 2:
return -1
return a[1]
22 changes: 22 additions & 0 deletions Week_02/id_55/LeetCode_783_55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def minDiffInBST(self, root: TreeNode) -> int:
self.prev = None
self.min_val = float('inf')
self.inOrder(root)
return self.min_val

def inOrder(self, root):
if not root:
return
self.inOrder(root.left)
if self.prev:
self.min_val = min(self.min_val, root.val - self.prev.val)
self.prev = root
self.inOrder(root.right)
42 changes: 42 additions & 0 deletions Week_03/id_55/LeetCode_104.55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None


class Solution:
# 深度优先搜索DFS递归解法:
def maxDepthDFS(self, root: TreeNode) -> int:
# print("root val:%d" % (root.val))
print("root:%s" % (root))
if root == None: # 递归边界
return 0
else:
depth_l = self.maxDepthDFS(root.left)
if depth_l:
print("depth_l:%d" % (depth_l))
depth_r = self.maxDepthDFS(root.right)
if depth_r:
print("depth_r:%d" % (depth_r))
return max(depth_l, depth_r) + 1

def maxDepthBFS(self, root):
stack = []
if root is not None:
stack.append((1, root)) # 如果root不是空就把root加入stack,深度为1

depth = 0
while stack != []: # 开始循环stack
print("stack before pop :%s" % (stack)) # 打印pop前的栈
current_depth, root = stack.pop() # 先取出最后放进去的
print("current_depth:%d" % (current_depth)) # 打印当前深度从1开始
print("stack after pop :%s" % (stack)) # 打印pop后的栈
if root:
print("root.val:%d" % (root.val))
if root is not None:
depth = max(depth, current_depth)
stack.append((current_depth + 1, root.left))
stack.append((current_depth + 1, root.right))
return depth
24 changes: 24 additions & 0 deletions Week_03/id_55/LeetCode_429_55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Definition for a Node.


class Node:
def __init__(self, val, children):
self.val = val
self.children = children


class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
level = []
if not root:
return []
level.append((0, root))
res = []
while level:
depth, root = level.pop(0)
if depth >= len(res):
res.append([])
res[depth].append(root.val)
for node in root.children:
level.append((depth+1, node))
return res
Binary file added Week_04/.DS_Store
Binary file not shown.
45 changes: 45 additions & 0 deletions Week_04/id_55/LeetCode_169_55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# coding=UTF8
# 给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

# 你可以假设数组是非空的,并且给定的数组总是存在众数。

# 示例 1:

# 输入: [3,2,3]
# 输出: 3
# 示例 2:

# 输入: [2,2,1,1,1,2,2]
# 输出: 2


from collections import Counter


class Solution:
def majorityElement(self, nums):
majority = int(len(nums)/2)
print(majority)
count_dict = {}
theBiggest = ''
for num in nums:
if num in count_dict.keys():
a = count_dict[num]
count_dict[num] = a + 1
else:
count_dict[num] = 1
print(count_dict)
for key, value in count_dict.items():
if value > majority:
theBiggest = key
return theBiggest

# 学一波counter的用法...
def majorityElement2(self, nums):
c = Counter(nums)
res = c.most_common(1)[0][0]
return res

words = [1, 2, 2, 2, 1, 1, 1, 2, 2]
demo = Solution()
print("result: %s" % demo.majorityElement3(words))
66 changes: 66 additions & 0 deletions Week_04/id_55/LeetCode_455_55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# coding=UTF8
# ---------------------
# 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。
# 对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,
# 都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
# 注意:
# 你可以假设胃口值为正。
# 一个小朋友最多只能拥有一块饼干。
# 示例 1:
# 输入: [1,2,3], [1,1]
# 输出: 1
# 解释:
# 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
# 虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
# 所以你应该输出1。
# 示例 2:
# 输入: [1,2], [1,2,3]
# 输出: 2
# 解释:
# 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
# 你拥有的饼干数量和尺寸都足以让所有孩子满足。
# 所以你应该输出2.


class Solution:
# 执行用时 : 2564 ms, 在Assign Cookies的Python3提交中击败了5.08% 的用户
# 内存消耗 : 14.7 MB, 在Assign Cookies的Python3提交中击败了17.98% 的用户
def findContentChildren(self, g, s):
g = sorted(g) # 胃口
s = sorted(s) # 饼干
num, ss, gg = 0, 0, 0
for i in range(ss, len(s)):
for j in range(gg, len(g)):
if s[i] >= g[j]:
num += 1
gg = j + 1
break
else:
ss = i + 1
continue
return num

# 用while改造了一下居然提高这么多
# 执行用时 : 108 ms, 在Assign Cookies的Python3提交中击败了50.07% 的用户
# 内存消耗 : 14.4 MB, 在Assign Cookies的Python3提交中击败了87.93% 的用户
def findContentChildren(self, g, s):
g.sort()
s.sort()
count = 0
i = 0
j = 0
while i < len(g) and j < len(s):
if g[i] <= s[j]:
count += 1
i += 1
j += 1
else:
j += 1
return count

s = [1, 1] # 饼干
g = [1, 2, 3] # 孩子

demo = Solution()
print("result: %s" % demo.findContentChildren3(g, s))

38 changes: 38 additions & 0 deletions Week_04/id_55/LeetCode_720_55.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution:
# 暴力方法破解,暴力遍历每个字符串前缀是不是都在数组中,在比较是不是最长的、如果等长看是不是字母序更小
# 开始没用set,直接用words List结果超时,果然差别很大,Set居然是O(1)
def longestWord(self, words):
wordSet = set(words)
theWord = ""
for w in words:
print(w)
isIn = True
for i in range(1, len(w)):
if w[:i] not in wordSet:
print("%s is not in " % w[:i])
isIn = False
break
if isIn:
if not theWord or len(theWord) < len(w):
theWord = w
elif len(w) == len(theWord) and theWord > w:
theWord = w
return theWord

def longestWord2(self, words):
words.sort() # sort成树状结构
res = set(['']) # 建立一个空的set 直接去重了
longestWord = ''
for word in words:
print(word)
if word[:-1] in res: # 判断每个单词的除去最后一个字母是否在set里
res.add(word)
print(res)
if len(word) > len(longestWord):
longestWord = word # 保存最长的词
return longestWord


words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
demo = Solution()
print("result: %s" % demo.longestWord(words))