How can I pair socks from a pile efficiently?

后端 未结 30 1176
旧巷少年郎
旧巷少年郎 2020-11-27 08:37

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

30条回答
  •  猫巷女王i
    2020-11-27 09:32

    The theoretical limit is O(n) because you need to touch each sock (unless some are already paired somehow).

    You can achieve O(n) with radix sort. You just need to pick some attributes for the buckets.

    1. First you can choose (hers, mine) - split them into 2 piles,
    2. then use colors (can have any order for the colors, e.g. alphabetically by color name) - split them into piles by color (remember to keep the initial order from step 1 for all socks in the same pile),
    3. then length of the sock,
    4. then texture, ....

    If you can pick a limited number of attributes, but enough attributes that can uniquely identify each pair, you should be done in O(k * n), which is O(n) if we can consider k is limited.

提交回复
热议问题