1+ package leetcode .easy ;
2+
3+ import java .util .HashMap ;
4+
5+ /**
6+ * https://leetcode.com/problems/majority-element/description/
7+ * <p>
8+ * Example 1:
9+ * Input: nums = [3,2,3]
10+ * Output: 3
11+ * <p>
12+ * Example 2:
13+ * Input: nums = [2,2,1,1,1,2,2]
14+ * Output: 2
15+ */
16+ class MajorityElement {
17+ public static void main (String [] args ) {
18+
19+ int [] nums1 = {3 , 2 , 3 };
20+ System .out .println ("Majority Element in [3, 2, 3]: " + majorityElement (nums1 )); // Expected: 3
21+
22+ int [] nums2 = {2 , 2 , 1 , 1 , 1 , 2 , 2 };
23+ System .out .println ("Majority Element in [2, 2, 1, 1, 1, 2, 2]: " + majorityElement (nums2 )); // Expected: 2
24+ }
25+
26+ public static int majorityElement (int [] nums ) {
27+ HashMap <Integer , Integer > map = new HashMap <>();
28+ int n = nums .length ;
29+
30+ // Populate the map with counts of each element
31+ for (int num : nums ) {
32+ map .put (num , map .getOrDefault (num , 0 ) + 1 );
33+ }
34+
35+ // Find the majority element (greater than n/2)
36+ for (int key : map .keySet ()) {
37+ if (map .get (key ) > n / 2 ) { // Fixed condition to be strictly greater
38+ return key ;
39+ }
40+ }
41+
42+ // Since the problem guarantees a majority element, this line should not be reached
43+ return -1 ;
44+ }
45+ }
0 commit comments