📜  计算给定数组中存在完美平方的数组元素

📅  最后修改于: 2021-06-26 19:02:54             🧑  作者: Mango

给定一个数组arr [] ,任务是查找数组中已经存在平方的数组元素的数量。

例子:

天真的方法:请按照以下步骤解决问题:

  • 初始化一个变量,例如count ,以存储所需的计数。
  • 遍历数组,并对每个数组元素执行以下操作:
    • 遍历数组并搜索数组中是否存在当前元素的平方。
    • 如果找到平方,则增加计数。
  • 打印计数作为答案。

下面是上述方法的实现:

C++14
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the count of elements whose
// squares are already present int the array
void countSquares(int arr[], int N)
{
    // Stores the required count
    int count = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Square of the element
        int square = arr[i] * arr[i];
 
        // Traverse the array
        for (int j = 0; j < N; j++) {
 
            // Check whether the value
            // is equal to square
            if (arr[j] == square) {
 
                // Increment count
                count = count + 1;
            }
        }
    }
 
    // Print the count
    cout << count;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 4, 5, 20, 16 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    countSquares(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
// Function to find the count of elements whose
// squares are already present int the array
static void countSquares(int arr[], int N)
{
   
    // Stores the required count
    int count = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
 
        // Square of the element
        int square = arr[i] * arr[i];
 
        // Traverse the array
        for (int j = 0; j < N; j++)
        {
 
            // Check whether the value
            // is equal to square
            if (arr[j] == square)
            {
 
                // Increment count
                count = count + 1;
            }
        }
    }
 
    // Print the count
    System.out.print(count);
}
 
// Driver Code
public static void main(String[] args)
{
   
    // Given array
    int arr[] = { 2, 4, 5, 20, 16 };
 
    // Size of the array
    int N = arr.length;
    countSquares(arr, N);
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python program for the above approach
 
# Function to find the count of elements whose
# squares are already present the array
def countSquares(arr, N):
   
    # Stores the required count
    count = 0;
 
    # Traverse the array
    for i in range(N):
 
        # Square of the element
        square = arr[i] * arr[i];
 
        # Traverse the array
        for j in range(N):
 
            # Check whether the value
            # is equal to square
            if (arr[j] == square):
               
                # Increment count
                count = count + 1;
 
    # Prthe count
    print(count);
 
# Driver Code
if __name__ == '__main__':
   
    # Given array
    arr = [2, 4, 5, 20, 16];
 
    # Size of the array
    N = len(arr);
    countSquares(arr, N);
 
# This code is contributed by shikhasingrajput


C#
// C# program of the above approach
using System;
 
class GFG{
     
// Function to find the count of elements whose
// squares are already present int the array
static void countSquares(int[] arr, int N)
{
     
    // Stores the required count
    int count = 0;
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Square of the element
        int square = arr[i] * arr[i];
   
        // Traverse the array
        for(int j = 0; j < N; j++)
        {
             
            // Check whether the value
            // is equal to square
            if (arr[j] == square)
            {
                 
                // Increment count
                count = count + 1;
            }
        }
    }
     
    // Print the count
    Console.WriteLine(count);
}   
 
// Driver code   
static void Main()
{
     
    // Given array
    int[] arr = { 2, 4, 5, 20, 16 };
     
    // Size of the array
    int N = arr.Length;
     
    countSquares(arr, N);
}
}
 
// This code is contributed by divyeshrabadiya07


Javascript


C++14
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the count of elements whose
// squares is already present int the array
int countSquares(int arr[], int N)
{
    // Stores the count of array elements
    int count = 0;
 
    // Stores frequency of visited elements
    unordered_map m;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
        m[arr[i]] = m[arr[i]] + 1;
    }
 
    for (int i = 0; i < N; i++) {
 
        // Square of the element
        int square = arr[i] * arr[i];
 
        // Update the count
        count += m[square];
    }
 
    // Print the count
    cout << count;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 4, 5, 20, 16 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    countSquares(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to find the count of elements whose
// squares is already present int the array
static void countSquares(int arr[], int N)
{
   
    // Stores the count of array elements
    int count = 0;
 
    // Stores frequency of visited elements
    HashMap mp = new HashMap();
 
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
        if(mp.containsKey(arr[i]))
        {
            mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
            mp.put(arr[i], 1);
        }
    }
    for (int i = 0; i < N; i++)
    {
 
        // Square of the element
        int square = arr[i] * arr[i];
 
        // Update the count
        count += mp.containsKey(square)?mp.get(square):0;
    }
 
    // Print the count
    System.out.print(count);
}
 
// Driver Code
public static void main(String[] args)
{
   
    // Given array
    int arr[] = { 2, 4, 5, 20, 16 };
 
    // Size of the array
    int N = arr.length;
 
    // Function Call
    countSquares(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python 3 program for the above approach
from collections import defaultdict
 
# Function to find the count of elements whose
# squares is already present int the array
def countSquares( arr, N):
 
    # Stores the count of array elements
    count = 0;
 
    # Stores frequency of visited elements
    m = defaultdict(int);
 
    # Traverse the array
    for i in range(N):
        m[arr[i]] = m[arr[i]] + 1
 
    for i in range( N ):
 
        # Square of the element
        square = arr[i] * arr[i]
 
        # Update the count
        count += m[square]
 
    # Print the count
    print(count)
 
# Driver Code
if __name__ == "__main__":
   
    # Given array
    arr = [ 2, 4, 5, 20, 16 ]
 
    # Size of the array
    N = len(arr)
 
    # Function Call
    countSquares(arr, N);
 
# This code is contributed by chitranayal.


C#
# Python 3 program for the above approach
from collections import defaultdict
# Function to find the count of elements whose
# squares is already present int the array
 
 
def countSquares(arr, N):
 
    # Stores the count of array elements
    count = 0
 
    # Stores frequency of visited elements
    m = defaultdict(int)
 
    # Traverse the array
    for i in range(N):
        m[arr[i]] = m[arr[i]] + 1
 
    for i in range(N):
 
        # Square of the element
        square = arr[i] * arr[i]
 
        # Update the count
        count += m[square]
 
    # Print the count
    print(count)
 
 
# Driver Code
if __name__ == "__main__":
 
    # Given array
    arr = [2, 4, 5, 20, 16]
 
    # Size of the array
    N = len(arr)
 
    # Function Call
    countSquares(arr, N)


Javascript


输出:
2

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

高效的方法:最佳方法是使用unordered_map保留访问元素的计数并相应地更新变量计数。步骤如下:

  • 初始化Map来存储数组元素的频率,并初始化变量,例如count
  • 遍历数组,并为每个元素在Map中增加其计数。
  • 再次遍历数组,对于每个元素,检查图中元素的平方频率,并将其添加到变量计数中。
  • 打印计数为数组中已存在其正方形的元素数。

下面是上述方法的实现:

C++ 14

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the count of elements whose
// squares is already present int the array
int countSquares(int arr[], int N)
{
    // Stores the count of array elements
    int count = 0;
 
    // Stores frequency of visited elements
    unordered_map m;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
        m[arr[i]] = m[arr[i]] + 1;
    }
 
    for (int i = 0; i < N; i++) {
 
        // Square of the element
        int square = arr[i] * arr[i];
 
        // Update the count
        count += m[square];
    }
 
    // Print the count
    cout << count;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 4, 5, 20, 16 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    countSquares(arr, N);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to find the count of elements whose
// squares is already present int the array
static void countSquares(int arr[], int N)
{
   
    // Stores the count of array elements
    int count = 0;
 
    // Stores frequency of visited elements
    HashMap mp = new HashMap();
 
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
        if(mp.containsKey(arr[i]))
        {
            mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
            mp.put(arr[i], 1);
        }
    }
    for (int i = 0; i < N; i++)
    {
 
        // Square of the element
        int square = arr[i] * arr[i];
 
        // Update the count
        count += mp.containsKey(square)?mp.get(square):0;
    }
 
    // Print the count
    System.out.print(count);
}
 
// Driver Code
public static void main(String[] args)
{
   
    // Given array
    int arr[] = { 2, 4, 5, 20, 16 };
 
    // Size of the array
    int N = arr.length;
 
    // Function Call
    countSquares(arr, N);
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python 3 program for the above approach
from collections import defaultdict
 
# Function to find the count of elements whose
# squares is already present int the array
def countSquares( arr, N):
 
    # Stores the count of array elements
    count = 0;
 
    # Stores frequency of visited elements
    m = defaultdict(int);
 
    # Traverse the array
    for i in range(N):
        m[arr[i]] = m[arr[i]] + 1
 
    for i in range( N ):
 
        # Square of the element
        square = arr[i] * arr[i]
 
        # Update the count
        count += m[square]
 
    # Print the count
    print(count)
 
# Driver Code
if __name__ == "__main__":
   
    # Given array
    arr = [ 2, 4, 5, 20, 16 ]
 
    # Size of the array
    N = len(arr)
 
    # Function Call
    countSquares(arr, N);
 
# This code is contributed by chitranayal.

C#

# Python 3 program for the above approach
from collections import defaultdict
# Function to find the count of elements whose
# squares is already present int the array
 
 
def countSquares(arr, N):
 
    # Stores the count of array elements
    count = 0
 
    # Stores frequency of visited elements
    m = defaultdict(int)
 
    # Traverse the array
    for i in range(N):
        m[arr[i]] = m[arr[i]] + 1
 
    for i in range(N):
 
        # Square of the element
        square = arr[i] * arr[i]
 
        # Update the count
        count += m[square]
 
    # Print the count
    print(count)
 
 
# Driver Code
if __name__ == "__main__":
 
    # Given array
    arr = [2, 4, 5, 20, 16]
 
    # Size of the array
    N = len(arr)
 
    # Function Call
    countSquares(arr, N)

Java脚本


输出:
2

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

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。