I was solving Majority Element problem of GFG. I had done same problem with 2 approaches
Method 1
static int majorityElement1(int a[], int size) {
HashMap<Integer, Integer> mp = new HashMap<>();
int count = 0;
int maxNum = 0;
for (int i = 0; i < a.length; i++) {
if (mp.containsKey(a[i])) {
if (count < mp.get(a[i]) + 1) {
count = mp.get(a[i]) + 1;
maxNum = a[i];
}
mp.replace(a[i], mp.get(a[i]) + 1);
} else {
if (count < 1) {
count = 1;
maxNum = a[i];
}
mp.put(a[i], 1);
}
}
return (mp.get(maxNum) > size / 2) ? maxNum : -1;
}
Method 2
static int majorityElement(int a[], int size) {
int count = 0;
int maxNum = 0;
for (int i = 0; i < a.length; i++) {
if (count == 0) {
maxNum = a[i];
count++;
} else {
if (maxNum == a[i]) {
count++;
} else {
count--;
}
}
}
count = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == maxNum) {
count++;
}
}
return (count > size / 2) ? maxNum : -1;
}
Even thought method 1 is solving the problem in O(n) time complexity time compiler of GFG shows that time limit exceeded. But it is showing execution successful when I am using the code of method 2 whose time complexity is O(2n) . Can some please help me understand way this is happening.