-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMajority.java
More file actions
43 lines (39 loc) · 740 Bytes
/
Majority.java
File metadata and controls
43 lines (39 loc) · 740 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
43
/**
*
* Ashish Patel
* e: ashishsushilPatel@gmail.com
* w: https://ashish.me
*
*/
class Majority {
static int func(int[] nums){
int result = 0;
int count = 1;
for(int i = 1; i < nums.length; i++){
if(nums[result] == nums[i]){
count += 1;
} else {
count -= 1;
}
if(count == 0){
result = i;
count = 1;
}
}
count = 0;
for(int i = 0; i < nums.length; i++){
if(nums[result] == nums[i]){
count += 1;
}
}
if(count <= nums.length/2){
return -1;
}
return result;
}
public static void main(String[] args){
int[] nums = {8, 3, 4, 8, 8};
int result = func(nums);
System.out.println(result);
}
}