Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
Given two arrays a
and b
, check whether they are similar.
Example
-
For
a = [1, 2, 3]
andb = [1, 2, 3]
, the output should beareSimilar(a, b) = true
.The arrays are equal, no need to swap any elements.
-
For
a = [1, 2, 3]
andb = [2, 1, 3]
, the output should beareSimilar(a, b) = true
.We can obtain
b
froma
by swapping2
and1
inb
. -
For
a = [1, 2, 2]
andb = [2, 1, 1]
, the output should beareSimilar(a, b) = false
.Any swap of any two elements either in
a
or inb
won't makea
andb
equal.
我的解答:
def areSimilar(a, b):
count = 0
if sorted(a) == sorted(b):
for i in zip(a,b):
if i[0] != i[1]:
count +=1
if count > 2:
return False
else:
return True
else:
return False
膜拜大佬:
def areSimilar(A, B):
return sorted(A)==sorted(B) and sum([a!=b for a,b in zip(A,B)])<=2