亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么這個 while 循環不會中斷?

為什么這個 while 循環不會中斷?

慕桂英3389331 2023-07-28 15:50:45
這是用 Java 編寫的 while 循環。目的是從列表中刪除所有重復項。但循環并沒有中斷??赡苓€有其他錯誤。public static <E extends Comparable<? super E>> void removeDuplicates(ArrayList<E> L) {    ArrayList<E> temp = new ArrayList<E>(L.size());    ArrayList<Integer> index = new ArrayList<>(L.size());    int stop = 0;    while (true) {        //test for duplicates and save their indexes        for (int i = 0; i < L.size(); i++) {            if (!temp.contains(L.get(i))) {                temp.add(L.get(i));                index.add(i);            }        }        // if there were duplicates they will be removed        if (!index.isEmpty()) {            stop = 1;            for (int j = 0; j < index.size(); j++) {                L.remove(index.get(j));            }        }        //if nothing is removed there should be no duplicates and the loop should break        if (stop == 0) {            break;        }        index.clear();        temp.clear();        stop = 0;    }} 
查看完整描述

1 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

當臨時列表中已存在要刪除的項目時,您需要更新它們的列表。因此索引列表將包含所有重復元素的索引:


public static <E extends Comparable<? super E>> void removeDuplicates(final ArrayList<E> L) {

final ArrayList<E> temp = new ArrayList<E>(L.size());

final ArrayList<Integer> index = new ArrayList<>(L.size());

int stop = 0;


while (true) {

  //test for duplicates and save their indexes

  for (int i = 0; i < L.size(); i++) {

    if (!temp.contains(L.get(i))) {

      temp.add(L.get(i));

    } else {


      index.add(i);

    }

  }

  // if there were duplicates they will be removed

  if (!index.isEmpty()) {

    stop = 1;

    for (int j = index.size() - 1; j >= 0; j--) {

      L.remove((int) index.get(j));

    }

  }

  //if nothing is removed there should be no duplicates and the loop should break

  if (stop == 0) {

    break;

  }

  index.clear();

  temp.clear();

  stop = 0;

}


查看完整回答
反對 回復 2023-07-28
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號