差130个样例,等佬解
class Solution:
def ifqual(self,str1,str2):
return int(str1)==int(str2)
def change(self,str1,str2):
str1 = list(str1)
n=len(str1)
t=0
for i in range(n):
for j in range(i+1,n):
str1[i],str1[j]=str1[j],str1[i]
t+=1
if self.ifqual("".join(str1),str2):
return True
if t==2:
str1[i],str1[j]=str1[j],str1[i]
return False
def countPairs(self, nums: List[int]) -> int:
n=len(nums)
ret=0
for i in range(n):
for j in range(i+1,n):
if nums[i]==nums[j]:
ret+=1
else:
num1=str(nums[i])
num2=str(nums[j])
if self.change(num1,num2) or self.change(num2,num1):
ret+=1
return ret
大佬题解
class Solution:
def countPairs(self, nums: List[int]) -> int:
nums.sort()
ret=0
dict=defaultdict(int)
for num in nums:
#不交换
st={num}
#num的长度
s=list(str(num))
m=len(s)
#数位交换
for i in range(m):
for j in range(i+1,m):
s[i],s[j]=s[j],s[i]
st.add(int(''.join(s)))
for p in range(i+1,m):
for q in range(p+1,m):
s[p],s[q]=s[q],s[p]
st.add(int(''.join(s)))
#交换2次
s[p],s[q]=s[q],s[p]
#换回来
s[i],s[j]=s[j],s[i]
ret+=sum(dict[v] for v in st)
dict[num]+=1
return ret
思路确实好用,2题都能解。
ps:
力扣刷完还能atcoder>codeforces.