1 parent 93a3fa6 commit 8e34f23Copy full SHA for 8e34f23
1 file changed
solutions/169. Majority Element/AC_MoorVote.java
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 1、Moore voting algorithm,摩尔投票法
3
+ * wiki:https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
4
+ *
5
+ */
6
+public class MajorityElement {
7
+ public static int majorityElement(int[] nums) {
8
+ //
9
+ int times = 0;
10
+ int majority = 0;
11
+ for(int i = 0; i < nums.length; i++){
12
+ // 如果出现次数为0,则前面没有出现大于一般的数字,重新设置新的数字
13
+ if(times == 0){
14
+ majority = nums[i];
15
+ }
16
+ if(nums[i] != majority){
17
+ times++;
18
+ }else{
19
+ times--;
20
21
22
+ return majority;
23
24
+}
0 commit comments