forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajorityElement.java
More file actions
47 lines (43 loc) · 1.15 KB
/
MajorityElement.java
File metadata and controls
47 lines (43 loc) · 1.15 KB
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
38
39
40
41
42
43
44
45
46
47
package com.examplehub.leetcode.easy;
import java.util.Arrays;
import java.util.HashMap;
/** https://leetcode.com/problems/majority-element/ */
public class MajorityElement {
public static int solution1(int... nums) {
int majorityIndex = 0;
int majorityTimes = 0;
for (int i = 0; i < nums.length; ++i) {
int countTimes = 0;
for (int num : nums) {
if (num == nums[i]) {
countTimes++;
}
}
if (countTimes > majorityTimes) {
majorityTimes = countTimes;
majorityIndex = i;
}
}
return nums[majorityIndex];
}
public static int solution2(int... nums) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
int majorityElement = 0;
int majorityTimes = 0;
for (int num : nums) {
if (!hashMap.containsKey(num)) {
hashMap.put(num, 0);
}
hashMap.put(num, hashMap.get(num) + 1);
if (hashMap.get(num) > majorityTimes) {
majorityElement = num;
majorityTimes = hashMap.get(num);
}
}
return majorityElement;
}
public static int solution3(int... nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}