[英]Removing words from ArrayList using binarySearch
我有一個未排序順序的arraylist,另一個是已排序順序的arraylist。 我需要添加一個刪除按鈕,以從“原始順序”和“已排序順序”中刪除單詞,但是要使用binarySearch刪除,我需要對原始順序進行排序。 但是我需要保持排序...
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)
而在HashMap
remove
/ get
為O(1)
。
我認為,創建配對列表是個好主意。 一對保持位置,另一對保持價值。 看這個問題 。 您仍然可以根據自己的值對列表進行排序。
如果要保留原始順序並快速搜索,可以將Map和ArrayList結合使用。
對於每個項目,將其添加到ArrayList中,然后將其與列表的索引一起添加到地圖中,並使用鍵將要按順序具有的字段作為鍵。
例:
ArrayList<Song> originalSort = new ArrayList<>();
Map<String, Song> theMap = new HashMap<>(); //we will sort by name of song
//add some items
Song song = new Song();
song.author = "thatMan";
song.name = "someTitle";
//the index will be the index within the ArrayList
song.index = originalSort.size();
originalSort.add(song);
theMap.put(song.name, song);
//...
//iterate with the original order:
for (Song song : originalSort) {
System.out.print(song.name);
}
//fast search and remove
song = theMap.remove(song.name);
originalSort.remove(song.index); //ArrayList has a fast acces by index
如果出於測試目的,您可以簡單地通過在排序之前復制列表來存儲原始訂單:
List listBackup = originalList.clone(); //remember to use clone method or you will be pointing to the same intance
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.