【问题标题】:Check if two arrays are "almost equal" (one can be transformed to the other)检查两个数组是否“几乎相等”(一个可以转换为另一个)
【发布时间】:2016-08-04 22:28:00
【问题描述】:

我遇到了一个我无法解决的面试问题,我认为这是一个合适的地方。

问题的前提是检查两个数组是否“差不多相等”。

背景:

给定两个数组 A 和 B,count(B) >= count(A)。 A 和 B 中的元素是包含字母字符和可能 ONE SET 大括号的字符串。

示例:

A = {'Hello', 'World', 'This is {cool}'}
B = {'Hello', 'World', 'This is {cool}', '{This is cool}'}

'{This is {cool}} 这样的东西永远不会出现,因为它有两组大括号。

如果满足以下条件,则称数组 A 和 B“几乎相等”:

  • B 包含 A 中的所有元素
  • 可以通过将大括号应用于 A 中的元素 (Hello => {Hello}) 或将 A 中元素内的大括号移动到元素外部 (@987654325) 来获得 B 中不在 A 中的每个元素@)

编写一个函数来确定两个数组 A 和 B 是否“差不多相等”。注重效率。

我的幼稚解决方案:

我写了一个函数来从 A 中删除一个元素,检查该元素是否出现在 B 中,以及该元素的任何“排列”是否出现在 B 中。如果是,则从 B 中删除它们。最后我返回如果 A 和 B 都为空,则为真。我想知道是否有更有效的解决方案。

【问题讨论】:

  • 我会通过这次面试测试
  • 我想知道他们是否只需要这个功能,所以他们发布了一个虚假的职位空缺,让申请人免费编写代码。
  • 哈哈,不知整个面试过程中经常出现这种情况

标签: php arrays algorithm


【解决方案1】:

B 包含 A 中的所有元素

这可以使用array_diff来实现:

if (array_diff($a, $b) == array()) {
    // Check #1: pass
}

来自手册:

将 array1 与一个或多个其他数组进行比较,并返回 array1 中不存在于任何其他数组中的值。

因此,如果 $a 中存在 $b 中不存在的值,则上述检查将返回 false


B 中不在 A 中的每个元素都可以通过将大括号应用于 A 中的元素 (Hello => {Hello}) 或将 A 中元素内的大括号移动到元素 (This is {cool} => {This is cool})

我希望这可以通过比较两个数组并完全删除括号来实现,但规则 or by moving the curly brackets within an element in A to the outside of the element 表明,如果它围绕其他单词之一,它应该会失败。

情况并非如此,但您仍然可以移除大括号并将它们放回每个字符串的边缘以进行比较:

/**
 * Remove any braces in the value and put them back in at the edges of the string
 * @param  string $value
 * @return string
 */
function addOrMoveBraces($value)
{
    return sprintf('{%s}', str_replace(['{', '}'], '', $value));;
}

$aWithBraces = array_map('addOrMoveBraces', $a);
$bWithBraces = array_map('addOrMoveBraces', $b);

if (array_diff($bWithBraces, $aWithBraces) == array()) {
    // Check #2: pass
}

放在一起

你需要一个函数,所以你可以这样做:

/**
 * Remove any braces in the value and put them back in at the edges of the string
 * @param  string $value
 * @return string
 */
function addOrMoveBraces($value)
{
    return sprintf('{%s}', str_replace(['{', '}'], '', $value));;
}

function justAboutEqual($a, $b)
{
    // Check #1
    if (array_diff($a, $b) == array()) {
        return true;
    }

    // Check #2
    if (array_diff(array_map('addOrMoveBraces', $b), array_map('addOrMoveBraces', $a)) == array()) {
        return true;
    }

    return false;
}

Here's a couple of simple unit tests 反对这些功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多