第一个博客,写的不好,大家将就看看就好
输入描述:
输入: 第1行为n代表用户的个数 第2行为n个整数,第i个代表用户标号为i的用户对某类文章的喜好度 第3行为一个正整数q代表查询的组数 第4行到第(3+q)行,每行包含3个整数l,r,k代表一组查询,即标号为l<=i<=r的用户中对这类文章喜好值为k的用户的个数。 数据范围n <= 300000,q<=300000 k是整型
输出描述:
输出:一共q行,每行一个整数代表喜好值为k的用户的个数
示例1
输入
5
1 2 3 3 5
3
1 2 1
2 4 5
3 5 3
输出
1
0
2
说明
样例解释:
有5个用户,喜好值为分别为1、2、3、3、5,
第一组询问对于标号[1,2]的用户喜好值为1的用户的个数是1
第二组询问对于标号[2,4]的用户喜好值为5的用户的个数是0
第三组询问对于标号[3,5]的用户喜好值为3的用户的个数是2
思路是参考某博客的,只是发现其代码有点问题,于是自己动手写的代码。如果有更好的解决方案,欢迎留言。
package toutiao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class toutiao_2018_2_1 {
public static void main(String[] args) {
Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
int[] arr = new int[3000];
int n = sc.nextInt();
for(int i = 0;i<n;i++) {
arr[i] = sc.nextInt();
}
//k记录元素 v记录元素出现位置
for(int i=1;i<=n;i++) {
int k = arr[i-1];
int v = i;
if(!map.containsKey(k)) {
List<Integer> list = new ArrayList<Integer>();
list.add(i);
map.put(k, list);
}else {
List<Integer> list = map.get(k);
list.add(v);
}
List<Integer> l = map.get(k);
for(int ii:l) {
System.out.println(k+"-->"+ii);
}
}
//查询的组数
int check = sc.nextInt();
List<Integer> list1 = new ArrayList<Integer>();
for(int i=1;i<=check;i++) {
//四行以后 l r k
int l = sc.nextInt();
int r = sc.nextInt();
int k = sc.nextInt();
List<Integer> list = map.get(k);
//次数
int count = 0;
if(list!=null) {
for(int temp:list) {
if(temp>=l&&temp<=r) {
count++;
}
}
}
list1.add(count);
}
for(int i:list1) {
System.out.println(i);
}
}
}