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/0214.最短回文串/0214-最短回文串.py | class Solution(object):
def shortestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
reversedS = s[::-1]
# print reversedS
i = 0
for i in range(len(s)):
# print reversedS[i:], s[:len(s) - i]
if reversedS[i:] == s[:len(s) - i]:
return reversedS[:i] + s
return "" | 382 | 26.357143 | 49 | py |
LeetCode-Python | LeetCode-Python-master/1436.旅行终点站/1436-旅行终点站 2.py | class Solution(object):
def destCity(self, paths):
"""
:type paths: List[List[str]]
:rtype: str
"""
return (set(pair[1] for pair in paths) - set(pair[0] for pair in paths)).pop() | 222 | 30.857143 | 86 | py |
LeetCode-Python | LeetCode-Python-master/1436.旅行终点站/1436-旅行终点站.py | class Solution(object):
def destCity(self, paths):
"""
:type paths: List[List[str]]
:rtype: str
"""
return (set(pair[1] for pair in paths) - set(pair[0] for pair in paths)).pop() | 222 | 30.857143 | 86 | py |
LeetCode-Python | LeetCode-Python-master/2336.无限集中的最小数字/2336-无限集中的最小数字.py | from heapq import *
class SmallestInfiniteSet:
def __init__(self):
self.min_heap = [i for i in range(1, 1001)]
heapify(self.min_heap)
self.set = set(self.min_heap)
def popSmallest(self) -> int:
val = heappop(self.min_heap)
self.set.remove(val)
return val
def addBack(self, num: int) -> None:
if num not in self.set:
heappush(self.min_heap, num)
self.set.add(num)
# Your SmallestInfiniteSet object will be instantiated and called as such:
# obj = SmallestInfiniteSet()
# param_1 = obj.popSmallest()
# obj.addBack(num) | 613 | 25.695652 | 74 | py |
LeetCode-Python | LeetCode-Python-master/2161.根据给定数字划分数组/2161-根据给定数字划分数组.py | class Solution:
def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
small, equal, larger = [], 0, []
for num in nums:
if num < pivot:
small.append(num)
elif num == pivot:
equal += 1
else:
larger.append(num)
return small + equal * [pivot] + larger | 380 | 28.307692 | 67 | py |
LeetCode-Python | LeetCode-Python-master/0268.缺失数字/0268-缺失数字.py | class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = set(nums)
for num in range(len(nums)):
if num not in s:
return num
return len(nums) | 272 | 23.818182 | 36 | py |
LeetCode-Python | LeetCode-Python-master/0961.重复N次的元素/0961-重复N次的元素.py | class Solution(object):
def repeatedNTimes(self, A):
"""
:type A: List[int]
:rtype: int
"""
half_l = len(A) / 2
temp = sorted(A)
return temp[half_l] if temp[half_l] == temp[half_l + 1] else temp[half_l - 1]
| 275 | 26.6 | 85 | py |
LeetCode-Python | LeetCode-Python-master/1431.拥有最多糖果的孩子/1431-拥有最多糖果的孩子.py | class Solution(object):
def kidsWithCandies(self, candies, extraCandies):
"""
:type candies: List[int]
:type extraCandies: int
:rtype: List[bool]
"""
maxCandies = max(candies)
return [curCandies + extraCandies >= maxCandies for curCandies in candies] | 322 | 34.888889 | 82 | py |
LeetCode-Python | LeetCode-Python-master/0147.对链表进行插入排序/0147-对链表进行插入排序.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
dummy = ListNode(-9999999999)
dummy.next = head
p = head
while p:
while p and p.next and p.val < p.next.val:
p = p.next
if not p.next:
break
cur = p.next
tail = cur.next
p.next = tail
cur.next = None
tmp = dummy
while tmp and tmp.next and tmp.next.val < cur.val:
tmp = tmp.next
tmp2 = tmp.next
tmp.next = cur
cur.next = tmp2
# self.printList(dummy.next)
return dummy.next
def printList(self, head):
res = []
while head:
res.append(head.val)
head = head.next
print res | 1,184 | 24.212766 | 62 | py |
LeetCode-Python | LeetCode-Python-master/0438.找到字符串中所有字母异位词/0438-找到字符串中所有字母异位词.py | class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
res = list()
ls, lp = len(s), len(p)
if lp > ls:
return list()
lo, hi = 0, lp - 1
s1 = [0 for _ in range(26)]
s2 = [0 for _ in range(26)]
for i in range(lp):
s2[ord(p[i]) - 97] += 1
for i in range(lp - 1):
s1[ord(s[i]) - 97] += 1
for i in range(ls - lp + 1):
s1[ord(s[i + lp - 1]) - 97] += 1
if s1 == s2:
res.append(i)
s1[ord(s[i]) - 97] -= 1
return res | 772 | 22.424242 | 44 | py |
LeetCode-Python | LeetCode-Python-master/1614.括号的最大嵌套深度/1614-括号的最大嵌套深度 2.py | class Solution(object):
def maxDepth(self, s):
"""
:type s: str
:rtype: int
"""
depth = 0
res = 0
for ch in s:
if ch == "(":
depth += 1
res = max(res, depth)
elif ch == ")":
depth -= 1
return res | 336 | 20.0625 | 37 | py |
LeetCode-Python | LeetCode-Python-master/1614.括号的最大嵌套深度/1614-括号的最大嵌套深度.py | class Solution(object):
def maxDepth(self, s):
"""
:type s: str
:rtype: int
"""
depth = 0
res = 0
for ch in s:
if ch == "(":
depth += 1
res = max(res, depth)
elif ch == ")":
depth -= 1
return res | 336 | 20.0625 | 37 | py |
LeetCode-Python | LeetCode-Python-master/0213.打家劫舍II/0213-打家劫舍II.py | class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
return max(self.rob2(nums[1:]), self.rob2(nums[:-1]))
def rob2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# return 0
if not nums:
return 0
dp = [0 for _ in nums]
dp[0] = nums[0]
for i in range(1, len(nums)):
if i == 1:
dp[i] = max(dp[0], nums[i])
else:
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
return dp[-1] | 665 | 24.615385 | 61 | py |
LeetCode-Python | LeetCode-Python-master/0213.打家劫舍II/0213-打家劫舍II 2.py | class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
return max(self.rob2(nums[1:]), self.rob2(nums[:-1]))
def rob2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# return 0
if not nums:
return 0
dp = [0 for _ in nums]
dp[0] = nums[0]
for i in range(1, len(nums)):
if i == 1:
dp[i] = max(dp[0], nums[i])
else:
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
return dp[-1] | 665 | 24.615385 | 61 | py |
LeetCode-Python | LeetCode-Python-master/1165.单行键盘/1165-单行键盘.py | class Solution(object):
def calculateTime(self, keyboard, word):
"""
:type keyboard: str
:type word: str
:rtype: int
"""
dic = dict()
for i, char in enumerate(keyboard):
dic[char] = i
res, cur_pos = 0, 0
for char in word:
res += abs(dic[char] - cur_pos)
cur_pos = dic[char]
return res
| 429 | 24.294118 | 44 | py |
LeetCode-Python | LeetCode-Python-master/1165.单行键盘/1165-单行键盘 2.py | class Solution(object):
def calculateTime(self, keyboard, word):
"""
:type keyboard: str
:type word: str
:rtype: int
"""
dic = dict()
for i, char in enumerate(keyboard):
dic[char] = i
res, cur_pos = 0, 0
for char in word:
res += abs(dic[char] - cur_pos)
cur_pos = dic[char]
return res
| 429 | 24.294118 | 44 | py |
LeetCode-Python | LeetCode-Python-master/1136.平行课程/1136-平行课程.py | class Solution(object):
def minimumSemesters(self, N, relations):
"""
:type N: int
:type relations: List[List[int]]
:rtype: int
"""
indegree = [0 for i in range(N + 1)]
adj = [set() for _ in range(N + 1)]
for pre, cur in relations:
indegree[cur] += 1 #统计入度
adj[pre].add(cur) #统计邻居节点
from collections import deque
queue = deque()
for i, x in enumerate(indegree):
if x == 0 and i > 0: #将入度为0的节点入队
queue.append(i)
semester_cnt= 0
finished_course = 0
while queue:
next_queue = deque()
semester_cnt += 1 #新的学期来了
for cur in queue:
finished_course += 1 #又一门课学完了
for neighbor in adj[cur]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
next_queue.append(neighbor) #下个学期可以学neighbor这门课了
queue = next_queue
return semester_cnt if finished_course == N else -1 #如果所有的课都学完了,那么finished_course == N | 1,133 | 33.363636 | 94 | py |
LeetCode-Python | LeetCode-Python-master/0647.回文子串/0647-回文子串.py | class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
self.res = 0
def extend(left, right):
for i in range(len(s)):
while(left >= 0 and right < len(s) and s[left] == s[right]):
self.res += 1
left -= 1
right += 1
for i in range(len(s)):
extend(i, i)
extend(i, i+1)
return self.res
| 544 | 24.952381 | 76 | py |
LeetCode-Python | LeetCode-Python-master/0299.猜数字游戏/0299-猜数字游戏.py | class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
from collections import Counter
dic_s = Counter(secret)
dic_g = Counter(guess)
a, b = 0, 0
for i in range(len(secret)):
if secret[i] == guess[i]:
a += 1
dic_s[secret[i]] -= 1
dic_g[secret[i]] -= 1
for i in dic_s & dic_g:
b += min(dic_s[i], dic_g[i])
return "{}A{}B".format(a, b) | 602 | 26.409091 | 40 | py |
LeetCode-Python | LeetCode-Python-master/0701.二叉搜索树中的插入操作/0701-二叉搜索树中的插入操作.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 insertIntoBST(self, root, val):
if not root:
return TreeNode(val)
node, parent = root, root
while node:
parent = node
node = parent.left if val < parent.val else parent.right
if val > parent.val:
parent.right = TreeNode(val)
else:
parent.left = TreeNode(val)
return root
# class Solution(object):
# def insertIntoBST(self, root, val):
# """
# :type root: TreeNode
# :type val: int
# :rtype: TreeNode
# """
# if not root:
# return TreeNode(val)
# if root.val > val:
# root.left = self.insertIntoBST(root.left, val)
# else:
# root.right = self.insertIntoBST(root.right, val)
# return root | 1,008 | 29.575758 | 68 | py |
LeetCode-Python | LeetCode-Python-master/0241.为运算表达式设计优先级/0241-为运算表达式设计优先级.py | class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
self.record = collections.defaultdict(list)
self.work(input)
return self.record[input]
def work(self, input):
if not input:
return []
if input in self.record:
return self.record[input]
if input.isdigit():
self.record[input] = [int(input)]
return self.record[input]
res = []
for i in range(len(input)):
if input[i] in "+-*":
left = self.diffWaysToCompute(input[:i])
right = self.diffWaysToCompute(input[i + 1:])
for l in left:
for r in right:
if input[i] == "+":
res.append(l + r)
elif input[i] == "-":
res.append(l - r)
else:
res.append(l * r)
self.record[input] = res
return self.record[input] | 1,192 | 29.589744 | 61 | py |
LeetCode-Python | LeetCode-Python-master/0292.Nim游戏/0292-Nim游戏 2.py | class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 != 0 | 143 | 19.571429 | 27 | py |
LeetCode-Python | LeetCode-Python-master/0292.Nim游戏/0292-Nim游戏.py | class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 != 0 | 143 | 19.571429 | 27 | py |
LeetCode-Python | LeetCode-Python-master/1027.最长等差数列/1027-最长等差数列.py | class Solution(object):
def longestArithSeqLength(self, A):
"""
:type A: List[int]
:rtype: int
"""
#dp[i][d]ʾ±iβΪdеij
res = 1
l = len(A)
dp = [[1] * 20001 for j in range(l)]
for i in range(1, len(A)):
for j in range(i - 1, -1, -1):
d = A[i] - A[j]
d += 10001
dp[i][d] = max(dp[i][d], dp[j][d] + 1)
res = max(res, dp[i][d])
return res
# class Solution(object):
# def longestArithSeqLength(self, A):
# """
# :type A: List[int]
# :rtype: int
# """
# def helper(A):
# dp = [[1] * 20000 for i in range(len(A))]
# ans = 1
# for i in range(1, len(A)):
# for j in range(i-1, -1, -1):
# diff = A[i]-A[j]
# diff += 10000
# dp[i][diff] = max(dp[i][diff], dp[j][diff] + 1)
# ans = max(ans, dp[i][diff])
# return ans
# return helper(A) | 1,103 | 29.666667 | 69 | py |
LeetCode-Python | LeetCode-Python-master/2278.字母在字符串中的百分比/2278-字母在字符串中的百分比.py | class Solution:
def percentageLetter(self, s: str, letter: str) -> int:
return 100 * s.count(letter) // len(s) | 122 | 40 | 59 | py |
LeetCode-Python | LeetCode-Python-master/1558.得到目标数组的最少函数调用次数/1558-得到目标数组的最少函数调用次数.py | class Solution(object):
def minOperations(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = 0
for num in nums:
res += bin(num).count("1")
res += len(bin(max(nums))[2:]) - 1
return res | 275 | 22 | 42 | py |
LeetCode-Python | LeetCode-Python-master/剑指 Offer II 036.后缀表达式/剑指 Offer II 036-后缀表达式.py | import math
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
num_stack = []
res = 0
for token in tokens:
# print(num_stack)
if token[-1].isdigit():
num_stack.append(int(token))
else:
second, first = num_stack.pop(), num_stack.pop()
if token == "+":
num_stack.append(first + second)
elif token == "-":
num_stack.append(first - second)
elif token == "*":
num_stack.append(first * second)
elif token == "/":
num_stack.append(int(first / second))
return num_stack[0] | 728 | 32.136364 | 64 | py |
LeetCode-Python | LeetCode-Python-master/2482.行和列中一和零的差值/2482-行和列中一和零的差值.py | class Solution:
def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]:
m, n = len(grid), len(grid[0])
row2one = {}
col2one = {}
for i, row in enumerate(grid):
row2one[i] = sum(row)
for j, col in enumerate(zip(*grid)):
col2one[j] = sum(col)
diff = [[0 for i in range(n)] for j in range(m)]
for i in range(m):
for j in range(n):
diff[i][j] = row2one[i] + col2one[j] - (n - row2one[i]) - (m - col2one[j])
return diff | 547 | 35.533333 | 90 | py |
LeetCode-Python | LeetCode-Python-master/面试题 16.01.交换数字/面试题 16.01-交换数字.py | class Solution:
def swapNumbers(self, numbers: List[int]) -> List[int]:
return [numbers[1], numbers[0]] | 115 | 37.666667 | 59 | py |
LeetCode-Python | LeetCode-Python-master/0104.二叉树的最大深度/0104-二叉树的最大深度.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/2357.使数组中所有元素都等于零/2357-使数组中所有元素都等于零.py | class Solution:
def minimumOperations(self, nums: List[int]) -> int:
res = 0
while sum(nums):
res += 1
m = 101
for num in nums:
if num:
m = min(m, num)
for i, num in enumerate(nums):
if num:
nums[i] -= m
return res | 362 | 26.923077 | 56 | py |
LeetCode-Python | LeetCode-Python-master/1537.最大得分/1537-最大得分.py | class Solution(object):
def maxSum(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
dups = set(nums1) & set(nums2)
s1 = self.getFragmentedSum(nums1, dups)
s2 = self.getFragmentedSum(nums2, dups)
res = 0
for sum1, sum2 in zip(s1, s2):
res += max(sum1, sum2)
return res % (10 ** 9 + 7)
def getFragmentedSum(self, nums, dups):
l = []
s = 0
for num in nums:
s += num
if num in dups:
l.append(s)
s = 0
l.append(s)
return l | 663 | 23.592593 | 47 | py |
LeetCode-Python | LeetCode-Python-master/0728.自除数/0728-自除数.py | class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
res = list()
for i in range(left, right + 1):
flag = True
n = i
while(n):
num = n % 10
n //= 10
if not num or i % num != 0:
flag = False
break
if flag:
res.append(i)
return res | 593 | 23.75 | 47 | py |
LeetCode-Python | LeetCode-Python-master/0361.轰炸敌人/0361-轰炸敌人.py | class Solution(object):
def maxKilledEnemies(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
res = 0
def count(x0, y0):
cnt = 0
for x in range(x0, -1, -1): #
if grid[x][y0] == "E":
cnt += 1
elif grid[x][y0] == "W":
break
for x in range(x0, m): #
if grid[x][y0] == "E":
cnt += 1
elif grid[x][y0] == "W":
break
for y in range(y0, -1, -1): #
if grid[x0][y] == "E":
cnt += 1
elif grid[x0][y] == "W":
break
for y in range(y0, n): #
if grid[x0][y] == "E":
cnt += 1
elif grid[x0][y] == "W":
break
return cnt
for i in range(m):
for j in range(n):
if grid[i][j] == "0":
res = max(res, count(i, j))
return res | 1,292 | 29.069767 | 47 | py |
LeetCode-Python | LeetCode-Python-master/0852.山脉数组的峰顶索引/0852-山脉数组的峰顶索引 2.py | class Solution(object):
def peakIndexInMountainArray(self, A):
"""
:type A: List[int]
:rtype: int
"""
left = 0
right = len(A) - 1
while( left <= right):
mid = left + (right - left) / 2
if A[mid - 1] < A[mid] < A[mid + 1]:
left = mid + 1
elif A[mid - 1] > A[mid] > A[mid + 1]:
right = mid -1
else:
break
print mid
return mid | 495 | 26.555556 | 50 | py |
LeetCode-Python | LeetCode-Python-master/0852.山脉数组的峰顶索引/0852-山脉数组的峰顶索引.py | class Solution(object):
def peakIndexInMountainArray(self, A):
"""
:type A: List[int]
:rtype: int
"""
left = 0
right = len(A) - 1
while( left <= right):
mid = left + (right - left) / 2
if A[mid - 1] < A[mid] < A[mid + 1]:
left = mid + 1
elif A[mid - 1] > A[mid] > A[mid + 1]:
right = mid -1
else:
break
print mid
return mid | 495 | 26.555556 | 50 | py |
LeetCode-Python | LeetCode-Python-master/1409.查询带键的排列/1409-查询带键的排列.py | class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
P = [i for i in range(1, m + 1)]
res = []
for query in queries:
index = P.index(query)
res.append(index)
P = [P[index]] + P[:index] + P[index + 1:]
return res | 313 | 33.888889 | 70 | py |
LeetCode-Python | LeetCode-Python-master/0430.扁平化多级双向链表/0430-扁平化多级双向链表.py | """
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution(object):
def flatten(self, head):
"""
:type head: Node
:rtype: Node
"""
if not head:
return head
def helper(node):
# 返回的是最后一个节点
if not node:
return
while node:
nxt = node.next # 备份 next
if not nxt:
tail = node # 记录 tail,用于返回
if node.child:
node.next = node.child # 把child 变成next
node.next.prev = node
t = helper(node.child) # 递归处理,t 是处理之后的 原来的child 的最后一个节点
node.child = None # 把child 置空
if nxt: # 如果有next 部分,就让next的prev指向 原来的child 处理之后的最后一个节点
nxt.prev = t
t.next = nxt # 让 t.next 指向原来的 next
node = node.next
return tail
helper(head)
return head | 1,135 | 28.894737 | 75 | py |
LeetCode-Python | LeetCode-Python-master/0436.寻找右区间/0436-寻找右区间.py | class Solution(object):
def findRightInterval(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[int]
"""
dic = {}
for i, (start, end) in enumerate(intervals):
dic[start] = i
res = [-1 for _ in range(len(intervals))]
l = [interval[0] for interval in intervals]
l = sorted(l, key = lambda x:x)
for i, (start, end) in enumerate(intervals):
idx = bisect.bisect_left(l, end)
if idx < len(l):
res[i] = dic[l[idx]]
return res
| 626 | 26.26087 | 52 | py |
LeetCode-Python | LeetCode-Python-master/0841.钥匙和房间/0841-钥匙和房间.py | class Solution(object):
def canVisitAllRooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
n = len(rooms)
key = [0 for i in range(0, n)]
key[0] = 1
queue = [0]
while(queue):
newqueue = list()
for i in queue:
for k in rooms[i]:
if key[k] == 0:
key[k] = 1
newqueue.append(k)
queue = newqueue[:]
return sum(key) == n
| 566 | 24.772727 | 42 | py |
LeetCode-Python | LeetCode-Python-master/1499.满足不等式的最大值/1499-满足不等式的最大值.py | class Solution(object):
def findMaxValueOfEquation(self, points, k):
"""
:type points: List[List[int]]
:type k: int
:rtype: int
"""
from collections import deque
queue = deque([(points[0][0], points[0][0] - points[0][1])])
res = float("-inf")
for yi, yj in points[1:]:
while queue and queue[0][0] < yi - k:
queue.popleft()
if queue:
res = max(res, -queue[0][1] + yi + yj)
sub = yi - yj
while queue and queue[-1][1] > sub:
queue.pop()
queue.append((yi, sub))
return res | 660 | 32.05 | 68 | py |
LeetCode-Python | LeetCode-Python-master/面试题16.17.连续数列/面试题16.17-连续数列.py | class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0 for _ in nums]
for i, x in enumerate(nums):
dp[i] = max(x, dp[i - 1] + x) if i else x
return max(dp) | 275 | 26.6 | 53 | py |
LeetCode-Python | LeetCode-Python-master/1171.从链表中删去总和值为零的连续节点/1171-从链表中删去总和值为零的连续节点.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeZeroSumSublists(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(-1)
dummy.next = head
record = {0:dummy}
pre_sum = 0
while head:
pre_sum += head.val
if pre_sum in record:
record[pre_sum].next = head.next
else:
record[pre_sum] = head
head = head.next
return dummy.next | 654 | 24.192308 | 48 | py |
LeetCode-Python | LeetCode-Python-master/0786.第K个最小的素数分数/0786-第K个最小的素数分数.py | class Solution:
def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:
res = []
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
res.append((arr[i], arr[j], arr[i] * 1.0 / arr[j]))
res.sort(key = lambda x: x[2])
return [res[k - 1][0], res[k - 1][1]] | 343 | 33.4 | 76 | py |
LeetCode-Python | LeetCode-Python-master/0341.扁平化嵌套列表迭代器/0341-扁平化嵌套列表迭代器.py | # """
# 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 True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class NestedIterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
if nestedList:
self.stack = nestedList[::-1]
else:
self.stack = []
def next(self):
"""
:rtype: int
"""
return self.stack.pop()
def hasNext(self):
"""
:rtype: bool
"""
if self.stack:
top = self.stack.pop()
while not top.isInteger():
self.stack += top.getList()[::-1]
if self.stack:
top = self.stack.pop()
else:
return False
self.stack.append(top)
return True
else:
return False
| 1,658 | 26.65 | 95 | py |
LeetCode-Python | LeetCode-Python-master/0231.2的幂/0231-2的幂.py | class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and not (n & (n - 1)) | 163 | 22.428571 | 42 | py |
LeetCode-Python | LeetCode-Python-master/0231.2的幂/0231-2的幂 2.py | class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and not (n & (n - 1)) | 163 | 22.428571 | 42 | py |
LeetCode-Python | LeetCode-Python-master/0284.顶端迭代器/0284-顶端迭代器.py | # Below is the interface for Iterator, which is already defined for you.
#
# class Iterator(object):
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self):
# """
# Returns true if the iteration has more elements.
# :rtype: bool
# """
#
# def next(self):
# """
# Returns the next element in the iteration.
# :rtype: int
# """
class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.l = []
while iterator.hasNext():
self.l.append(iterator.next())
# self.l = iterator
self.index = 0
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self.l[self.index]
def next(self):
"""
:rtype: int
"""
self.index += 1
return self.l[self.index - 1]
def hasNext(self):
"""
:rtype: bool
"""
return self.index < len(self.l)
# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
# val = iter.peek() # Get the next element but not advance the iterator.
# iter.next() # Should return the same value as [val]. | 1,550 | 25.288136 | 81 | py |
LeetCode-Python | LeetCode-Python-master/0203.移除链表元素/0203-移除链表元素.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if not head:
return head
dummy = ListNode(-1)
dummy.next = head
pre, cur = dummy, head
while cur:
if cur.val == val: #Ҫɾ
pre.next = cur.next
cur.next = None
cur = pre.next
else:
pre = pre.next
cur = cur.next
return dummy.next | 707 | 24.285714 | 40 | py |
LeetCode-Python | LeetCode-Python-master/1021.删除最外层的括号/1021-删除最外层的括号 2.py | class Solution(object):
def removeOuterParentheses(self, S):
"""
:type S: str
:rtype: str
"""
s = list()
l,r = 0, 0
res = ""
for i, x in enumerate(S):
if x == "(":
s.append(x)
l += 1
elif x == ")":
r += 1
if l == r:
print s[1:]
res += "".join(s[1:]) #s[0]x= ")"պù"()"ԲҪǾͺ
s = list()
else:
s.append(x)
return res
| 610 | 24.458333 | 70 | py |
LeetCode-Python | LeetCode-Python-master/1021.删除最外层的括号/1021-删除最外层的括号.py | class Solution(object):
def removeOuterParentheses(self, S):
"""
:type S: str
:rtype: str
"""
s = list()
l,r = 0, 0
res = ""
for i, x in enumerate(S):
if x == "(":
s.append(x)
l += 1
elif x == ")":
r += 1
if l == r:
print s[1:]
res += "".join(s[1:]) #s[0]x= ")"պù"()"ԲҪǾͺ
s = list()
else:
s.append(x)
return res
| 610 | 24.458333 | 70 | py |
LeetCode-Python | LeetCode-Python-master/1584.连接所有点的最小费用/1584-连接所有点的最小费用.py |
class UnionFindSet(object):
def __init__(self, n):
# m, n = len(grid), len(grid[0])
self.roots = [i for i in range(n + 1)]
self.rank = [0 for i in range(n + 1)]
self.count = n
def find(self, member):
tmp = []
while member != self.roots[member]:
tmp.append(member)
member = self.roots[member]
for root in tmp:
self.roots[root] = member
return member
def union(self, p, q):
parentP = self.find(p)
parentQ = self.find(q)
if parentP != parentQ:
if self.rank[parentP] > self.rank[parentQ]:
self.roots[parentQ] = parentP
elif self.rank[parentP] < self.rank[parentQ]:
self.roots[parentP] = parentQ
else:
self.roots[parentQ] = parentP
self.rank[parentP] -= 1
self.count -= 1
class Solution(object):
def minCostConnectPoints(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
from heapq import *
queue = []
res = 0
n = len(points)
for i in range(n):
for j in range(i + 1, n):
d = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])
heappush(queue, (d, i, j))
ufs = UnionFindSet(n)
while ufs.count > 1:
d, i, j = heappop(queue)
if ufs.find(i) != ufs.find(j):
res += d
ufs.union(i, j)
return res | 1,585 | 28.37037 | 87 | py |
LeetCode-Python | LeetCode-Python-master/2235.两整数相加/2235-两整数相加.py | class Solution:
def sum(self, num1: int, num2: int) -> int:
return num1 + num2 | 90 | 29.333333 | 47 | py |
LeetCode-Python | LeetCode-Python-master/1646.获取生成数组中的最大值/1646-获取生成数组中的最大值.py | class Solution(object):
def getMaximumGenerated(self, n):
"""
:type n: int
:rtype: int
"""
nums = [0, 1]
for i in range(2, n + 1):
if i % 2 == 0:
nums.append(nums[i // 2])
else:
nums.append(nums[i // 2] + nums[i // 2 + 1])
# print nums
return max(nums) if n else 0 | 388 | 26.785714 | 60 | py |
LeetCode-Python | LeetCode-Python-master/0232.用栈实现队列/0232-用栈实现队列.py | class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack1 = []
self.stack2 = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
self.stack1.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if not self.stack2:
while self.stack1:
tmp = self.stack1.pop()
self.stack2.append(tmp)
res = self.stack2.pop()
return res
def peek(self):
"""
Get the front element.
:rtype: int
"""
# print self.stack1, self.stack2
if not self.stack2:
while self.stack1:
tmp = self.stack1.pop()
self.stack2.append(tmp)
return self.stack2[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return not self.stack1 and not self.stack2
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty() | 1,305 | 22.745455 | 76 | py |
LeetCode-Python | LeetCode-Python-master/0785.判断二分图/0785-判断二分图.py | class Solution(object):
def isBipartite(self, graph):
"""
:type graph: List[List[int]]
:rtype: bool
"""
dic = {}
self.res = True
def dfs(node):
if not self.res:
return
for child in graph[node]:
# print node, child
if child in dic:
if dic[child] == dic[node]:
# print child, node, graph, dic
self.res = False
return
else:
dic[child] = not dic[node]
dfs(child)
for node in range(len(graph)):
if node not in dic:
dic[node] = True
dfs(node)
return self.res
| 848 | 27.3 | 55 | py |
LeetCode-Python | LeetCode-Python-master/1249.移除无效的括号/1249-移除无效的括号.py | class Solution(object):
def minRemoveToMakeValid(self, s):
"""
:type s: str
:rtype: str
"""
left, right = 0, 0
stack = []
remove = set()
for i, ch in enumerate(s):
if ch == "(":
stack.append(i)
elif ch == ")":
if stack:
stack.pop()
else:
remove.add(i)
stack = set(stack)
res = ""
for i, ch in enumerate(s):
if i not in stack and i not in remove:
res += ch
return res | 614 | 25.73913 | 50 | py |
LeetCode-Python | LeetCode-Python-master/0326.3的幂/0326-3的幂.py | class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
t = 1
while t < n:
t *= 3
return n == t | 198 | 18.9 | 32 | py |
LeetCode-Python | LeetCode-Python-master/0082.删除排序链表中的重复元素II/0082-删除排序链表中的重复元素II 2.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
newhead = ListNode(-1)
newhead.next = head
if head.val != head.next.val:
head.next = self.deleteDuplicates(head.next)
else:
p = head
while p and p.val == head.val:
p = p.next
newhead.next = self.deleteDuplicates(p)
return newhead.next
| 739 | 25.428571 | 56 | py |
LeetCode-Python | LeetCode-Python-master/0082.删除排序链表中的重复元素II/0082-删除排序链表中的重复元素II.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
newhead = ListNode(-1)
newhead.next = head
if head.val != head.next.val:
head.next = self.deleteDuplicates(head.next)
else:
p = head
while p and p.val == head.val:
p = p.next
newhead.next = self.deleteDuplicates(p)
return newhead.next
| 739 | 25.428571 | 56 | py |
LeetCode-Python | LeetCode-Python-master/2562.找出数组的串联值/2562-找出数组的串联值.py | class Solution:
def findTheArrayConcVal(self, nums: List[int]) -> int:
res = 0
while nums:
if len(nums) > 1:
serial = int(str(nums[0]) + str(nums[-1]))
else:
serial = nums[0]
res += serial
nums = nums[1:-1]
return res | 325 | 28.636364 | 58 | py |
LeetCode-Python | LeetCode-Python-master/1351.统计有序矩阵中的负数/1351-统计有序矩阵中的负数 2.py | class Solution(object):
def countNegatives(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] < 0:
res += 1
return res | 401 | 24.125 | 38 | py |
LeetCode-Python | LeetCode-Python-master/1351.统计有序矩阵中的负数/1351-统计有序矩阵中的负数.py | class Solution(object):
def countNegatives(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] < 0:
res += 1
return res | 401 | 24.125 | 38 | py |
LeetCode-Python | LeetCode-Python-master/0677.键值映射/0677-键值映射.py | class MapSum(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = {}
def insert(self, key, val):
"""
:type key: str
:type val: int
:rtype: None
"""
self.data[key] = val
def sum(self, prefix):
"""
:type prefix: str
:rtype: int
"""
res = 0
for key, val in self.data.items():
if key.startswith(prefix):
res += val
return res
# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix) | 690 | 19.323529 | 61 | py |
LeetCode-Python | LeetCode-Python-master/1474.删除链表M个节点之后的N个节点/1474-删除链表M个节点之后的N个节点.py | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteNodes(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if not head:
return head
p = head
tm = m - 1
while tm and p:
tm -= 1
p = p.next
if p:
pp = p.next
tn = n
while tn and pp:
tn -= 1
pp = pp.next
p.next = self.deleteNodes(pp, m, n)
return head | 706 | 22.566667 | 47 | py |
LeetCode-Python | LeetCode-Python-master/1342.将数字变成0的操作次数/1342-将数字变成0的操作次数.py | class Solution(object):
def numberOfSteps (self, num):
"""
:type num: int
:rtype: int
"""
cnt = 0
while num:
if num % 2:
num -= 1
else:
num >>= 1
cnt += 1
return cnt | 294 | 20.071429 | 34 | py |
LeetCode-Python | LeetCode-Python-master/0294.翻转游戏II/0294-翻转游戏II.py | class Solution(object):
def canWin(self, string):
"""
:type s: str
:rtype: bool
"""
record = {}
def helper(s):
if s in record:
return record[s]
for i in range(len(s) - 1):
if s[i:i + 2] == "++":
next_s = s[:i] + "--" + s[i + 2:]
if not helper(next_s):
record[next_s] = False
return True
return False # ++
return helper(string) | 551 | 28.052632 | 53 | py |
LeetCode-Python | LeetCode-Python-master/1269.停在原地的方案数/1269-停在原地的方案数.py | class Solution(object):
def numWays(self, steps, arrLen):
"""
:type steps: int
:type arrLen: int
:rtype: int
"""
# dp[i][j] 代表走 i 步,到位置 j 的解
# dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] + dp[i - 1][j + 1]
n = min(steps, arrLen)
dp = [[0 for _ in range(n)] for _ in range(steps + 1)]
mod = 10 ** 9 + 7
dp[0][0] = 1
for i in range(1, steps + 1):
for j in range(n):
if j == 0:
dp[i][j] += (dp[i - 1][0] + dp[i - 1][1]) % mod
elif j == n - 1:
dp[i][j] += (dp[i - 1][j] + dp[i - 1][j - 1]) % mod
else:
dp[i][j] += (dp[i - 1][j - 1] + dp[i - 1][j] + dp[i - 1][j + 1]) % mod
return dp[steps][0] | 850 | 36 | 116 | py |
LeetCode-Python | LeetCode-Python-master/1334.阈值距离内邻居最少的城市/1334-阈值距离内邻居最少的城市.py | class Solution(object):
def findTheCity(self, n, edges, distanceThreshold):
"""
:type n: int
:type edges: List[List[int]]
:type distanceThreshold: int
:rtype: int
"""
distance = [[float("inf") for j in range(n)] for i in range(n)]
for start, end, w in edges:
distance[start][end] = w
distance[end][start] = w
for i in range(n):
distance[i][i] = 0
for i in range(n):
for j in range(n):
for k in range(n):
distance[j][k] = min(distance[j][k], distance[j][i] + distance[i][k])
min_cnt = 101
res = None
for i in range(n):
cnt = 0
for j in range(n):
if distance[i][j] <= distanceThreshold:
cnt += 1
if cnt <= min_cnt:
res = i
min_cnt = cnt
return res
| 974 | 28.545455 | 90 | py |
LeetCode-Python | LeetCode-Python-master/0312.戳气球/0312-戳气球.py | class Solution(object):
def maxCoins(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
nums = [1] + nums + [1]
n = len(nums)
dp = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n-2, -1, -1):
for j in range(i+1, n):
for k in range(i+1, j):
dp[i][j] = max(dp[i][j], dp[i][k] + nums[i]*nums[k]*nums[j] + dp[k][j])
return dp[0][-1] | 522 | 28.055556 | 91 | py |
LeetCode-Python | LeetCode-Python-master/1221.分割平衡字符串/1221-分割平衡字符串.py | class Solution(object):
def balancedStringSplit(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
# print s
l, r = 0, 0
for i in range(len(s)):
if s[i] == "R":
r += 1
else:
l += 1
# print r, l
if l == r:
return 1 + self.balancedStringSplit(s[i + 1:])
return 0 | 477 | 21.761905 | 62 | py |
LeetCode-Python | LeetCode-Python-master/1221.分割平衡字符串/1221-分割平衡字符串 2.py | class Solution(object):
def balancedStringSplit(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
# print s
l, r = 0, 0
for i in range(len(s)):
if s[i] == "R":
r += 1
else:
l += 1
# print r, l
if l == r:
return 1 + self.balancedStringSplit(s[i + 1:])
return 0 | 477 | 21.761905 | 62 | py |
LeetCode-Python | LeetCode-Python-master/1688.比赛中的配对次数/1688-比赛中的配对次数.py | class Solution:
def numberOfMatches(self, n: int) -> int:
res = 0
while n != 1:
if n % 2:
res += (n - 1) // 2
n = (n - 1) // 2 + 1
else:
res += n // 2
n = n // 2
return res | 288 | 25.272727 | 45 | py |
LeetCode-Python | LeetCode-Python-master/0059.螺旋矩阵II/0059-螺旋矩阵II.py | class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
i, j = 0, 0
state = "right"
cnt = 0
res = [[0 for _ in range(n)] for _ in range(n)]
while(cnt < n * n):
cnt += 1
res[i][j] = cnt
if state == "right":
j += 1
if j == n or res[i][j] != 0:
i += 1
j -= 1
state = "down"
elif state == "down":
i += 1
if i == n or res[i][j] != 0:
i -= 1
j -= 1
state = "left"
elif state == "left":
j -= 1
if j == -1 or res[i][j] != 0:
j += 1
i -= 1
state = "up"
elif state == "up":
i -= 1
if i == -1 or res[i][j] != 0:
i += 1
j += 1
state = "right"
return res | 1,107 | 28.157895 | 55 | py |
LeetCode-Python | LeetCode-Python-master/1967.作为子字符串出现在单词中的字符串数目/1967-作为子字符串出现在单词中的字符串数目.py | class Solution:
def numOfStrings(self, patterns: List[str], word: str) -> int:
res = 0
for pattern in patterns:
if pattern in word:
res += 1
return res | 209 | 22.333333 | 66 | py |
LeetCode-Python | LeetCode-Python-master/1486.数组异或操作/1486-数组异或操作.py | class Solution(object):
def xorOperation(self, n, start):
"""
:type n: int
:type start: int
:rtype: int
"""
res = start
for i in range(1, n):
res ^= start + 2 * i
return res | 255 | 22.272727 | 37 | py |
LeetCode-Python | LeetCode-Python-master/2181.合并零之间的节点/2181-合并零之间的节点.py | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(-1)
p_new = dummy
p = head
cur_sum = 0
while p:
if p.val == 0:
if cur_sum:
node = ListNode(cur_sum)
p_new.next = node
p_new = p_new.next
cur_sum = 0
else:
cur_sum += p.val
p = p.next
return dummy.next | 652 | 26.208333 | 73 | py |
LeetCode-Python | LeetCode-Python-master/1147.段式回文/1147-段式回文.py | class Solution(object):
def longestDecomposition(self, text):
"""
:type text: str
:rtype: int
"""
# print text
for i in range(1, len(text)):
if text[:i] == text[len(text) - i:]:
return 2 + self.longestDecomposition(text[i:len(text) - i])
return 1 if text else 0 | 349 | 30.818182 | 75 | py |
LeetCode-Python | LeetCode-Python-master/1669.合并两个链表/1669-合并两个链表.py | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
dummy = ListNode(-1)
dummy.next = list1
prev, cur = dummy, list1
left, right = None, None
count = 0
while cur:
if count == a:
left = prev
if count == b:
right = cur.next
count += 1
prev, cur = cur, cur.next
left.next = list2
p = list2
while p and p.next:
p = p.next
p.next = right
return dummy.next | 751 | 25.857143 | 91 | py |
LeetCode-Python | LeetCode-Python-master/0260.只出现一次的数字III/0260-只出现一次的数字III.py | class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
a, b = 0, 0
mask = 0
for num in nums:
mask ^= num
mask = mask & (-mask)
for num in nums:
if mask & num:
a ^= num
else:
b ^= num
return [a, b] | 404 | 21.5 | 33 | py |
LeetCode-Python | LeetCode-Python-master/1582.二进制矩阵中的特殊位置/1582-二进制矩阵中的特殊位置.py | class Solution(object):
def numSpecial(self, mat):
"""
:type mat: List[List[int]]
:rtype: int
"""
# 找出所有满足条件的行和列
possible_rows = [i for i, row in enumerate(mat) if sum(row) == 1]
possible_cols = [i for i, col in enumerate(zip(*mat)) if sum(col) == 1]
# 在满足条件的行和列里统计值为1的点
return sum([mat[i][j] for i in possible_rows for j in possible_cols]) | 425 | 34.5 | 79 | py |
LeetCode-Python | LeetCode-Python-master/0164.最大间距/0164-最大间距.py | class Solution(object):
def maximumGap(self, nums):
if len(nums) < 2:
return 0
min_val, max_val = min(nums), max(nums)
if min_val == max_val:
return 0
n = len(nums) + 1 # Ͱĸ
step = (max_val - min_val) // n
exist = [0 for _ in range(n + 1)] #ʾͰǷΪ
max_num = [0 for _ in range(n + 1)]#ʾͰԪصֵ
min_num = [0 for _ in range(n + 1)]#ʾͰԪصСֵ
for num in nums: #еͰ
idx = self.findBucketIndex(num, min_val, max_val, n)
max_num[idx] = num if not exist[idx] else max(num, max_num[idx])
min_num[idx] = num if not exist[idx] else min(num, min_num[idx])
exist[idx] = 1
res = 0
pre = max_num[0]
for i in range(1, n + 1):
if exist[i]:
res = max(res, min_num[i] - pre)
pre = max_num[i]
return res
def findBucketIndex(self, num, min_val, max_val, n):
return int((num - min_val) * n / (max_val - min_val))
| 1,088 | 34.129032 | 76 | py |
LeetCode-Python | LeetCode-Python-master/2451.差值数组不同的字符串/2451-差值数组不同的字符串.py | class Solution:
def oddString(self, words: List[str]) -> str:
l = []
for word in words:
diff = []
for i, char in enumerate(word):
if i:
diff.append(ord(char) - ord(word[i - 1]))
l.append(diff)
# print(l)
if l[0] != l[1] and l[0] != l[2]:
return words[0]
for i, diff in enumerate(l):
if diff != l[0]:
return words[i] | 481 | 27.352941 | 61 | py |
LeetCode-Python | LeetCode-Python-master/0441.排列硬币/0441-排列硬币.py | class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
import math
# 1 +2 + 3 + ... + k = (k + 1) * k / 2 < n
return (-1 + int(math.sqrt(1 + 8 * n))) // 2 | 243 | 26.111111 | 52 | py |
LeetCode-Python | LeetCode-Python-master/0009.回文数/0009-回文数.py | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
#2019.6.1
xx = x
if x < 0:
return False
reverse = 0
while x > 0:
x, tmp = divmod(x, 10)
reverse = reverse * 10 + tmp
return reverse == xx | 344 | 19.294118 | 40 | py |
LeetCode-Python | LeetCode-Python-master/0009.回文数/0009-回文数 2.py | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
#2019.6.1
xx = x
if x < 0:
return False
reverse = 0
while x > 0:
x, tmp = divmod(x, 10)
reverse = reverse * 10 + tmp
return reverse == xx | 344 | 19.294118 | 40 | py |
LeetCode-Python | LeetCode-Python-master/面试题 08.02.迷路的机器人/面试题 08.02-迷路的机器人.py | from collections import deque
class Solution:
def pathWithObstacles(self, obstacleGrid: List[List[int]]) -> List[List[int]]:
if not obstacleGrid or not obstacleGrid[0] or obstacleGrid[0][0] == 1:
return []
m, n = len(obstacleGrid), len(obstacleGrid[0])
if obstacleGrid[m -1][n - 1] == 1:
return []
self.res = []
# dfs
visited = set([(0, 0)])
def dfs(i, j, path):
if not 0 <= i < m or not 0 <= j < n:
return
path.append([i, j])
if i == m - 1 and j == n - 1:
self.res = path[:]
return
if not self.res:
if i + 1 < m and obstacleGrid[i + 1][j] != 1 and (i + 1, j) not in visited:
visited.add((i + 1, j))
dfs(i + 1, j, path[:])
if j + 1 < n and obstacleGrid[i][j + 1] != 1 and (i, j + 1) not in visited:
visited.add((i, j + 1))
dfs(i, j + 1, path[:])
dfs(0, 0, [])
return self.res
| 1,107 | 35.933333 | 91 | py |
LeetCode-Python | LeetCode-Python-master/2586.统计范围内的元音字符串数/2586-统计范围内的元音字符串数.py | class Solution:
def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
vowelStringCount = [0 for _ in words]
VOWELS = set("aeiou")
for i in range(len(words)):
if words[i][0] in VOWELS and words[i][-1] in VOWELS:
vowelStringCount[i] = vowelStringCount[i - 1] + 1
else:
vowelStringCount[i] = vowelStringCount[i - 1]
res = []
for l, r in queries:
if l:
res.append(vowelStringCount[r] - vowelStringCount[l - 1])
else:
res.append(vowelStringCount[r])
return res
| 648 | 35.055556 | 84 | py |
LeetCode-Python | LeetCode-Python-master/0057.插入区间/0057-插入区间.py | class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
intervals.append(newInterval)
return self.merge(intervals)
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if not intervals:
return intervals
intervals = sorted(intervals, key = lambda x: x[0])
start, end = intervals[0][0], intervals[0][1]
res = []
for i, interval in enumerate(intervals):
if interval[0] > end:
res.append([start, end])
start, end = interval[0], interval[1]
else:
end = max(end, interval[1])
res.append([start, end])
return res | 894 | 30.964286 | 59 | py |
LeetCode-Python | LeetCode-Python-master/1119.删去字符串中的元音/1119-删去字符串中的元音 2.py | class Solution(object):
def removeVowels(self, S):
"""
:type S: str
:rtype: str
"""
return "".join(char for char in S if char not in "aeiou") | 194 | 23.375 | 65 | py |
LeetCode-Python | LeetCode-Python-master/1119.删去字符串中的元音/1119-删去字符串中的元音.py | class Solution(object):
def removeVowels(self, S):
"""
:type S: str
:rtype: str
"""
return "".join(char for char in S if char not in "aeiou") | 194 | 23.375 | 65 | py |
LeetCode-Python | LeetCode-Python-master/1874.两个数组的最小乘积和/1874-两个数组的最小乘积和.py | class Solution:
def minProductSum(self, nums1: List[int], nums2: List[int]) -> int:
nums1.sort()
nums2.sort()
# print(nums1, nums2[::-1])
res = 0
for i in range(len(nums1)):
res += nums1[i] * nums2[-(i + 1)]
return res | 283 | 27.4 | 71 | py |
LeetCode-Python | LeetCode-Python-master/LCP 67.装饰树/LCP 67-装饰树.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 expandBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(node):
if not node:
return node
left, right = node.left, node.right
if left:
node.left = TreeNode(-1, left)
if right:
node.right = TreeNode(-1, None, right)
dfs(left)
dfs(right)
return node
return dfs(root)
| 669 | 24.769231 | 79 | py |
LeetCode-Python | LeetCode-Python-master/0551.学生出勤记录I/0551-学生出勤记录I.py | class Solution(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
return s.count("A") <= 1 and "LLL" not in s | 171 | 23.571429 | 51 | py |
LeetCode-Python | LeetCode-Python-master/0103.二叉树的锯齿形层次遍历/0103-二叉树的锯齿形层次遍历.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 zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
reverse = 0
queue = [root]
res = []
while queue:
next_queue = []
layer = []
for node in queue:
if node:
layer.append(node.val)
next_queue += [node.left, node.right]
queue = next_queue[:]
if layer:
if not reverse:
res.append(layer[:])
else:
res.append(layer[::-1])
reverse = 1 - reverse
return res | 858 | 26.709677 | 57 | py |
LeetCode-Python | LeetCode-Python-master/1196.最多可以买到的苹果数量/1196-最多可以买到的苹果数量.py | class Solution(object):
def maxNumberOfApples(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
arr.sort()
s = 0
for i, num in enumerate(arr):
if s + num > 5000:
return i
s += num
return len(arr) | 306 | 22.615385 | 37 | py |
LeetCode-Python | LeetCode-Python-master/0013.罗马数字转整数/0013-罗马数字转整数.py | class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dic = {"I":1, "V": 5, "X":10, "L":50, "C":100, "D":500, "M":1000}
res = 0
pre_value = None
for ch in s:
if (ch in ["V", "X"] and pre_value == 1) or \
(ch in ["L", "C"] and pre_value == 10) or \
(ch in ["D", "M"] and pre_value == 100):
res += dic[ch] - 2 * pre_value
else:
res += dic[ch]
pre_value = dic[ch]
return res
| 579 | 29.526316 | 73 | py |
LeetCode-Python | LeetCode-Python-master/剑指 Offer II 044.二叉树每层的最大值/剑指 Offer II 044-二叉树每层的最大值.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 largestValues(self, root: TreeNode) -> List[int]:
queue = [root]
res = []
while queue:
next_queue = []
max_val = float("-inf")
for node in queue:
if node:
max_val = max(max_val, node.val)
next_queue.extend([node.left, node.right])
queue = next_queue
if max_val != float("-inf"):
res.append(max_val)
return res | 692 | 27.875 | 62 | py |
LeetCode-Python | LeetCode-Python-master/剑指 Offer II 018.有效的回文/剑指 Offer II 018-有效的回文.py | class Solution:
def isPalindrome(self, s: str) -> bool:
s = "".join([char.lower() for char in s if char.isalpha() or char.isdigit()])
print(s)
return s == s[::-1] | 190 | 37.2 | 85 | py |
LeetCode-Python | LeetCode-Python-master/0053.最大子序和/0053-最大子序和.py | class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = [0 for _ in nums]
dp[0] = nums[0]
for i, x in enumerate(nums):
if i:
if dp[i - 1] > 0:
dp[i] = max(dp[i - 1] + x, dp[i])
else:
dp[i] = x
return max(dp) | 475 | 24.052632 | 53 | py |