Last active
December 26, 2023 16:41
-
-
Save mounicasrinivas/29538bc88e105855f2ff64c18c83efcc to your computer and use it in GitHub Desktop.
No Of Occurrences In An Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NoOfOccuranceInAnArray { | |
public static void main(String[] args) { | |
//Given an integer array a and value v, | |
//find the number of Occurancences of v in a | |
int [] a = {1,2,2,2,2,3,4,5,5,6,7,7,}; | |
int v = 2; | |
// Create a HashMap to store element-frequency pairs | |
Map<Integer,Integer> map = new HashMap<>(); | |
// Iterate through the array to populate the HashMap | |
for(int i : a){ | |
if(map.containsKey(i)){ | |
// If the element is already in the map, increment its frequency | |
map.put(i,map.get(i) + 1); | |
} | |
else{ | |
// If the element is not in the map, add it with a frequency of 1 | |
map.put(i,1); | |
} | |
} | |
System.out.println(map.get(v)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment