提示:在算法处理过程中,未必就要将出现在前面的作为关键字检索。比如本题,非得先去检索范围,再去判断范围中key的个数。反其道而行,把输入的数字当作关键字,组成Map
package test;import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner;public class Main6 {/** 相当于在输入的权值数组的下面,进行序号装入* 1 2 3 3 5 -> * 1:1 * 2:2 * 3:3,4* 4:5* 入此进行判断范围* * * */public static void main(String[] args) {// TODO Auto-generated method stubScanner sc=new Scanner(System.in);int n=sc.nextInt();HashMap<Integer,ArrayList<Integer>> hm=new HashMap<Integer,ArrayList<Integer>>();for(int i=0;i<n;i++) {int temp=sc.nextInt();if(hm.containsKey(temp)) {hm.get(temp).add(i);}else {ArrayList<Integer> al=new ArrayList<Integer>();al.add(i);hm.put(temp,al);}}int m=sc.nextInt();int b[]=new int[m];for(int j=0;j<m;j++) {int low=sc.nextInt()-1;int high=sc.nextInt()-1;int key=sc.nextInt();if(!hm.containsKey(key)) {b[j]=0;}else {b[j]=getNum(low, high,hm.get(key));}}for(int j=0;j<m;j++) {System.out.println(b[j]);}sc.close();}public static int getNum(int low ,int high,ArrayList<Integer> al) {int i=0;int j=al.size()-1;//如果list中的最小值比你范围中最大值还大,例如你查找[1,2] 3 //显然al.get(3)中最小的也是三,所以里面定然无值,返回0.同理最小值大于它最大值也是返回0.比如2 4 5肯定返回0 if(al.get(i)>high || al.get(j)<low ) {return 0;}else {while(al.get(i)<low || al.get(j)>high) {if(al.get(i)<low) i++;if(al.get(j)>high) j--;}return j-i+1;}} }