Skip to content

Commit a423b86

Browse files
refactor 169
1 parent 06e24d4 commit a423b86

File tree

1 file changed

+7
-30
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+7
-30
lines changed

src/main/java/com/fishercoder/solutions/_169.java

+7-30
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,27 @@
11
package com.fishercoder.solutions;
22

3-
import java.util.Arrays;
4-
import java.util.HashMap;
5-
import java.util.Map;
6-
73
/**
84
* 169. Majority Element
95
106
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
11-
127
You may assume that the array is non-empty and the majority element always exist in the array.
138
149
Example 1:
15-
1610
Input: [3,2,3]
1711
Output: 3
1812
1913
Example 2:
20-
2114
Input: [2,2,1,1,1,2,2]
2215
Output: 2
2316
*/
2417
public class _169 {
2518
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*/
2725
public int majorityElement(int[] nums) {
2826
int count = 1;
2927
int majority = nums[0];
@@ -42,27 +40,6 @@ public int majorityElement(int[] nums) {
4240
}
4341

4442
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 {
6643
//bit manipulation
6744
public int majorityElement(int[] nums) {
6845
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) {
7754
//this below for loop is to construct the majority element: since every bit of this element would have appeared more than n/2 times
7855
for (int i = 0; i < 32; i++) {
7956
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
8158
res += bit[i] * (1 << (31 - i));
8259
}
8360
return res;

0 commit comments

Comments
 (0)