📌  相关文章
📜  查找与给定数组中元素索引相同的非负幂的最高频率

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

查找与给定数组中元素索引相同的非负幂的最高频率

给定一个具有N个非负整数的数组arr[] ,找出与其索引的非负幂相同的元素的最大数量。

任务是返回 X 的最大频率。

例子:

方法:给定问题可以通过查找每个索引的幂并检查它们是否等于该索引处存在的元素来解决。

请按照以下步骤解决问题:

  • 从索引 2 到末尾以及每个索引处迭代数组arr
    • 使用循环将索引与自身相乘,直到该值小于整数的最大值且小于或等于该索引处存在的元素
      • 如果幂变得等于元素,则检查它是否存在于哈希图中:
        • 如果电源不存在,则将其添加到值为 1 的哈希映射中
        • 否则,如果电源已经存在,则将其频率增加 1
  • 如果arr[0] = 1,则将 hashmap 中 0 的频率增加 1
  • 迭代 HashMap 并找到具有最大频率的值:
    • 如果arr[0] = 1,则除 0 以外的所有值的频率都增加 1
  • 如果arr[1] = 1,则返回, maxFreq +1,否则返回maxFreq

下面是上述方法的实现:

C++
// C++ code for the above approach
#include 
using namespace std;
 
// Function to find count of elements which
// are a non-negative power of their indices
int indPowEqualsEle(vector arr)
{
 
    // Length of the array
    int len = arr.size();
 
    // Initialize the hashmap to store
    // the frequency of elements
    unordered_map map;
 
    // Initialize maximum value
    // of integer into long
    long limit = INT_MAX;
 
    // Iterate the array arr from index 2
    for (int i = 2; i < len; i++)
    {
 
        // If current element is equal to 1
        // then its equal to index power 0
        if (arr[i] == 1)
        {
 
            // Increment the frequency of 0 by 1
            map[0]++;
            continue;
        }
 
        // Initialize a variable to index
        // which is to be multiplied
        // by the index
        long indPow = i;
 
        // Initialize a variable to
        // store the power of the index
        int p = 1;
 
        while (indPow <= limit && indPow <= arr[i])
        {
 
            // Element is equal to
            // a power of its index
            if (arr[i] == indPow)
            {
 
                // Increment the frequency
                // of p by 1
                map[p]++;
 
                break;
            }
 
            // Increment power
            p++;
 
            // Multiply current value with
            // index to get the next power
            indPow *= i;
        }
    }
 
    // If arr[0] == 1, then increment
    // the frequency of 0 in the hashmap
    map[0]++;
 
    // Initialize maxFreq to 0 to calculate
    // maximum frequency of powers
    int maxFreq = 0;
 
    // Iterate the hashmap
    for (auto it = map.begin(); it != map.end(); it++)
    {
        int power = it->second;
        // If arr[0] == 0, then increment the
        // frequency of all powers except 0
        if (arr[0] == 0 && power != 0)
        {
 
            maxFreq = max(maxFreq,
                          map[power] + 1);
        }
        else
        {
 
            maxFreq = max(maxFreq,
                          map[power]);
        }
    }
 
    // Increment the maximum frequency by 1
    // If arr[1] is equal to 1
    return arr[1] == 1
               ? maxFreq + 1
               : maxFreq;
}
 
// Driver function
int main()
{
 
    // Initialize an array
    vector arr = {0, 1, 1, 9, 1, 25};
 
    // Call the function
    // and print the answer
    cout << (indPowEqualsEle(arr));
}
 
// This code is contributed by Potta Lokesh


Java
// Java implementation for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find count of elements which
    // are a non-negative power of their indices
    public static int indPowEqualsEle(int[] arr)
    {
 
        // Length of the array
        int len = arr.length;
 
        // Initialize the hashmap to store
        // the frequency of elements
        Map map
            = new HashMap<>();
 
        // Initialize maximum value
        // of integer into long
        long limit = (long)Integer.MAX_VALUE;
 
        // Iterate the array arr from index 2
        for (int i = 2; i < len; i++) {
 
            // If current element is equal to 1
            // then its equal to index power 0
            if (arr[i] == 1) {
 
                // Increment the frequency of 0 by 1
                map.put(0,
                        map.getOrDefault(0, 0) + 1);
                continue;
            }
 
            // Initialize a variable to index
            // which is to be multiplied
            // by the index
            long indPow = i;
 
            // Initialize a variable to
            // store the power of the index
            int p = 1;
 
            while (indPow <= limit
                   && indPow <= arr[i]) {
 
                // Element is equal to
                // a power of its index
                if (arr[i] == indPow) {
 
                    // Increment the frequency
                    // of p by 1
                    map
                        .put(p,
                             map.getOrDefault(p, 0) + 1);
 
                    break;
                }
 
                // Increment power
                p++;
 
                // Multiply current value with
                // index to get the next power
                indPow *= i;
            }
        }
 
        // If arr[0] == 1, then increment
        // the frequency of 0 in the hashmap
        map.put(0, map.getOrDefault(0, 0) + 1);
 
        // Initialize maxFreq to 0 to calculate
        // maximum frequency of powers
        int maxFreq = 0;
 
        // Iterate the hashmap
        for (int power : map.keySet()) {
 
            // If arr[0] == 0, then increment the
            // frequency of all powers except 0
            if (arr[0] == 0 && power != 0) {
 
                maxFreq
                    = Math.max(maxFreq,
                               map.get(power) + 1);
            }
            else {
 
                maxFreq = Math.max(maxFreq,
                                   map.get(power));
            }
        }
 
        // Increment the maximum frequency by 1
        // If arr[1] is equal to 1
        return arr[1] == 1
            ? maxFreq + 1
            : maxFreq;
    }
 
    // Driver function
    public static void main(String[] args)
    {
 
        // Initialize an array
        int[] arr = { 0, 1, 1, 9, 1, 25 };
 
        // Call the function
        // and print the answer
        System.out.println(indPowEqualsEle(arr));
    }
}


Python3
# Python 3 code for the above approach
from collections import defaultdict
import sys
 
# Function to find count of elements which
# are a non-negative power of their indices
def indPowEqualsEle(arr):
 
    # Length of the array
    length = len(arr)
 
    # Initialize the hashmap to store
    # the frequency of elements
    map = defaultdict(int)
 
    # Initialize maximum value
    # of integer into long
    limit = sys.maxsize
 
    # Iterate the array arr from index 2
    for i in range(2, length):
 
        # If current element is equal to 1
        # then its equal to index power 0
        if (arr[i] == 1):
 
            # Increment the frequency of 0 by 1
            map[0] += 1
            continue
 
        # Initialize a variable to index
        # which is to be multiplied
        # by the index
        indPow = i
 
        # Initialize a variable to
        # store the power of the index
        p = 1
 
        while (indPow <= limit and indPow <= arr[i]):
 
            # Element is equal to
            # a power of its index
            if (arr[i] == indPow):
 
                # Increment the frequency
                # of p by 1
                map[p] += 1
 
                break
 
            # Increment power
            p += 1
 
            # Multiply current value with
            # index to get the next power
            indPow *= i
 
    # If arr[0] == 1, then increment
    # the frequency of 0 in the hashmap
    map[0] += 1
 
    # Initialize maxFreq to 0 to calculate
    # maximum frequency of powers
    maxFreq = 0
 
    # Iterate the hashmap
    for it in range(len(map)):
 
        power = map[it]
        # If arr[0] == 0, then increment the
        # frequency of all powers except 0
        if (arr[0] == 0 and power != 0):
 
            maxFreq = max(maxFreq,
                          map[power] + 1)
        else:
 
            maxFreq = max(maxFreq,
                          map[power])
 
    # Increment the maximum frequency by 1
    # If arr[1] is equal to 1
    if(arr[1] == 1):
        return maxFreq + 1
    return maxFreq
 
# Driver function
if __name__ == "__main__":
 
    # Initialize an array
    arr = [0, 1, 1, 9, 1, 25]
 
    # Call the function
    # and print the answer
    print(indPowEqualsEle(arr))
 
    # This code is contributed by ukasp.


C#
// C# implementation for the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Function to find count of elements which
    // are a non-negative power of their indices
    public static int indPowEqualsEle(int[] arr)
    {
 
        // Length of the array
        int len = arr.Length;
 
        // Initialize the hashmap to store
        // the frequency of elements
        Dictionary map
            = new Dictionary();
 
        // Initialize maximum value
        // of integer into long
        long limit = (long)int.MaxValue;
 
        // Iterate the array arr from index 2
        for (int i = 2; i < len; i++) {
 
            // If current element is equal to 1
            // then its equal to index power 0
            if (arr[i] == 1) {
 
                // Increment the frequency of 0 by 1
                if(map.ContainsKey(0))
                    map[0] = map[0]+1;
                else
                    map.Add(0, 1);
                continue;
            }
 
            // Initialize a variable to index
            // which is to be multiplied
            // by the index
            long indPow = i;
 
            // Initialize a variable to
            // store the power of the index
            int p = 1;
 
            while (indPow <= limit
                   && indPow <= arr[i]) {
 
                // Element is equal to
                // a power of its index
                if (arr[i] == indPow) {
 
                    // Increment the frequency
                    // of p by 1
                    if(map.ContainsKey(p))
                    map[p] = map[p]+1;
                else
                    map.Add(p, 1);
 
                    break;
                }
 
                // Increment power
                p++;
 
                // Multiply current value with
                // index to get the next power
                indPow *= i;
            }
        }
 
        // If arr[0] == 1, then increment
        // the frequency of 0 in the hashmap
        if(map.ContainsKey(0))
            map[0] = map[0]+1;
        else
            map.Add(0, 1);
 
        // Initialize maxFreq to 0 to calculate
        // maximum frequency of powers
        int maxFreq = 0;
 
        // Iterate the hashmap
        foreach (int power in map.Keys) {
 
            // If arr[0] == 0, then increment the
            // frequency of all powers except 0
            if (arr[0] == 0 && power != 0) {
 
                maxFreq
                    = Math.Max(maxFreq,
                               map[power] + 1);
            }
            else {
 
                maxFreq = Math.Max(maxFreq,
                                   map[power]);
            }
        }
 
        // Increment the maximum frequency by 1
        // If arr[1] is equal to 1
        return arr[1] == 1
            ? maxFreq + 1
            : maxFreq;
    }
 
    // Driver function
    public static void Main(String[] args)
    {
 
        // Initialize an array
        int[] arr = { 0, 1, 1, 9, 1, 25 };
 
        // Call the function
        // and print the answer
        Console.WriteLine(indPowEqualsEle(arr));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript



输出
4

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