题目描述
DL 算缘分算得很烦闷,所以常常到体育馆去打保龄球解闷。因为他保龄球已经打了几十年了,所以技术上不成问题,于是他就想玩点新花招。
DL 的视力真的很不错,竟然能够数清楚在他前方十米左右每个位置的瓶子的数量。他突然发现这是一个炫耀自己好视力的借口——他看清远方瓶子的个数后从某个位置发球,这样就能打倒一定数量的瓶子。
-
◯◯◯◯◯◯
-
◯◯◯ ◯◯◯◯ ◯
-
◯◯
-
◯ ◯◯ ◯
如上图,每个 “◯◯” 代表一个瓶子。如果 DL 想要打倒 3 个瓶子就在 1 位置发球,想要打倒 4 个瓶子就在 2 位置发球。
现在他想要打倒 𝑚 个瓶子。他告诉你每个位置的瓶子数,请你给他一个发球位置。
输入格式
第一行包含一个正整数 𝑛,表示位置数。
第二行包含 𝑛n 个正整数 𝑎𝑖 ,表示第 𝑖个位置的瓶子数,保证各个位置的瓶子数不同。
第三行包含一个正整数 𝑄,表示 DL 发球的次数。
第四行至文件末尾,每行包含一个正整数 𝑚,表示 DL 需要打倒 𝑚 个瓶子。
输出格式
共 𝑄 行。每行包含一个整数,第 𝑖 行的整数表示 D 第 𝑖 次的发球位置。若无解,则输出 0。
代码:
1.暴力解法(60)
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n + 1];
for(int i = 1;i <= n;i ++)
{
a[i] = sc.nextInt();
}
int q = sc.nextInt();
while(q -- != 0)
{
int index = 0;
int tmp = sc.nextInt();
for(int i = 1;i <= n;i ++)
{
int temp = a[i];
if(tmp == temp)
{
index = i;
}
}
if(index == 0)
{
System.out.println(0);
}else{
System.out.println(index);
}
}
}
}
2.STL解法(90)
package lanqiao;
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Map<Integer,Integer> map = new HashMap<>();
for(int i = 1;i <= n;i ++)
{
int a = sc.nextInt();
map.put(a,i);
}
int q = sc.nextInt();
while(q -- != 0)
{
int tmp = sc.nextInt();
if(map.get(tmp) == null)
{
System.out.println(0);
}else{
System.out.println(map.get(tmp));
}
}
}
}