54.Sum of similar frequency element

53

Problem of the Day:
You are given an integer array nums.
First, count the frequency of each distinct number in the array.
Then, for each frequency f, compute the sum of all numbers in the array that appear exactly f times.Return a mapping (or any suitable output format) where:
Key = frequency
Value = sum of elements that occur with that frequency


  • Input 1:
    nums = [1,7,1,1,2,2,2,3,3,5,5]
    Output:
    1 -> 7
    2 -> 16
    3 -> 9



  • Input 2:
    nums = [nums = [1,1,2,2,2,3]
    Output:
    1 -> 3
    2 -> 2
    3 -> 6


Comments

  1. import java.util.HashMap;
    class Ques54{

    public static void main(String[] args){

    int[] arr={1,7,1,1,2,2,2,3,3,5,5};

    //int[] arr={1,1,2,2,2,3};

    HashMapmap=new HashMap<>();

    for(int i=0;imap1=new HashMap<>();


    for(int key:map.keySet()){

    if(map1.containsKey(map.get(key))){

    map1.put(map.get(key),map1.get(map.get(key))+(key*map.get(key)));

    }else{

    map1.put(map.get(key),key*map.get(key));

    }



    }


    System.out.println(map1);


    }
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Strings

Arrays