Skip to content

Instantly share code, notes, and snippets.

@YusufAbdelaziz
Last active March 29, 2020 01:58
Show Gist options
  • Save YusufAbdelaziz/3e60a97f4bbc1636c17b1b78c337224c to your computer and use it in GitHub Desktop.
Save YusufAbdelaziz/3e60a97f4bbc1636c17b1b78c337224c to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.*;
public class problemSolving {
private static int getMajorityElement(int[] a) {
//Java's sort is a dual pivot quick sort which is basically O(nlog n)
Arrays.sort(a);
//We here set a counter to count the duplicated elements
int count = 1;
//We set our first element to compare it with the remaining elements
int currentElement = a[0];
//We don't need to loop or count over the half of the array, I'm satisfied with counter which is basically more than half
//of the array by one.
for (int i = 1; i < a.length && count <= a.length / 2; i++) {
if (currentElement == a[i]) {
count++;
} else {
count = 1;
currentElement = a[i];
}
}
if (count > a.length / 2)
return 1;
else
return -1;
}
public static void main(String[] args) {
FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
if (getMajorityElement(a) != -1) {
System.out.println(1);
} else {
System.out.println(0);
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment