Select the code snippet which prints the element with maximum frequency.

Select the code snippet which prints the element with maximum frequency.
A.
Code:
public int findPopular(int[] a) 
{
	if (a == null || a.length == 0)
		return 0;
	Arrays.sort(a);
	int previous = a[0];
	int popular = a[0];
	int count = 1;
	int maxCount = 1;
	for (int i = 1; i < a.length; i++)
        {
		if (a[i] == previous)
		count++;
		else 
                {
			if (count > maxCount) 
                        {
				popular = a[i-1];
				maxCount = count;
			}
		previous = a[i];
		count = 1;
		}
	}
	return count > maxCount ? a[a.length-1] : popular;
}
B.
Code:
public int findPopular(int[] a) 
{
	if (a == null || a.length == 0)
		return 0;
	Arrays.sort(a);
	int previous = a[0];
	int popular = a[0];
	int count = 1;
	int maxCount = 1;
	for (int i = 1; i < a.length; i++) 
        {
		if (a[i] == previous)
			count++;
		else 
                {
			if (count > maxCount) 
                        {
				popular = a[i];
				maxCount = count;
			}
			previous = a[i];
			count = 1;
		}
	}
	return count > maxCount ? a[a.length-1] : popular;
}
C.
Code:
public int findPopular(int[] a) 
{
	if (a == null || a.length == 0)
		return 0;
	Arrays.sort(a);
	int previous = a[0];
	int popular = a[0];
	int count = 1;
	int maxCount = 1;
	for (int i = 1; i < a.length; i++) 
        {
		if (a[i+1] == previous)
			count++;
		else 
                {
			if (count > maxCount) 
                        {
				popular = a[i-1];
				maxCount = count;
			}
			previous = a[i];
			count = 1;
		}
	}
	return count > maxCount ? a[a.length-1] : popular;
}
D.
Code:
public int findPopular(int[] a) 
{
	if (a == null || a.length == 0)
		return 0;
	Arrays.sort(a);
	int previous = a[0];
	int popular = a[0];
	int count = 1;
	int maxCount = 1;
	for (int i = 1; i < a.length; i++) 
        {
		if (a[i+2] == previous)
			count++;
		else 
                {
			if (count > maxCount) 
                        {
				popular = a[i-1];
				maxCount = count;
			}
			previous = a[i];
			count = 1;
		}
	}
	return count > maxCount ? a[a.length-1] : popular;
}
 
Answer: A
Explanation: Traverse through the array and see if it is equal to the previous element, since the array is sorted this method works with a time complexity of O(nlogn), without sorting a Brute force technique must be applied for which the time complexity will be O(n$^{2}$).
 

Tìm kiếm

Back
Top