📜  排列中的双毕达哥拉斯三胞胎

📅  最后修改于: 2021-04-22 02:02:09             🧑  作者: Mango

给定一个整数数组arr [] ,任务是检查数组中是否有Twin Pythagorean Triplet

例子

天真的方法:一个简单的解决方案是运行三个循环,三个循环选择三个数组元素,并检查当前的三个元素是否形成了双勾子勾股三重态。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if there exist
// a twin pythagorean triplet in
// the given array
bool isTriplet(int ar[], int n)
{
    // Loop to check if there is a
    // Pythagorean triplet in the array
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            for (int k = j + 1; k < n; k++) {
 
                // Check if there is
                // consecutive triple
                if (abs(ar[i] - ar[j]) == 1
                    || abs(ar[j] - ar[k]) == 1
                    || abs(ar[i] - ar[k]) == 1) {
 
                    // Calculate square of
                    // array elements
                    int x = ar[i] * ar[i],
                        y = ar[j] * ar[j],
                        z = ar[k] * ar[k];
 
                    if (x == y + z
                        || y == x + z
                        || z == x + y)
                        return true;
                }
            }
        }
    }
 
    return false;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 3, 1, 4, 6, 5 };
    int ar_size = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    isTriplet(arr, ar_size)
        ? cout << "Yes"
        : cout << "No";
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if there exist
// a twin pythagorean triplet in
// the given array
static boolean isTriplet(int ar[], int n)
{
     
    // Loop to check if there is a
    // Pythagorean triplet in the array
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
            for(int k = j + 1; k < n; k++)
            {
                 
                // Check if there is
                // consecutive triple
                if (Math.abs(ar[i] - ar[j]) == 1 ||
                    Math.abs(ar[j] - ar[k]) == 1 ||
                    Math.abs(ar[i] - ar[k]) == 1)
                {
 
                    // Calculate square of
                    // array elements
                    int x = ar[i] * ar[i],
                        y = ar[j] * ar[j],
                        z = ar[k] * ar[k];
 
                    if (x == y + z ||
                        y == x + z ||
                        z == x + y)
                        return true;
                }
            }
        }
    }
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 3, 1, 4, 6, 5 };
    int ar_size = arr.length;
 
    // Function call
    if(isTriplet(arr, ar_size))
        System.out.print("Yes");
    else
        System.out.print("No");
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program for the above approach
 
# Function to check if there exist
# a twin pythagorean triplet in
# the given array
def isTriplet(ar, n):
     
    # Loop to check if there is a
    # Pythagorean triplet in the array
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                 
                # Check if there is
                # consecutive triple
                if (abs(ar[i] - ar[j]) == 1 or
                    abs(ar[j] - ar[k]) == 1 or
                    abs(ar[i] - ar[k]) == 1):
                     
                        # Calculate square of
                        # array elements
                        x = ar[i] * ar[i]
                        y = ar[j] * ar[j]
                        z = ar[k] * ar[k]
                         
                        if (x == y + z or
                            y == x + z or
                            z == x + y):
                            return True
                             
    return False
 
# Driver Code
if __name__=='__main__':
     
    # Given array arr[]
    arr = [ 3, 1, 4, 6, 5 ]
    ar_size = len(arr)
     
    # Function call
    if isTriplet(arr, ar_size):
        print('Yes')
    else:
        print('No')
 
# This code is contributed by rutvik_56


C#
// C# program for the above approach
using System;
class GFG{
 
// Function to check if there exist
// a twin pythagorean triplet in
// the given array
static bool isTriplet(int []ar, int n)
{
     
    // Loop to check if there is a
    // Pythagorean triplet in the array
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
            for(int k = j + 1; k < n; k++)
            {
                 
                // Check if there is
                // consecutive triple
                if (Math.Abs(ar[i] - ar[j]) == 1 ||
                    Math.Abs(ar[j] - ar[k]) == 1 ||
                    Math.Abs(ar[i] - ar[k]) == 1)
                {
 
                    // Calculate square of
                    // array elements
                    int x = ar[i] * ar[i],
                        y = ar[j] * ar[j],
                        z = ar[k] * ar[k];
 
                    if (x == y + z ||
                        y == x + z ||
                        z == x + y)
                        return true;
                }
            }
        }
    }
    return false;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 3, 1, 4, 6, 5 };
    int ar_size = arr.Length;
 
    // Function call
    if(isTriplet(arr, ar_size))
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed by Rohit_ranjan


C++
// C++ program for the above approach
#include 
 
using namespace std;
 
// Function to check if any of the
// two numbers are consecutive
// in the given triplet
bool isConsective(int a, int b, int c)
{
    return abs(a - b) == 1
           || abs(b - c) == 1
           || abs(c - a) == 1;
}
 
// Function to check if there exist a
// pythagorean triplet in the array
bool isTriplet(int arr[], int n)
{
 
    // Square array elements
    for (int i = 0; i < n; i++)
        arr[i] = arr[i] * arr[i];
 
    // Sort array elements
    sort(arr, arr + n);
 
    // Now fix one element one by one
    // and find the other two elements
    for (int i = n - 1; i >= 2; i--) {
 
        // To find the other two elements,
        // start two index variables from
        // two corners of the array and move
        // them toward each other
        int l = 0;
        int r = i - 1;
 
        while (l < r) {
 
            // A triplet found
            if (arr[l] + arr[r] == arr[i]
                && isConsective(sqrt(arr[l]),
                                sqrt(arr[r]),
                                sqrt(arr[i]))) {
 
                return true;
            }
 
            // Else either move 'l' or 'r'
            (arr[l] + arr[r] < arr[i])
                ? l++
                : r--;
        }
    }
 
    // If we reach here,
    // then no triplet found
    return false;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 3, 1, 4, 6, 5 };
    int arr_size = sizeof(arr)
                   / sizeof(arr[0]);
 
    // Function Call
    isTriplet(arr, arr_size)
        ? cout << "Yes"
        : cout << "No";
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if any of the
// two numbers are consecutive
// in the given triplet
static boolean isConsective(int a, int b, int c)
{
    return Math.abs(a - b) == 1 ||
           Math.abs(b - c) == 1 ||
           Math.abs(c - a) == 1;
}
 
// Function to check if there exist a
// pythagorean triplet in the array
static boolean isTriplet(int arr[], int n)
{
 
    // Square array elements
    for(int i = 0; i < n; i++)
        arr[i] = arr[i] * arr[i];
 
    // Sort array elements
    Arrays.sort(arr);
 
    // Now fix one element one by one
    // and find the other two elements
    for(int i = n - 1; i >= 2; i--)
    {
 
        // To find the other two elements,
        // start two index variables from
        // two corners of the array and move
        // them toward each other
        int l = 0;
        int r = i - 1;
 
        while (l < r)
        {
             
            // A triplet found
            if (arr[l] + arr[r] == arr[i] &&
                isConsective((int)Math.sqrt(arr[l]),
                             (int)Math.sqrt(arr[r]),
                             (int)Math.sqrt(arr[i])))
            {
                return true;
            }
 
            // Else either move 'l' or 'r'
            if(arr[l] + arr[r] < arr[i])
                l++;
            else
                r--;
        }
    }
 
    // If we reach here,
    // then no triplet found
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 3, 1, 4, 6, 5 };
    int arr_size = arr.length;
 
    // Function call
    if(isTriplet(arr, arr_size))
        System.out.print("Yes");
    else
        System.out.print("No");
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program for the above approach
import math
 
# Function to check if any of the
# two numbers are consecutive
# in the given triplet
def isConsective(a, b, c):
     
    return bool(abs(a - b) == 1 or
                abs(b - c) == 1 or
                abs(c - a) == 1)
   
# Function to check if there exist a
# pythagorean triplet in the array
def isTriplet(arr, n):
   
    # Square array elements
    for i in range(n):
        arr[i] = arr[i] * arr[i]
   
    # Sort array elements
    arr.sort()
   
    # Now fix one element one by one
    # and find the other two elements
    for i in range(n - 1, 1, -1):
   
        # To find the other two elements,
        # start two index variables from
        # two corners of the array and move
        # them toward each other
        l = 0
        r = i - 1
   
        while (l < r):
   
            # A triplet found
            if (arr[l] + arr[r] == arr[i] and
                isConsective(math.sqrt(arr[l]),
                             math.sqrt(arr[r]),
                             math.sqrt(arr[i]))):
   
                return bool(True)
   
            # Else either move 'l' or 'r'
            if(arr[l] + arr[r] < arr[i]):
                l = l + 1
            else:
                r = r - 1
   
    # If we reach here,
    # then no triplet found
    return bool(False)
     
# Driver code
 
# Given array arr[]
arr = [ 3, 1, 4, 6, 5 ]
arr_size = len(arr)
 
# Function call
if(isTriplet(arr, arr_size)):
    print("Yes")
else:
    print("No")
 
# This code is contributed divyeshrabadiya07


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to check if any of the
// two numbers are consecutive
// in the given triplet
static bool isConsective(int a, int b, int c)
{
    return Math.Abs(a - b) == 1 ||
           Math.Abs(b - c) == 1 ||
           Math.Abs(c - a) == 1;
}
 
// Function to check if there exist a
// pythagorean triplet in the array
static bool isTriplet(int []arr, int n)
{
 
    // Square array elements
    for(int i = 0; i < n; i++)
        arr[i] = arr[i] * arr[i];
 
    // Sort array elements
    Array.Sort(arr);
 
    // Now fix one element one by one
    // and find the other two elements
    for(int i = n - 1; i >= 2; i--)
    {
         
        // To find the other two elements,
        // start two index variables from
        // two corners of the array and move
        // them toward each other
        int l = 0;
        int r = i - 1;
 
        while (l < r)
        {
             
            // A triplet found
            if (arr[l] + arr[r] == arr[i] &&
                isConsective((int)Math.Sqrt(arr[l]),
                             (int)Math.Sqrt(arr[r]),
                             (int)Math.Sqrt(arr[i])))
            {
                return true;
            }
 
            // Else either move 'l' or 'r'
            if(arr[l] + arr[r] < arr[i])
                l++;
            else
                r--;
        }
    }
 
    // If we reach here,
    // then no triplet found
    return false;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 3, 1, 4, 6, 5 };
    int arr_size = arr.Length;
 
    // Function call
    if(isTriplet(arr, arr_size))
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed by gauravrajput1


输出:
Yes

时间复杂度: O(N 3 )
辅助村: O(1)

高效方法:

  • 对输入数组中的每个元素求平方。此步骤需要O(n)时间。
  • 以递增顺序对平方数组进行排序。此步骤需要O(nLogn)时间。
  • 要找到三元组(a,b,c)使得a 2 = b 2 + c 2且至少一对是连续的,请执行以下操作。
    • 修复“ a”作为排序数组的最后一个元素。
    • 现在在第一个元素和“ a”之间的子数组中搜索对(b,c)。可以使用本文中方法1中讨论的中间算法中的Meet在O(n)时间内找到一对具有给定总和的(b,c)。
    • 如果找不到当前“ a”对,则将“ a”移回一个位置并重复上一步。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
 
using namespace std;
 
// Function to check if any of the
// two numbers are consecutive
// in the given triplet
bool isConsective(int a, int b, int c)
{
    return abs(a - b) == 1
           || abs(b - c) == 1
           || abs(c - a) == 1;
}
 
// Function to check if there exist a
// pythagorean triplet in the array
bool isTriplet(int arr[], int n)
{
 
    // Square array elements
    for (int i = 0; i < n; i++)
        arr[i] = arr[i] * arr[i];
 
    // Sort array elements
    sort(arr, arr + n);
 
    // Now fix one element one by one
    // and find the other two elements
    for (int i = n - 1; i >= 2; i--) {
 
        // To find the other two elements,
        // start two index variables from
        // two corners of the array and move
        // them toward each other
        int l = 0;
        int r = i - 1;
 
        while (l < r) {
 
            // A triplet found
            if (arr[l] + arr[r] == arr[i]
                && isConsective(sqrt(arr[l]),
                                sqrt(arr[r]),
                                sqrt(arr[i]))) {
 
                return true;
            }
 
            // Else either move 'l' or 'r'
            (arr[l] + arr[r] < arr[i])
                ? l++
                : r--;
        }
    }
 
    // If we reach here,
    // then no triplet found
    return false;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 3, 1, 4, 6, 5 };
    int arr_size = sizeof(arr)
                   / sizeof(arr[0]);
 
    // Function Call
    isTriplet(arr, arr_size)
        ? cout << "Yes"
        : cout << "No";
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if any of the
// two numbers are consecutive
// in the given triplet
static boolean isConsective(int a, int b, int c)
{
    return Math.abs(a - b) == 1 ||
           Math.abs(b - c) == 1 ||
           Math.abs(c - a) == 1;
}
 
// Function to check if there exist a
// pythagorean triplet in the array
static boolean isTriplet(int arr[], int n)
{
 
    // Square array elements
    for(int i = 0; i < n; i++)
        arr[i] = arr[i] * arr[i];
 
    // Sort array elements
    Arrays.sort(arr);
 
    // Now fix one element one by one
    // and find the other two elements
    for(int i = n - 1; i >= 2; i--)
    {
 
        // To find the other two elements,
        // start two index variables from
        // two corners of the array and move
        // them toward each other
        int l = 0;
        int r = i - 1;
 
        while (l < r)
        {
             
            // A triplet found
            if (arr[l] + arr[r] == arr[i] &&
                isConsective((int)Math.sqrt(arr[l]),
                             (int)Math.sqrt(arr[r]),
                             (int)Math.sqrt(arr[i])))
            {
                return true;
            }
 
            // Else either move 'l' or 'r'
            if(arr[l] + arr[r] < arr[i])
                l++;
            else
                r--;
        }
    }
 
    // If we reach here,
    // then no triplet found
    return false;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = { 3, 1, 4, 6, 5 };
    int arr_size = arr.length;
 
    // Function call
    if(isTriplet(arr, arr_size))
        System.out.print("Yes");
    else
        System.out.print("No");
}
}
 
// This code is contributed by gauravrajput1

Python3

# Python3 program for the above approach
import math
 
# Function to check if any of the
# two numbers are consecutive
# in the given triplet
def isConsective(a, b, c):
     
    return bool(abs(a - b) == 1 or
                abs(b - c) == 1 or
                abs(c - a) == 1)
   
# Function to check if there exist a
# pythagorean triplet in the array
def isTriplet(arr, n):
   
    # Square array elements
    for i in range(n):
        arr[i] = arr[i] * arr[i]
   
    # Sort array elements
    arr.sort()
   
    # Now fix one element one by one
    # and find the other two elements
    for i in range(n - 1, 1, -1):
   
        # To find the other two elements,
        # start two index variables from
        # two corners of the array and move
        # them toward each other
        l = 0
        r = i - 1
   
        while (l < r):
   
            # A triplet found
            if (arr[l] + arr[r] == arr[i] and
                isConsective(math.sqrt(arr[l]),
                             math.sqrt(arr[r]),
                             math.sqrt(arr[i]))):
   
                return bool(True)
   
            # Else either move 'l' or 'r'
            if(arr[l] + arr[r] < arr[i]):
                l = l + 1
            else:
                r = r - 1
   
    # If we reach here,
    # then no triplet found
    return bool(False)
     
# Driver code
 
# Given array arr[]
arr = [ 3, 1, 4, 6, 5 ]
arr_size = len(arr)
 
# Function call
if(isTriplet(arr, arr_size)):
    print("Yes")
else:
    print("No")
 
# This code is contributed divyeshrabadiya07

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to check if any of the
// two numbers are consecutive
// in the given triplet
static bool isConsective(int a, int b, int c)
{
    return Math.Abs(a - b) == 1 ||
           Math.Abs(b - c) == 1 ||
           Math.Abs(c - a) == 1;
}
 
// Function to check if there exist a
// pythagorean triplet in the array
static bool isTriplet(int []arr, int n)
{
 
    // Square array elements
    for(int i = 0; i < n; i++)
        arr[i] = arr[i] * arr[i];
 
    // Sort array elements
    Array.Sort(arr);
 
    // Now fix one element one by one
    // and find the other two elements
    for(int i = n - 1; i >= 2; i--)
    {
         
        // To find the other two elements,
        // start two index variables from
        // two corners of the array and move
        // them toward each other
        int l = 0;
        int r = i - 1;
 
        while (l < r)
        {
             
            // A triplet found
            if (arr[l] + arr[r] == arr[i] &&
                isConsective((int)Math.Sqrt(arr[l]),
                             (int)Math.Sqrt(arr[r]),
                             (int)Math.Sqrt(arr[i])))
            {
                return true;
            }
 
            // Else either move 'l' or 'r'
            if(arr[l] + arr[r] < arr[i])
                l++;
            else
                r--;
        }
    }
 
    // If we reach here,
    // then no triplet found
    return false;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 3, 1, 4, 6, 5 };
    int arr_size = arr.Length;
 
    // Function call
    if(isTriplet(arr, arr_size))
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed by gauravrajput1
输出:
Yes

时间复杂度: O(N 2 )
辅助空间: O(1)