반응형

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. 


code>>


bool areSimilar(std::vector<int> a, std::vector<int> b) {

bool swap = false;

for (int i = 0; i < a.size(); i++)

{

if (a[i] != b[i] && !swap)

{

for (int j = i + 1; j < a.size(); j++)

{

if (a[j] != b[j])

{

int t = a[i];

a[i] = a[j];

a[j] = t;

swap = true;

break;

}

}

}

if (a[i] != b[i]) return false;

}

return true;

}


라이브러리를 사용해서 짠 코드인데 보기도 깔끔하다.

한개는 정방향 한개는 역방향에서 다른 부분을 찾아서 SWAP


다른 사람의 코드>>


bool areSimilar(std::vector<int> a, std::vector<int> b) {

    if (a == b)

        return true;

    std::iter_swap(

        std::mismatch(a.begin(), a.end(), b.begin(), b.end()).first,

        std::mismatch(a.rbegin(), a.rend(), b.rbegin(), b.rend()).first

    );

    return a == b;

}

반응형

'알고리즘 > codefights' 카테고리의 다른 글

18>palindromeRearranging  (0) 2017.07.02
17>arrayChange  (0) 2017.07.01
15>addBorder  (0) 2017.06.28
14>alternatingSums  (0) 2017.06.28
13>reverseParentheses  (0) 2017.06.28

+ Recent posts