10.16
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
array = set()
n = len(nums)
for i in range(n):
if nums[i] not in array:
array.add(nums[i])
else:
array.remove(nums[i])
return list(array)
10.17
class Solution:
def sumOfMultiples(self, n: int) -> int:
#容斥原理
def f(m: int) -> int:
return (m + n // m * m) * (n // m) // 2
return f(3) + f(5) + f(7) - f(3 * 5) - f(3 * 7) - f(5 * 7) + f(3 * 5 * 7)
#暴力
#ans = 0
#for i in range (1,n+1):
#if i%3==0 or i%5==0 or i%7==0:
#ans+=i
#return ans
10.18
#TLE
import math
class Solution(object):
def maxKelements(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
ans = 0
while k:
max_value = max(nums)
ans += max_value
nums[nums.index(max_value)] = math.ceil(max_value / 3.0)
#print(math.ceil(max_value / 3))
k -= 1
return int(ans)
#模拟大顶堆
class Solution(object):
def maxKelements(self, nums, k):
q = [-x for x in nums]
heapify(q)
ans = 0
for _ in range(k):
x = heappop(q)
ans += -x
heappush(q, -((-x + 2) // 3))
return ans
10.19
#若a*b = c*d,那么通过排序就可得到8组
#找到每个乘积对应的数量(Counter)
#然后任选其中两个/2*8即可
class Solution(object):
def tupleSameProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
cnt = Counter([nums[i] * nums[j] for i in range(n) for j in range(i+1,n)])
ans = 0
for key,value in cnt.items():
ans += value * (value-1) * 4
return ans
10.20
class Solution:
def categorizeBox(self, length, width, height, mass):
maxd = max(length, width, height)
vol = length * width * height
isBulky = maxd >= 10000 or vol >= 10**9
isHeavy = mass >= 100
if isBulky and isHeavy:
return 'Both'
if isBulky:
return 'Bulky'
if isHeavy:
return 'Heavy'
return 'Neither'
#语法题
10.21
#并查集
class Solution(object):
def countPairs(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
#初始化
uf = UnionFind(n)
#合并
for x, y in edges:
uf.union(x, y)
res = 0
for i in range(n):
#不和自己同集的均加入到res
res += n - uf.getSize(uf.find(i))
return res//2
class UnionFind:
def __init__(self, n):
self.parents = [i for i in range(n)]
self.sizes = [1] * n
def find(self, x):
if self.parents[x] == x:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
rx = self.find(x)
ry = self.find(y)
if rx!=ry:
if self.sizes[rx] > self.sizes[ry]:
self.parents[ry] = rx
self.sizes[rx] += self.sizes[ry]
else:
self.parents[rx] = ry
self.sizes[ry] += self.sizes[rx]
def getSize(self, x):
return self.sizes[x]
10.22
#动态规划,背包问题
class Solution(object):
def maxSatisfaction(self, satisfaction):
"""
:type satisfaction: List[int]
:rtype: int
"""
#价值可为负的背包问题
n = len(satisfaction)
satisfaction.sort()
res = 0
dp = [[0 for _ in range(n+1)] for _ in range(n+1)]
#前i道菜,拿了j道,得到的最大利润
for i in range(1,n+1):
for j in range(1,i+1):
dp[i][j] = dp[i-1][j-1] + j * satisfaction[i - 1]
#如果j!=i 意味着不是前i道全拿 就有取max的机会
if j < i:
dp[i][j] = max(dp[i][j], dp[i-1][j])
res = max(res, dp[i][j])
return res