1
1
package com .fishercoder .solutions ;
2
2
3
- import java .util .Arrays ;
4
- import java .util .HashMap ;
5
- import java .util .Map ;
6
-
7
3
/**
8
4
* 169. Majority Element
9
5
10
6
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
11
-
12
7
You may assume that the array is non-empty and the majority element always exist in the array.
13
8
14
9
Example 1:
15
-
16
10
Input: [3,2,3]
17
11
Output: 3
18
12
19
13
Example 2:
20
-
21
14
Input: [2,2,1,1,1,2,2]
22
15
Output: 2
23
16
*/
24
17
public class _169 {
25
18
public static class Solution1 {
26
- /**Moore Voting Algorithm*/
19
+ /**Moore Voting Algorithm
20
+ * How to understand this:
21
+ * 1. For a number to qualify as a majority element, it needs to occur more than 1/2 times, which
22
+ * means there are a max of only one such element in any given array.
23
+ * 2. E.g. given this array [1,2,3,1,1,1], two of the 1s will be balanced off by 2 and 3, still there are two 1s remaining in the end
24
+ * which is the majority element*/
27
25
public int majorityElement (int [] nums ) {
28
26
int count = 1 ;
29
27
int majority = nums [0 ];
@@ -42,27 +40,6 @@ public int majorityElement(int[] nums) {
42
40
}
43
41
44
42
public static class Solution2 {
45
- public int majorityElement (int [] nums ) {
46
- Map <Integer , Integer > map = new HashMap ();
47
- for (int i : nums ) {
48
- map .put (i , map .getOrDefault (i , 0 ) + 1 );
49
- if (map .get (i ) > nums .length / 2 ) {
50
- return i ;
51
- }
52
- }
53
- return -1 ;
54
- }
55
- }
56
-
57
- public static class Solution3 {
58
- //This is O(nlogn) time.
59
- public int majorityElement (int [] nums ) {
60
- Arrays .sort (nums );
61
- return nums [nums .length / 2 ];
62
- }
63
- }
64
-
65
- public static class Solution4 {
66
43
//bit manipulation
67
44
public int majorityElement (int [] nums ) {
68
45
int [] bit = new int [32 ];//because an integer is 32 bits, so we use an array of 32 long
@@ -77,7 +54,7 @@ public int majorityElement(int[] nums) {
77
54
//this below for loop is to construct the majority element: since every bit of this element would have appeared more than n/2 times
78
55
for (int i = 0 ; i < 32 ; i ++) {
79
56
bit [i ] = bit [i ] > nums .length / 2 ? 1
80
- : 0 ;//we get rid of those that bits that are not part of the majority number
57
+ : 0 ;//we get rid of those that bits that are not part of the majority number
81
58
res += bit [i ] * (1 << (31 - i ));
82
59
}
83
60
return res ;
0 commit comments