将某些玩具从左到右的固定排列可以增加客流量,将这种排列称为完美排列。
现在店员记录下了玩具店里面N个玩具的排列顺序,现在想让你帮忙找找这个排列里面有没有完美排列。如果有,返回最先出现的下标(下标从1开始计算),如果没有,返回0。
输入:
第一行一个整数K表示完美排列的长度
第二行K个整数Ai,表示完美排列从左到右的外观值
第三行K个整数Bi,表示完美排列从左到右的价格值
第四行一个正整数N,表示当前玩具店里面排列的玩具数量
第五行N个整数Ci,表示玩具店里从左到右的外观值
第六行N个整数Di,表示玩具店里从左到右的价格值
例子
3
1 2 3
3 2 1
1 2 3 3 2 1
3 2 1 1 2 3
返回1,因为从1号开始满足完美排列。
思路,输入的时候,将玩具店里面的在完美排列中第一个需要的外观值的下标放入一个队列里保存下来,然后只要搜索队列里面的开始的下标即可,而不用一位一位地来搜索。
直接看代码把:
public static Queue<Integer> queue;//保存actual中,完美排列需要的的第一个值的下标
public static int process(int[] example1,int[] example2,int[] actual1,int[] actual2){
int res=0;
while(!queue.isEmpty()){
int start=queue.poll();//actual的下标
int save=start;
int i=0;//example的下标
while(i<example1.length&&start<actual1.length&&example1[i]==actual1[start]&&example2[i]==actual2[start]){
i++;
start++;
}
if(start-save==example1.length){
res=save+1;
break;
}
}
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
queue=new PriorityQueue<>();
while(sc.hasNext()){
int n=sc.nextInt();
sc.nextLine();
int[] example1=new int[n];//example表示需要的完美排列
int[] example2=new int[n];
for(int i=0;i<n;i++){
example1[i]=sc.nextInt();
}
sc.nextLine();
for(int i=0;i<n;i++){
example2[i]=sc.nextInt();
}
int m=sc.nextInt();
sc.nextLine();
int[] actual1=new int[m];//actual表示玩具店的实际排列
int[] actual2=new int[m];
for(int i=0;i<m;i++){
actual1[i]=sc.nextInt();
if(actual1[i]==example1[0]&&actual1.length-i>=example1.length){
queue.add(i);//如果找到了完美排列的第一个,就放入队列
}
}
sc.nextLine();
for(int i=0;i<m;i++){
actual2[i]=sc.nextInt();
}
System.out.println( process(example1,example2,actual1,actual2));
}
}