Sabari import java.util.ArrayList; public class three { public static void main(String[] args) { int size = 3; int arr[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0 }; ArrayList cache = new ArrayList(); int count = 0; for (int i = 0; i < arr.length; i++) { if (!cache.contains(arr[i])) { if (cache.size() < size) { count++; cache.add(arr[i]); } else { count++; cache.remove(0); cache.add(arr[i]); } } else { int index = cache.indexOf(arr[i]); cache.remove(index); cache.add(arr[i]); } } System.out.print(count); } } Log in to Reply
Aqib Solution:- import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int p=sc.nextInt(); int v=sc.nextInt(); int miss=0,f=0,r=0; int arr[]=new int[v]; int que[]=new int[v]; for(int i=0;i<v;i++) arr[i]=sc.nextInt(); for(int i=0;i<v;i++) { int flag=0,pos=-1; if(r<p) { que[i]=arr[i]; r++; miss++; } else { for(int j=f;j<r;j++) { if(arr[i]==que[j]) { flag=1; pos=j; break; } } if(flag==1) { for(int j=pos;j<r-1;j++) { que[j]=que[j+1]; } que[r-1]=arr[i]; } else { f++; que[r++]=arr[i]; miss++; } } } System.out.println("Miss="+miss); } } Log in to Reply
import java.util.ArrayList;
public class three {
public static void main(String[] args) {
int size = 3;
int arr[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0 };
ArrayList cache = new ArrayList();
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (!cache.contains(arr[i])) {
if (cache.size() < size) {
count++;
cache.add(arr[i]);
}
else {
count++;
cache.remove(0);
cache.add(arr[i]);
}
} else {
int index = cache.indexOf(arr[i]);
cache.remove(index);
cache.add(arr[i]);
}
}
System.out.print(count);
}
}
Solution:-
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int p=sc.nextInt();
int v=sc.nextInt();
int miss=0,f=0,r=0;
int arr[]=new int[v];
int que[]=new int[v];
for(int i=0;i<v;i++)
arr[i]=sc.nextInt();
for(int i=0;i<v;i++)
{
int flag=0,pos=-1;
if(r<p)
{
que[i]=arr[i];
r++;
miss++;
}
else
{
for(int j=f;j<r;j++)
{
if(arr[i]==que[j])
{
flag=1;
pos=j;
break;
}
}
if(flag==1)
{
for(int j=pos;j<r-1;j++)
{
que[j]=que[j+1];
}
que[r-1]=arr[i];
}
else
{
f++;
que[r++]=arr[i];
miss++;
}
}
}
System.out.println("Miss="+miss);
}
}