【问题标题】:Inserting String into an array in order [duplicate]按顺序将字符串插入数组[重复]
【发布时间】:2016-08-08 16:23:57
【问题描述】:

我有一个已经按字母顺序排列的字符串列表。这里我们只是假设用户按字母顺序输入项目。

我有一个类中的字符串项列表和一个方法,在该方法中有人可以传入另一个要插入到数组中的字符串对象。

String[] strings = new Strings[0];

public void add(String a){
//here the current list is resized and we need to add the new item
Strings[] newSizedList = new String[strings.length+1];
//for loop here to copy items over into the new resized array.
}

问题是,该列表已被假定为按字母顺序排列。我需要做的是将传入的字符串插入到数组中的正确位置,同时仍保持其他项目按字母顺序排列。

限制是我不想使用任何类型的“排序算法”。换句话说,我不想一次将整个列表排序并按顺序排列。

我想保持该项目按顺序排列,因为它已经按顺序排列,但将当前项目插入其在列表中的相应位置。

我不能使用任何 Collection 静态方法或 Java 集合类静态方法

有谁知道如何做到这一点?

【问题讨论】:

标签: java


【解决方案1】:

由于无论如何您都将使用 for 循环克隆数组,因此无需在此处进行任何排序(这应该是个好消息,因为您说这不是一个选项)。浏览项目时,只需将新项目插入正确的位置即可。

//for loop here to copy items over into the new resized array.
//We use two counters here, ii for the old list and i for the new
int ii = 0, nn = strings.length;
for(int i = 0, n = newSizedList.length; i < n; i++) {

    if(ii != nn && (ii != i || strings[ii].compareTo(a) < 0)){
        //The item in newSizedList[i] will be taken from the original list if
        //we have not already taken all the items from there (ii != nn) and
        //a) we have already inserted the new item (ii != i)
        //or b) a is alphabetically "greater" than the corresponding item in original array
        newSizedList[i] = strings[ii];
        ii++;//Keep the other counter in sync
    } else  {
        //Otherwise, this is the place for the new item
        newSizedList[i] = a;
    }

}

【讨论】:

  • 如果我有一个传入的项目列表,我想使用上述相同的算法按字母顺序在传入的列表中输入这些项目?
  • 不幸的是,这会给问题增加相当多的复杂性,因此这个 sn-p 也需要一些更改。例如,i != ii 测试不起作用,您需要与该数组中的所有项目进行比较,现在我们只是与a 进行比较。通过一些更改应该仍然可以,但是如果您只是对数组进行排序或像其他人建议的那样使用 SortedSet,您将节省很多麻烦。这种方法在这里行得通,因为仅插入一项的任务非常简单。
  • 我明白你的意思。所以我要做的是有一个方法,它将字符串列表作为参数,然后通过为列表中的每个字符串调用上面的方法,循环遍历列表,将每个字符串添加到数组中的正确位置。这听起来像是一个好的解决方案吗?
  • @user1664285 嗯...好吧,无论如何我都试了一下,毕竟它并没有那么困难,至少如果新列表也已经排序的话。看看repl.it/CGsy/0
【解决方案2】:

Arrays.binarySearch 可用于高效找到正确的插入点。

【讨论】:

  • 我不能使用任何 Collection 静态方法
  • 在这种情况下查找二进制搜索算法并自己实现它,假设您需要在 O(logn) 时间内运行插入。
【解决方案3】:

只需在 Arrays 类中调用正确的方法。

Arrays.sort(newSizedList);

【讨论】:

  • 我不能使用任何 Collection 静态方法
猜你喜欢
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 2015-03-16
  • 1970-01-01
  • 2021-03-16
  • 2013-12-18
  • 2018-05-29
相关资源
最近更新 更多