算法:用户喜好--Map与List配合下的查找
Posted thewinter
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:用户喜好--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 stub Scanner 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;
以上是关于算法:用户喜好--Map与List配合下的查找的主要内容,如果未能解决你的问题,请参考以下文章
C#中list<>定义的变量,我用foreach()循环查找 与 list<> .find 查找两个哪个效率高?后者是不是用了算法