forked from ghostmkg/programming-language
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMajorityVote.java
67 lines (55 loc) · 1.79 KB
/
MajorityVote.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//GFG POTD Date: 03/09/24
// You are given an array of integer nums[] where each number represents a vote to a candidate. Return the candidates that have votes greater than one-third of the total votes, If there's not a majority vote, return -1.
// Examples:
// Input: nums = [2, 1, 5, 5, 5, 5, 6, 6, 6, 6, 6]
// Output: [5, 6]
// Explanation: 5 and 6 occur more n/3 times.
// Input: nums = [1, 2, 3, 4, 5]
// Output: [-1]
// Explanation: no candidate occur more than n/3 times.
import java.util.*;
class MajorityVote {
static List<Integer> findMajority(List<Integer> nums) {
int count1 = 0, count2 = 0, candidate1 = 0, candidate2 = 0;
for (int num : nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
} else if (count1 == 0) {
candidate1 = num;
count1 = 1;
} else if (count2 == 0) {
candidate2 = num;
count2 = 1;
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (int num : nums) {
if (num == candidate1) count1++;
else if (num == candidate2) count2++;
}
List<Integer> result = new ArrayList<>();
int n = nums.size();
if (count1 > n / 3) result.add(candidate1);
if (count2 > n / 3) result.add(candidate2);
if (result.isEmpty()) {
result.add(-1);
}
return result;
}
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>();
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(4);
nums.add(5);
List<Integer> result = findMajority(nums);
System.out.println(result);
}
}