zoukankan      html  css  js  c++  java
  • 算法:用户喜好--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;
            }
        }
    }
  • 相关阅读:
    Fy's dota2
    Black Rock Shooter
    树上的颜色
    8.spring:事务管理(上):Spring的数据库编程、编程式事务管理
    7.spring:SpringAOP(配置文件)
    6.spring:AOP(注解)
    5.spring:注解配置 Bean
    4.spriing:Bean的生命周期/工厂方法配置Bean/FactoryBean
    3.spring:自动装配/Bean之间的关系/作用域/外部文件/spel/
    2.spring:集合属性
  • 原文地址:https://www.cnblogs.com/theWinter/p/11261972.html
Copyright © 2011-2022 走看看