-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajorityElement.java
More file actions
60 lines (44 loc) · 1.31 KB
/
MajorityElement.java
File metadata and controls
60 lines (44 loc) · 1.31 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
48
49
50
51
52
53
54
55
56
57
58
59
60
package leetcode;
import java.util.Arrays;
import java.util.HashMap;
public class MajorityElement {
public static void main(String[] args) {
int[] arr = {3,2,3};
//majorityElement(arr);
majorElement(arr);
}
public static int majorityElement(int[] nums) {
int majNum = nums.length / 2;
int result = nums[0]; // init the result
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
int count = 0;
for (int j = i+1; j < nums.length; j++) {
if (nums[i] == nums[j]){
count++;
}
}
if (count>=majNum){
result = nums[i];
return result;
}
}
return result;
}
public static int majorElement(int[] nums){
HashMap<Integer,Integer> map = new HashMap<>();
int result = nums[0];
for (int num : nums ) {
if (!map.containsKey(num)){
map.put(num,1);
}else {
map.put(num,map.get(num)+1);
}
if (map.get(num)> nums.length/2){
result = num;
break;
}
}
return result;
}
}