【发布时间】:2021-09-07 19:35:58
【问题描述】:
如果该值在数组中出现多次,代码可以说该值出现在索引中:0、1 等,我该如何做到这一点?
我正在做一个家庭作业,要求编写一个名为 linearSearch 的方法,该方法对整数数组执行线性搜索:从索引 0 开始搜索,然后是 1、2、3……。它应该返回包含目标的数组的索引,如果在数组中找不到它,则返回 -1。我已经这样做了,但是我看到的一个问题是,如果目标在数组中多次出现,则 print 语句只会打印它首先位于的位置。例如,如果我的数组是 [6, 3, 9, 2, 7, 6]。打印语句说“在索引:0 找到 6”。当值出现多次时,有没有办法改变它,所以打印语句会说“6 is found at index: 0 and 5”?
import java.util.Arrays;
import java.util.Random;
public class Q6 {
public static void main(String[] args) {
Random random = new Random();
int x = random.nextInt(10);
int[] y = createRandomIntArray(x);
int z = x;
System.out.println(Arrays.toString(y));
System.out.println(z + " is found at index: " + linearSearch(y, z));
}
public static int[] createRandomIntArray(int n) {
Random random = new Random();
int[] result = new int[n];
for (int i = 0; i < result.length; i++)
result[i] = random.nextInt(10);
return result;
}
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
}
Output:
[6, 3, 9, 2, 7, 6]
6 is found at index: 0
【问题讨论】:
-
将找到的索引保存在一个数组中并返回该数组而不是返回 i。