[JavaScript 刷题] Code Signal - 相似数组(Are Similar?)

Posted GoldenaArcher

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[JavaScript 刷题] Code Signal - 相似数组(Are Similar?)相关的知识,希望对你有一定的参考价值。

[javascript 刷题] Code Signal - 相似数组(Are Similar?)

题目地址: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.

解题思路

解题思路和 近乎增长序列(almostIncreasingSequence) 很相似,不过有点稍微变种。

  1. 因为先决条件最多只能调换 一个数组中一对元素,所以二者之间的不同只能为 0(不需要调换),或者 2(调换一对)

  2. 当最大不同为 0 时,代表数组完全相等,返回 true 即可

  3. 当最大不同为 2 时,因为只需要交换一个数组中的两个元素,所以只要满足下列条件即可:

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

这样跑下来的时间复杂度是 O ( n ) O(n) O(n),需要遍历一次所有的数组,空间复杂度为 O ( n ) O(n) O(n),需要保存所有不同数。当然,后者也可以被优化到 O ( 1 ) O(1) O(1),只需要当 包含所有不同的数组 长度超过 2 时直接返回即可,这样最大也就需要 3 个额外空间去进行存储。

使用 JavaScript 解题

// swapping at most one pair of elements in one of the arrays.
function areSimilar(a, b) {
  const maxDiff = maxDiffs(a, b);

  if (maxDiff.length > 2 || maxDiff.length === 1) return false;

  if (maxDiff.length === 0) return true; // identical

  const [diff1, diff2] = maxDiff;

  return a[diff1] === b[diff2] && a[diff2] === b[diff1];
}

const maxDiffs = (a, b) => {
  let maxDiff = [];
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      maxDiff.push(i);
    }
  }

  return maxDiff;
};

console.log(areSimilar([1, 2, 3], [1, 2, 3]));

以上是关于[JavaScript 刷题] Code Signal - 相似数组(Are Similar?)的主要内容,如果未能解决你的问题,请参考以下文章

[JavaScript 刷题] Code Signal - 形状面积(shapeArea)

[JavaScript 刷题] Code Signal - 幸运数(is lucky)

[JavaScript 刷题] Code Signal - 翻转括号内字符(reverseInParentheses)

[JavaScript 刷题] Code Signal - 相似数组(Are Similar?)

[JavaScript 刷题] Code Signal - 共用字符数(commonCharacterCount)

[JavaScript 刷题] Code Signal - 矩阵元素之和(matrixElementsSum)