思路:
1.分奇偶统计数频
2.然后看是否相等
3.相等酌情取下一个
src:
lass Solution:
def minimumOperations(self, nums: List[int]) -> int:
num1 = nums[::2]
num2 = nums[1::2]
n1 = len(num1)
n2 = len(num2)
if n1 * n2 == 0:
return 0
cnt1 = defaultdict(int)
for num in num1:
cnt1[num] += 1
cnt2 = defaultdict(int)
for num in num2:
cnt2[num] += 1
sort1 = sorted(cnt1.items(),key=lambda x:x[1],reverse=True) #根据词频降序排序
sort2 = sorted(cnt2.items(),key=lambda x:x[1],reverse=True) #根据词频降序排序
has = 0
if sort1[0][0] != sort2[0][0]:
has = sort1[0][1] + sort2[0][1]
else:
if len(sort1) == 1 and len(sort2) == 1:
has = max(sort1[0][1], sort2[0][1])
elif len(sort1) == 1:
has = sort1[0][1] + sort2[1][1]
elif len(sort2) == 1:
has = sort2[0][1] + sort1[1][1]
else:
if sort1[1][1] + sort2[0][1] > sort1[0][1] + sort2[1][1]:
has = sort1[1][1] + sort2[0][1]
else:
has = sort1[0][1] + sort2[1][1]
return n1 + n2 - has
思路:
绝对值方程求解,给定x
若大于等于x,则做差;若小于x, 则取该数和0的距离
通过遍历x,可以得到最小的ans
注意,不用每遍历算一次,只需要-一些+一些就好,这就是绝对值函数和遍历混合出来的魅力
src:
class Solution:
def minimumRemoval(self, beans: List[int]) -> int:
# 全部变成最小的or最小的变0
beans.sort()
n = len(beans)
#print(beans)
# 确定一个值x,小于它就全部加上,大于它就取差
temp = 0
x = beans[0]
index = 0
ans = 0xffffffff
for num in beans:
temp += num - x
ans = min(ans, temp)
while index < n:
nextIndex = index
while nextIndex < n and beans[nextIndex] == x:
nextIndex += 1
if nextIndex >= n:
break
temp += x * (nextIndex - index)
y = beans[nextIndex]
temp -= (y - x) * (n - nextIndex)
ans = min(ans, temp)
x = y
index = nextIndex
return ans
总结:
如果没有bug,就前300了,都怪第二题写错了index