记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
统计各个数字出现次数 从小到大排序 依次给两个数
def splitNum(num):
"""
:type num: int
:rtype: int
"""
s = sorted(str(num))
ans = int(''.join(s[::2]))+int(''.join(s[1::2]))
return ans
根据题意碰撞可以忽略 两机器人可以视作互相穿透
所以每个机器人可以得到最后位置为nums[i]+/-d
排序后计算两两距离
def sumDistance(nums, s, d):
"""
:type nums: List[int]
:type s: str
:type d: int
:rtype: int
"""
mod=10**9+7
n=len(nums)
l = [nums[i]-d if s[i]=='L' else nums[i]+d for i in range(n)]
l.sort()
ans = 0
for i in range(1,n):
ans =(ans + (l[i]-l[i-1])*i*(n-i))%mod
return ans
一个分值ma存放词汇分值
算出每个学生分数后排序
def topStudents(positive_feedback, negative_feedback, report, student_id, k):
"""
:type positive_feedback: List[str]
:type negative_feedback: List[str]
:type report: List[str]
:type student_id: List[int]
:type k: int
:rtype: List[int]
"""
m = {}
for w in positive_feedback:
m[w]=3
for w in negative_feedback:
m[w]=-1
ans=[]
for st,re in zip(student_id,report):
v = 0
for w in re.split():
v+=m.get(w,0)
ans.append((v,st))
ans.sort(key=lambda x :(-x[0],x[1]))
return [x[1] for x in ans[:k]]
依次累加
def findTheArrayConcVal(nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
ans = 0
for i in range(n//2):
ans += int(str(nums[i])+str(nums[n-1-i]))
if n%2==1:
ans += nums[n//2]
return ans
sun记录晴天 如果遇到洪水 找晚于第一次并且早于洪水的晴天 抽干
def avoidFlood(rains):
"""
:type rains: List[int]
:rtype: List[int]
"""
from sortedcontainers import SortedList
ans = [1]*len(rains)
sun = SortedList()
m = {}
for i,r in enumerate(rains):
if r==0:
sun.add(i)
else:
ans[i]=-1
if r in m:
d = sun.bisect(m[r])
if len(sun)==d:
return []
ans[sun[d]]=r
sun.discard(sun[d])
m[r]=i
return ans
两两异或 相同的数字会抵消
最后剩下来的就是只出现过一次的
def singleNumber(nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = 0
for num in nums:
ans ^=num
return ans
1.one,two,three分别代表出现了一次 两次 三次
位运算使得一个数在出现了三次后 被重置
2.通用方法 set去重 每个数乘3求和 减去原有和 剩下的为出现一次的数值的两倍
def singleNumber(nums):
"""
:type nums: List[int]
:rtype: int
"""
one,two,three=0,0,0
for num in nums:
two = two | (one & num)
one = one ^ num
three = (one & two)
two = two & ~three
one = one & ~three
return one
def singleNumber2(nums):
"""
:type nums: List[int]
:rtype: int
"""
return int((sum(set(nums))*3-sum(nums))/2)