📜  找出其左右素数个数相等的数组元素

📅  最后修改于: 2021-09-07 02:19:23             🧑  作者: Mango

给定一个由N 个正整数组成的数组arr[] ,任务是从数组中找到一个索引,该索引的左边和右边的素数计数相等。

例子:

朴素方法:解决给定问题的最简单方法是通过遍历数组来计算每个数组元素左侧和右侧的素数,并打印发现素数计数相等的索引。
时间复杂度: O(N 2 )
辅助空间: O(1)

有效的方法:上述方法也可以使用埃拉托色尼筛法和前缀和技术进行优化,以将素数左右预先存储到数组元素。请按照以下步骤解决问题:

  • 首先,找到数组arr[]的最大值并将其存储在一个变量中,比如maxValue
  • 初始化一个 map < int, int> ,比如St ,以存储其中的所有素数。
  • 迭代范围[2, maxValue]并推送St 中的所有值。
  • 迭代范围[2, maxValue]并执行以下操作:
    • 将变量j初始化为1并在i*j小于或等于maxValue 时进行迭代。
    • 在上述步骤的每次迭代中,从St 中删除i*j并将j增加1
  • 初始化两个变量,比如LeftCountRightCount ,以分别将素数的计数存储在前缀数组和后缀数组中。
  • 初始化两个数组,例如Prefix[]Suffix[] ,以存储数组arr[]素数计数的前缀和数组和后缀和数组。
  • 遍历数组arr[]并执行以下操作:
    • LeftCount分配给Prefix[i]
    • 如果arr[i] 的值存在于St 中,则将LeftCount的值增加1
  • 反向迭代范围[0, N-1]并执行以下操作:
    • RightCount分配给Suffix[i]
    • 如果arr[i]存在于St 中,则将RightCount的值增加1
  • 迭代范围[0, N – 1]并且如果Prefix[i]的值等于Suffix[i]的值,则打印索引i作为答案并跳出循环。
  • 完成上述步骤后,如果以上情况都不满足,则打印-1

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the index of the
// array such that the count of prime
// numbers to its either ends are same
int findIndex(int arr[], int N)
{
    // Store the maximum value in
    // the array
    int maxValue = INT_MIN;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
        maxValue = max(maxValue, arr[i]);
    }
 
    // Stores all the numbers
    map St;
 
    // Iterate over the range [1, Max]
    for (int i = 1; i <= maxValue; i++) {
 
        // Increment the value of st[i]
        St[i]++;
    }
 
    // Removes 1 from the map St
    if (St.find(1) != St.end()) {
        St.erase(1);
    }
 
    // Perform Sieve of Prime Numbers
    for (int i = 2;
         i <= sqrt(maxValue); i++) {
        int j = 2;
 
        // While i*j is less than
        // the maxValue
        while ((i * j) <= maxValue) {
 
            // If i*j is in map St
            if (St.find(i * j)
                != St.end()) {
 
                // Erase the value (i * j)
                St.erase(i * j);
            }
 
            // Increment the value of j
            j++;
        }
    }
 
    // Stores the count of prime from
    // index 0 to i
    int LeftCount = 0;
 
    // Stores the count of prime numbers
    int Prefix[N];
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        Prefix[i] = LeftCount;
 
        // If arr[i] is present in the
        // map st
        if (St.find(arr[i])
            != St.end()) {
            LeftCount++;
        }
    }
 
    // Stores the count of prime from
    // index i to N-1
    int RightCount = 0;
 
    // Stores the count of prime numbers
    int Suffix[N];
 
    // Iterate over the range [0, N-1]
    // in reverse order
    for (int i = N - 1; i >= 0; i--) {
 
        Suffix[i] = RightCount;
 
        // If arr[i] is in map st
        if (St.find(arr[i])
            != St.end()) {
            RightCount++;
        }
    }
 
    // Iterate over the range [0, N-1]
    for (int i = 0; i < N; i++) {
 
        // If prefix[i] is equal
        // to the Suffix[i]
        if (Prefix[i] == Suffix[i]) {
            return i;
        }
    }
 
    // Return -1 if no such index
    // is present
    return -1;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 4, 7, 5, 10, 1, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << findIndex(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.HashMap;
 
public class GFG
{
   
    // Function to find the index of the
    // array such that the count of prime
    // numbers to its either ends are same
    static int findIndex(int arr[], int N)
    {
       
        // Store the maximum value in
        // the array
        int maxValue = Integer.MIN_VALUE;
 
        // Traverse the array arr[]
        for (int i = 0; i < N; i++)
        {
            maxValue = Math.max(maxValue, arr[i]);
        }
 
        // Stores all the numbers
        HashMap St = new HashMap<>();
 
        // Iterate over the range [1, Max]
        for (int i = 1; i <= maxValue; i++) {
 
            // Increment the value of st[i]
            St.put(i, St.getOrDefault(i, 0) + 1);
        }
 
        // Removes 1 from the map St
        if (St.containsKey(1)) {
            St.remove(1);
        }
 
        // Perform Sieve of Prime Numbers
        for (int i = 2; i <= Math.sqrt(maxValue); i++) {
            int j = 2;
 
            // While i*j is less than
            // the maxValue
            while ((i * j) <= maxValue) {
 
                // If i*j is in map St
                if (St.containsKey(i * j)) {
 
                    // Erase the value (i * j)
                    St.remove(i * j);
                }
 
                // Increment the value of j
                j++;
            }
        }
 
        // Stores the count of prime from
        // index 0 to i
        int LeftCount = 0;
 
        // Stores the count of prime numbers
        int Prefix[] = new int[N];
 
        // Traverse the array arr[]
        for (int i = 0; i < N; i++) {
 
            Prefix[i] = LeftCount;
 
            // If arr[i] is present in the
            // map st
            if (St.containsKey(arr[i])) {
                LeftCount++;
            }
        }
 
        // Stores the count of prime from
        // index i to N-1
        int RightCount = 0;
 
        // Stores the count of prime numbers
        int Suffix[] = new int[N];
 
        // Iterate over the range [0, N-1]
        // in reverse order
        for (int i = N - 1; i >= 0; i--) {
 
            Suffix[i] = RightCount;
 
            // If arr[i] is in map st
            if (St.containsKey(arr[i])) {
                RightCount++;
            }
        }
 
        // Iterate over the range [0, N-1]
        for (int i = 0; i < N; i++) {
 
            // If prefix[i] is equal
            // to the Suffix[i]
            if (Prefix[i] == Suffix[i]) {
                return i;
            }
        }
 
        // Return -1 if no such index
        // is present
        return -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 2, 3, 4, 7, 5, 10, 1, 8 };
        int N = arr.length;
        System.out.println(findIndex(arr, N));
    }
}
 
// This code is contributed by abhinavjain194


Python3
# Python 3 program for the above approach
from collections import defaultdict
import sys
import math
 
# Function to find the index of the
# array such that the count of prime
# numbers to its either ends are same
 
 
def findIndex(arr, N):
 
    # Store the maximum value in
    # the array
    maxValue = -sys.maxsize - 1
 
    # Traverse the array arr[]
    for i in range(N):
        maxValue = max(maxValue, arr[i])
 
    # / Stores all the numbers
    St = defaultdict(int)
 
    # Iterate over the range [1, Max]
    for i in range(1, maxValue + 1):
 
        # Increment the value of st[i]
        St[i] += 1
 
    # Removes 1 from the map St
    if (1 in St):
        St.pop(1)
 
    # Perform Sieve of Prime Numbers
    for i in range(2, int(math.sqrt(maxValue)) + 1):
        j = 2
 
        # While i*j is less than
        # the maxValue
        while ((i * j) <= maxValue):
 
            # If i*j is in map St
            if (i * j) in St:
 
                # Erase the value (i * j)
                St.pop(i * j)
 
            # Increment the value of j
            j += 1
 
    # Stores the count of prime from
    # index 0 to i
    LeftCount = 0
 
    # Stores the count of prime numbers
    Prefix = [0] * N
 
    # Traverse the array arr[]
    for i in range(N):
 
        Prefix[i] = LeftCount
 
        # If arr[i] is present in the
        # map st
        if (arr[i] in St):
            LeftCount += 1
 
    # Stores the count of prime from
    # index i to N-1
    RightCount = 0
 
    # Stores the count of prime numbers
    Suffix = [0] * N
 
    # Iterate over the range [0, N-1]
    # in reverse order
    for i in range(N - 1, -1, -1):
 
        Suffix[i] = RightCount
 
        # If arr[i] is in map st
        if arr[i] in St:
            RightCount += 1
 
    # Iterate over the range [0, N-1]
    for i in range(N):
 
        # If prefix[i] is equal
        # to the Suffix[i]
        if (Prefix[i] == Suffix[i]):
            return i
 
    # Return -1 if no such index
    # is present
    return -1
 
 
# Driver Code
if __name__ == "__main__":
 
    arr = [2, 3, 4, 7, 5, 10, 1, 8]
    N = len(arr)
    print(findIndex(arr, N))
 
    # This code is contributed by ukasp.


Javascript


输出:
2

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live