[英]How to make a void method that will remove and replace duplicates from integer array in java
我正在嘗試從 Java 中的 int 數組中刪除重復項。此方法無效,應該只更改我給出的數組。 我還應該用 0 替換每個重復項。
//array's duplicates are replaced with zero
//array is returned
public static void removeDuplicates(int[] array) {
//create a temp variable to compare all other other int values in result array
int temp;
//double for loop iterates through array and compares each value to temp.
for(int i = 0; i < array.length; i++) {
temp = array[i];
for(int j = 0; j < array.length; j++) {
if ((array[j] == temp) && (j+1 < array.length)) {
array[j] = 0;
}
}
}
}
到目前為止,這是我嘗試過的。 它運行,但是,我無法將所有重復項替換為零。 例如,如果我有一個數組 {2,2},那么我將得到一個數組 {0,2},這不是我想要的。 相反,我應該得到 {0,0}。 我試過把它畫出來,但仍然找不到問題所在。
Temp 保存要刪除的值,但前提是它是重復的。 內層循環必須從i+1到結束go,看temp
是否存在其他值。 如果是這樣,將它們歸零。 但是由於第一個也等於temp
如果它是重復的,它也必須被刪除。
將循環更改為以下內容:
for(int i = 0; i < array.length-1; i++) {
temp = array[i];
for(int j = i+1; j < array.length; j++) {
if (array[j] == temp) {
array[j] = 0;
array[i] = 0; // remove the first one too
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.