-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathElectionWinner.java
More file actions
34 lines (26 loc) · 849 Bytes
/
Copy pathElectionWinner.java
File metadata and controls
34 lines (26 loc) · 849 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
package com.sarvesh.javabasics;
import java.util.Arrays;
public class ElectionWinner {
public static void main(String[] args) {
int[] votes = {2, 2, 1, 1, 1, 2, 2};
System.out.println("Counting votes for: " + Arrays.toString(votes));
int winner = majorityElement(votes);
System.out.println("The Election Winner is Candidate: " + winner);
}
public static int majorityElement(int[] nums) {
int candidate = 0;
int count = 0;
for (int i=0;i<nums.length;i++) {
int currentVote=nums[i];
if (count==0) {
candidate=currentVote;
}
if (currentVote==candidate) {
count++;
} else {
count--;
}
}
return candidate;
}
}