-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajorityElement.java
More file actions
29 lines (27 loc) · 747 Bytes
/
MajorityElement.java
File metadata and controls
29 lines (27 loc) · 747 Bytes
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
package leetcode.array;
/**
* @ClassName MajorityElement
* @Description 多数元素
* https://leetcode-cn.com/problems/majority-element/
* @Author changxuan
* @Date 2020/8/12 下午7:57
**/
public class MajorityElement {
public static void main(String[] args) {
int[] test = {2,2,1,1,1,2,2};
System.out.println(majorityElement(test));
}
// 使用投票法
public static int majorityElement(int[] nums) {
int major = 0, count = 0;
for (int i = 0; i < nums.length; i++){
if (count == 0 || (count > 0 && major == nums[i])){
major = nums[i];
count++;
}else {
count--;
}
}
return major;
}
}