[CodeSignal]Are Similar?

bbolddagu·2023년 4월 20일
0

알고리즘

목록 보기
2/11

문제

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
    solution(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
    solution(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
    solution(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 (py3)
[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.

풀이

[나의 풀이]

def solution(a, b):
    
    n = len(a)
    cnt = 0
    first_a = -1
    first_b = -1
    second_a = -1
    second_b = -1
    for i in range(n):
        if a[i] != b[i]:
            cnt += 1
            if cnt > 2:
                return False
            
            elif cnt == 2:
                second_a = a[i]
                second_b = b[i]
                if first_a == second_b and second_a == first_b:
                    pass
                else:
                    return False
            
            elif cnt == 1:
                first_a = a[i]
                first_b = b[i]
    
    # 히든 케이스 !!! 주의!!
    if cnt == 1:
        return False
        
    return True

[Best 풀이]

def solution(A, B):
    return sorted(A)==sorted(B) and sum([a!=b for a,b in zip(A,B)])<=2
  1. A와 B를 정렬한 결과가 같은지 확인합니다. 만약 같지 않다면, A와 B는 비슷하지 않은 것으로 판단하고 False를 반환합니다.

  2. A와 B를 하나씩 비교하면서 다른 원소의 개수가 2개 이하인지 확인합니다. 다른 원소의 개수가 2개 이하라면, A와 B는 비슷한 것으로 판단하고 True를 반환합니다. 그렇지 않으면, A와 B는 비슷하지 않은 것으로 판단하고 False를 반환합니다.

0개의 댓글