# Code Signal – 相似数组(Are Similar)

## 02 Feb Code Signal – 相似数组(Are Similar)

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] and b = [1, 2, 3], the output should be areSimilar(a, b) = true.

The arrays are equal, no need to swap any elements.

For a = [1, 2, 3] and b = [2, 1, 3], the output should be areSimilar(a, b) = true.

We can obtain b from a by swapping 2 and 1 in b.

For a = [1, 2, 2] and b = [2, 1, 1], the output should be areSimilar(a, b) = false.

Any swap of any two elements either in a or in b won’t make a and b equal.

Input/Output:

[execution time limit] 4 seconds (js)

[input] array.integer a

Array of integers.

Guaranteed constraints:

3 ≤ a.length ≤ 105,

1 ≤ a[i] ≤ 1000.

[input] array.integer b

Array of integers of the same length as a.

Guaranteed constraints:

b.length = a.length,

1 ≤ b[i] ≤ 1000.

[output] boolean

true if a and b are similar, false otherwise.

a [ y ] = b [ x ] , a [ x ] = b [ y ] a[y] = b[x], a[x] = b[y]a[y]=b[x],a[x]=b[y]

class Solution:
def areSimilar(a, b):
print(a)
print(b)
diffArray = []
if len(a) != len(b):
return False
for i in range(len(a)):
if a[i] != b[i]:
diffArray.append(i)

if len(diffArray) > 2 or len(diffArray) == 1:
return False

if len(diffArray) == 0:
return True

x = diffArray[0]
y = diffArray[1]
return a[x] == b[y] and a[y] == b[x]
print(areSimilar([1, 2, 3], [1, 2, 3]))
print(areSimilar([1, 2, 3], [2, 1, 3]))
print(areSimilar([1, 2, 2], [2, 1, 1]))

def solution(a, b):
a_length = len(a)
b_length = len(b)

if a_length != b_length:
returnFalse

if a == b:
returnTrue

count = 0
m = 0
n = 0
for i in range(0, a_length):
if a[i] != b[i]:
if count == 0:
m = i
if count == 1:
n = i
count += 1

if count > 2 or count ==1:
return False
else:
return a[m] == b[n] and a[n] == b[m]