-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray169.java
More file actions
37 lines (32 loc) · 967 Bytes
/
Array169.java
File metadata and controls
37 lines (32 loc) · 967 Bytes
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
import java.util.*;
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int target = 0;;
int targetCount = 0;
int maxElement = 0;
int maxElementCount = 0;
for (int i = 0; i < nums.length; i++) {
if (i == 0) {
target = nums[i];
targetCount++;
} else {
if (target != nums[i]) {
if (maxElementCount < targetCount) {
maxElement = target;
maxElementCount = targetCount;
}
target = nums[i];
targetCount = 1;
} else {
targetCount++;
}
}
}
if (targetCount > maxElementCount) {
return target;
} else {
return maxElement;
}
}
}