java - 使用binarySearch从ArrayList中删除单词

标签 java arrays list arraylist

我有一个未排序的数组列表和另一个已排序的数组列表。我需要添加一个删除按钮来从原始顺序和排序顺序中删除单词,但要使用二进制搜索删除,我需要对原始顺序进行排序。但我需要保持它不排序...

    int songIndex = Collections.binarySearch(song, titleArtistInput.getText());
    int sortedSongIndex = Collections.binarySearch(sortedSong, titleArtistInput.getText());

    //To test the values.
    System.out.println(songIndex + " " + sortedSongIndex);



    if (sortedSongIndex < 0)
    {
        titleArtistOutput.setText("That CD does not exist in the collection, please try again");
    }
    else if (sortedSongIndex >= 0)
    {
        sortedSong.remove(sortedSongIndex);
        Collections.sort(song);
        song.remove(Collections.binarySearch(song, titleArtistInput.getText()));
    }

是否有一种方法可以恢复 Collections.sort?或者有什么方法可以在不对歌曲 ArrayList 进行排序的情况下做到这一点?

编辑: 我自己搞定了!最后。

int sortedSongIndex = Collections.binarySearch(sortedSong, titleArtistInput.getText());

    //if the Collections.binarySearch is negative (song not found), it will output 
    //"That CD does not exist in the collection, please try again", if the sortedSongIndex is positive
    //(the song had been found!) and will remove the indexOf titleArtistInput.getText() from the ArrayLists
    if (sortedSongIndex < 0)
    {
        titleArtistOutput.setText("That CD does not exist in the collection, please try again");
    }
    else if (sortedSongIndex >= 0)
    {
        sortedSong.remove(sortedSong.indexOf(titleArtistInput.getText()));
        song.remove(song.indexOf(titleArtistInput.getText()));

    }

最佳答案

使用 Map<String, Integer> songToIndexMap存储每首歌曲的索引。

然后就这样做:

Integer index = songToIndexMap.remove(titleArtistInput.getText());
if(index != null) {    // the song has been found!
    song.remove(index);
}

二分查找是 O(log n)remove/getHashMapO(1) .

关于java - 使用binarySearch从ArrayList中删除单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21262043/

相关文章:

java - 查找文本文件中每个字母的出现频率

python - 如何在 python 排序(列表)中指定 2 个键?

c - 双端队列,通过引用调用(创建 header )

java - 表单中的 LocalDate

java - 获取二维数组的数组切片

java - 使用 JTabbedPane 自动扩展

C - 汉诺塔 - 使用数组显示算法每次迭代的每个 Hook 的内容

python - 如何将字符串中的列表转换为列表

java - SpringBoot Thymeleaf 无法解析模板

java - JPanel 上的圆角边框