repo
stringlengths 3
91
| file
stringlengths 16
152
| code
stringlengths 0
3.77M
| file_length
int64 0
3.77M
| avg_line_length
float64 0
16k
| max_line_length
int64 0
273k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
LeetCode-Python | LeetCode-Python-master/0202.快乐数/0202-快乐数 2.py | class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
def happy(num):
res = 0
while num:
num, tmp = divmod(num, 10)
res += tmp ** 2
return res
visited = set()
while n and n not in visited:
visited.add(n)
tmp = happy(n)
if tmp == 1:
return True
n = tmp
return False | 490 | 23.55 | 42 | py |
LeetCode-Python | LeetCode-Python-master/0202.快乐数/0202-快乐数.py | class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
def happy(num):
res = 0
while num:
num, tmp = divmod(num, 10)
res += tmp ** 2
return res
visited = set()
while n and n not in visited:
visited.add(n)
tmp = happy(n)
if tmp == 1:
return True
n = tmp
return False | 490 | 23.55 | 42 | py |
LeetCode-Python | LeetCode-Python-master/0589.N叉树的前序遍历/0589-N叉树的前序遍历 2.py | """
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
res = [root.val]
for child in root.children:
res += self.preorder(child)
return res | 450 | 21.55 | 48 | py |
LeetCode-Python | LeetCode-Python-master/0589.N叉树的前序遍历/0589-N叉树的前序遍历.py | """
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
res = [root.val]
for child in root.children:
res += self.preorder(child)
return res | 450 | 21.55 | 48 | py |
LeetCode-Python | LeetCode-Python-master/1391.检查网格中是否存在有效路径/1391-检查网格中是否存在有效路径.py | class Solution(object):
def hasValidPath(self, grid):
"""
:type grid: List[List[int]]
:rtype: bool
"""
m, n = len(grid), len(grid[0])
dir = {}
dir[1] = [0, 1, 0, 1]
dir[2] = [1, 0, 1, 0]
dir[3] = [0, 0, 1, 1]
dir[4] = [0, 1, 1, 0]
dir[5] = [1, 0, 0, 1]
dir[6] = [1, 1, 0, 0]
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
queue = [(0, 0)]
visited = set(queue)
cor = {0:2, 1:3, 3:1, 2:0}
while queue:
x0, y0 = queue.pop()
if [x0, y0] == [m - 1, n - 1]:
return True
for k in range(4):
x = x0 + dx[k]
y = y0 + dy[k]
if 0 <= x < m and 0 <= y < n and (x, y) not in visited and dir[grid[x0][y0]][k] & dir[grid[x][y]][cor[k]]:
visited.add((x, y))
queue.append((x, y))
return False
| 972 | 27.617647 | 122 | py |
LeetCode-Python | LeetCode-Python-master/1550.存在连续三个奇数的数组/1550-存在连续三个奇数的数组.py | class Solution(object):
def threeConsecutiveOdds(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
l = 0
for num in arr:
if num % 2:
l += 1
if l == 3:
return True
else:
l = 0
return False | 344 | 22 | 40 | py |
LeetCode-Python | LeetCode-Python-master/1492.n的第k个因子/1492-n的第k个因子.py | class Solution(object):
def kthFactor(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
l = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
l.append(i)
total = len(l) * 2 if l[-1] ** 2 != n else len(l) * 2 - 1
if total < k:
return -1
if k - 1 < len(l):
return l[k - 1]
else:
idx = (len(l) - 1) * 2 - k
return n // l[idx] if total % 2 else n // l[idx + 2]
| 557 | 25.571429 | 65 | py |
LeetCode-Python | LeetCode-Python-master/2465.不同的平均值数目/2465-不同的平均值数目.py | class Solution:
def distinctAverages(self, nums: List[int]) -> int:
nums.sort()
res = set()
while nums:
res.add((nums[0] + nums[-1]) / 2.0)
nums = nums[1:-1]
return len(res) | 234 | 25.111111 | 55 | py |
LeetCode-Python | LeetCode-Python-master/1929.数组串联/1929-数组串联.py | class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
return nums + nums | 104 | 34 | 61 | py |
LeetCode-Python | LeetCode-Python-master/0540.有序数组中的单一元素/0540-有序数组中的单一元素.py | class Solution(object):
def singleNonDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
for num in nums:
i ^= num
return i | 214 | 20.5 | 39 | py |
LeetCode-Python | LeetCode-Python-master/0561.数组拆分I/0561-数组拆分I.py | class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
nums.sort()
return sum(nums[i] for i in range(0, len(nums),2)) | 259 | 25 | 59 | py |
LeetCode-Python | LeetCode-Python-master/0141.环形链表/0141-环形链表.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return False
slow, fast = head, head
while fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
if slow == fast:
return True
return False | 584 | 23.375 | 37 | py |
LeetCode-Python | LeetCode-Python-master/0141.环形链表/0141-环形链表 2.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return False
slow, fast = head, head
while fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
if slow == fast:
return True
return False | 584 | 23.375 | 37 | py |
LeetCode-Python | LeetCode-Python-master/1452.收藏清单/1452-收藏清单.py | class Solution(object):
def peopleIndexes(self, favoriteCompanies):
"""
:type favoriteCompanies: List[List[str]]
:rtype: List[int]
"""
s = [set(l) for l in favoriteCompanies]
return [i for i, s1 in enumerate(s) if not any(s1 < s2 for s2 in s)] | 295 | 36 | 76 | py |
LeetCode-Python | LeetCode-Python-master/0254.因子的组合/0254-因子的组合.py | class Solution(object):
def getFactors(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
res = []
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
comb = sorted([i, n // i])
if comb not in res: #ȥ
res.append(comb)
for item in self.getFactors(n // i) :
comb = sorted([i] + item)
if comb not in res: #ȥ
res.append(comb)
return res | 543 | 27.631579 | 53 | py |
LeetCode-Python | LeetCode-Python-master/0543.二叉树的直径/0543-二叉树的直径.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
def Height(node):
if not node:
return 0
return 1 + max(Height(node.left), Height(node.right))
return max(self.diameterOfBinaryTree(root.left), Height(root.left) + Height(root.right), self.diameterOfBinaryTree(root.right)) | 629 | 30.5 | 135 | py |
LeetCode-Python | LeetCode-Python-master/0216.组合总和III/0216-组合总和III.py | class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
res = []
def dfs(start, cnt, target, tmp):
if target < 0:
return
if target == 0:
if cnt == 0:
res.append(tmp)
else:
return
for num in range(start, 10):
visited.add(num)
dfs(num + 1, cnt - 1, target - num, tmp + [num])
visited.remove(num)
visited = set()
dfs(1, k, n, [])
return res | 677 | 27.25 | 64 | py |
LeetCode-Python | LeetCode-Python-master/0101.对称二叉树/0101-对称二叉树.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def isSame(node1, node2):
if not node1 and not node2:
return True
if not node1 and node2:
return False
if node1 and not node2:
return False
return node1.val == node2.val and isSame(node1.left, node2.right) and isSame(node1.right, node2.left)
return isSame(root, root) | 691 | 27.833333 | 113 | py |
LeetCode-Python | LeetCode-Python-master/1494.并行课程II/1494-并行课程II.py | class Solution(object):
def minNumberOfSemesters(self, n, dependencies, k):
"""
:type n: int
:type dependencies: List[List[int]]
:type k: int
:rtype: int
"""
from collections import defaultdict
inDegree = defaultdict(int)
outDegree = defaultdict(int)
children = defaultdict(set)
for src, dec in dependencies: # 建图
inDegree[dec] += 1
outDegree[src] += 1
children[src].add(dec)
queue = []
for i in range(1, n + 1):
if inDegree[i] == 0: # 入度为0(没有先修课了)的课入队
heappush(queue, (-outDegree[i], i, -1)) # 出度越大(以这门课作为先修课的课越多),优先级越高
semesterCnt = 0
while queue:
semesterCnt += 1
nextSemesterCourses = [] # 存放这个学期不能上的课
courseCnt = 0
while courseCnt < k and queue: # 每个学期最多上 k 门课
priority, node, preFinishedSemester = heappop(queue)
if preFinishedSemester >= semesterCnt: # 当前学期不能上这门课
nextSemesterCourses.append((priority, node, preFinishedSemester))
continue
for child in children[node]: # 这门课可以学,学它,然后处理孩子课的入度
inDegree[child] -= 1
if inDegree[child] == 0: # 孩子课的先修课全上完了
heappush(queue, (-outDegree[child], child, semesterCnt))
courseCnt += 1
for item in nextSemesterCourses: # 把之前存起来的本学期不能上的课再重新入队
heappush(queue, item)
return semesterCnt
| 1,714 | 34 | 85 | py |
LeetCode-Python | LeetCode-Python-master/0070.爬楼梯/0070-爬楼梯.py | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2:
return [1, 2][n - 1]
first = 1
second = 2
cnt = 2
while cnt < n:
cnt += 1
cur = first + second
if cnt == n:
return cur
first = second
second = cur
| 413 | 20.789474 | 32 | py |
LeetCode-Python | LeetCode-Python-master/0070.爬楼梯/0070-爬楼梯 2.py | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2:
return [1, 2][n - 1]
first = 1
second = 2
cnt = 2
while cnt < n:
cnt += 1
cur = first + second
if cnt == n:
return cur
first = second
second = cur
| 413 | 20.789474 | 32 | py |
LeetCode-Python | LeetCode-Python-master/0040.组合总和II/0040-组合总和II.py | class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
def dfs(start, t, tmp):
if t == 0:
tmp.sort()
if tmp not in res:
res.append(tmp)
return
for i in range(start, len(candidates)):
x = candidates[i]
if t - x < 0:
break
dfs(i + 1, t - x, tmp + [x])
dfs(0, target, [])
return res | 675 | 26.04 | 51 | py |
LeetCode-Python | LeetCode-Python-master/1243.数组变换/1243-数组变换.py | class Solution(object):
def transformArray(self, arr):
"""
:type arr: List[int]
:rtype: List[int]
"""
flag = 1
while flag:
flag = 0
res = [num for num in arr]
for i in range(1, len(arr) - 1):
if arr[i - 1] < arr[i] and arr[i] > arr[i + 1]:
res[i] -= 1
flag = 1
elif arr[i - 1] > arr[i] and arr[i] < arr[i + 1]:
res[i] += 1
flag = 1
arr = res[:]
return res
| 588 | 28.45 | 65 | py |
LeetCode-Python | LeetCode-Python-master/1583.统计不开心的朋友/1583-统计不开心的朋友.py | class Solution(object):
def unhappyFriends(self, n, preferences, pairs):
"""
:type n: int
:type preferences: List[List[int]]
:type pairs: List[List[int]]
:rtype: int
"""
# 建立亲密度矩阵,prefer_degrees[i][j]即为 i 对 j 的亲密度
prefer_degrees = [[-n-1 for _ in range(n)] for _ in range(n)]
for i, preference in enumerate(preferences):
for degree, j in enumerate(preference):
prefer_degrees[i][j] = -degree
# 建立配对字典,给定x, ppl2friends[x]即为 x 分配的朋友
ppl2friends = dict()
for x, y in pairs:
ppl2friends[x] = y
ppl2friends[y] = x
def isUnhappy(x):
# 判定 x 是否快乐
y = ppl2friends[x]
for u in range(n):
v = ppl2friends[u]
if x != u and prefer_degrees[x][u] > prefer_degrees[x][y] and \
prefer_degrees[u][x] > prefer_degrees[u][v]:
return 1
return 0
return sum([isUnhappy(i) for i in range(n)]) | 1,057 | 32.0625 | 79 | py |
LeetCode-Python | LeetCode-Python-master/1381.设计一个支持增量操作的栈/1381-设计一个支持增量操作的栈.py | class CustomStack(object):
def __init__(self, maxSize):
"""
:type maxSize: int
"""
self.stack = []
self.maxSize = maxSize
def push(self, x):
"""
:type x: int
:rtype: None
"""
if len(self.stack) < self.maxSize:
self.stack.append(x)
def pop(self):
"""
:rtype: int
"""
return self.stack.pop() if self.stack else -1
def increment(self, k, val):
"""
:type k: int
:type val: int
:rtype: None
"""
for i in range(min(k, len(self.stack))):
self.stack[i] += val
# Your CustomStack object will be instantiated and called as such:
# obj = CustomStack(maxSize)
# obj.push(x)
# param_2 = obj.pop()
# obj.increment(k,val) | 812 | 20.394737 | 66 | py |
LeetCode-Python | LeetCode-Python-master/面试题 02.02.返回倒数第k个节点/面试题 02.02-返回倒数第k个节点.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def kthToLast(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: int
"""
slow, fast = head, head
while k:
k -= 1
fast = fast.next
while fast:
slow = slow.next
fast = fast.next
return slow.val | 506 | 22.045455 | 36 | py |
LeetCode-Python | LeetCode-Python-master/面试题 02.02.返回倒数第k个节点/面试题 02.02-返回倒数第k个节点 2.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def kthToLast(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: int
"""
slow, fast = head, head
while k:
k -= 1
fast = fast.next
while fast:
slow = slow.next
fast = fast.next
return slow.val | 506 | 22.045455 | 36 | py |
LeetCode-Python | LeetCode-Python-master/面试题17.04.消失的数字/面试题17.04-消失的数字.py | class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = set(nums)
for i in range(len(nums) + 1):
if i not in s:
return i | 245 | 23.6 | 38 | py |
LeetCode-Python | LeetCode-Python-master/1339.分裂二叉树的最大乘积/1339-分裂二叉树的最大乘积.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxProduct(self, root):
"""
:type root: TreeNode
:rtype: int
"""
dic = {}
def SumOfTree(node):
if not node:
return 0
ls, rs = SumOfTree(node.left), SumOfTree(node.right)
dic[node] = ls + rs + node.val
return dic[node]
SumOfTree(root)
TotalSum = dic[root]
self.res = 0
def dfs(node):
if not node:
return
tmp = (TotalSum - dic[node]) * dic[node]
self.res = max(self.res, tmp)
dfs(node.left)
dfs(node.right)
dfs(root)
return self.res % (10 ** 9 + 7) | 943 | 23.842105 | 64 | py |
LeetCode-Python | LeetCode-Python-master/0653.两数之和IV-输入BST/0653-两数之和IV-输入BST.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
values = set()
self.result = False
def inorderTraversal(node):
if not node:
return []
if not self.result:
if k - node.val in values:
self.result = True
return
values.add(node.val)
inorderTraversal(node.left)
inorderTraversal(node.right)
inorderTraversal(root)
return self.result
| 835 | 26.866667 | 55 | py |
LeetCode-Python | LeetCode-Python-master/1155.掷骰子的N种方法/1155-掷骰子的N种方法.py | class Solution(object):
def numRollsToTarget(self, d, f, target):
"""
:type d: int
:type f: int
:type target: int
:rtype: int
"""
record = dict()
def backtrack(dice, face, t):
if (dice, face, t) in record: #Ѿ֪ǰĽ
return record[(dice, face, t)] #ֱӶȡ
if dice == 0: #ûӵʱжһDzǸպҵtarget
return 1 if t == 0 else 0
if t < 0 or dice <= 0: #Чʱûн⣬Է0
return 0
tmp = 0 #tmpڼ¼ǰжٸ
for i in range(1, face + 1): #е
tmp += backtrack(dice - 1, face, t - i)
record[(dice, face, t)] = tmp #ѽԺ
return tmp
backtrack(d, f, target)
return max(record.values()) % (10 ** 9 + 7) #ĽĸĽ
| 868 | 28.965517 | 56 | py |
LeetCode-Python | LeetCode-Python-master/0069.x的平方根/0069-x的平方根.py | class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left, right = 1, x
while left <= right:
mid = (left + right) // 2
s = mid ** 2
if s == x:
return mid
elif s < x:
left = mid + 1
elif s > x:
right = mid - 1
return left - 1 | 417 | 23.588235 | 37 | py |
LeetCode-Python | LeetCode-Python-master/0069.x的平方根/0069-x的平方根 2.py | class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left, right = 1, x
while left <= right:
mid = (left + right) // 2
s = mid ** 2
if s == x:
return mid
elif s < x:
left = mid + 1
elif s > x:
right = mid - 1
return left - 1 | 417 | 23.588235 | 37 | py |
LeetCode-Python | LeetCode-Python-master/1469.寻找所有的独生节点/1469-寻找所有的独生节点 2.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getLonelyNodes(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.res = []
def dfs(node, siblings_cnt):
if not node:
return
if siblings_cnt == 1:
self.res.append(node.val)
siblings_cnt = 0
if node.left:
siblings_cnt += 1
if node.right:
siblings_cnt += 1
dfs(node.left, siblings_cnt)
dfs(node.right, siblings_cnt)
dfs(root, 0)
return self.res | 802 | 25.766667 | 55 | py |
LeetCode-Python | LeetCode-Python-master/1469.寻找所有的独生节点/1469-寻找所有的独生节点.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getLonelyNodes(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.res = []
def dfs(node, siblings_cnt):
if not node:
return
if siblings_cnt == 1:
self.res.append(node.val)
siblings_cnt = 0
if node.left:
siblings_cnt += 1
if node.right:
siblings_cnt += 1
dfs(node.left, siblings_cnt)
dfs(node.right, siblings_cnt)
dfs(root, 0)
return self.res | 802 | 25.766667 | 55 | py |
LeetCode-Python | LeetCode-Python-master/0897.递增顺序查找树/0897-递增顺序查找树.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return root
new_root = TreeNode(-1)
cur, stack = root, []
parent = None
while cur or stack:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
cur.left = None
if not parent:
parent = cur
new_root.right = parent
else:
parent.right = cur
parent = cur
cur = cur.right
return new_root.right
| 907 | 24.942857 | 44 | py |
LeetCode-Python | LeetCode-Python-master/1030.距离顺序排列矩阵单元格/1030-距离顺序排列矩阵单元格.py | class Solution(object):
def allCellsDistOrder(self, R, C, r0, c0):
"""
:type R: int
:type C: int
:type r0: int
:type c0: int
:rtype: List[List[int]]
"""
dx = [1, -1, 0, 0]
dy = [0, 0 , -1, 1]
res = [[r0, c0]]
queue = res[:]
visited = [[0 for i in range(101)] for j in range(101)]
visited[r0][c0] = 1
while(queue):
next_queue = list()
for node in queue:
x0, y0 = node[0], node[1]
for k in range(4):
x = x0 + dx[k]
y = y0 + dy[k]
# print x, y
if x < 0 or x >= R:
continue
if y < 0 or y >= C:
continue
if visited[x][y] == 1:
continue
# print visited
res.append([x,y])
visited[x][y] = 1
next_queue.append([x,y])
queue = next_queue[:]
# print queue, res
return res
| 1,207 | 28.463415 | 63 | py |
LeetCode-Python | LeetCode-Python-master/剑指 Offer II 052.展平二叉搜索树/剑指 Offer II 052-展平二叉搜索树.py | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
def inorder(node):
if not node:
return []
return inorder(node.left) + [node.val] + inorder(node.right)
inorder_list = inorder(root)
dummy = TreeNode(-1)
p = dummy
for val in inorder_list:
p.right = TreeNode(val)
p = p.right
return dummy.right
| 640 | 25.708333 | 72 | py |
LeetCode-Python | LeetCode-Python-master/1354.多次求和构造目标数组/1354-多次求和构造目标数组.py | class Solution(object):
def isPossible(self, target):
"""
:type target: List[int]
:rtype: bool
"""
from heapq import *
if len(target) == 1:
return target[0] == 1
s = sum(target)
target = [-item for item in target]
heapify(target)
while s > len(target):
# 找当前最大的数和第二大的数
m = -heappop(target)
s_m = -target[0]
# 更新 m 并更新 s
diff = s - m
if not diff:
break
new_m = m - (max(1, (m - s_m) / diff) * diff)
s = s - m + new_m
heappush(target, -new_m)
return not any([num != -1 for num in target]) | 743 | 24.655172 | 57 | py |
LeetCode-Python | LeetCode-Python-master/0161.相隔为1的编辑距离/0161-相隔为1的编辑距离.py | class Solution(object):
def isOneEditDistance(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
edit = 0 #༭
distance = len(s) - len(t)
if abs(distance) > 1: #ȶ˲ֹһλ϶
return False
if not s or not t:
return s != t
i, j = 0, 0
while i < len(s) and j < len(t):
if s[i] == t[j]: #༭
i += 1 #ָ붼˳һλ
j += 1
else:
if edit: #ΨһĻѾ
return False
if distance == 1: #ɾ
i += 1
elif distance == -1:#
j += 1
else: #滻
i += 1
j += 1
edit += 1
# print i, j, edit
if i < len(s):
return edit == 0
if j < len(t):
return edit == 0
return i == len(s) and j == len(t) and edit == 1
| 975 | 26.111111 | 56 | py |
LeetCode-Python | LeetCode-Python-master/0560.和为K的子数组/0560-和为K的子数组.py | class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# prefix[i] = sum(nums[:i])
# prefix[j] - prefix[i] = sum(nums[i:j])
from collections import defaultdict
prefix = [0 for _ in range(len(nums) + 1)]
for i, x in enumerate(nums):
prefix[i + 1] = prefix[i] + x
dic = defaultdict(int)
res = 0
for i, x in enumerate(prefix):
res += dic[x - k]
dic[x] += 1
return res | 612 | 25.652174 | 50 | py |
LeetCode-Python | LeetCode-Python-master/面试题 01.04.回文排列/面试题 01.04-回文排列.py | class Solution:
def canPermutePalindrome(self, s: str) -> bool:
from collections import Counter
odd = False
for char, freq in Counter(s).items():
if freq % 2:
if odd:
return False
odd = True
return True | 302 | 29.3 | 51 | py |
LeetCode-Python | LeetCode-Python-master/1536.排布二进制网格的最少交换次数/1536-排布二进制网格的最少交换次数.py | class Solution(object):
def minSwaps(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
dic = dict() # key 是每行的idx, val 是这一行末尾0的个数
n = len(grid)
for i, row in enumerate(grid): # 统计每一行末尾有几个0
cnt = 0
for j in range(n - 1, -1, -1):
if not row[j]:
cnt += 1
else:
break
dic[i] = cnt
res = 0
for i in range(n):
if dic[i] < n - i - 1: # 这一行0太少,需要放到下面去
for j in range(i + 1, n):
if dic[j] >= n - i - 1: # 找到0足够多的行
break
if dic[j] < n - i - 1: # 没找到说明无解
return -1
for k in range(j, i, -1): #把第i行换到第j行的位置上去
dic[k] = dic[k - 1]
res += j - i
return res | 906 | 28.258065 | 57 | py |
LeetCode-Python | LeetCode-Python-master/1013.将数组分成和相等的三个部分/1013-将数组分成和相等的三个部分.py | class Solution(object):
def canThreePartsEqualSum(self, A):
"""
:type A: List[int]
:rtype: bool
"""
# from collections import defaultdict
target = sum(A) // 3
snow = 0
cnt = 0
for i, x in enumerate(A):
snow += x
if target == snow:
snow = 0
cnt += 1
return cnt >= 3
| 405 | 22.882353 | 45 | py |
LeetCode-Python | LeetCode-Python-master/1008.先序遍历构造二叉树/1008-先序遍历构造二叉树.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def bstFromPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: TreeNode
"""
if not preorder:
return None
inorder = sorted(preorder)
idx = inorder.index(preorder[0])
root = TreeNode(preorder[0])
root.left = self.bstFromPreorder(preorder[1:idx + 1])
root.right = self.bstFromPreorder(preorder[idx + 1:])
return root | 626 | 27.5 | 61 | py |
LeetCode-Python | LeetCode-Python-master/0038.报数/0038-报数.py | class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
record = ["1"]
for i in range(1, n):
pre = record[i - 1]
idx = 0
tmp = ""
while idx < len(pre):
cnt = 1
while(idx + 1 < len(pre) and pre[idx] == pre[idx + 1]):
idx += 1
cnt += 1
tmp += str(cnt) + pre[idx]
idx += 1
record.append(tmp)
return record[-1] | 557 | 26.9 | 71 | py |
LeetCode-Python | LeetCode-Python-master/0049.字母异位词分组/0049-字母异位词分组.py | class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
record = dict()
for word in strs:
tmp = tuple(sorted(word))
# print tmp
if tmp in record:
record[tmp].append(word)
else:
record[tmp] = [word]
return [val for key, val in record.items()]
| 473 | 25.333333 | 51 | py |
LeetCode-Python | LeetCode-Python-master/0049.字母异位词分组/0049-字母异位词分组 2.py | class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
record = dict()
for word in strs:
tmp = tuple(sorted(word))
# print tmp
if tmp in record:
record[tmp].append(word)
else:
record[tmp] = [word]
return [val for key, val in record.items()]
| 473 | 25.333333 | 51 | py |
LeetCode-Python | LeetCode-Python-master/1169.查询无效交易/1169-查询无效交易.py | class Solution(object):
def invalidTransactions(self, transactions):
"""
:type transactions: List[str]
:rtype: List[str]
"""
recordByName = collections.defaultdict(list)
for trans in transactions:
name, time, amount, city = trans.split(",")
recordByName[name].append([name, int(time), int(amount), city])
def convert(l):
return l[0] + "," + str(l[1]) + "," + str(l[2]) + "," + l[3]
res = set()
for name, rec in recordByName.items():
curRec = sorted(rec, key = lambda x:x[1])
for i in range(len(curRec)):
if curRec[i][2] > 1000:
res.add(convert(curRec[i]))
for j in range(i + 1, len(curRec)):
if abs(curRec[j][1] - curRec[i][1]) > 60:
break
if curRec[j][3] != curRec[i][3]:
res.add(convert(curRec[i]))
res.add(convert(curRec[j]))
return res
| 1,169 | 35.5625 | 75 | py |
LeetCode-Python | LeetCode-Python-master/0263.丑数/0263-丑数.py | class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
while not num % 2:
num /= 2
while not num % 3:
num /= 3
while not num % 5:
num /= 5
return num == 1 | 333 | 21.266667 | 26 | py |
LeetCode-Python | LeetCode-Python-master/0784.字母大小写全排列/0784-字母大小写全排列.py | class Solution(object):
def letterCasePermutation(self, S):
l = len(S)
n = 2 ** l
res = list()
if l == 0:
res.append("")
for i in range(0, n):
temp = ""
for j in range(0, l):
if ((2 ** j) &i) == 0:
temp += S[j].lower()
else:
temp += S[j].upper()
if temp not in res:
res.append(temp)
return res
| 483 | 24.473684 | 40 | py |
LeetCode-Python | LeetCode-Python-master/0287.寻找重复数/0287-寻找重复数.py | class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
slow, fast = 0, 0
while 1:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
fast = 0
while nums[slow] != nums[fast]:
slow = nums[slow]
fast = nums[fast]
return nums[fast] | 453 | 27.375 | 47 | py |
LeetCode-Python | LeetCode-Python-master/1130.叶值的最小代价生成树/1130-叶值的最小代价生成树.py | class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
res = 0
stack = [16]
for num in arr:
while stack and stack[-1] < num:
res += stack.pop() * min(stack[-1], num)
stack.append(num)
while len(stack) > 2:
res += stack.pop() * stack[-1]
return res | 365 | 29.5 | 56 | py |
LeetCode-Python | LeetCode-Python-master/0639.解码方法2/0639-解码方法2.py | class Solution:
def numDecodings(self, s: str) -> int:
if not s or s[0] == "0":
return 0
dp = [0]*(len(s) + 1) # dp[i] represents ways of s[:i + 1]
if s[0] == "*":
dp[0] = 1
dp[1] = 9
else:
dp[0] = dp[1] = 1
MOD = 10 ** 9 + 7
for i in range(2, len(s) + 1):
if s[i - 1] == "*":
if s[i - 2] == "1":
dp[i] = dp[i - 2] * 9
elif s[i - 2] == "2":
dp[i] = dp[i - 2] * 6
elif s[i - 2] == "*":
dp[i] = dp[i - 2] * 15
dp[i] += 9 * dp[i - 1]
elif s[i - 1] == "0":
if s[i - 2] == "1" or s[i - 2] == "2":
dp[i] = dp[i - 2]
elif s[i - 2] == "*":
dp[i] = dp[i - 2] * 2
else:
return 0
else:
if s[i - 2] == "1" or (s[i - 2] == "2" and "1" <= s[i - 1] <= "6"):
dp[i] = dp[i - 2]
elif s[i - 2] == "*":
if "1" <= s[i - 1] <= "6":
dp[i] = dp[i - 2] * 2
else:
dp[i] = dp[i - 2]
dp[i] += dp[i - 1]
dp[i] = dp[i] % MOD
# print (dp, i)
return dp[-1] | 1,401 | 30.863636 | 83 | py |
LeetCode-Python | LeetCode-Python-master/1498.满足条件的子序列数目/1498-满足条件的子序列数目.py | class Solution(object):
def numSubseq(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
left, right = 0, len(nums) - 1
res = 0
MOD = 10 ** 9 + 7
while left <= right:
s = nums[left] + nums[right]
l = right - left
if s <= target:
res = (res + (1 << l)) % MOD
left += 1
else:
right -= 1
return res | 525 | 25.3 | 44 | py |
LeetCode-Python | LeetCode-Python-master/1103.分糖果II/1103-分糖果II.py | class Solution(object):
def distributeCandies(self, candies, num_people):
"""
:type candies: int
:type num_people: int
:rtype: List[int]
"""
res = [0 for _ in range(num_people)]
cnt = 1
while candies:
for i in range(num_people):
if candies >= cnt:
res[i] += cnt
candies -= cnt
cnt += 1
else:
res[i] += candies
candies = 0
break
return res | 582 | 28.15 | 53 | py |
LeetCode-Python | LeetCode-Python-master/1103.分糖果II/1103-分糖果II 2.py | class Solution(object):
def distributeCandies(self, candies, num_people):
"""
:type candies: int
:type num_people: int
:rtype: List[int]
"""
res = [0 for _ in range(num_people)]
cnt = 1
while candies:
for i in range(num_people):
if candies >= cnt:
res[i] += cnt
candies -= cnt
cnt += 1
else:
res[i] += candies
candies = 0
break
return res | 582 | 28.15 | 53 | py |
LeetCode-Python | LeetCode-Python-master/剑指 Offer II 004.只出现一次的数字/剑指 Offer II 004-只出现一次的数字.py | class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(lambda x, y: x ^ y, nums) | 115 | 37.666667 | 51 | py |
LeetCode-Python | LeetCode-Python-master/0463.岛屿的周长/0463-岛屿的周长.py | class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m = len(grid)
n = len(grid[0])
r = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
r += 4
if i < m-1 and grid[i+1][j] == 1:
r -= 2
if j < n-1 and grid[i][j+1] == 1:
r -= 2
return r | 509 | 27.333333 | 53 | py |
LeetCode-Python | LeetCode-Python-master/0856.括号的分数/0856-括号的分数.py | class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
# ()1 )))*2, )(+
s = ""
for i in range(len(S) - 1):
if S[i] == "(":
if S[i + 1] == "(":
s += "("
else:
s += "1"
else:
if S[i + 1] == "(":
s += "+"
else:
s += ")*2"
# print s
return eval(s) | 573 | 22.916667 | 36 | py |
LeetCode-Python | LeetCode-Python-master/2466.统计构造好字符串的方案数/2466-统计构造好字符串的方案数.py | class Solution:
def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
# f(i) = f(i - zero) + f(i - one)
# 00, 10, 11, 10, 0, 1
# self.res = 0
# MOD = int(1e9 + 7)
# memo = dict()
# def dfs(i):
# if i == 0:
# return 1
# count = 0
# if i in memo:
# return memo[i]
# if i >= zero:
# count += dfs(i - zero)
# if i >= one:
# count += dfs(i - one)
# # l represents count of distinct good string of length i
# if i >= low:
# self.res += count % MOD
# memo[i] = count
# return count
# dfs(high)
# return self.res % MOD
MOD = int(1e9 + 7)
dp = [0] * (high + max(zero, one))
dp[0] = 1
res = 0
for i in range(1, high + 1):
if i >= zero:
dp[i] += dp[i - zero]
if i >= one:
dp[i] += dp[i - one]
if i >= low:
res += dp[i] % MOD
return res % MOD | 1,142 | 30.75 | 80 | py |
LeetCode-Python | LeetCode-Python-master/0211.添加与搜索单词-数据结构设计/0211-添加与搜索单词-数据结构设计.py | class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.roots = {}
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: None
"""
print word
node = self.roots
for char in word:
node = node.setdefault(char, {})
node["end"] = True
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
self.res = False
self.searchHelper(self.roots, word)
return self.res
def searchHelper(self, dic, word):
if not word:
self.res |= "end" in dic
return
node = dic
i, char = 0, word[0]
if char == ".":#ȫƥ
for x in "abcedfghijklmnopqrstuvwxyz":
if x in node:
self.searchHelper(node[x], word[1:])
elif char in node:
self.searchHelper(node[char], word[1:])
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word) | 1,304 | 27.369565 | 125 | py |
LeetCode-Python | LeetCode-Python-master/1768.交替合并字符串/1768-交替合并字符串.py | class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
res = ""
for index, char1 in enumerate(word1):
res += char1
if index < len(word2):
res += word2[index]
if index < len(word2):
res += word2[index + 1:]
return res | 334 | 26.916667 | 62 | py |
LeetCode-Python | LeetCode-Python-master/1192.查找集群内的「关键连接」/1192-查找集群内的「关键连接」.py | from collections import defaultdict
class Solution(object):
def criticalConnections(self, n, connections):
"""
:type n: int
:type connections: List[List[int]]
:rtype: List[List[int]]
"""
visited = set()
low = [9999999] * n
discover = [999999] * n
parent = [-1] * n
graph = defaultdict(list)
self.time = 0
res = []
for u, v in connections:
graph[u].append(v)
graph[v].append(u)
def dfs(u):
visited.add(u)
discover[u] = self.time
low[u] = self.time
self.time += 1
for v in graph[u]:
if v not in visited:
parent[v] = u
dfs(v)
low[u] = min(low[u], low[v])
if low[v] > discover[u]:
res.append([u, v])
elif v != parent[u]:
low[u] = min(low[u], discover[v])
for i in range(n):
if i not in visited:
dfs(i)
return res
| 1,141 | 26.190476 | 53 | py |
LeetCode-Python | LeetCode-Python-master/1352.最后K个数的乘积/1352-最后K个数的乘积.py | class ProductOfNumbers(object):
def __init__(self):
self.prefix = [1]
def add(self, num):
"""
:type num: int
:rtype: None
"""
if num:
self.prefix.append(self.prefix[-1] * num)
else:
self.prefix = [1]
def getProduct(self, k):
"""
:type k: int
:rtype: int
"""
if k >= len(self.prefix):
return 0
return self.prefix[-1] / self.prefix[-k - 1] | 492 | 20.434783 | 53 | py |
LeetCode-Python | LeetCode-Python-master/0389.找不同/0389-找不同.py | class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
# return chr(sum(ord(i) for i in list(t)) - sum(ord(j) for j in list(s)))
# res = 0
# for i in s:
# res ^= ord(i) - 97
# for i in t:
# res ^= ord(i) - 97
# return chr(res + 97)
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if s.count(char) != t.count(char):
return char | 570 | 24.954545 | 81 | py |
LeetCode-Python | LeetCode-Python-master/0295.数据流的中位数/0295-数据流的中位数.py | from heapq import *
# class Heaps(object):
# def __init__(self):
# self.min_heap = []
# self.max_heap = []
# def __
class MedianFinder(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.min_heap = []
self.max_heap = []
heapify(self.min_heap)
heapify(self.max_heap)
def addNum(self, num):
"""
:type num: int
:rtype: None
"""
heappush(self.min_heap, num)
heappush(self.max_heap, -heappop(self.min_heap))
if len(self.max_heap) > len(self.min_heap):
heappush(self.min_heap, -heappop(self.max_heap))
def findMedian(self):
"""
:rtype: float
"""
l_min_heap = len(self.min_heap)
l_max_heap = len(self.max_heap)
if l_min_heap == l_max_heap:
return (self.min_heap[0] - self.max_heap[0]) /2.
else:
return self.min_heap[0]/1.
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian() | 1,164 | 23.787234 | 67 | py |
LeetCode-Python | LeetCode-Python-master/0298.二叉树最长连续序列/0298-二叉树最长连续序列.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left and not root.right:
return 1
self.res = 1
def dfs(node, tmp, parent_val):
if not node:
return
if node.val == parent_val + 1:
tmp += 1
self.res = max(self.res, tmp)
else:
tmp = 1
dfs(node.left, tmp, node.val)
dfs(node.right, tmp, node.val)
dfs(root.left, 1, root.val)
dfs(root.right, 1, root.val)
return self.res
| 924 | 24.694444 | 45 | py |
LeetCode-Python | LeetCode-Python-master/0994.腐烂的橘子/0994-腐烂的橘子.py | class Solution(object):
def orangesRotting(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
from collections import deque
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
queue = deque()
for i in range(m):
for j in range(n):
if grid[i][j] == 2:
queue.append((i, j))
res = 0
while queue:
for i in range(len(queue)):
pair = queue.popleft()
x0, y0 = pair[0], pair[1]
for k in range(4):
x = x0 + dx[k]
y = y0 + dy[k]
if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:
grid[x][y] = 2
queue.append((x, y))
if not queue:
break
res += 1
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
return -1
return res
| 1,179 | 26.44186 | 69 | py |
LeetCode-Python | LeetCode-Python-master/0027.移除元素/0027-移除元素 2.py | class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
nums.sort()
for i, num in enumerate(nums):
if num == val:
j = i + 1
while(j < len(nums) and nums[j] == num):
j += 1
t = j
while(j < len(nums)):
nums[i] = nums[j]
i += 1
j += 1
return i
| 571 | 26.238095 | 56 | py |
LeetCode-Python | LeetCode-Python-master/0027.移除元素/0027-移除元素.py | class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
nums.sort()
for i, num in enumerate(nums):
if num == val:
j = i + 1
while(j < len(nums) and nums[j] == num):
j += 1
t = j
while(j < len(nums)):
nums[i] = nums[j]
i += 1
j += 1
return i
| 571 | 26.238095 | 56 | py |
LeetCode-Python | LeetCode-Python-master/1237.找出给定方程的正整数解/1237-找出给定方程的正整数解.py | """
This is the custom function interface.
You should not implement it, or speculate about its implementation
class CustomFunction:
# Returns f(x, y) for any given positive integers x and y.
# Note that f(x, y) is increasing with respect to both x and y.
# i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
def f(self, x, y):
"""
class Solution:
def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:
res = []
for x in range(1, 1001):
left, right = 1, 1001
while left <= right:
mid = (left + right)// 2
if customfunction.f(x, mid) == z:
res.append([x, mid])
break
elif customfunction.f(x, mid) < z:
left = mid + 1
else:
right = mid - 1
return res
| 918 | 33.037037 | 92 | py |
LeetCode-Python | LeetCode-Python-master/面试题27.二叉树的镜像/面试题27-二叉树的镜像.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mirrorTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return root
root.left, root.right = self.mirrorTree(root.right), self.mirrorTree(root.left)
return root | 460 | 23.263158 | 87 | py |
LeetCode-Python | LeetCode-Python-master/0140.单词拆分II/0140-单词拆分II.py | class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
def helper(s, memo):
if s in memo:
return memo[s]
if not s:
return []
res = []
for word in wordDict:
if not s.startswith(word):
continue
if len(word) == len(s):
res.append(word)
else:
resultOfTheRest = helper(s[len(word):], memo)
for item in resultOfTheRest:
item = word + ' ' + item
res.append(item)
memo[s] = res
return res
return helper(s, {}) | 732 | 32.318182 | 66 | py |
LeetCode-Python | LeetCode-Python-master/0646.最长数对链/0646-最长数对链.py | class Solution(object):
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
pairs = sorted(pairs, key = lambda x: x[1])
end = pairs[0][0] - 1
res = 0
for pair in pairs:
if pair[0] > end:
res += 1
end = pair[1]
return res | 390 | 23.4375 | 51 | py |
LeetCode-Python | LeetCode-Python-master/0973.最接近原点的K个点/0973-最接近原点的K个点.py | class Solution(object):
def kClosest(self, points, K):
"""
:type points: List[List[int]]
:type K: int
:rtype: List[List[int]]
"""
return sorted(points, key = lambda x:x[0] **2 + x[1] ** 2)[:K]
| 253 | 27.222222 | 70 | py |
LeetCode-Python | LeetCode-Python-master/0973.最接近原点的K个点/0973-最接近原点的K个点 2.py | class Solution(object):
def kClosest(self, points, K):
"""
:type points: List[List[int]]
:type K: int
:rtype: List[List[int]]
"""
return sorted(points, key = lambda x:x[0] **2 + x[1] ** 2)[:K]
| 253 | 27.222222 | 70 | py |
LeetCode-Python | LeetCode-Python-master/2130.链表最大孪生和/2130-链表最大孪生和.py | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
p, l = head, 0
while p:
l += 1
p = p.next
stack = []
cur = 0
p = head
while cur < l // 2:
cur += 1
stack.append(p.val)
p = p.next
res = 0
while cur < l:
cur += 1
res = max(res, p.val + stack.pop())
p = p.next
return res | 620 | 22.884615 | 55 | py |
LeetCode-Python | LeetCode-Python-master/面试题 04.02.最小高度树/面试题 04.02-最小高度树.py | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid], self.sortedArrayToBST(nums[:mid]), self.sortedArrayToBST(nums[mid + 1:]))
return root | 442 | 30.642857 | 108 | py |
LeetCode-Python | LeetCode-Python-master/1282.用户分组/1282-用户分组.py | class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
from collections import defaultdict
size2people = defaultdict(list)
for i, size in enumerate(groupSizes):
size2people[size].append(i)
res = []
for size, peoples in size2people.items():
for i in range(0, len(peoples), size):
res.append(peoples[i: i + size])
return res | 445 | 33.307692 | 71 | py |
LeetCode-Python | LeetCode-Python-master/1104.分糖果II/1104-分糖果II.py | class Solution(object):
def distributeCandies(self, candies, n):
"""
:type candies: int
:type num_people: int
:rtype: List[int]
"""
res = [0 for _ in range(n)]
multi = 0
while candies > 0:
for i in range(len(res)):
distri = i + 1 + multi * n
if candies > distri:
res[i] += distri
candies -= distri
else:
res[i] += candies
candies = 0
break
multi += 1
return res | 609 | 28.047619 | 44 | py |
LeetCode-Python | LeetCode-Python-master/0788.旋转数字/0788-旋转数字.py | class Solution(object):
def rotatedDigits(self, N):
"""
:type N: int
:rtype: int
"""
valid = [2, 5, 6, 9]
same = [0, 1, 8]
res = 0
for i in range(1, N + 1):
t = i
flag = 1
while(t):
temp = t % 10
if temp not in same:
flag = 0
break
t /= 10
if flag:
continue
t = i
flag = 1
while(t):
temp = t % 10
if temp not in valid and temp not in same:
flag = 0
break
t /= 10
if flag:
# print i
res += 1
return res | 838 | 22.971429 | 58 | py |
LeetCode-Python | LeetCode-Python-master/面试题 02.04.分割链表/面试题 02.04-分割链表.py | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
dummy1, dummy2 = ListNode(-1), ListNode(-2)
smaller, larger = dummy1, dummy2
p = head
while p:
if p.val < x:
smaller.next = ListNode(p.val)
smaller = smaller.next
else:
larger.next = ListNode(p.val)
larger = larger.next
p = p.next
smaller.next = dummy2.next
return dummy1.next | 647 | 26 | 60 | py |
LeetCode-Python | LeetCode-Python-master/0173.二叉搜索树迭代器/0173-二叉搜索树迭代器.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.cur = root
def next(self):
"""
@return the next smallest number
:rtype: int
"""
while self.cur or self.stack:
if self.cur:
self.stack.append(self.cur)
self.cur = self.cur.left
else:
self.cur = self.stack.pop()
res = self.cur.val
self.cur = self.cur.right
return res
def hasNext(self):
"""
@return whether we have a next smallest number
:rtype: bool
"""
return self.cur or self.stack
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext() | 1,077 | 22.955556 | 66 | py |
LeetCode-Python | LeetCode-Python-master/面试题55-I.二叉树的深度/面试题55-I-二叉树的深度.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) | 415 | 25 | 75 | py |
LeetCode-Python | LeetCode-Python-master/0938.二叉搜索树的范围和/0938-二叉搜索树的范围和 2.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
res = 0
if not root:
return 0
if L <= root.val <= R:
res += root.val
if root.val < R:
res += self.rangeSumBST(root.right, L, R)
if root.val > L:
res += self.rangeSumBST(root.left, L, R)
return res
| 680 | 23.321429 | 53 | py |
LeetCode-Python | LeetCode-Python-master/0938.二叉搜索树的范围和/0938-二叉搜索树的范围和.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
res = 0
if not root:
return 0
if L <= root.val <= R:
res += root.val
if root.val < R:
res += self.rangeSumBST(root.right, L, R)
if root.val > L:
res += self.rangeSumBST(root.left, L, R)
return res
| 680 | 23.321429 | 53 | py |
LeetCode-Python | LeetCode-Python-master/面试题01.08.零矩阵/面试题01.08-零矩阵.py | class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
if not matrix or not matrix[0]:
return matrix
m, n = len(matrix), len(matrix[0])
row0, col0 = set(), set()
for i in range(m):
for j in range(n):
if not matrix[i][j]:
row0.add(i)
col0.add(j)
for i in range(m):
for j in range(n):
if i in row0 or j in col0:
matrix[i][j] = 0
return matrix | 663 | 25.56 | 76 | py |
LeetCode-Python | LeetCode-Python-master/0739.每日温度/0739-每日温度.py | class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
res = [0] * len(T)
s = []
# print res
for i in range(0, len(T)):
while(s and T[i] > T[s[-1]]):
res[s[-1]] = i - s[-1]
s.pop()
s.append(i)
return res | 393 | 25.266667 | 41 | py |
LeetCode-Python | LeetCode-Python-master/剑指 Offer 52.两个链表的第一个公共节点/剑指 Offer 52-两个链表的第一个公共节点.py | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:
return None
pa, pb = headA, headB
while pa != pb:
if pa:
pa = pa.next
else:
pa = headB
if pb:
pb = pb.next
else:
pb = headA
return pa | 549 | 24 | 80 | py |
LeetCode-Python | LeetCode-Python-master/0237.删除链表中的节点/0237-删除链表中的节点 2.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
| 403 | 25.933333 | 74 | py |
LeetCode-Python | LeetCode-Python-master/0237.删除链表中的节点/0237-删除链表中的节点.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
| 403 | 25.933333 | 74 | py |
LeetCode-Python | LeetCode-Python-master/0617.合并二叉树/0617-合并二叉树 2.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if not t1:
return t2
if not t2:
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1
| 572 | 23.913043 | 54 | py |
LeetCode-Python | LeetCode-Python-master/0617.合并二叉树/0617-合并二叉树.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if not t1:
return t2
if not t2:
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1
| 572 | 23.913043 | 54 | py |
LeetCode-Python | LeetCode-Python-master/0986.区间列表的交集/0986-区间列表的交集.py | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def intervalIntersection(self, A, B):
"""
:type A: List[Interval]
:type B: List[Interval]
:rtype: List[Interval]
"""
i, j = 0, 0
res = list()
while(i < len(A) and j < len(B)):
start = max(A[i][0], B[j][0])
end = min(A[i][1], B[j][1])
if start <= end:
res.append([start, end])
if A[i][1] < B[j][1]:
i += 1
else:
j += 1
return res
# la,lb = A[-1][1], B[-1][1]
# dica, dicb = dict(), dict()
# for i in A:
# for j in range(i[0],i[1] + 1):
# dica[j] = 1
# for i in B:
# for j in range(i[0], i[1] + 1):
# dicb[j] = 1
# res = list()
# i = 0
# while(i <= max(la, lb)):
# print dica.get(i, 0), dicb.get(i, 0)
# if dica.get(i,0) and dicb.get(i,0):#صʼ
# start = i
# while(dica.get(i,0) and dicb.get(i, 0)): #ûп䣬ǵؿ˵
# i +=1
# res.append([start, i - 1])
# i += 1
# return res
| 1,680 | 22.027397 | 66 | py |
LeetCode-Python | LeetCode-Python-master/0760.找出变位映射/0760-找出变位映射.py | class Solution(object):
def anagramMappings(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
dic = dict()
for i, x in enumerate(B):
dic[x] = i
return [dic[x] for x in A] | 287 | 21.153846 | 36 | py |
LeetCode-Python | LeetCode-Python-master/剑指 Offer II 049.从根节点到叶节点的路径数字之和/剑指 Offer II 049-从根节点到叶节点的路径数字之和.py | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
self.res = False
self.res = 0
def dfs(node, path_sum):
if not node:
return
path_sum = path_sum * 10 + node.val
if not node.left and not node.right:
self.res += path_sum
dfs(node.left, path_sum)
dfs(node.right, path_sum)
dfs(root, 0)
return self.res | 661 | 27.782609 | 55 | py |
LeetCode-Python | LeetCode-Python-master/0156.上下翻转二叉树/0156-上下翻转二叉树.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def upsideDownBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root or (not root.left and not root.right):
return root
newroot = self.upsideDownBinaryTree(root.left)
right = root.right
root.left.left = right
root.left.right = root
root.left = None
root.right = None
return newroot
| 642 | 24.72 | 58 | py |
LeetCode-Python | LeetCode-Python-master/0043.字符串相乘/0043-字符串相乘.py | class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if num1 == "0" or num2 == "0": #
return "0"
l1, l2 = len(num1), len(num2)
if l1 < l2:
num1, num2 = num2, num1 #num1ʼձnum2
l1, l2 = l2, l1
num2 = num2[::-1]
res = "0"
for i, digit in enumerate(num2):
tmp = self.StringMultiplyDigit(num1, int(digit)) + "0" * i #num1num2ĵǰλij˻
res = self.StringPlusString(res, tmp) #restmpĺ
return res
def StringMultiplyDigit(self,string, n):
#Ĺǣһַһij˻ַ
#Ϊ "123", 3 "369"
s = string[::-1]
res = []
for i, char in enumerate(s):
num = int(char)
res.append(num * n)
res = self.CarrySolver(res)
res = res[::-1]
return "".join(str(x) for x in res)
def CarrySolver(self, nums):
#Ĺǣеÿһλýλ
#[15, 27, 12], [5, 8, 4, 1]
i = 0
while i < len(nums):
if nums[i] >= 10:
carrier = nums[i] // 10
if i == len(nums) - 1:
nums.append(carrier)
else:
nums[i + 1] += carrier
nums[i] %= 10
i += 1
return nums
def StringPlusString(self, s1, s2):
#Ĺǣַĺ
#Ϊ123 456, Ϊ"579"
l1, l2 = len(s1), len(s2)
if l1 < l2:
s1, s2 = s2, s1
l1, l2 = l2, l1
s1 = [int(x) for x in s1]
s2 = [int(x) for x in s2]
s1, s2 = s1[::-1], s2[::-1]
for i, digit in enumerate(s2):
s1[i] += s2[i]
s1 = self.CarrySolver(s1)
s1 = s1[::-1]
return "".join(str(x) for x in s1)
| 1,940 | 25.958333 | 85 | py |
LeetCode-Python | LeetCode-Python-master/0824.山羊拉丁文/0824-山羊拉丁文.py | class Solution(object):
def toGoatLatin(self, S):
"""
:type S: str
:rtype: str
"""
vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
res = []
T = S.split(" ")
for index, word in enumerate(T):
temp = word
if word[0] in vowel:
temp += "ma"
else:
temp = temp[1:] + temp[0] + "ma"
temp += "a" * (index + 1)
res.append(temp)
return " ".join(item for item in res) | 580 | 26.666667 | 66 | py |