forked from ghostmkg/programming-language
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMajorityVote.java
More file actions
Latest commit
67 lines (55 loc) · 1.79 KB
/
Copy pathMajorityVote.java
File metadata and controls
67 lines (55 loc) · 1.79 KB
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.
importjava.util.*;
classMajorityVote {
staticList<Integer> findMajority(List<Integer> nums) {
intcount1 = 0, count2 = 0, candidate1 = 0, candidate2 = 0;
for (intnum : nums) {
if (num == candidate1) {
count1++;
} elseif (num == candidate2) {
count2++;
} elseif (count1 == 0) {
candidate1 = num;
count1 = 1;
} elseif (count2 == 0) {
candidate2 = num;
count2 = 1;
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (intnum : nums) {
if (num == candidate1) count1++;
elseif (num == candidate2) count2++;
}
List<Integer> result = newArrayList<>();
intn = nums.size();
if (count1 > n / 3) result.add(candidate1);
if (count2 > n / 3) result.add(candidate2);
if (result.isEmpty()) {
result.add(-1);
}
returnresult;
}
publicstaticvoidmain(String[] args) {
List<Integer> nums = newArrayList<>();
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(4);
nums.add(5);
List<Integer> result = findMajority(nums);
System.out.println(result);
}
}