forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajorityElement.java
More file actions
42 lines (38 loc) · 879 Bytes
/
MajorityElement.java
File metadata and controls
42 lines (38 loc) · 879 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
30
31
32
33
34
35
36
37
38
39
40
41
42
package normal; /**
* @program JavaBooks
* @description: 169.求众数
* @author: mf
* @create: 2019/11/04 15:25
*/
/**
* 题目:https://leetcode-cn.com/problems/majority-element/
* 难度:easy
*/
/*
输入: [3,2,3]
输出: 3
输入: [2,2,1,1,1,2,2]
输出: 2
*/
public class MajorityElement {
public static void main(String[] args) {
int[] arr = {3,2,3};
int[] arr1 = {2,2,1,1,1,2,2};
System.out.println(majorityElement(arr1));
}
private static int majorityElement(int[] nums) {
int count = 1;
int ans = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] == ans) {
count++;
} else {
count--;
if (count == 0) {
ans = nums[i + 1];
}
}
}
return ans;
}
}