Below code is to find how many times a number is shown in an array. For Example:
1,2,2,2,3,4,5,5,5,5
number 2 = 3 times
number 5 = 4 times.
What is the time complexity in Java for the below code? What is the best way to solve this problem in respect to Time complexity?
public static void main(String[]args)
{
int[] data = {1,1,2,3,4,4,4,5,6,7,8,8,8,8};
System.out.println(count(data,8));
}
public static int count(int[] a, int x)
{
int count=0;
int index=0;
while(index<a.length)
{
if(a[index]==x)
{
count++;
}
index++;
}
return count;
}
O(n)ando(n)are not the same thing. In some sense they're the opposites of each other. See en.wikipedia.org/wiki/Big_O_notation