问题描述:
样例如下:
代码如下:利用map解决即可
import java.util.*;
public class Solution {
//随机数索引
Map<Integer, List<Integer>> map=new HashMap<>();//利用map来存储nums数组中的值和下标
public Solution(int[] nums) {
for (int i = 0; i <nums.length ; i++) {
if (map.containsKey(nums[i])){//利用map查重,若存在,则直接添加后修改
List<Integer> list=map.get(nums[i]);
list.add(i);
map.put(nums[i],list);
}else {
List<Integer> list=new LinkedList<>();
list.add(i);
map.put(nums[i],list);
}
}
}
public int pick(int target) {
int res=0;
if (map.containsKey(target)) {
List<Integer> list = map.get(target);
if (list.size() == 1) res = list.get(0);
else {
int random = new Random().nextInt(list.size());
res = list.get(random);
}
return res;
}else return -1;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入数组长度");
int n=scanner.nextInt();
int[] nums=new int[n];
System.out.println("请输入数组内容");
for (int i = 0; i <n ; i++) {
nums[i]=scanner.nextInt();
}
Solution solution=new Solution(nums);
while (true) {
System.out.println("请输入要查找的数字");
int target = scanner.nextInt();
System.out.println(solution.pick(target));
}
}
}
运行结果如下: