We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b95cc3f commit 4d18a9bCopy full SHA for 4d18a9b
Arrays/169_Majority_Element.java
@@ -1,16 +1,19 @@
1
class Solution {
2
public int majorityElement(int[] nums) {
3
- Map<Integer, Integer> hm = new HashMap<>();
4
- int n = nums.length;
5
- int result = 0;
+ if (nums == null || nums.length == 0) { return 0; }
6
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];
+ int candidate = 0, count = 0;
+
+ for (int num : nums) {
+ if (count == 0) {
+ candidate = num;
+ ++count;
11
+ } else {
12
+ if (candidate == num) { ++count; }
13
+ else { --count; }
14
}
15
16
- return result;
17
+ return candidate;
18
19
0 commit comments