首页  >  问答  >  正文

php 数组旋转

<p>在这两个整数数组中,如何确定第二个数组是否是第一个数组的旋转版本以及需要哪个 php 函数?</p> <p>示例: 原始数组 A=[1,2,3,4,5,6,7,8] 旋转数组 B=[6,7,8,1,2,3,4,5]</p> <p>在此示例中,数组 A 的所有数字都向右旋转 5 个位置。</p>
P粉043295337P粉043295337385 天前494

全部回复(1)我来回复

  • P粉111627787

    P粉1116277872023-09-04 00:34:22

    没有内置函数,但您可以旋转每个位置并比较是否正确。

    $isRotated = function (array $original, array $maybeRotated): bool {
        $originalCount     = count($original);
        $maybeRotatedCount = count($maybeRotated);
        if ($originalCount !== $maybeRotatedCount || $original === $maybeRotated) {
            return false;
        }
    
        for ($i = 0; $i < $originalCount; $i++) {
            $original[] = array_shift($original);
            if ($original === $maybeRotated) {
                return true;
            }
        }
    
        return false;
    };
    
    echo $isRotated([1, 2, 3, 4, 5, 6, 7, 8], [6, 7, 8, 1, 2, 3, 4, 5]) ? 'true' : 'false', PHP_EOL;
    echo $isRotated([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8]) ? 'true' : 'false', PHP_EOL;
    echo $isRotated([1, 2, 3, 4, 5, 6, 7, 8], [2, 3, 4, 5, 6, 7, 8, 1]) ? 'true' : 'false', PHP_EOL;

    输出

    true
    false
    true

    回复
    0
  • 取消回复