Skip to content

Commit

Permalink
Create majorityElementHashhmap.java
Browse files Browse the repository at this point in the history
 HashMap has ability to efficiently store and manage data by associating keys with values and it also improves the Time Complexity. The question which is solved in the provided java code is a very known question and it builds a strong foundation for the topic hashmap. Question follows:
 Given an Array of size n, find all the elements that appear more than n/3 times Array={1, 3, 2, 5, 1, 3, 1, 5, 1 }.
Using two nested for loops to solve this problem would result in a less efficient solution with a time complexity of O(n^2), making it slower for large input arrays compared to the HashMap-based solution, which has a time complexity of O(n). This code uses a HashMap to efficiently count how many times each unique element appears in an array. It then checks if any of these elements appear more than one-third of the total elements in the array and prints them if they do. This demonstrates how HashMaps are valuable for tracking and analyzing data efficiently in real-world programming scenarios.
  • Loading branch information
Diptigit11 authored Oct 9, 2023
1 parent d733e97 commit cb01000
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Hashmaps/majorityElementHashhmap.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import java.util.*;

public class majorityElementHashhmap {
public static void majorityElement(int nums[]) {
HashMap<Integer, Integer> map = new HashMap<>();
int n = nums.length;
for (int i = 0; i < n; i++) {
if (map.containsKey(nums[i])) { //if num is present already
map.put(nums[i], map.get(nums[i]) + 1);
} else { //if num is not present
map.put(nums[i], 1);
}
}
for (int Key : map.keySet()) {
if (map.get(Key) > n / 3) {
System.out.println(" The no. of elements which appeared more than n/3 times is: " + Key);
}
}
}

public static void main(String[] args) {
int nums[] = { 1, 3, 2, 5, 1, 3, 1, 5, 1 };
majorityElement(nums);
}
}

0 comments on commit cb01000

Please sign in to comment.