Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create majorityElementHashhmap.java #158

Merged
merged 1 commit into from
Oct 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}