3

我有一个关于如何将任何数字插入有序 ArrayList 的有趣问题。假设用户输入[12,34,37,60,89];该方法addListElement()应该遍历数组以找到新元素所在的索引。

用户输入数字 50,新数组应该是[12,34,37,50,60,89]. 我使用 for 循环遍历 ArrayList,但我不确定我的 if() 语句。

public void addListElement() {
    System.out.println("Add number to arrayList");
    Scanner scan = new Scanner(System.in);
    int number = scan.nextInt();

    int loc = 0;
    for (int i = 0; i < aryList.size(); i++) {
        if (number > 0 && i < loc) {
            loc++;
        }
    }

    aryList.add(loc, number);
    System.out.println(aryList.toString());
}
4

6 回答 6

5

试试这个:

int position = Collections.binarySearch(aryList, number);
aryList.add(position < 0 ? -position - 1 : position, number);

编辑感谢指出旧代码崩溃,如果数字已经存在

于 2012-10-14T21:40:13.290 回答
2

您会想要使用该List<E>.add(int idx, E element)方法。按顺序插入元素的想法是,对于某些数组a,元素a i和某些整数n

a i <= n <= a i+1 , 0 < i < len(a)-1。

// edge case:  Size one list, number coming in is smaller.
if(aryList.size() == 1 && aryList.get(0) >= number) {
    aryList.add(0, number);
} else {
    for(int i = 0; i < aryList.size()-1; i++) {
        if(number >= aryList.get(i) && number <= aryList.get(i+1)) {
            aryList.add(i, number);
        }
    }
    // number is the largest seen; add it to the end.
    aryList.add(number);
}
于 2012-10-14T21:50:13.363 回答
1

这也应该有效。由于列表已经按升序排列,当您发现列表中的数字大于当前数字时,请在 arrayList 中的该数字之前插入新的第一索引。

 for (int i = 0; i < aryList.size(); i++) {
    if (aryList.get(i)>number) {
       break;
    }
  loc++;
}
于 2012-10-14T22:01:56.157 回答
0
int loc = 0;
int prevNumber = aryList.get(0);
for(int i = 1; i<aryList.size(); i++){
            if(number > prevNumber && number <= aryList.get(i)){ 
               return i;
            }
    prevNumber = aryList.get(i);
  }
于 2012-10-14T21:44:52.400 回答
0

只要有更多元素并且数量小于当前元素,就增加索引。当用户给出的数字大于当前列表中的任何数字时,您还必须检查 i != list.size() 是否完成。

while (number >= 0 && number <= list.get(i) && i < list.size()) {
    i++;
}

list.add(i, number);
于 2012-10-14T21:49:50.130 回答
0

我想你的元素是按升序排列的

 public void insert(int x){
        // loop through all elements
        for (int i = 0; i < arrayList.size(); i++) {
            // if the element you are looking at is smaller than x, 
            // go to the next element
            if (arrayList.get(i) < x) continue;
            // if the element equals x, return, because we don't add duplicates
            if (arrayList.get(i) == x) return;
            // otherwise, we have found the location to add x
            arrayList.add(i, x);
            return;
        }
        // we looked through all of the elements, and they were all
        // smaller than x, so we add x to the end of the list
        arrayList.add(x);
    }

如果要在 ArrayList 中插入重复项,只需删除代码行

if (arrayList.get(i) == x) return;
于 2012-10-14T22:19:23.583 回答