Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,959 questions

51,901 answers

573 users

How to find elements that appear more than array_size/K times in an array with Java

1 Answer

0 votes
import java.util.HashMap;
import java.util.Map;
 
class Program {
    static HashMap<Integer,Integer> elements_that_appear_more_than_x_times(int[] arr, int k) {
    	int size = arr.length;
    	int times = size / k;
    	System.out.println("more than " + times + " times");

    	HashMap<Integer, Integer> freqency_map = new HashMap<Integer, Integer>();
    
    	for (int i = 0; i < size; i++) {
    	    int val = freqency_map.get(arr[i]) == null ? 0 : freqency_map.get(arr[i]);
            freqency_map.put(arr[i], val + 1);
    	}
    
    	return new HashMap<Integer, Integer>(freqency_map);
    }
  
    public static void main(String[] args) {
        int k = 4;
	    int[] arr = {4, 8, 6, 5, 5, 8, 3, 2, 1, 2, 2, 5, 5, 5, 5, 8, 9, 8, 8};
	    
	    HashMap<Integer, Integer> freqency_map = elements_that_appear_more_than_x_times(arr, k);

	    for (Map.Entry el : freqency_map.entrySet()) {
            int val = (int) el.getValue();
            if (val > (arr.length / k)) {
                System.out.println(el.getKey() + " ");  
            }     
        }
    }
}



/*
run:

more than 4 times
5
8

*/

 



answered Feb 10, 2024 by avibootz
edited Feb 10, 2024 by avibootz
...