📜  检查给定的数组是否是镜像反转的

📅  最后修改于: 2022-05-13 01:57:46.876000             🧑  作者: Mango

检查给定的数组是否是镜像反转的

给定一个数组arr[] ,任务是找出该数组是否镜像逆。数组的逆表示如果数组元素与其对应的索引交换,并且如果数组的逆等于自身,则该数组称为镜像逆。如果数组是镜像反转的,则打印Yes否则打印No
例子:

一个简单的方法是通过交换给定数组的值和索引来创建一个新数组,并检查新数组是否等于原始数组。
更好的方法是遍历数组并且对于所有索引,如果arr[arr[index]] = index满足,那么给定的数组是镜像反转的。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include
using namespace std;
 
// Function that returns true if
// the array is mirror-inverse
bool isMirrorInverse(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
 
        // If condition fails for any element
        if (arr[arr[i]] != i)
            return false;
    }
 
    // Given array is mirror-inverse
    return true;
}
 
// Driver code
int main()
{
        int arr[] = { 1, 2, 3, 0 };
        int n = sizeof(arr)/sizeof(arr[0]);
        if (isMirrorInverse(arr,n))
            cout << "Yes";
        else
            cout << "No";
        return 0;
}
 
// This code is contributed by Rajput-Ji


Java
// Java implementation of the approach
public class GFG {
 
    // Function that returns true if
    // the array is mirror-inverse
    static boolean isMirrorInverse(int arr[])
    {
        for (int i = 0; i < arr.length; i++) {
 
            // If condition fails for any element
            if (arr[arr[i]] != i)
                return false;
        }
 
        // Given array is mirror-inverse
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 0 };
        if (isMirrorInverse(arr))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}


Python3
# Python 3 implementation of the approach
 
# Function that returns true if
# the array is mirror-inverse
def isMirrorInverse(arr, n) :
 
    for i in range(n) :
 
        # If condition fails for any element
        if (arr[arr[i]] != i) :
            return False;
     
    # Given array is mirror-inverse
    return true;
 
# Driver code
if __name__ == "__main__" :
     
    arr = [ 1, 2, 3, 0 ];
     
    n = len(arr) ;
    if (isMirrorInverse(arr,n)) :
        print("Yes");
    else :
        print("No");
 
# This code is contributed by Ryuga


C#
// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function that returns true if
    // the array is mirror-inverse
    static bool isMirrorInverse(int []arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
 
            // If condition fails for any element
            if (arr[arr[i]] != i)
                return false;
        }
 
        // Given array is mirror-inverse
        return true;
    }
 
    // Driver code
    static public void Main ()
    {
        int []arr = { 1, 2, 3, 0 };
        if (isMirrorInverse(arr))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by ajit...


PHP


Javascript


输出:
No