問題:
Yesterday I was pairing the socks from the clean laundry and figured out the way I was doing it is not very efficient.昨天我把洗乾淨的衣服的襪子配對,發現我這樣做的方式效率不高。 I was doing a naive search — picking one sock and "iterating" the pile in order to find its pair.我正在做一個天真的搜索 - 挑選一隻襪子並“迭代”一堆以找到它的一雙。 This requires iterating over n/2 * n/4 = n 2 /8 socks on average.這需要平均迭代 n/2 * n/4 = n 2 /8 個襪子。
As a computer scientist I was thinking what I could do?作爲一名計算機科學家,我在想我能做什麼? Sorting (according to size/color/...) of course came to mind to achieve an O(NlogN) solution.排序(根據大小/顏色/...)當然會想到實現 O(NlogN) 解決方案。
Hashing or other not-in-place solutions are not an option, because I am not able to duplicate my socks (though it could be nice if I could).散列或其他非就地解決方案不是一種選擇,因爲我無法複製我的襪子(儘管如果可以的話可能會很好)。
So, the question is basically:所以,問題基本上是:
Given a pile of n
pairs of socks, containing 2n
elements (assume each sock has exactly one matching pair), what is the best way to pair them up efficiently with up to logarithmic extra space?給定一堆n
雙襪子,包含2n
元素(假設每隻襪子正好有一對匹配),用最多對數額外空間將它們有效配對的最佳方法是什麼? (I believe I can remember that amount of info if needed.) (如果需要,我相信我能記住那麼多信息。)
I will appreciate an answer that addresses the following aspects:我將感謝解決以下方面的答案:
- A general theoretical solution for a huge number of socks.大量襪子的通用理論解決方案。
- The actual number of socks is not that large, I don't believe my spouse and I have more than 30 pairs.襪子的實際數量並沒有那麼大,我不相信我和我的配偶有30多雙。 (And it is fairly easy to distinguish between my socks and hers; can this be used as well?) (而且很容易區分我的襪子和她的襪子;這也可以使用嗎?)
- Is it equivalent to the element distinctness problem ?是否等價於元素區分問題?
解決方案:
參考一: https://stackoom.com/question/yUED參考二: How can I pair socks from a pile efficiently?