-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode0169.java
37 lines (32 loc) · 952 Bytes
/
LeetCode0169.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* Majority Element
* Input: [2,2,1,1,1,2,2]
* Output: 2
* */
import java.util.Arrays;
import java.util.HashMap;
public class LeetCode0169 {
public static void main(String args[]) {
int[] nums = {3, 3, 4};
System.out.println(majorityElement(nums));
}
public static int majorityElement(int[] nums) {
HashMap<Integer, Integer> counts = new HashMap<>();
for (int num : nums) {
if (!counts.containsKey(num))
counts.put(num, 1);
else
counts.put(num, counts.get(num) + 1);
}
int res = 0;
for (int num : nums) {
if (counts.get(num) > nums.length / 2)
res = num;
}
return res;
}
//Another approach : Sorting
public static int majorityElement_Sorting(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}