Skip to content

Commit 4d18a9b

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 169_Majority_Element.java
1 parent b95cc3f commit 4d18a9b

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

Arrays/169_Majority_Element.java

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
class Solution {
22
public int majorityElement(int[] nums) {
3-
Map<Integer, Integer> hm = new HashMap<>();
4-
int n = nums.length;
5-
int result = 0;
3+
if (nums == null || nums.length == 0) { return 0; }
64

7-
for (int i = 0; i < n; i++) {
8-
hm.put(nums[i], hm.getOrDefault(nums[i], 0) + 1);
9-
if (hm.get(nums[i]) > n / 2) {
10-
result = nums[i];
5+
int candidate = 0, count = 0;
6+
7+
for (int num : nums) {
8+
if (count == 0) {
9+
candidate = num;
10+
++count;
11+
} else {
12+
if (candidate == num) { ++count; }
13+
else { --count; }
1114
}
1215
}
1316

14-
return result;
17+
return candidate;
1518
}
1619
}

0 commit comments

Comments
 (0)