数列查询算法

来源:互联网 发布:c 窗体编程视频教程 编辑:程序博客网 时间:2024/05/17 01:13

今日头条的一道面试题:题目描述是这样的
给定两个长度为n的数列A和B,在给定q组查询,每次查询给出两个整数x和y,求满足Ai >= x 且 Bi >= y这样的i的数量

输入:
第一行给定两个整数n和q
第二行给定数列A,包含n个整数
第三行给定数列B,包含n个整数
接下来q行,每行两个整数x和y,意义如上所述

输出:
对于每组查询,输出所求下标数量

样例输入:
3 2
3 2 4
6 5 8
1 1
4 8

输出:
3
1

思路:我认为是先把A,B两个数组先分开,然后满足Ai >= x 的i的位置存到一个list里面,再把满足Bi >= y的i的位置存到一个list里面,最后比较两个list里面相同的i的数量

代码:

import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class Series{    public static void queryCondition(int[] a,int[] b,List<String> query){        for (int i = 0; i < query.size(); i++) {            int x,y;            List<Integer> SmailX = new ArrayList<Integer>(); //用于存放满足Ai >= x的list            List<Integer> SmailY = new ArrayList<Integer>(); //用于存放满足Bi >= y的list            int count = 0;            String[] str = query.get(i).split(" ");            x = Integer.valueOf(str[0]);            y = Integer.valueOf(str[1]);            for (int j = 0; j < a.length; j++) {                if(a[j] >= x){                    SmailX.add(j);                }            }            for (int j = 0; j < b.length; j++) {                if(b[j] >= y){                    SmailY.add(j);                }            }            for(Integer e : SmailY) {                if(SmailX.contains(e)){                    count++;                }            }            System.out.println(count);        }    }    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        String[] str = scanner.nextLine().split(" "); //输入n和q,用数组分开        int n = Integer.valueOf(str[0]);        int q = Integer.valueOf(str[1]);        List<String> query = new ArrayList<String>(); //存放查询条件的list        String[] stringArrayA = scanner.nextLine().split(" ");   //用数组存放数组A        String[] stringArrayB = scanner.nextLine().split(" ");  //用数组存放数组B        for(int i = 0; i < q; i++){            query.add(scanner.nextLine());        }        int[] A = new int[n];        int[] B = new int[n];        for (int i = 0; i < n; i++) {            A[i] = Integer.valueOf(stringArrayA[i]);        }        for (int i = 0; i < n; i++) {            B[i] = Integer.valueOf(stringArrayB[i]);        }        queryCondition(A,B,query);    }}

这个是当时匆匆忙忙写的,应该还有其他的办法,欢迎提出,可以关注微信公众号“java从无到有”,我自己新申请的,想逼着自己做点笔记,搞点原创,欢迎大家来和我一起,我们一起讨论,一起进步,我只是一个刚刚起步的小菜鸟
我的公众号二维码:
这里写图片描述

0 0