我有一个未排序的数组列表和另一个已排序的数组列表。我需要添加一个删除按钮来从原始顺序和排序顺序中删除单词,但要使用二进制搜索删除,我需要对原始顺序进行排序。但我需要保持它不排序...
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
/get
在 HashMap
是 O(1)
.
关于java - 使用binarySearch从ArrayList中删除单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21262043/