-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path169_MajorityElement.java
More file actions
40 lines (38 loc) · 1.05 KB
/
169_MajorityElement.java
File metadata and controls
40 lines (38 loc) · 1.05 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
/*
* Given an array of size n, find the majority element. The majority
* element is the element that appears more than ⌊ n/2 ⌋ times.
* You may assume that the array is non-empty and the majority
* element always exist in the array.
*/
//hashmap
public class Solution {
public int majorityElement(int[] nums) {
int res = nums[0];
Map<Integer, Integer> map = new HashMap<>();
for(int num : nums) {
if(map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
if(map.get(num) > nums.length / 2) res = num;;
}
return res;
}
}
//666
public class Solution {
public int majorityElement(int[] nums) {
int cnt = 0;
int maj = 0;
for(int i=0; i<nums.length; i++) {
if(cnt == 0) {
maj = nums[i];
cnt ++;
} else if(maj == nums[i]) {
cnt ++;
} else cnt --;
}
return maj;
}
}