算法:用户喜好--Map与List配合下的查找
生活随笔
收集整理的這篇文章主要介紹了
算法:用户喜好--Map与List配合下的查找
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
?提示:在算法處理過程中,未必就要將出現在前面的作為關鍵字檢索。比如本題,非得先去檢索范圍,再去判斷范圍中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;}} }轉載于:https://www.cnblogs.com/theWinter/p/11261972.html
總結
以上是生活随笔為你收集整理的算法:用户喜好--Map与List配合下的查找的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: usb驱动怎么安装?
- 下一篇: 云技术-SaaS架构初步理解