我怎樣才能使它在一個陣列中如果值出現不止一次,那么代碼就可以說該值出現在索引中。0,1,等等?
我正在完成一項家庭作業,該作業要求撰寫一個名為 linearSearch 的方法,該方法將對一個整數陣列執行線性搜索:從索引 0 開始搜索,然后是 1、2、3....。 它應該回傳包含目標的陣列的索引,如果在陣列中沒有找到,則回傳-1。我已經這樣做了,但我看到的一個問題是,如果目標在陣列中出現不止一次,那么列印陳述句將只列印它首先出現的位置。例如,如果我的陣列是[6, 3, 9, 2, 7, 6]。列印陳述句說 "6在索引處被發現。0". 有什么方法可以改變它,當值出現超過一次時,列印陳述句就會說 "6在索引處被發現。0和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 " 在索引處找到。" linearSearch(y, z))。
}
public static int[] createRandomIntArray(int n) {
Random random = new Random()。
int[] result = new int。
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;
}
}
輸出。
[6, 3, 9, 2, 7, 6]
6在索引中發現。0] 6 在索引中發現:6
uj5u.com熱心網友回復:
我將使用一個串列來存盤找到目標號碼的每個索引,然后在回傳它們之前將它們加在一起變成一個字串:
public static String linearSearch(int[] array, int target) {
List<Integer> indices = new ArrayList<Integer>()。
for (int i = 0; i < array.length; i ) {
if (array[i] == target) {
indices.add(i);
}
}
return indices.stream().map(String::valueOf).collectors.join(" and ") 。
}
但是我想,你的教授還不想讓你使用串列,更不用說流了。所以,這里有另一種方法,它創建了一個新的陣列來存盤索引,使其與源陣列的大小相同,并使用一個變數matches來跟蹤該陣列中存盤了多少個索引:
public static String linearSearch(int[] array, int target) {
int[] indices = new int[array.length] 。
int matches = 0;
for (int i = 0; i < array.length; i ) {
if (array[i] == target) {
indices[matches ] = i;
}
}
if (matches == 1) {
return String.valueOf(indices[0]) 。
} else {
String builder = String.valueOf(indices[0] )。)
for (int i = 1; i < matches; i ) {
builder = " and " indices[i];
}
return builder。
}
uj5u.com熱心網友回復:
與其修改你的linearSearch方法的回傳值來處理多個匹配,你不如為搜索添加一個起始位置。
public static int linearSearch(int[] array, int target, int off) {
for (int i = off; i < array.length; i ) {
if (array[i] == target) {
return i;
}
}
return -1;
}
然后你將進行(潛在的)多次呼叫,使用先前確定的匹配位置作為下一次搜索的起點。當你找不到匹配的時候,你就退出。
public static void main(String[] args)
{
int x = 6;
int[] y = {6, 3, 9, 2, 7, 6}。
int off = 0;
while(true)
{
off = linearSearch(y, x, off)。
if(off < 0) break;
System.out.println("在索引處發現:" off)。
off = 1;
}
}
輸出:
在索引處發現。0
在索引處發現。5
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/308368.html
標籤:
